diff --git a/tests/test_migrations.py b/tests/test_migrations.py index 9aa578d..6d1a631 100644 --- a/tests/test_migrations.py +++ b/tests/test_migrations.py @@ -39,7 +39,7 @@ TESTS_DIR = Path(__file__).resolve().parent PROJECT_ROOT = TESTS_DIR.parent VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions" -HEAD_REVISION = "20261118_0093" +HEAD_REVISION = "20261118_0094" # 迁移新增、但不声明在模型里的复合查询索引。 EXTRA_INDEXES = ( diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index 5187509..357ff54 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -16,6 +16,7 @@ from web.backend.models import ( AccountEvent, AccountLease, AutomationJob, + DouyuExternalOrder, DouyuGoodsSnapshot, DouyuTask, IntegrationOutbox, @@ -25,6 +26,8 @@ from web.backend.models import ( PlatformFulfillmentTask, User, ) +from web.backend.schemas import DouyuCollabOrderOut +from web.backend.services import douyu_collab_service as collab from web.backend.services.automation.jobs import ( platform_fulfillment_lease_reaper as reaper, ) @@ -438,6 +441,247 @@ class TestSyncAndMapping(_Base): assert task.required_points == 1280 +class TestFulfillmentCollabSync(_Base): + def _task_with_account( + self, + *, + execution_status: str = "ready", + ) -> PlatformFulfillmentTask: + task = self.task() + account = self.account("collab-sync-account") + task.account_id = account.id + task.execution_status = execution_status + self.session.commit() + return task + + def test_manual_sync_creates_projected_collab_order(self): + task = self._task_with_account() + mapping = self.session.query(PlatformCommodityMapping).one() + mapping.goods_name = "套装-兔兔白日梦(斗鱼)" + self.session.add( + DouyuGoodsSnapshot( + commodity_id=COMMODITY, + name="不应覆盖显式映射", + score=999, + ) + ) + bind_task = DouyuTask( + batch_id="collab-sync-bind", + account_id=task.account_id, + task_type="get_bind_qr", + handbook_scope="elite", + status="success", + result={ + "role_name": "已确认角色", + "bind_confirmed": True, + "area_name": "微信", + "plat_name": "苹果(iOS)", + }, + created_by=self.admin_id, + ) + self.session.add(bind_task) + self.session.flush() + task.bind_task_id = bind_task.id + self.session.commit() + + order, action = collab.sync_platform_fulfillment_order( + self.session, + self.admin, + task, + ) + + assert action == "created" + assert order.order_no == f"PF{task.id}" + assert order.source_type == "platform_fulfillment" + assert order.source_task_id == task.id + assert order.source_order_id == task.source_order_id + assert order.source_order_item_id == task.source_order_item_id + assert order.source_platform_order_id == task.platform_order_id + assert order.last_synced_at is not None + assert order.shop == task.shop_name + assert order.gift_name == "套装-兔兔白日梦(斗鱼)" + assert order.commodity_id == COMMODITY + assert order.required_points == 1280 + assert order.account_id == task.account_id + assert order.account_username == "collab-sync-account" + assert order.bind_game_role == "已确认角色" + assert order.bind_game_channel == "微信 / 苹果(iOS)" + assert order.status == collab.STATUS_INCOMPLETE + payload = DouyuCollabOrderOut.model_validate( + collab.serialize_one(self.session, order) + ).model_dump() + assert payload["source_task_id"] == task.id + assert payload["source_platform_order_id"] == task.platform_order_id + assert ( + self.session.query(AccountEvent) + .filter(AccountEvent.event_type == "collab_synced") + .count() + == 1 + ) + + def test_manual_sync_does_not_clear_account_added_in_collab(self): + task = self.task() + order, _ = collab.sync_platform_fulfillment_order( + self.session, + self.admin, + task, + ) + account = self.account("manual-collab-account") + order.account_id = account.id + order.account_username = account.username + self.session.commit() + + synced, _ = collab.sync_platform_fulfillment_order( + self.session, + self.admin, + task, + ) + + assert synced.account_id == account.id + assert synced.account_username == account.username + + def test_manual_sync_is_idempotent_and_preserves_human_fields(self): + task = self._task_with_account() + order, _ = collab.sync_platform_fulfillment_order( + self.session, + self.admin, + task, + ) + other_owner = User( + username="collab-owner", + password_hash="h", + role="operator", + ) + self.session.add(other_owner) + self.session.commit() + order.owner_id = other_owner.id + order.fish_fin_balance = 321 + order.points_balance = 654 + order.points_check_message = "人工核账快照" + order.remark = "客服人工备注" + self.session.commit() + + synced, action = collab.sync_platform_fulfillment_order( + self.session, + self.admin, + task, + ) + + assert action == "updated" + assert self.session.query(DouyuExternalOrder).count() == 1 + assert synced.id == order.id + assert synced.owner_id == other_owner.id + assert synced.fish_fin_balance == 321 + assert synced.points_balance == 654 + assert synced.points_check_message == "人工核账快照" + assert synced.remark == "客服人工备注" + + def test_manual_sync_maps_only_safe_terminal_statuses(self): + task = self._task_with_account() + order, _ = collab.sync_platform_fulfillment_order( + self.session, + self.admin, + task, + ) + order.status = collab.STATUS_TO_RECHARGE + self.session.commit() + + task.execution_status = "completed" + task.completed_at = NOW + self.session.commit() + order, _ = collab.sync_platform_fulfillment_order( + self.session, + self.admin, + task, + ) + assert order.status == collab.STATUS_DONE + assert order.done_at == NOW + + cancelled = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="200", + source_order_item_id="201", + source_fulfillment_id="301", + platform_order_id="ORDER-201", + sku_code=INTERNAL_SKU, + sku_name=INTERNAL_SKU, + internal_sku_key=INTERNAL_SKU, + commodity_mapping_id=task.commodity_mapping_id, + commodity_id=COMMODITY, + required_points=1280, + execution_status="cancelled", + paid_at=NOW, + created_at=NOW, + updated_at=NOW, + ) + self.session.add(cancelled) + self.session.commit() + cancelled_order, action = collab.sync_platform_fulfillment_order( + self.session, + self.admin, + cancelled, + ) + assert action == "created" + assert cancelled_order.status == collab.STATUS_VOID + assert cancelled_order.void_reason == "直播履约任务已取消" + + def test_manual_sync_batch_reports_created_and_missing(self): + first = self.task() + second = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="300", + source_order_item_id="301", + source_fulfillment_id="401", + platform_order_id="ORDER-301", + sku_code=INTERNAL_SKU, + sku_name=INTERNAL_SKU, + internal_sku_key=INTERNAL_SKU, + commodity_mapping_id=first.commodity_mapping_id, + commodity_id=COMMODITY, + required_points=1280, + execution_status="ready", + paid_at=NOW, + created_at=NOW, + updated_at=NOW, + ) + self.session.add(second) + self.session.commit() + + result = collab.sync_platform_fulfillment_orders( + self.session, + self.admin, + task_ids=[first.id, second.id, 99999999], + ) + + assert result["requested"] == 3 + assert result["created"] == 2 + assert result["updated"] == 0 + assert result["skipped"] == 1 + assert result["failed"] == 0 + assert [item["action"] for item in result["items"]] == [ + "created", + "created", + "skipped", + ] + + def test_task_list_exposes_linked_collab_order(self): + task = self._task_with_account() + order, _ = collab.sync_platform_fulfillment_order( + self.session, + self.admin, + task, + ) + + listed = service.list_tasks(self.session) + + assert listed["items"][0]["collabOrder"] == { + "id": order.id, + "orderNo": order.order_no, + "status": collab.STATUS_INCOMPLETE, + "lastSyncedAt": order.last_synced_at, + } + + class TestSnapshotSync(_Base): def snapshot(self, **overrides): payload = { diff --git a/web/backend/migrations/versions/20261118_0094_douyu_collab_fulfillment_source.py b/web/backend/migrations/versions/20261118_0094_douyu_collab_fulfillment_source.py new file mode 100644 index 0000000..6046c8d --- /dev/null +++ b/web/backend/migrations/versions/20261118_0094_douyu_collab_fulfillment_source.py @@ -0,0 +1,137 @@ +"""斗鱼外部单协作关联直播履约来源。 + +手工协作单保持 ``source_type=manual``;从直播履约同步的订单通过唯一 +``source_task_id`` 幂等关联,重复点击同步不会生成重复订单。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision: str = "20261118_0094" +down_revision: str | None = "20261118_0093" +branch_labels: str | None = None +depends_on: str | None = None + +TABLE = "douyu_external_orders" +INDEX = "uq_douyu_external_source_task" +FOREIGN_KEY = "fk_douyu_external_orders_source_task" + + +def _column_exists(name: str) -> bool: + return bool( + op.get_bind() + .execute( + sa.text( + "SELECT COUNT(*) FROM information_schema.columns " + "WHERE table_schema = DATABASE() " + "AND table_name = :table AND column_name = :name" + ), + {"table": TABLE, "name": name}, + ) + .scalar() + ) + + +def _index_exists(name: str) -> bool: + return bool( + op.get_bind() + .execute( + sa.text( + "SELECT COUNT(*) FROM information_schema.statistics " + "WHERE table_schema = DATABASE() " + "AND table_name = :table AND index_name = :name" + ), + {"table": TABLE, "name": name}, + ) + .scalar() + ) + + +def _foreign_key_exists(name: str) -> bool: + return any( + item.get("name") == name + for item in sa.inspect(op.get_bind()).get_foreign_keys(TABLE) + ) + + +def upgrade() -> None: + if not _column_exists("source_type"): + op.add_column( + TABLE, + sa.Column( + "source_type", + sa.String(length=24), + nullable=False, + server_default="manual", + ), + ) + if not _column_exists("source_task_id"): + op.add_column( + TABLE, + sa.Column("source_task_id", sa.BigInteger(), nullable=True), + ) + if not _column_exists("source_order_id"): + op.add_column( + TABLE, + sa.Column( + "source_order_id", + sa.String(length=64), + nullable=False, + server_default="", + ), + ) + if not _column_exists("source_order_item_id"): + op.add_column( + TABLE, + sa.Column( + "source_order_item_id", + sa.String(length=64), + nullable=False, + server_default="", + ), + ) + if not _column_exists("source_platform_order_id"): + op.add_column( + TABLE, + sa.Column( + "source_platform_order_id", + sa.String(length=128), + nullable=False, + server_default="", + ), + ) + if not _column_exists("last_synced_at"): + op.add_column( + TABLE, + sa.Column("last_synced_at", sa.DateTime(), nullable=True), + ) + if not _index_exists(INDEX): + op.create_index(INDEX, TABLE, ["source_task_id"], unique=True) + if not _foreign_key_exists(FOREIGN_KEY): + op.create_foreign_key( + FOREIGN_KEY, + TABLE, + "platform_fulfillment_tasks", + ["source_task_id"], + ["id"], + ondelete="SET NULL", + ) + + +def downgrade() -> None: + if _foreign_key_exists(FOREIGN_KEY): + op.drop_constraint(FOREIGN_KEY, TABLE, type_="foreignkey") + if _index_exists(INDEX): + op.drop_index(INDEX, table_name=TABLE) + for column in ( + "last_synced_at", + "source_platform_order_id", + "source_order_item_id", + "source_order_id", + "source_task_id", + "source_type", + ): + if _column_exists(column): + op.drop_column(TABLE, column) diff --git a/web/backend/models.py b/web/backend/models.py index 4cf75f8..8be7b83 100644 --- a/web/backend/models.py +++ b/web/backend/models.py @@ -630,6 +630,27 @@ class DouyuExternalOrder(Base): owner_id: Mapped[int | None] = mapped_column( ForeignKey("users.id"), nullable=True, index=True ) + # ---- 来源关联(手工协作单为空)---- + source_type: Mapped[str] = mapped_column( + String(24), nullable=False, default="manual", server_default="manual" + ) + source_task_id: Mapped[int | None] = mapped_column( + BigInteger, + ForeignKey("platform_fulfillment_tasks.id", ondelete="SET NULL"), + nullable=True, + ) + source_order_id: Mapped[str] = mapped_column( + String(64), nullable=False, default="", server_default="" + ) + source_order_item_id: Mapped[str] = mapped_column( + String(64), nullable=False, default="", server_default="" + ) + source_platform_order_id: Mapped[str] = mapped_column( + String(128), nullable=False, default="", server_default="" + ) + last_synced_at: Mapped[datetime | None] = mapped_column( + UTCDateTime, nullable=True + ) # ---- 内部斗鱼账号(CK 不落本表)---- account_id: Mapped[int | None] = mapped_column( @@ -713,6 +734,14 @@ class DouyuExternalOrder(Base): UTCDateTime, default=_utcnow, onupdate=_utcnow, index=True ) + __table_args__ = ( + Index( + "uq_douyu_external_source_task", + "source_task_id", + unique=True, + ), + ) + class DouyuExternalOrderMetric(Base): """斗鱼协作单的鱼翅/积分/兑换记录快照(只追加,不存 CK)。""" diff --git a/web/backend/routers/platform_fulfillment.py b/web/backend/routers/platform_fulfillment.py index 9b4e606..f94c0a7 100644 --- a/web/backend/routers/platform_fulfillment.py +++ b/web/backend/routers/platform_fulfillment.py @@ -11,12 +11,15 @@ from ..database import get_db from ..deps import require_permission from ..models import User from ..schemas import ( + PlatformFulfillmentCollabSyncRequest, PlatformFulfillmentCompleteRequest, PlatformFulfillmentMappingUpsert, PlatformFulfillmentReasonRequest, PlatformFulfillmentSettingsUpdate, ) +from ..services import douyu_collab_service from ..services.audit_service import record_audit +from ..services.douyu_collab_events import collab_events from ..services.platform_fulfillment import service router = APIRouter(prefix="/api/platform-fulfillment", tags=["直播账号履约"]) @@ -95,6 +98,26 @@ def sync_tasks( return result +@router.post("/tasks/sync-collab") +def sync_tasks_to_douyu_collab( + req: PlatformFulfillmentCollabSyncRequest, + db: Session = Depends(get_db), + current: User = Depends(require_permission("platform_fulfillment:use")), +) -> dict[str, Any]: + result = douyu_collab_service.sync_platform_fulfillment_orders( + db, + current, + task_ids=req.task_ids, + ) + if result["created"] or result["updated"]: + collab_events.publish( + scope="orders", + action="order.sync_from_platform_fulfillment", + actor_id=int(current.id), + ) + return result + + @router.get("/tasks/{task_id}") def get_task( task_id: int, diff --git a/web/backend/schemas.py b/web/backend/schemas.py index 4ea52b3..aa0995c 100644 --- a/web/backend/schemas.py +++ b/web/backend/schemas.py @@ -1598,6 +1598,10 @@ class PlatformFulfillmentCustomerSessionBatchRequest(BaseModel): task_ids: list[int] = Field(default_factory=list, max_length=100) +class PlatformFulfillmentCollabSyncRequest(BaseModel): + task_ids: list[int] = Field(..., min_length=1, max_length=100) + + class DouyuTaskBatchRequest(BaseModel): account_ids: list[int] task_type: str @@ -2667,6 +2671,12 @@ class DouyuCollabOrderOut(BaseModel): shop: str = "" owner_id: int | None = None owner_name: str = "" + source_type: str = "manual" + source_task_id: int | None = None + source_order_id: str = "" + source_order_item_id: str = "" + source_platform_order_id: str = "" + last_synced_at: datetime | None = None account_id: int | None = None account_username: str = "" diff --git a/web/backend/services/account_events_service.py b/web/backend/services/account_events_service.py index 262a297..1141288 100644 --- a/web/backend/services/account_events_service.py +++ b/web/backend/services/account_events_service.py @@ -77,6 +77,7 @@ EVENT_TASK_STOPPED = "task_stopped" # 斗鱼账号任务停止/中断 EVENT_QUERY_COMPLETED = "query_completed" # 同步查询完成(含部分失败) EVENT_LEASE_ACQUIRED = "lease_acquired" # 分配履约账号使用权 EVENT_LEASE_RELEASED = "lease_released" # 释放履约账号使用权 +EVENT_COLLAB_SYNCED = "collab_synced" # 直播履约任务同步到外部单协作 # 有符号金额的事件类型(用于页面「累计充值/累计消耗」): # 充值为正、兑换为负,其余不计入金额统计。 diff --git a/web/backend/services/douyu_collab_service.py b/web/backend/services/douyu_collab_service.py index 37dfcf5..e149c6b 100644 --- a/web/backend/services/douyu_collab_service.py +++ b/web/backend/services/douyu_collab_service.py @@ -17,6 +17,7 @@ from collections.abc import Mapping, Sequence from datetime import UTC, datetime from typing import Any +from loguru import logger from sqlalchemy import func, or_ from sqlalchemy.orm import Session @@ -31,9 +32,14 @@ from ..models import ( DouyuExternalOrder, DouyuExternalOrderMetric, DouyuGoodsSnapshot, + DouyuTask, + PlatformCommodityMapping, + PlatformFulfillmentTask, User, ) -from .audit_service import record_audit +from .account_binding import binding_channel, binding_role_from_result +from .account_events_service import EVENT_COLLAB_SYNCED +from .audit_service import record_account_action, record_audit from .business_events import record_account_query from .collab_common import apply_order_visibility, count_archived from .douyu_activity_query import ( @@ -97,6 +103,8 @@ STATUS_FLOW: tuple[str, ...] = ( STATUS_DONE, ) +SOURCE_TYPE_PLATFORM_FULFILLMENT = "platform_fulfillment" + STAGE_INDEX = { STATUS_INCOMPLETE: 0, STATUS_TO_RECHARGE: 1, @@ -667,6 +675,292 @@ def create_order( return order +def _platform_fulfillment_gift( + db: Session, + task: PlatformFulfillmentTask, +) -> tuple[str, str, int | None]: + """解析履约任务对应的斗鱼商品,优先显式映射,再回退到商品快照。""" + mapping = ( + db.query(PlatformCommodityMapping) + .filter(PlatformCommodityMapping.id == task.commodity_mapping_id) + .first() + if task.commodity_mapping_id + else None + ) + snapshot = ( + db.query(DouyuGoodsSnapshot) + .filter(DouyuGoodsSnapshot.commodity_id == task.commodity_id) + .first() + if task.commodity_id + else None + ) + name = _text( + (mapping.goods_name if mapping else "") + or (snapshot.name if snapshot else "") + or task.sku_name, + max_length=128, + ) + commodity_id = _text( + task.commodity_id + or (mapping.commodity_id if mapping else "") + or (snapshot.commodity_id if snapshot else ""), + max_length=64, + ) + required_points = _to_int(task.required_points) + if required_points is None and mapping is not None: + required_points = _to_int(mapping.required_points) + if required_points is None and snapshot is not None: + required_points = _to_int(snapshot.score) + return name, commodity_id, required_points + + +def _apply_platform_fulfillment_binding( + db: Session, + order: DouyuExternalOrder, + task: PlatformFulfillmentTask, +) -> None: + """把履约任务已确认的本地绑定结果投影到协作单,不额外联网。""" + bind_task = ( + db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() + if task.bind_task_id + else None + ) + result = bind_task.result if bind_task and isinstance(bind_task.result, dict) else None + role = binding_role_from_result(result) + if not role: + return + order.bind_game_role = _text(role, max_length=128) + channel = binding_channel(result) + if channel: + order.bind_game_channel = _text(channel, max_length=128) + order.bind_snapshot_at = order.bind_snapshot_at or _now() + + +def _apply_platform_fulfillment_status( + order: DouyuExternalOrder, + task: PlatformFulfillmentTask, + *, + created: bool, +) -> None: + """只做不会倒退的状态映射,保留协作台里人工推进的中间状态。""" + if created: + if task.execution_status == "completed": + order.status = STATUS_DONE + order.done_at = order.done_at or task.completed_at or _now() + elif task.execution_status == "cancelled": + order.status = STATUS_VOID + order.void_reason = order.void_reason or "直播履约任务已取消" + else: + order.status = STATUS_INCOMPLETE + return + + if task.execution_status == "completed" and order.status not in ( + STATUS_DONE, + STATUS_VOID, + ): + order.status = STATUS_DONE + order.done_at = order.done_at or task.completed_at or _now() + elif task.execution_status == "cancelled" and order.status != STATUS_VOID: + order.status = STATUS_VOID + order.void_reason = order.void_reason or "直播履约任务已取消" + + +def sync_platform_fulfillment_order( + db: Session, + current: User, + task: PlatformFulfillmentTask, + *, + commit: bool = True, +) -> tuple[DouyuExternalOrder, str]: + """把一条直播履约任务幂等同步为斗鱼外部协作单。 + + 这里只复制本地已确认的数据,不调用斗鱼接口,也不覆盖协作台上人工维护的 + 负责人、余额、核账快照和备注。``source_task_id`` 是幂等键。 + """ + if task.source_system != "order_site": + raise CollabError("仅支持同步 order_site 履约任务", code="source_unsupported") + + order = ( + db.query(DouyuExternalOrder) + .filter(DouyuExternalOrder.source_task_id == task.id) + .first() + ) + created = order is None + now = _now() + account = ( + db.query(Account).filter(Account.id == task.account_id).first() + if task.account_id + else None + ) + gift_name, commodity_id, required_points = _platform_fulfillment_gift(db, task) + + if order is None: + order_no = f"PF{task.id}" + occupied = ( + db.query(DouyuExternalOrder) + .filter(DouyuExternalOrder.order_no == order_no) + .first() + ) + if occupied is not None: + raise CollabError( + f"协作单号 {order_no} 已被其他订单占用", + code="order_no_conflict", + ) + order = DouyuExternalOrder( + order_no=order_no, + source_type=SOURCE_TYPE_PLATFORM_FULFILLMENT, + source_task_id=task.id, + status=STATUS_INCOMPLETE, + points_threshold=POINTS_THRESHOLD_DEFAULT, + owner_id=current.id, + created_by=current.id, + version=0, + created_at=now, + ) + db.add(order) + + order.source_type = SOURCE_TYPE_PLATFORM_FULFILLMENT + order.source_task_id = int(task.id) + order.source_order_id = _text(task.source_order_id, max_length=64) + order.source_order_item_id = _text(task.source_order_item_id, max_length=64) + order.source_platform_order_id = _text(task.platform_order_id, max_length=128) + order.last_synced_at = now + order.updated_by = current.id + order.updated_at = now + order.shop = _text(task.shop_name or task.shop_id, max_length=64) + order.gift_name = gift_name + order.commodity_id = commodity_id + order.required_points = required_points + if account is not None: + order.account_id = int(account.id) + order.account_username = _text(account.username, max_length=128) + order.account_uid = _text(account.uid, max_length=32) + order.account_nickname = _text(account.nickname, max_length=128) + _apply_platform_fulfillment_binding(db, order, task) + _apply_platform_fulfillment_status(order, task, created=created) + order.version = int(order.version or 0) + 1 + db.flush() + + audit_detail = { + "taskId": int(task.id), + "orderNo": order.order_no, + "created": created, + "status": order.status, + } + if account is not None: + record_account_action( + db, + current, + account=account, + action="douyu:collab:sync_from_platform_fulfillment", + event_type=EVENT_COLLAB_SYNCED, + title=f"同步外部单协作:{order.order_no}", + target=f"douyu_external_order:{order.id}", + detail=audit_detail, + ) + else: + record_audit( + db, + current, + action="douyu:collab:sync_from_platform_fulfillment", + target=f"douyu_external_order:{order.id}", + detail=audit_detail, + ) + if commit: + db.commit() + db.refresh(order) + return order, "created" if created else "updated" + + +def sync_platform_fulfillment_orders( + db: Session, + current: User, + *, + task_ids: Sequence[int], + commit: bool = True, +) -> dict[str, Any]: + """批量同步履约任务;单条失败回滚自己的 SAVEPOINT,不拖垮整批。""" + requested_ids = list(dict.fromkeys(int(item) for item in task_ids if item)) + tasks = ( + db.query(PlatformFulfillmentTask) + .filter(PlatformFulfillmentTask.id.in_(requested_ids)) + .all() + if requested_ids + else [] + ) + tasks_by_id = {int(task.id): task for task in tasks} + result = { + "requested": len(requested_ids), + "created": 0, + "updated": 0, + "skipped": 0, + "failed": 0, + "items": [], + } + + for task_id in requested_ids: + task = tasks_by_id.get(task_id) + if task is None: + result["skipped"] += 1 + result["items"].append( + { + "taskId": task_id, + "action": "skipped", + "reason": "履约任务不存在", + "collabOrderId": None, + "orderNo": "", + } + ) + continue + try: + with db.begin_nested(): + order, action = sync_platform_fulfillment_order( + db, + current, + task, + commit=False, + ) + result[action] += 1 + result["items"].append( + { + "taskId": task_id, + "action": action, + "reason": "", + "collabOrderId": int(order.id), + "orderNo": order.order_no, + } + ) + except CollabError as exc: + result["failed"] += 1 + result["items"].append( + { + "taskId": task_id, + "action": "failed", + "reason": exc.detail, + "collabOrderId": None, + "orderNo": "", + } + ) + except Exception: # noqa: BLE001 - 批量边界需隔离单条未知故障 + logger.exception( + "同步直播履约任务 {} 到斗鱼外部协作失败", task_id + ) + result["failed"] += 1 + result["items"].append( + { + "taskId": task_id, + "action": "failed", + "reason": "同步失败,请稍后重试", + "collabOrderId": None, + "orderNo": "", + } + ) + + if commit: + db.commit() + return result + + def update_order( db: Session, current: User, @@ -1792,6 +2086,12 @@ def serialize_order( "shop": order.shop or "", "owner_id": order.owner_id, "owner_name": users.get(int(order.owner_id), "") if order.owner_id else "", + "source_type": order.source_type or "manual", + "source_task_id": order.source_task_id, + "source_order_id": order.source_order_id or "", + "source_order_item_id": order.source_order_item_id or "", + "source_platform_order_id": order.source_platform_order_id or "", + "last_synced_at": order.last_synced_at, "account_id": order.account_id, "account_username": order.account_username or "", "account_uid": order.account_uid or "", @@ -1927,6 +2227,9 @@ def _apply_order_filters( DouyuExternalOrder.bind_game_role.ilike(pattern), DouyuExternalOrder.shop.ilike(pattern), DouyuExternalOrder.remark.ilike(pattern), + DouyuExternalOrder.source_order_id.ilike(pattern), + DouyuExternalOrder.source_order_item_id.ilike(pattern), + DouyuExternalOrder.source_platform_order_id.ilike(pattern), ) ) return query diff --git a/web/backend/services/platform_fulfillment/service.py b/web/backend/services/platform_fulfillment/service.py index 23d33be..d8d3d50 100644 --- a/web/backend/services/platform_fulfillment/service.py +++ b/web/backend/services/platform_fulfillment/service.py @@ -17,6 +17,7 @@ from sqlalchemy.orm import Session from ...models import ( Account, AccountLease, + DouyuExternalOrder, DouyuGoodsSnapshot, DouyuTask, PlatformCommodityMapping, @@ -949,6 +950,11 @@ def _task_out( 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 {} # 外层只消费共享绑定规则,不再自己比较角色名或 bindAct。 pending_role = pending_binding_role_from_result(bind_result) @@ -982,6 +988,16 @@ def _task_out( "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, diff --git a/web/frontend/src/api/douyuCollab.ts b/web/frontend/src/api/douyuCollab.ts index aa6399a..bcdac54 100644 --- a/web/frontend/src/api/douyuCollab.ts +++ b/web/frontend/src/api/douyuCollab.ts @@ -31,6 +31,12 @@ export interface DouyuCollabOrder { shop: string; owner_id: number | null; owner_name: string; + source_type: string; + source_task_id: number | null; + source_order_id: string; + source_order_item_id: string; + source_platform_order_id: string; + last_synced_at: string | null; account_id: number | null; account_username: string; account_uid: string; diff --git a/web/frontend/src/api/platformFulfillment.ts b/web/frontend/src/api/platformFulfillment.ts index bcf0f76..694e146 100644 --- a/web/frontend/src/api/platformFulfillment.ts +++ b/web/frontend/src/api/platformFulfillment.ts @@ -1,6 +1,7 @@ import api from './client'; import type { PlatformFulfillmentDetail, + PlatformFulfillmentCollabSyncResult, PlatformFulfillmentListResponse, PlatformFulfillmentMapping, PlatformFulfillmentSettings, @@ -38,6 +39,11 @@ export const platformFulfillmentApi = { null, { params: { limit } }, ), + syncCollab: (taskIds: number[]) => + api.post( + '/platform-fulfillment/tasks/sync-collab', + { task_ids: taskIds }, + ), getTask: (taskId: number) => api.get( `/platform-fulfillment/tasks/${taskId}`, diff --git a/web/frontend/src/api/types.ts b/web/frontend/src/api/types.ts index 833dd66..34dd31d 100644 --- a/web/frontend/src/api/types.ts +++ b/web/frontend/src/api/types.ts @@ -2213,6 +2213,12 @@ export interface PlatformFulfillmentTask { paidAt: string | null; createdAt: string; updatedAt: string; + collabOrder: { + id: number; + orderNo: string; + status: string; + lastSyncedAt: string | null; + } | null; account: PlatformFulfillmentAccount | null; lease: { id: number; status: string; expiresAt: string | null } | null; bindTask: PlatformFulfillmentBindTask | null; @@ -2248,3 +2254,20 @@ export interface PlatformFulfillmentListResponse { items: PlatformFulfillmentTask[]; pagination: { page: number; pageSize: number; total: number }; } + +export interface PlatformFulfillmentCollabSyncItem { + taskId: number; + action: 'created' | 'updated' | 'skipped' | 'failed'; + reason: string; + collabOrderId: number | null; + orderNo: string; +} + +export interface PlatformFulfillmentCollabSyncResult { + requested: number; + created: number; + updated: number; + skipped: number; + failed: number; + items: PlatformFulfillmentCollabSyncItem[]; +} diff --git a/web/frontend/src/pages/AccountDetailPage.tsx b/web/frontend/src/pages/AccountDetailPage.tsx index 71eee0a..61d2e53 100644 --- a/web/frontend/src/pages/AccountDetailPage.tsx +++ b/web/frontend/src/pages/AccountDetailPage.tsx @@ -43,6 +43,7 @@ const EVENT_STYLE: Record = { task_stopped: { label: '任务停止', color: 'orange' }, query_completed: { label: '查询完成', color: 'blue' }, lease_acquired: { label: '账号占用', color: 'cyan' }, + collab_synced: { label: '外部协作同步', color: 'geekblue' }, lease_released: { label: '账号释放', color: 'default' }, }; diff --git a/web/frontend/src/pages/DouyuCollabPage.tsx b/web/frontend/src/pages/DouyuCollabPage.tsx index c29545b..07d3080 100644 --- a/web/frontend/src/pages/DouyuCollabPage.tsx +++ b/web/frontend/src/pages/DouyuCollabPage.tsx @@ -1089,6 +1089,9 @@ export default function DouyuCollabPage() { {value} + {row.source_type === 'platform_fulfillment' && ( + 履约同步 · #{row.source_task_id} + )} {row.status === 'void' && 已作废:{row.void_reason || '-'}} ), @@ -2218,6 +2221,19 @@ export default function DouyuCollabPage() { {detail.status_label} + {detail.source_type === 'platform_fulfillment' ? ( + <> + + #{detail.source_task_id ?? '-'} + + + {detail.source_platform_order_id || detail.source_order_id || '-'} + + + {detail.last_synced_at ? formatTime(detail.last_synced_at) : '-'} + + + ) : null} {detail.account_username || '-'} {detail.account_nickname || '-'} {detail.bind_game_role || '-'} diff --git a/web/frontend/src/pages/PlatformFulfillmentPage.tsx b/web/frontend/src/pages/PlatformFulfillmentPage.tsx index 2fc0e9b..3c0ae99 100644 --- a/web/frontend/src/pages/PlatformFulfillmentPage.tsx +++ b/web/frontend/src/pages/PlatformFulfillmentPage.tsx @@ -43,6 +43,17 @@ const STATUS_COLORS: Record = { cancelled: 'default', }; +const COLLAB_STATUS_LABELS: Record = { + incomplete: '待补资料', + to_recharge: '待充值', + recharged: '已充值', + scripted: '已上脚本', + done: '抢购成功', + points_error: '积分异常', + failed: '抢购失败', + void: '已作废', +}; + const BINDING_STATUS_LABELS: Record = { not_started: '未开始', preparing: '准备中', @@ -121,6 +132,10 @@ function exchangeStatusLabel(value: string) { return EXCHANGE_STATUS_LABELS[value] || '未知状态'; } +function collabStatusLabel(value: string) { + return COLLAB_STATUS_LABELS[value] || value || '-'; +} + function issueLabel(value: string) { if (!value) return '-'; return ISSUE_LABELS[value] || '其他处理事项'; @@ -254,6 +269,8 @@ export default function PlatformFulfillmentPage() { const [total, setTotal] = useState(0); const [loading, setLoading] = useState(false); const [syncing, setSyncing] = useState(false); + const [collabSyncing, setCollabSyncing] = useState(false); + const [selectedRowKeys, setSelectedRowKeys] = useState([]); const [selectedId, setSelectedId] = useState(null); const [detail, setDetail] = useState(null); const [detailLoading, setDetailLoading] = useState(false); @@ -381,6 +398,50 @@ export default function PlatformFulfillmentPage() { } }; + const syncCollab = async () => { + const taskIds = selectedRowKeys.map(Number).filter((value) => Number.isInteger(value)); + if (taskIds.length === 0) { + message.warning('请先勾选要同步的履约任务'); + return; + } + setCollabSyncing(true); + try { + const result = await platformFulfillmentApi.syncCollab(taskIds); + const summary = `外部协作同步完成:新增 ${result.created},更新 ${result.updated}`; + if (result.failed || result.skipped) { + message.warning(`${summary},跳过 ${result.skipped},失败 ${result.failed}`); + const problems = result.items.filter( + (item) => item.action === 'failed' || item.action === 'skipped', + ); + Modal.warning({ + title: '部分履约任务未同步', + width: 560, + content: ( + + {problems.slice(0, 20).map((item) => ( + + #{item.taskId}:{item.reason || '未同步'} + + ))} + {problems.length > 20 ? ( + 另有 {problems.length - 20} 条未显示 + ) : null} + + ), + }); + } else { + message.success(summary); + } + setSelectedRowKeys([]); + await loadTasks(); + if (selectedId) await loadDetail(selectedId, true); + } catch (error) { + message.error(getErrorMessage(error)); + } finally { + setCollabSyncing(false); + } + }; + const runTaskAction = async (action: () => Promise) => { try { const result = await action(); @@ -669,6 +730,22 @@ export default function PlatformFulfillmentPage() { ), }, + { + title: '外部协作', + key: 'collab', + width: 150, + render: (_, task) => + task.collabOrder ? ( + + + {collabStatusLabel(task.collabOrder.status)} + + {task.collabOrder.orderNo} + + ) : ( + 未同步 + ), + }, { title: '更新时间', dataIndex: 'updatedAt', @@ -778,6 +855,14 @@ export default function PlatformFulfillmentPage() { + @@ -815,7 +900,11 @@ export default function PlatformFulfillmentPage() { loading={loading} columns={columns} dataSource={rows} - scroll={{ x: 1600 }} + rowSelection={{ + selectedRowKeys, + onChange: setSelectedRowKeys, + }} + scroll={{ x: 1900 }} pagination={{ current: page, pageSize, @@ -891,6 +980,11 @@ export default function PlatformFulfillmentPage() { {selected.requiredPoints ?? '-'} {statusLabel(selected.executionStatus)} {bindingStatusLabel(selected.bindingStatus)} + + {selected.collabOrder + ? `${selected.collabOrder.orderNo} · ${collabStatusLabel(selected.collabOrder.status)}` + : '未同步'} + {exchangeStatusLabel(selected.exchangeStatus)} {issueLabel(selected.issueCode)}