diff --git a/tests/test_account_actions.py b/tests/test_account_actions.py index 5fc3466..392fb74 100644 --- a/tests/test_account_actions.py +++ b/tests/test_account_actions.py @@ -395,6 +395,9 @@ class TestEventsCategoryFilter(_Base): assert item["category"] == svc.CATEGORY_BUSINESS assert item["subject_key"] == "sku-1" assert item["actor_id"] == self.admin.id + assert item["actor_name"] == "act-admin" + assert item["actor_role"] == "super_admin" + assert item["actor_role_label"] == "超级管理员" class TestBatchDeleteRecordsIds(_Base): diff --git a/tests/test_business_events.py b/tests/test_business_events.py index 70fbded..81344c9 100644 --- a/tests/test_business_events.py +++ b/tests/test_business_events.py @@ -61,6 +61,7 @@ class TestConstructors(_Base): amount=100, channel="wechat_qr", douyu_uid="u1", + actor_id=self.user.id, ) is True ) @@ -73,6 +74,8 @@ class TestConstructors(_Base): assert event.source_ref == "douyu_task:101" assert event.detail["channel"] == "wechat_qr" assert event.detail["confirmed"] is True + assert event.actor_type == "user" + assert event.actor_id == self.user.id def test_recharge_without_amount_still_records(self): """金额拿不到时宁可记一条金额为空的事件,也不要凭空编一个数字。""" diff --git a/tests/test_douyu_task_assigned_optimization.py b/tests/test_douyu_task_assigned_optimization.py index b35a8af..7354465 100644 --- a/tests/test_douyu_task_assigned_optimization.py +++ b/tests/test_douyu_task_assigned_optimization.py @@ -1,10 +1,15 @@ """验证 DouyuTask 的 account_assigned_to 字段与任务查询优化。""" +import pytest +from fastapi import HTTPException from sqlalchemy.orm import Session from tests.support.db import init_test_schema, make_test_session -from web.backend.models import Account, DouyuTask, User -from web.backend.routers.douyu import _visible_tasks_query +from web.backend.models import Account, DouyuTask, PlatformFulfillmentTask, User +from web.backend.routers.douyu import ( + _require_task_account_access, + _visible_tasks_query, +) from web.backend.services.douyu_service import create_douyu_planned_tasks @@ -67,13 +72,12 @@ def test_douyu_task_assigned_to_flow(): assert task_map[acc_1.id].account_assigned_to == user_a.id assert task_map[acc_2.id].account_assigned_to == user_b.id - # 2. 验证 _visible_tasks_query 能够精准过滤所属客服 + # 2. 客服能看到自己创建的任务;被分配账号的客服也能看到。 query_a = _visible_tasks_query(db, user_a).filter( DouyuTask.batch_id == batch_id ) visible_a = query_a.all() - assert len(visible_a) == 1 - assert visible_a[0].account_id == acc_1.id + assert {row.account_id for row in visible_a} == {acc_1.id, acc_2.id} query_b = _visible_tasks_query(db, user_b).filter( DouyuTask.batch_id == batch_id @@ -99,3 +103,92 @@ def test_douyu_task_assigned_to_flow(): finally: db.rollback() db.close() + + +def test_platform_task_context_allows_shared_account_operation(): + init_test_schema() + db: Session = make_test_session() + try: + owner = User( + username="ctx-owner", + password_hash="h", + role="support", + is_active=True, + ) + operator = User( + username="ctx-operator", + password_hash="h", + role="support", + custom_permissions=[ + "douyu:task", + "account:view_assigned", + "platform_fulfillment:use", + ], + is_active=True, + ) + db.add_all([owner, operator]) + db.flush() + account = Account( + username="ctx-shared-account", + password="p", + email="ctx@test.com", + email_password="p", + cookie="acf_uid=1; acf_auth=x", + assigned_to=owner.id, + ) + db.add(account) + db.flush() + task = PlatformFulfillmentTask( + source_order_id="ctx-order", + source_order_item_id="ctx-item", + platform_order_id="ctx-platform-order", + account_id=account.id, + execution_status="allocated", + ) + db.add(task) + db.commit() + + with pytest.raises(HTTPException) as exc_info: + _require_task_account_access(db, operator, [account.id]) + assert exc_info.value.status_code == 403 + + _require_task_account_access( + db, + operator, + [account.id], + platform_task_id=task.id, + ) + batch_id, count = create_douyu_planned_tasks( + db, + [account.id], + "query_elite_status", + "elite", + operator.id, + platform_task_id=task.id, + ) + assert count == 1 + assert ( + db.query(DouyuTask).filter(DouyuTask.batch_id == batch_id).one().platform_task_id + == task.id + ) + + other = Account( + username="ctx-other-account", + password="p", + email="ctx-other@test.com", + email_password="p", + cookie="acf_uid=2; acf_auth=x", + assigned_to=owner.id, + ) + db.add(other) + db.commit() + with pytest.raises(HTTPException): + _require_task_account_access( + db, + operator, + [other.id], + platform_task_id=task.id, + ) + finally: + db.rollback() + db.close() diff --git a/tests/test_migrations.py b/tests/test_migrations.py index 388cf5a..b18ce85 100644 --- a/tests/test_migrations.py +++ b/tests/test_migrations.py @@ -40,7 +40,7 @@ TESTS_DIR = Path(__file__).resolve().parent PROJECT_ROOT = TESTS_DIR.parent VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions" -HEAD_REVISION = "20261118_0095" +HEAD_REVISION = "20261118_0096" # 迁移新增、但不声明在模型里的复合查询索引。 EXTRA_INDEXES = ( diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index ca0cf1b..939ebff 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -743,6 +743,62 @@ class TestFulfillmentCollabSync(_Base): } +class TestDouyuOperationTimeline(_Base): + def test_operation_start_and_result_are_written_once(self): + task = self.task() + account = self.account("operation-timeline-account") + task.account_id = account.id + self.session.commit() + douyu_task = DouyuTask( + batch_id="platform-operation", + account_id=account.id, + account_assigned_to=account.assigned_to, + task_type="create_gold_qr", + handbook_scope="elite", + status="planned", + created_by=self.admin_id, + platform_task_id=task.id, + ) + self.session.add(douyu_task) + self.session.commit() + + service.record_douyu_operation_started( + self.session, + task, + current=self.admin, + batch_id=douyu_task.batch_id, + task_type=douyu_task.task_type, + douyu_task_ids=[douyu_task.id], + payload={"amount": 18}, + ) + service.record_douyu_operation_result( + self.session, + douyu_task, + status="success", + message="充值鱼翅成功", + ) + service.record_douyu_operation_result( + self.session, + douyu_task, + status="success", + message="充值鱼翅成功", + ) + self.session.commit() + + detail = service.get_task_detail(self.session, task.id) + operation_events = [ + event + for event in detail["events"] + if event["eventType"].startswith("douyu_operation_") + ] + assert [event["eventType"] for event in operation_events] == [ + "douyu_operation_succeeded", + "douyu_operation_started", + ] + assert operation_events[0]["detail"]["douyuTaskId"] == douyu_task.id + assert operation_events[1]["detail"]["batchId"] == douyu_task.batch_id + + class TestSnapshotSync(_Base): def snapshot(self, **overrides): payload = { diff --git a/web/backend/migrations/versions/20261118_0096_douyu_task_platform_context.py b/web/backend/migrations/versions/20261118_0096_douyu_task_platform_context.py new file mode 100644 index 0000000..22d354e --- /dev/null +++ b/web/backend/migrations/versions/20261118_0096_douyu_task_platform_context.py @@ -0,0 +1,59 @@ +"""关联斗鱼任务与直播履约任务上下文。""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision: str = "20261118_0096" +down_revision: str | None = "20261118_0095" +branch_labels: str | None = None +depends_on: str | None = None + +TABLE = "douyu_tasks" +COLUMN = "platform_task_id" +INDEX = "ix_douyu_tasks_platform_task_id" + + +def _column_exists() -> 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 = :column" + ), + {"table": TABLE, "column": COLUMN}, + ) + .scalar() + ) + + +def _index_exists() -> 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 = :index" + ), + {"table": TABLE, "index": INDEX}, + ) + .scalar() + ) + + +def upgrade() -> None: + if not _column_exists(): + op.add_column(TABLE, sa.Column(COLUMN, sa.BigInteger(), nullable=True)) + if not _index_exists(): + op.create_index(INDEX, TABLE, [COLUMN]) + + +def downgrade() -> None: + if _index_exists(): + op.drop_index(INDEX, table_name=TABLE) + if _column_exists(): + op.drop_column(TABLE, COLUMN) diff --git a/web/backend/models.py b/web/backend/models.py index 8be7b83..42f67c7 100644 --- a/web/backend/models.py +++ b/web/backend/models.py @@ -357,6 +357,11 @@ class DouyuTask(Base): created_by: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False) created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow) finished_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) + platform_task_id: Mapped[int | None] = mapped_column( + BigInteger, + nullable=True, + index=True, + ) # 账号归属客服冗余字段,配合复合索引消除任务列表全表 filesort。 account_assigned_to: Mapped[int | None] = mapped_column( ForeignKey("users.id"), nullable=True diff --git a/web/backend/routers/accounts.py b/web/backend/routers/accounts.py index 1a802ce..a5242f4 100644 --- a/web/backend/routers/accounts.py +++ b/web/backend/routers/accounts.py @@ -19,7 +19,7 @@ from ..models import ( LoginTask, User, ) -from ..permissions import user_has_permission +from ..permissions import ROLE_LABELS, user_has_permission from ..schemas import ( AccountAssign, AccountAutomationUpdate, @@ -1856,8 +1856,34 @@ def account_events( .all() ) + items = [dict(row) for row in rows] + actor_ids = { + int(item["actor_id"]) + for item in items + if item.get("actor_type") == "user" + and item.get("actor_id") is not None + } + actors = { + int(user.id): user + for user in db.query(User).filter(User.id.in_(actor_ids)).all() + } if actor_ids else {} + for item in items: + actor = ( + actors.get(int(item["actor_id"])) + if item.get("actor_type") == "user" + and item.get("actor_id") is not None + else None + ) + item["actor_name"] = ( + actor.deleted_username or actor.username + ) if actor is not None else "" + item["actor_role"] = actor.role if actor is not None else "" + item["actor_role_label"] = ( + ROLE_LABELS.get(actor.role, actor.role) if actor is not None else "" + ) + return { - "items": [dict(row) for row in rows], + "items": items, "total": int(total), "page": page, "page_size": page_size, diff --git a/web/backend/routers/douyu.py b/web/backend/routers/douyu.py index e339515..783cc26 100644 --- a/web/backend/routers/douyu.py +++ b/web/backend/routers/douyu.py @@ -37,6 +37,7 @@ from ..models import ( DouyuWorkbench, DouyuWorkbenchAccount, DouyuXpdGoodsSnapshot, + PlatformFulfillmentTask, User, ) from ..permissions import user_has_permission @@ -70,6 +71,7 @@ from ..services.douyu_service import ( douyu_task_payload, ensure_douyu_config, ) +from ..services.platform_fulfillment import service as platform_fulfillment_service router = APIRouter(prefix="/api/douyu", tags=["斗鱼活动"]) @@ -159,6 +161,13 @@ async def supplier_recharge_callback(request: Request, db: Session = Depends(get ) task.result = result callback_success = status not in {3, 4} + if task.platform_task_id and status in {2, 3, 4}: + platform_fulfillment_service.record_douyu_operation_result( + db, + task, + status="success" if status == 2 else "failed", + message=task.message, + ) # 回调说成功了就补一条充值事件。幂等键与 runner 那条**完全一致** # (business_events.task_ref),所以「runner 也观测到了」时不会重复记账; # 而「runner 已判超时/失败、回调才到」这个黑洞则能被补上。 @@ -237,12 +246,21 @@ def _visible_tasks_query(db: Session, current: User): return query if user_has_permission(current, "account:view_assigned"): # 彻底消除全表 filesort:直接通过 douyu_tasks 上的 account_assigned_to 复合索引倒序定位 - return query.filter(DouyuTask.account_assigned_to == current.id) + return query.filter( + or_( + DouyuTask.account_assigned_to == current.id, + DouyuTask.created_by == current.id, + ) + ) raise HTTPException(status_code=403, detail="无权查看斗鱼任务") def _require_task_account_access( - db: Session, current: User, account_ids: list[int] + db: Session, + current: User, + account_ids: list[int], + *, + platform_task_id: int | None = None, ) -> None: """确保任务只会提交到当前用户可操作的账号。""" requested_ids = set(account_ids) @@ -252,8 +270,27 @@ def _require_task_account_access( raise HTTPException(status_code=403, detail="无权操作斗鱼账号") query = query.filter(Account.assigned_to == current.id) allowed_ids = {account_id for (account_id,) in query.all()} - if allowed_ids != requested_ids: - raise HTTPException(status_code=403, detail="包含无权操作的斗鱼账号") + if allowed_ids == requested_ids: + return + if ( + platform_task_id + and len(requested_ids) == 1 + and user_has_permission(current, "platform_fulfillment:use") + ): + task = ( + db.query(PlatformFulfillmentTask) + .filter( + PlatformFulfillmentTask.id == int(platform_task_id), + PlatformFulfillmentTask.account_id.in_(requested_ids), + PlatformFulfillmentTask.execution_status.notin_( + ["completed", "cancelled"] + ), + ) + .first() + ) + if task is not None: + return + raise HTTPException(status_code=403, detail="包含无权操作的斗鱼账号") def _require_batch_owner(db: Session, current: User, batch_id: str) -> None: @@ -731,7 +768,12 @@ async def create_task_batch( """创建斗鱼任务记录并启动后台执行器。""" if not req.account_ids: raise HTTPException(status_code=400, detail="请选择斗鱼账号") - _require_task_account_access(db, current, req.account_ids) + _require_task_account_access( + db, + current, + req.account_ids, + platform_task_id=req.platform_task_id, + ) cleanup_orphan_douyu_tasks( db, @@ -748,6 +790,7 @@ async def create_task_batch( req.handbook_scope, current.id, req.payload, + platform_task_id=req.platform_task_id, ) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc @@ -755,6 +798,31 @@ async def create_task_batch( raise HTTPException( status_code=400, detail="没有可执行的斗鱼账号,请先登录获取 Cookie" ) + if req.platform_task_id: + platform_task = ( + db.query(PlatformFulfillmentTask) + .filter(PlatformFulfillmentTask.id == int(req.platform_task_id)) + .first() + ) + douyu_task_ids = [ + int(task_id) + for (task_id,) in ( + db.query(DouyuTask.id) + .filter(DouyuTask.batch_id == batch_id) + .order_by(DouyuTask.id.asc()) + .all() + ) + ] + if platform_task is not None: + platform_fulfillment_service.record_douyu_operation_started( + db, + platform_task, + current=current, + batch_id=batch_id, + task_type=req.task_type, + douyu_task_ids=douyu_task_ids, + payload=req.payload, + ) if req.task_type == "create_gold_qr": config = ensure_douyu_config(db) @@ -783,6 +851,7 @@ async def create_task_batch( "batch_id": batch_id, "task_type": req.task_type, "count": count, + "platform_task_id": req.platform_task_id, "account_count": len(req.account_ids), "handbook_scope": req.handbook_scope, "recharge_channel": recharge_channel, diff --git a/web/backend/schemas.py b/web/backend/schemas.py index bf7d52c..933c437 100644 --- a/web/backend/schemas.py +++ b/web/backend/schemas.py @@ -1612,6 +1612,7 @@ class DouyuTaskBatchRequest(BaseModel): handbook_scope: str = Field(..., pattern="^(elite|esports|peace)$") concurrency: int = Field(3, ge=1, le=10) payload: dict[str, Any] = Field(default_factory=dict) + platform_task_id: int | None = Field(None, gt=0) class DouyuWorkbenchAccountsUpdate(BaseModel): diff --git a/web/backend/services/business_events.py b/web/backend/services/business_events.py index c4e527e..23cb0d2 100644 --- a/web/backend/services/business_events.py +++ b/web/backend/services/business_events.py @@ -114,6 +114,7 @@ def record_douyu_task_result( status: str, message: str = "", occurred_at: datetime | None = None, + actor_id: int | None = None, ) -> bool: """记录账号任务终态;成功不等于业务事实,因此单独作为活动事件。""" event_type = { @@ -146,6 +147,8 @@ def record_douyu_task_result( source="douyu_task", subject_type="task", subject_key=str(task_id), + actor_type="user" if actor_id else "system", + actor_id=actor_id, source_ref=f"douyu_task_result:{task_id}", ) @@ -194,6 +197,7 @@ def record_recharge( douyu_uid: str = "", balance_after: int | None = None, confirmed: bool = True, + actor_id: int | None = None, ) -> bool: """充值鱼翅到账。 @@ -226,6 +230,8 @@ def record_recharge( source="douyu_task", subject_type="recharge", subject_key=order_id or supplier_order_id or "", + actor_type="user" if actor_id else "system", + actor_id=actor_id, source_ref=task_ref(task_id), ) @@ -245,6 +251,7 @@ def record_exchange( game_channel: str = "", points_after: int | None = None, scope: str = "elite", + actor_id: int | None = None, ) -> bool: """商品/皮肤兑换成功 —— **只在真的消耗了积分并兑换成功时调用**。 @@ -276,6 +283,8 @@ def record_exchange( source="douyu_task", subject_type="commodity", subject_key=commodity_id or name or "", + actor_type="user" if actor_id else "system", + actor_id=actor_id, source_ref=task_ref(task_id), ) if commodity_id: @@ -311,6 +320,7 @@ def record_gold_spent( source_label: str = "", balance_after: int | None = None, confirmed: bool = True, + actor_id: int | None = None, ) -> bool: """鱼翅消耗(送礼等)。 @@ -338,6 +348,8 @@ def record_gold_spent( detail={"reason": reason, "source": source_label, "confirmed": confirmed}, source="douyu_task", subject_type="gold", + actor_type="user" if actor_id else "system", + actor_id=actor_id, # 副事件:同一个任务还会发「积分到账」,所以带后缀避免撞幂等键 source_ref=task_ref(task_id, "gold"), ) @@ -387,6 +399,7 @@ def record_points_credit( expire_at: Any = None, confirmed: bool = True, source_label: str = "精英令", + actor_id: int | None = None, ) -> bool: """积分到账(送礼/任务发放)。 @@ -417,6 +430,8 @@ def record_points_credit( }, source="douyu_task", subject_type="points", + actor_type="user" if actor_id else "system", + actor_id=actor_id, source_ref=task_ref(task_id), ) @@ -432,6 +447,7 @@ def record_bind( act_alias: str = "", rebind: bool = False, weak: bool = False, + actor_id: int | None = None, ) -> bool: """角色绑定 / 换绑**真的发生了**。 @@ -468,6 +484,8 @@ def record_bind( source="douyu_task", subject_type=f"{scope}_role", subject_key=role_name or "", + actor_type="user" if actor_id else "system", + actor_id=actor_id, source_ref=task_ref(task_id), ) diff --git a/web/backend/services/douyu_runner_bind.py b/web/backend/services/douyu_runner_bind.py index 5d0831d..2ae2189 100644 --- a/web/backend/services/douyu_runner_bind.py +++ b/web/backend/services/douyu_runner_bind.py @@ -1027,6 +1027,7 @@ class BindMixin: act_alias=use_confirm_alias, rebind=_bind_is_rebind(before_snapshot), weak=True, + actor_id=int(task.created_by), ) self._mark_task( db, @@ -1062,6 +1063,7 @@ class BindMixin: role_name=final_role_name, act_alias=use_confirm_alias, rebind=_bind_is_rebind(after_snapshot), + actor_id=int(task.created_by), ) self._mark_task( db, @@ -1218,6 +1220,7 @@ class BindMixin: scope="esports", role_name=role_text, act_alias=act_alias, + actor_id=int(task.created_by), ) self._mark_task( db, diff --git a/web/backend/services/douyu_runner_core.py b/web/backend/services/douyu_runner_core.py index fe73501..3935696 100644 --- a/web/backend/services/douyu_runner_core.py +++ b/web/backend/services/douyu_runner_core.py @@ -200,6 +200,30 @@ class DouyuBatchRunnerCore: "[douyu] 同步直播账号履约状态失败: task_id={}", task.id ) + def _sync_platform_fulfillment_operation( + self, + db: Session, + task: DouyuTask, + *, + status: str, + message: str, + ) -> None: + if not task.platform_task_id: + return + try: + from .platform_fulfillment.service import record_douyu_operation_result + + record_douyu_operation_result( + db, + task, + status=status, + message=message, + ) + except Exception: # noqa: BLE001 - 履约时间线不能覆盖任务执行结果 + logger.exception( + "[douyu] 写入履约操作时间线失败: task_id={}", task.id + ) + def _mark_task( self, db: Session, @@ -233,7 +257,14 @@ class DouyuBatchRunnerCore: status=status, message=message, occurred_at=task.finished_at, + actor_id=int(task.created_by), ) + self._sync_platform_fulfillment_operation( + db, + task, + status=status, + message=message, + ) db.commit() self._push_task_event(task) self._sync_platform_fulfillment(db, task) diff --git a/web/backend/services/douyu_runner_donate.py b/web/backend/services/douyu_runner_donate.py index 93a4172..a381dfa 100644 --- a/web/backend/services/douyu_runner_donate.py +++ b/web/backend/services/douyu_runner_donate.py @@ -202,6 +202,7 @@ class DonateMixin: points_after=account.esports_points, confirmed=confirmed, source_label=gift_name, + actor_id=int(task.created_by), ) record_gold_spent( db, @@ -211,6 +212,7 @@ class DonateMixin: reason=f"赠送{gift_name} x{gift_count}", source_label=f"赠送{gift_name}", balance_after=account.gold_balance, + actor_id=int(task.created_by), ) self._mark_task(db, task, "success", message, result) @@ -338,6 +340,7 @@ class DonateMixin: expire_at=expire_at, confirmed=confirmed, source_label="精英令", + actor_id=int(task.created_by), ) # 鱼翅出项:以前只记「积分到账」,花掉的鱼翅没有任何记录 —— # 充值有账、消耗没账,对不上。金额取实测余额差。 @@ -349,6 +352,7 @@ class DonateMixin: reason=f"赠送精英令 x{gift_count}", source_label="赠送精英令", balance_after=account.gold_balance, + actor_id=int(task.created_by), ) self._mark_task(db, task, "success", message, result) diff --git a/web/backend/services/douyu_runner_gold.py b/web/backend/services/douyu_runner_gold.py index e9e2798..95e2286 100644 --- a/web/backend/services/douyu_runner_gold.py +++ b/web/backend/services/douyu_runner_gold.py @@ -294,6 +294,7 @@ class GoldMixin: channel=channel, balance_after=account.gold_balance, confirmed=True, + actor_id=int(task.created_by), ) self._mark_task( db, @@ -453,6 +454,7 @@ class GoldMixin: channel="supplier_api", douyu_uid=str(result.get("douyu_uid") or ""), balance_after=account.gold_balance, + actor_id=int(task.created_by), # 供应商终态成功 ≠ 斗鱼余额已变,如实标注 confirmed=False, ) diff --git a/web/backend/services/douyu_runner_goods.py b/web/backend/services/douyu_runner_goods.py index d917d60..5e8487f 100644 --- a/web/backend/services/douyu_runner_goods.py +++ b/web/backend/services/douyu_runner_goods.py @@ -283,6 +283,7 @@ class GoodsMixin: game_channel=account.game_channel or "", points_after=account.points, scope="elite", + actor_id=int(task.created_by), ) self._mark_task( db, @@ -589,6 +590,7 @@ class GoodsMixin: game_channel=account.game_channel or "", points_after=(points_refresh or {}).get("points"), scope="elite", + actor_id=int(task.created_by), ) self._refresh_high_value_after_exchange( client, @@ -709,6 +711,7 @@ class GoodsMixin: game_channel=account.esports_game_channel or "", points_after=account.esports_points, scope="esports", + actor_id=int(task.created_by), ) self._mark_task(db, task, "success", message, result) diff --git a/web/backend/services/douyu_runner_manual.py b/web/backend/services/douyu_runner_manual.py index 78dff11..b58f442 100644 --- a/web/backend/services/douyu_runner_manual.py +++ b/web/backend/services/douyu_runner_manual.py @@ -406,6 +406,8 @@ class ManualMixin: "spent": spent, }, source="manual", + actor_type="user", + actor_id=int(task.created_by), source_ref=( f"elite_opened:{account.id}:{int(account.updated_at.timestamp())}" ), @@ -509,6 +511,8 @@ class ManualMixin: amount=-spent if spent else None, detail={"points": account.esports_points, "spent": spent}, source="manual", + actor_type="user", + actor_id=int(task.created_by), source_ref=( f"esports_opened:{account.id}:{int(account.updated_at.timestamp())}" ), diff --git a/web/backend/services/douyu_runner_xpd.py b/web/backend/services/douyu_runner_xpd.py index f088830..8cad50d 100644 --- a/web/backend/services/douyu_runner_xpd.py +++ b/web/backend/services/douyu_runner_xpd.py @@ -599,6 +599,7 @@ class XpdMixin: game_channel=channel, points_after=result.get("new_balance"), scope="peace", + actor_id=int(task.created_by), ) self._mark_task( db, diff --git a/web/backend/services/douyu_service.py b/web/backend/services/douyu_service.py index a85b93e..c127d65 100644 --- a/web/backend/services/douyu_service.py +++ b/web/backend/services/douyu_service.py @@ -273,6 +273,7 @@ def create_douyu_planned_tasks( handbook_scope: str, created_by: int, payload: dict | None = None, + platform_task_id: int | None = None, ) -> tuple[str, int]: """创建斗鱼任务记录,等待后台执行器消费。""" if task_type not in SUPPORTED_DOUYU_TASK_TYPES: @@ -304,6 +305,7 @@ def create_douyu_planned_tasks( message="任务已创建,等待执行", result={"payload": payload} if payload else None, created_by=created_by, + platform_task_id=platform_task_id, ) db.add(task) task_rows.append((task, account)) @@ -380,6 +382,15 @@ def cleanup_orphan_douyu_tasks( message=message, occurred_at=now, ) + if task.platform_task_id: + from .platform_fulfillment.service import record_douyu_operation_result + + record_douyu_operation_result( + db, + task, + status="stopped", + message=message, + ) db.commit() return len(tasks) diff --git a/web/backend/services/platform_fulfillment/service.py b/web/backend/services/platform_fulfillment/service.py index 1851584..fc24349 100644 --- a/web/backend/services/platform_fulfillment/service.py +++ b/web/backend/services/platform_fulfillment/service.py @@ -40,7 +40,11 @@ from ..business_events import record_account_query, record_douyu_task_started from ..douyu_account_state import DouyuLiveAccountState, refresh_douyu_account_state from ..douyu_activity_query import activity_client, query_exchange_eligibility from ..douyu_batch_launcher import start_douyu_batch, stop_douyu_batches -from ..douyu_service import douyu_config_value, ensure_douyu_config +from ..douyu_service import ( + SUPPORTED_DOUYU_TASK_TYPES, + douyu_config_value, + ensure_douyu_config, +) from ..external_order_source import ( OrderLookupUnavailable, list_pending_manual_fulfillments, @@ -648,6 +652,80 @@ def _append_event( ) +def record_douyu_operation_started( + db: Session, + task: PlatformFulfillmentTask, + *, + current: User, + batch_id: str, + task_type: str, + douyu_task_ids: list[int], + payload: dict[str, Any] | None = None, +) -> None: + """记录履约上下文发起的斗鱼操作,账号任务结果由执行器补写。""" + _append_event( + db, + task.id, + "douyu_operation_started", + actor_type="user", + actor_id=current.id, + detail={ + "batchId": batch_id, + "douyuTaskIds": douyu_task_ids, + "taskType": task_type, + "taskLabel": SUPPORTED_DOUYU_TASK_TYPES.get(task_type, task_type), + "accountId": task.account_id, + "payload": payload or {}, + }, + ) + db.commit() + + +def record_douyu_operation_result( + db: Session, + douyu_task: DouyuTask, + *, + status: str, + message: str, +) -> None: + """把履约上下文的斗鱼任务终态投影到履约时间线。""" + if not douyu_task.platform_task_id: + return + event_type = { + "success": "douyu_operation_succeeded", + "stopped": "douyu_operation_stopped", + }.get(status, "douyu_operation_failed") + exists = ( + db.query(PlatformFulfillmentEvent.id) + .filter( + PlatformFulfillmentEvent.task_id == int(douyu_task.platform_task_id), + PlatformFulfillmentEvent.event_type == event_type, + PlatformFulfillmentEvent.detail_json["douyuTaskId"].as_integer() + == int(douyu_task.id), + ) + .first() + ) + if exists is not None: + return + _append_event( + db, + int(douyu_task.platform_task_id), + event_type, + detail={ + "batchId": douyu_task.batch_id, + "douyuTaskId": int(douyu_task.id), + "taskType": douyu_task.task_type, + "taskLabel": SUPPORTED_DOUYU_TASK_TYPES.get( + douyu_task.task_type, + douyu_task.task_type, + ), + "accountId": douyu_task.account_id, + "status": status, + "message": (message or "")[:1000], + }, + ) + + def _emit_order_site_binding_state( db: Session, task_id: int, @@ -2500,6 +2578,8 @@ __all__ = [ "list_tasks", "mark_manual_required", "reconcile_binding_state_outbox", + "record_douyu_operation_result", + "record_douyu_operation_started", "refresh_binding", "refresh_exchange_eligibility", "release_task_account", diff --git a/web/frontend/src/api/types.ts b/web/frontend/src/api/types.ts index 6fb1c30..99312ac 100644 --- a/web/frontend/src/api/types.ts +++ b/web/frontend/src/api/types.ts @@ -187,6 +187,9 @@ export interface AccountEventItem { source: string; actor_type?: string; actor_id?: number | null; + actor_name?: string; + actor_role?: string; + actor_role_label?: string; } export interface AccountEventPage { @@ -749,6 +752,7 @@ export interface DouyuTaskBatchRequest { handbook_scope: "elite" | "esports" | "peace"; concurrency?: number; payload?: Record; + platform_task_id?: number; } export interface DouyuTaskBatchResult { diff --git a/web/frontend/src/pages/AccountDetailPage.tsx b/web/frontend/src/pages/AccountDetailPage.tsx index 61d2e53..9fcfff7 100644 --- a/web/frontend/src/pages/AccountDetailPage.tsx +++ b/web/frontend/src/pages/AccountDetailPage.tsx @@ -56,6 +56,12 @@ const CATEGORY_OPTIONS = [ { value: 'ops', label: '人工操作' }, ]; +const ACTOR_TYPE_LABELS: Record = { + user: '用户', + system: '系统', + public: '客户', +}; + /** 生命周期状态 → 展示色(与账号列表页保持一致,取值域见后端 account_lifecycle)。 */ const STATUS_TONES: Record = { imported: 'default', @@ -106,6 +112,16 @@ function eventTag(type: string) { return {style.label}; } +function actorLabel(item: AccountEventItem) { + if (item.actor_type === 'user') { + const name = item.actor_name || (item.actor_id ? `用户 #${item.actor_id}` : '用户'); + const role = item.actor_role_label ? `(${item.actor_role_label})` : ''; + const id = item.actor_id ? ` · ID ${item.actor_id}` : ''; + return `${name}${role}${id}`; + } + return ACTOR_TYPE_LABELS[item.actor_type || 'system'] || item.actor_type || '系统'; +} + const COMMODITY_STATE: Record = { available: { label: '可兑换', color: 'green' }, limited: { label: '已达上限', color: 'orange' }, @@ -296,6 +312,12 @@ export default function AccountDetailPage() { width: 100, render: (val: string) => eventTag(val), }, + { + title: '操作人', + key: 'actor', + width: 190, + render: (_value, record) => {actorLabel(record)}, + }, { title: '说明', dataIndex: 'title', ellipsis: true }, { title: '金额 / 变动', diff --git a/web/frontend/src/pages/PlatformFulfillmentPage.tsx b/web/frontend/src/pages/PlatformFulfillmentPage.tsx index d2e318d..5d8a57c 100644 --- a/web/frontend/src/pages/PlatformFulfillmentPage.tsx +++ b/web/frontend/src/pages/PlatformFulfillmentPage.tsx @@ -97,6 +97,10 @@ const EVENT_LABELS: Record = { manual_exchange_completed: '人工兑换完成', marked_manual_required: '转人工处理', released_to_manual: '释放账号并转人工', + douyu_operation_started: '斗鱼操作已提交', + douyu_operation_succeeded: '斗鱼操作成功', + douyu_operation_failed: '斗鱼操作失败', + douyu_operation_stopped: '斗鱼操作已停止', task_cancelled: '任务已取消', task_restored: '恢复已取消任务', }; @@ -187,7 +191,17 @@ function eventLabel(value: string) { function eventColor(value: string) { if (value.includes('failed') || value.includes('cancelled')) return 'red'; if (value.includes('manual_required') || value.includes('released_to_manual')) return 'orange'; - if (value.includes('completed') || value.includes('allocated') || value.includes('restored')) return 'green'; + if ( + value.includes('completed') || + value.includes('allocated') || + value.includes('restored') || + value.includes('succeeded') + ) { + return 'green'; + } + if (value.includes('douyu_operation_failed') || value.includes('douyu_operation_stopped')) { + return value.includes('stopped') ? 'orange' : 'red'; + } return 'blue'; } @@ -236,6 +250,16 @@ function eventDescription(event: { eventType: string; detail: Record