"""履约任务加载、集成操作人和绑定任务查询。""" from __future__ import annotations import os from datetime import UTC, datetime, timedelta from fastapi import HTTPException from sqlalchemy.orm import Session from ...models import ( AccountLease, DouyuTask, PlatformFulfillmentTask, User, ) from .common import ( BINDING_QR_TTL_SECONDS, _apply_order_match_cutoff, _now, _order_match_started_at, ) def _load_task(db: Session, task_id: int) -> PlatformFulfillmentTask: task = ( db.query(PlatformFulfillmentTask) .filter(PlatformFulfillmentTask.id == int(task_id)) .first() ) if task is None: raise HTTPException(status_code=404, detail="直播账号履约任务不存在") return task def _load_task_for_update(db: Session, task_id: int) -> PlatformFulfillmentTask: task = ( db.query(PlatformFulfillmentTask) .filter(PlatformFulfillmentTask.id == int(task_id)) .populate_existing() .with_for_update() .first() ) if task is None: raise HTTPException(status_code=404, detail="直播账号履约任务不存在") from .views import invalidate_task_list_count_cache # 所有用户操作写路径都会先拿行锁;在这里失效可覆盖完成、取消、恢复等状态变更。 invalidate_task_list_count_cache() return task def _retain_lease_for_active_collab( db: Session, *, task: PlatformFulfillmentTask, lease: AccountLease | None, current: User, reason: str, ) -> AccountLease | None: """平台释放账号前,把仍在活动的协作单占用接续到同一租约。""" if lease is None or not task.account_id: return None from ..douyu_collab_service import retain_lease_for_active_collab return retain_lease_for_active_collab( db, account_id=int(task.account_id), holder_user_id=int(current.id), current=current, lease=lease, source_task_id=int(task.id), reason=reason, commit=False, ) def _integration_actor(db: Session) -> User: raw_user_id = os.getenv("PLATFORM_FULFILLMENT_INTEGRATION_ACTOR_ID", "").strip() query = db.query(User).filter(User.is_active.is_(True)) if raw_user_id: try: user = query.filter(User.id == int(raw_user_id)).first() except ValueError: user = None else: user = query.filter(User.role == "super_admin").order_by(User.id.asc()).first() if user is None: raise HTTPException( status_code=503, detail="未配置可用的直播账号履约集成操作人", ) return user def _find_customer_task( db: Session, *, source_order_item_id: str, platform_order_id: str = "", ) -> PlatformFulfillmentTask | None: item_id = str(source_order_item_id or "").strip() if not item_id: return None query = db.query(PlatformFulfillmentTask).filter( PlatformFulfillmentTask.source_system == "order_site", PlatformFulfillmentTask.source_order_item_id == item_id, ) query = _apply_order_match_cutoff(query, _order_match_started_at(db)) order_no = str(platform_order_id or "").strip() if order_no: query = query.filter(PlatformFulfillmentTask.platform_order_id == order_no) return query.first() def _binding_qr_expired(bind_task: DouyuTask, now: datetime | None = None) -> bool: result = bind_task.result or {} raw_expires_at = str(result.get("qr_expires_at") or "").strip() if raw_expires_at: try: expires_at = datetime.fromisoformat(raw_expires_at) except ValueError: expires_at = None if expires_at is not None: if expires_at.tzinfo is None: expires_at = expires_at.replace(tzinfo=UTC) return expires_at <= (now or _now()) created_at = bind_task.created_at if created_at.tzinfo is None: created_at = created_at.replace(tzinfo=UTC) return created_at + timedelta(seconds=BINDING_QR_TTL_SECONDS) <= (now or _now())