"""履约任务列表、详情和面客绑定视图。""" from __future__ import annotations from datetime import UTC, datetime from typing import Any from sqlalchemy import or_ from sqlalchemy.orm import Session from ...models import ( Account, AccountLease, DouyuExternalOrder, DouyuGoodsSnapshot, DouyuTask, PlatformCommodityMapping, PlatformFulfillmentEvent, PlatformFulfillmentTask, User, ) from ...permissions import ROLE_LABELS from ..account_binding import ( binding_role_from_result, pending_binding_role_from_result, ) from ..file_service import build_file_url from . import classification from .binding_status import ( _customer_task_message, _customer_task_message_for, _effective_binding_issue, _effective_task_message, _normalized_event_detail, ) from .common import ( _apply_order_match_cutoff, _jsonable, _order_match_started_at, ) from .repository import _load_task def list_tasks( db: Session, *, status: str = "", queue_bucket: str = "", sale_mode: str = "", keyword: str = "", page: int = 1, page_size: int = 20, ) -> dict[str, Any]: query = db.query(PlatformFulfillmentTask) query = _apply_order_match_cutoff(query, _order_match_started_at(db)) query = query.filter( or_( PlatformFulfillmentTask.commodity_mapping_id.isnot(None), PlatformFulfillmentTask.commodity_id != "", ) ) mode_filter = classification.normalize_sale_mode(sale_mode) if sale_mode and mode_filter != "unknown": query = query.filter(PlatformFulfillmentTask.sale_mode == mode_filter) elif sale_mode == "unknown": query = query.filter(PlatformFulfillmentTask.sale_mode == "unknown") if queue_bucket: now = datetime.now(UTC) if queue_bucket == classification.QUEUE_CANCELLED: query = query.filter( PlatformFulfillmentTask.execution_status == "cancelled" ) elif queue_bucket == classification.QUEUE_COMPLETED: query = query.filter( PlatformFulfillmentTask.execution_status == "completed" ) elif queue_bucket == classification.QUEUE_PENDING_MAPPING: query = query.filter( PlatformFulfillmentTask.execution_status == "pending_mapping" ) elif queue_bucket == classification.QUEUE_NEEDS_ACTION: query = query.filter( PlatformFulfillmentTask.execution_status == "manual_required" ) elif queue_bucket == classification.QUEUE_PRESALE_WAITING: query = query.filter( PlatformFulfillmentTask.execution_status.notin_( ["completed", "cancelled", "pending_mapping", "manual_required"] ), PlatformFulfillmentTask.sale_mode == "presale", or_( PlatformFulfillmentTask.offer_available_from.is_(None), PlatformFulfillmentTask.offer_available_from > now, ), ) elif queue_bucket == classification.QUEUE_READY: query = query.filter( PlatformFulfillmentTask.execution_status.notin_( ["completed", "cancelled", "pending_mapping", "manual_required"] ), or_( PlatformFulfillmentTask.sale_mode != "presale", PlatformFulfillmentTask.offer_available_from.is_(None), PlatformFulfillmentTask.offer_available_from <= now, ), ) else: query = query.filter( PlatformFulfillmentTask.execution_status.notin_( ["completed", "cancelled"] ) ) if status: if status == "unfinished": query = query.filter( PlatformFulfillmentTask.execution_status.notin_( ["completed", "cancelled"] ) ) else: query = query.filter(PlatformFulfillmentTask.execution_status == status) text = keyword.strip() if text: pattern = f"%{text}%" query = query.outerjoin( Account, Account.id == PlatformFulfillmentTask.account_id, ).filter( or_( PlatformFulfillmentTask.platform_order_id.ilike(pattern), PlatformFulfillmentTask.sku_name.ilike(pattern), PlatformFulfillmentTask.sku_code.ilike(pattern), PlatformFulfillmentTask.internal_sku_key.ilike(pattern), PlatformFulfillmentTask.commodity_id.ilike(pattern), Account.username.ilike(pattern), Account.nickname.ilike(pattern), Account.uid.ilike(pattern), ) ) total = query.count() rows = ( query.order_by( PlatformFulfillmentTask.paid_at.desc(), PlatformFulfillmentTask.id.desc(), ) .offset((max(1, page) - 1) * max(1, page_size)) .limit(max(1, min(page_size, 100))) .all() ) return { "items": [_task_out(db, row) for row in rows], "pagination": { "page": max(1, page), "pageSize": max(1, page_size), "total": total, }, } def _task_out( db: Session, task: PlatformFulfillmentTask, *, include_qr: bool = False, include_exchange_task: bool = False, ) -> dict[str, Any]: mapping = ( db.query(PlatformCommodityMapping) .filter(PlatformCommodityMapping.id == task.commodity_mapping_id) .first() if task.commodity_mapping_id else None ) goods = ( db.query(DouyuGoodsSnapshot) .filter(DouyuGoodsSnapshot.commodity_id == task.commodity_id) .order_by(DouyuGoodsSnapshot.id.desc()) .first() if task.commodity_id else None ) goods_name = ( str(getattr(mapping, "goods_name", "") or "") or str(getattr(goods, "name", "") or "") or task.sku_name or task.internal_sku_key ) account = ( db.query(Account).filter(Account.id == task.account_id).first() if task.account_id else None ) lease = ( db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() if task.lease_id else None ) bind_task = ( db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() if task.bind_task_id else None ) collab_order = ( db.query(DouyuExternalOrder) .filter(DouyuExternalOrder.source_task_id == task.id) .first() ) bind_result = (bind_task.result or {}) if bind_task else {} effective_issue = _effective_binding_issue(task, bind_task, bind_result) effective_last_error = _effective_task_message(task, effective_issue) exchange_task_id = task.exchange_task_id if exchange_task_id is None and include_exchange_task: exchange_task_id = ( db.query(DouyuTask.id) .filter( DouyuTask.platform_task_id == task.id, DouyuTask.task_type == "exchange_goods", ) .order_by(DouyuTask.id.desc()) .limit(1) .scalar() ) # 外层只消费共享绑定规则,不再自己比较角色名或 bindAct。 pending_role = pending_binding_role_from_result(bind_result) sale_mode = classification.normalize_sale_mode(task.sale_mode) availability = classification.availability_state( sale_mode=sale_mode, available_from=task.offer_available_from, available_until=task.offer_available_until, ) queue_bucket = classification.queue_bucket( execution_status=task.execution_status, sale_mode=sale_mode, availability=availability, ) manual_reason = ( classification.manual_reason(effective_issue, task.exchange_status) if task.execution_status == "manual_required" else "" ) return { "id": task.id, "sourceSystem": task.source_system, "sourceOrderId": task.source_order_id, "sourceOrderItemId": task.source_order_item_id, "sourceFulfillmentId": task.source_fulfillment_id, "platformOrderId": task.platform_order_id, "provider": task.provider, "shopId": task.shop_id, "shopName": task.shop_name, "skuCode": task.sku_code, "skuName": task.sku_name, "internalSkuKey": task.internal_sku_key, "quantity": task.quantity, "orderAmountFen": task.order_amount_fen, "targetPlatform": task.target_platform, "scope": task.scope, "commodityMappingId": task.commodity_mapping_id, "commodityId": task.commodity_id, "goodsName": goods_name, "requiredPoints": task.required_points, "saleMode": sale_mode, "campaignKey": task.campaign_key, "campaignName": task.campaign_name, "offerAvailableFrom": task.offer_available_from, "offerAvailableUntil": task.offer_available_until, "availabilityState": availability, "queueBucket": queue_bucket, "manualReason": manual_reason, "classificationSource": task.classification_source, "bindingStatus": task.binding_status, "executionStatus": task.execution_status, "exchangeStatus": task.exchange_status, "issueCode": effective_issue, "lastError": effective_last_error, "operatorId": task.operator_id, "completedAt": task.completed_at, "paidAt": task.paid_at, "createdAt": task.created_at, "updatedAt": task.updated_at, "collabOrder": ( { "id": collab_order.id, "orderNo": collab_order.order_no, "status": collab_order.status, "lastSyncedAt": collab_order.last_synced_at, } if collab_order else None ), "account": ( { "id": account.id, "username": account.username, "nickname": account.nickname or "", "points": account.points, "goldBalance": account.gold_balance, "eliteOpened": account.elite_opened, "ckCheckStatus": account.ck_check_status, "roleBindStatus": account.role_bind_status, "gameName": account.game_name, "gameChannel": account.game_channel, "roleChangeAvailableAt": account.role_change_available_at, } if account else None ), "lease": ( { "id": lease.id, "status": lease.status, "expiresAt": lease.expires_at, } if lease else None ), "bindTask": ( { "id": bind_task.id, "taskType": bind_task.task_type, "status": bind_task.status, "message": bind_task.message, "qrUrl": str(bind_result.get("url") or "") if include_qr else "", "roleName": binding_role_from_result(bind_result), "areaName": str(bind_result.get("area_name") or ""), "platName": str(bind_result.get("plat_name") or ""), "bindPhase": str(bind_result.get("bind_phase") or ""), "bindReadyForConfirm": bool(pending_role), "bindConfirmed": bool(bind_result.get("bind_confirmed")), } if bind_task else None ), "exchangeTaskId": exchange_task_id, "exchangeResultImage": ( { "objectKey": task.exchange_result_image_key, "url": build_file_url(task.exchange_result_image_key), "savedAt": task.exchange_result_image_saved_at, } if task.exchange_result_image_key else None ), } def get_task_detail(db: Session, task_id: int) -> dict[str, Any]: task = _load_task(db, task_id) events = ( db.query(PlatformFulfillmentEvent) .filter(PlatformFulfillmentEvent.task_id == task.id) .order_by(PlatformFulfillmentEvent.id.desc()) .limit(200) .all() ) actor_ids = { int(event.actor_id) for event in events if event.actor_type == "user" and str(event.actor_id or "").isdigit() } actors = ( { int(user.id): user for user in db.query(User).filter(User.id.in_(actor_ids)).all() } if actor_ids else {} ) bind_task_ids: set[int] = set() for event in events: detail = event.detail_json or {} raw_id = ( detail.get("douyuTaskId") if event.event_type.startswith("douyu_operation_") else detail.get("bindTaskId") ) try: bind_task_id = int(raw_id) if raw_id is not None else 0 except (TypeError, ValueError): bind_task_id = 0 if bind_task_id: bind_task_ids.add(bind_task_id) bind_tasks = ( { int(row.id): row for row in db.query(DouyuTask).filter(DouyuTask.id.in_(bind_task_ids)).all() } if bind_task_ids else {} ) return { "task": _task_out(db, task, include_qr=True, include_exchange_task=True), "events": [ { "id": event.id, "eventType": event.event_type, "actorType": event.actor_type, "actorId": event.actor_id, "actorName": ( actors[int(event.actor_id)].deleted_username or actors[int(event.actor_id)].username ) if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors else "", "actorRole": actors[int(event.actor_id)].role if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors else "", "actorRoleLabel": ROLE_LABELS.get( actors[int(event.actor_id)].role, actors[int(event.actor_id)].role, ) if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors else "", "detail": _normalized_event_detail(event, bind_tasks), "createdAt": event.created_at, } for event in events ], } def _customer_binding_queue_state( task: PlatformFulfillmentTask, bind_task: DouyuTask | None, *, lease_ready: bool, ) -> tuple[str, int]: if task.execution_status == "completed": return "completed", 0 if task.execution_status == "cancelled": return "cancelled", 0 if task.issue_code == "mapping_missing": return "mapping_missing", 0 if not task.account_id or not task.lease_id: return "allocation_queued", 2000 if not lease_ready: return "lease_inactive", 0 if task.binding_status == "failed": return "failed", 0 if bind_task is None: return "ready_to_start", 0 result = bind_task.result or {} if bool(result.get("bind_confirmed")) or task.binding_status == "bound": return "confirmed", 0 if pending_binding_role_from_result(result): return "role_ready", 0 if bind_task.status in {"failed", "error", "stopped"}: return "failed", 0 if task.binding_status == "confirming": return "confirming", 1000 if bind_task.status in {"planned", "pending"}: return "qr_queued", 1000 if result.get("url"): return "waiting_scan", 5000 if result.get("bind_polling") else 0 return "preparing", 1000 def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]: """面向前端客户页的安全绑定快照,不包含账号、CK、积分和租约。""" task = _load_task(db, task_id) bind_task = ( db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() if task.bind_task_id else None ) bind_result = (bind_task.result or {}) if bind_task else {} pending_role = pending_binding_role_from_result(bind_result) effective_issue = _effective_binding_issue(task, bind_task, bind_result) lease = ( db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() if task.lease_id else None ) lease_ready = bool(task.account_id and lease and lease.status == "active") binding_failed = task.binding_status == "failed" binding_confirmed = task.binding_status == "bound" queue_state, retry_after_ms = _customer_binding_queue_state( task, bind_task, lease_ready=lease_ready, ) return { "sessionId": task.id, "platformOrderId": task.platform_order_id, "sourceOrderItemId": task.source_order_item_id, "productName": task.sku_name, "quantity": task.quantity, "executionStatus": task.execution_status, "bindingStatus": task.binding_status, "exchangeStatus": task.exchange_status, "issueCode": effective_issue, "message": ( _customer_task_message_for(effective_issue) if effective_issue != task.issue_code else _customer_task_message(task) ), "accountReady": lease_ready, "bindTaskId": bind_task.id if bind_task else None, "bindTaskStatus": bind_task.status if bind_task else "", "bindPhase": str(bind_result.get("bind_phase") or ""), "qrUrl": str(bind_result.get("url") or ""), "qrGeneratedAt": str(bind_result.get("qr_generated_at") or ""), "qrExpiresAt": str(bind_result.get("qr_expires_at") or ""), "roleName": binding_role_from_result(bind_result), "areaName": str(bind_result.get("area_name") or ""), "platName": str(bind_result.get("plat_name") or ""), "bindReadyForConfirm": (bool(pending_role) and not binding_failed), "bindConfirmed": bool(bind_result.get("bind_confirmed")) and binding_confirmed, "queueState": queue_state, "retryAfterMs": retry_after_ms, "queueLane": bind_task.queue_lane if bind_task else "", "accepted": False, "stateVersion": int(task.state_version or 0), "completedAt": _jsonable(task.completed_at), "updatedAt": _jsonable(task.updated_at), }