From e90e93d515ddf80c963396effcecc789b35082a5 Mon Sep 17 00:00:00 2001 From: yml Date: Wed, 18 Nov 2026 21:40:25 +0800 Subject: [PATCH] =?UTF-8?q?feat(fulfillment):=20=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E5=8F=96=E6=B6=88=E6=81=A2=E5=A4=8D=E4=B8=8E=E6=93=8D=E4=BD=9C?= =?UTF-8?q?=E4=BA=BA=E5=AE=A1=E8=AE=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/test_platform_fulfillment.py | 154 ++++++++++++++++++ web/backend/permissions.py | 3 + web/backend/routers/platform_fulfillment.py | 35 +++- web/backend/schemas.py | 4 + web/backend/services/external_order_source.py | 2 + .../services/platform_fulfillment/service.py | 133 +++++++++++++++ web/frontend/src/api/platformFulfillment.ts | 5 + web/frontend/src/api/types.ts | 3 + .../src/pages/PlatformFulfillmentPage.tsx | 92 ++++++++++- 9 files changed, 424 insertions(+), 7 deletions(-) diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index 4247105..8c501ef 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -10,6 +10,7 @@ import pytest from fastapi import HTTPException from tests.support.db import get_test_engine, make_test_session +from web.backend.deps import require_permission from web.backend.models import ( Account, AccountCommodityState, @@ -26,6 +27,7 @@ from web.backend.models import ( PlatformFulfillmentTask, User, ) +from web.backend.permissions import ROLE_PERMISSIONS from web.backend.schemas import DouyuCollabOrderOut from web.backend.services import douyu_collab_service as collab from web.backend.services.automation.jobs import ( @@ -1343,6 +1345,150 @@ class TestBindingAndCompletion(_Base): assert exc_info.value.status_code == 409 assert "仍在执行" in str(exc_info.value.detail) + def test_cancel_permission_excludes_support(self): + assert "platform_fulfillment:cancel" in ROLE_PERMISSIONS["operation"] + assert "platform_fulfillment:cancel" in ROLE_PERMISSIONS["super_admin"] + assert "platform_fulfillment:cancel" not in ROLE_PERMISSIONS["support"] + assert "platform_fulfillment:view" in ROLE_PERMISSIONS["support"] + assert "platform_fulfillment:use" in ROLE_PERMISSIONS["support"] + + checker = require_permission("platform_fulfillment:cancel") + support = User( + username="cancel-support", + password_hash="h", + role="support", + is_active=True, + ) + operator = User( + username="cancel-operator", + password_hash="h", + role="operation", + is_active=True, + ) + with pytest.raises(HTTPException) as exc_info: + checker(current_user=support) + assert exc_info.value.status_code == 403 + assert checker(current_user=operator) is operator + + def test_restore_permission_is_super_admin_only(self): + assert "platform_fulfillment:restore" in ROLE_PERMISSIONS["super_admin"] + assert "platform_fulfillment:restore" not in ROLE_PERMISSIONS["operation"] + assert "platform_fulfillment:restore" not in ROLE_PERMISSIONS["support"] + + checker = require_permission("platform_fulfillment:restore") + operator = User( + username="restore-operator", + password_hash="h", + role="operation", + is_active=True, + ) + admin = User( + username="restore-admin", + password_hash="h", + role="super_admin", + is_active=True, + ) + with pytest.raises(HTTPException) as exc_info: + checker(current_user=operator) + assert exc_info.value.status_code == 403 + assert checker(current_user=admin) is admin + + def test_restore_manual_cancel_requeues_task_and_restores_collab( + self, monkeypatch + ): + task = self.task() + service.cancel_task( + self.session, + task_id=task.id, + current=self.admin, + reason="客服误点取消", + ) + collab_order = DouyuExternalOrder( + order_no=task.platform_order_id, + source_type="platform_fulfillment", + source_task_id=task.id, + status="void", + void_reason="直播履约任务已取消", + ) + self.session.add(collab_order) + self.session.commit() + monkeypatch.setattr( + service, + "lookup_pending_manual_fulfillment", + lambda _item_id: { + "order_status": "paid", + "pay_status": "paid", + "fulfillment_issue_code": "", + }, + ) + + detail = service.restore_cancelled_task( + self.session, + task_id=task.id, + current=self.admin, + reason="核对订单仍有效,恢复误取消任务", + ) + + self.session.refresh(task) + self.session.refresh(collab_order) + assert detail["task"]["executionStatus"] == "ready" + assert task.account_id is None + assert task.lease_id is None + assert task.next_allocate_at is not None + assert collab_order.status == "incomplete" + assert collab_order.void_reason == "" + restored = next( + event for event in detail["events"] if event["eventType"] == "task_restored" + ) + assert restored["actorName"] == "pf-admin" + assert restored["detail"]["reason"] == "核对订单仍有效,恢复误取消任务" + + def test_restore_rejects_source_cancelled_task(self): + task = self.task() + task.execution_status = "cancelled" + task.issue_code = "source_cancelled" + self.session.commit() + + with pytest.raises(HTTPException) as exc_info: + service.restore_cancelled_task( + self.session, + task_id=task.id, + current=self.admin, + reason="尝试恢复来源取消任务", + ) + + assert exc_info.value.status_code == 409 + assert "来源订单已取消" in str(exc_info.value.detail) + + def test_restore_rejects_terminal_source_order(self, monkeypatch): + task = self.task() + service.cancel_task( + self.session, + task_id=task.id, + current=self.admin, + reason="客服误点取消", + ) + monkeypatch.setattr( + service, + "lookup_pending_manual_fulfillment", + lambda _item_id: { + "order_status": "refunded", + "pay_status": "paid", + "fulfillment_issue_code": "", + }, + ) + + with pytest.raises(HTTPException) as exc_info: + service.restore_cancelled_task( + self.session, + task_id=task.id, + current=self.admin, + reason="核对订单是否可恢复", + ) + + assert exc_info.value.status_code == 409 + assert "不能恢复" in str(exc_info.value.detail) + def test_cancel_releases_account_and_terminal_state_cannot_be_refreshed_back( self, monkeypatch ): @@ -1384,6 +1530,14 @@ class TestBindingAndCompletion(_Base): self.session.refresh(bind_task) lease = self.session.query(AccountLease).filter_by(id=lease_id).one() assert detail["task"]["executionStatus"] == "cancelled" + cancel_event = next( + event + for event in detail["events"] + if event["eventType"] == "task_cancelled" + ) + assert cancel_event["actorName"] == "pf-admin" + assert cancel_event["actorRole"] == "super_admin" + assert cancel_event["actorRoleLabel"] == "超级管理员" assert task.account_id is None assert task.lease_id is None assert task.bind_task_id is None diff --git a/web/backend/permissions.py b/web/backend/permissions.py index 638fd23..f87d03d 100644 --- a/web/backend/permissions.py +++ b/web/backend/permissions.py @@ -40,6 +40,8 @@ PERMISSIONS = { # 直播账号履约:order_site 订单由内部斗鱼账号完成游戏角色绑定和人工兑换 "platform_fulfillment:view": "查看直播账号履约任务", "platform_fulfillment:use": "分配账号、绑定角色和处理直播账号履约", + "platform_fulfillment:cancel": "取消直播账号履约任务", + "platform_fulfillment:restore": "恢复误取消的直播账号履约任务", "platform_fulfillment:admin": "维护直播账号履约商品映射", "yyb:session": "应用宝扫码登录与角色查询", "yyb:recharge": "应用宝充值与付款", @@ -119,6 +121,7 @@ ROLE_PERMISSIONS = { "douyu:collab:ck_export", "platform_fulfillment:view", "platform_fulfillment:use", + "platform_fulfillment:cancel", "platform_fulfillment:admin", "yyb:session", "yyb:recharge", diff --git a/web/backend/routers/platform_fulfillment.py b/web/backend/routers/platform_fulfillment.py index f94c0a7..3d9e553 100644 --- a/web/backend/routers/platform_fulfillment.py +++ b/web/backend/routers/platform_fulfillment.py @@ -15,6 +15,7 @@ from ..schemas import ( PlatformFulfillmentCompleteRequest, PlatformFulfillmentMappingUpsert, PlatformFulfillmentReasonRequest, + PlatformFulfillmentRestoreRequest, PlatformFulfillmentSettingsUpdate, ) from ..services import douyu_collab_service @@ -343,7 +344,7 @@ def cancel_task( task_id: int, req: PlatformFulfillmentReasonRequest, db: Session = Depends(get_db), - current: User = Depends(require_permission("platform_fulfillment:use")), + current: User = Depends(require_permission("platform_fulfillment:cancel")), ) -> dict[str, Any]: result = service.cancel_task( db, @@ -362,4 +363,36 @@ def cancel_task( return result +@router.post("/tasks/{task_id}/restore") +def restore_cancelled_task( + task_id: int, + req: PlatformFulfillmentRestoreRequest, + db: Session = Depends(get_db), + current: User = Depends(require_permission("platform_fulfillment:restore")), +) -> dict[str, Any]: + result = service.restore_cancelled_task( + db, + task_id=task_id, + current=current, + reason=req.reason, + ) + record_audit( + db, + current, + action="platform_fulfillment:restore", + target=f"platform_fulfillment_task:{task_id}", + detail={"reason": req.reason}, + ) + db.commit() + collab_events.publish( + scope="orders", + action="order.restore_from_platform_fulfillment", + actor_id=int(current.id), + ) + from ..services.platform_fulfillment.auto_allocator import wake_auto_allocator + + wake_auto_allocator([task_id]) + return result + + __all__ = ["router"] diff --git a/web/backend/schemas.py b/web/backend/schemas.py index aa0995c..bf7d52c 100644 --- a/web/backend/schemas.py +++ b/web/backend/schemas.py @@ -1576,6 +1576,10 @@ class PlatformFulfillmentReasonRequest(BaseModel): reason: str = Field(default="", max_length=2000) +class PlatformFulfillmentRestoreRequest(BaseModel): + reason: str = Field(..., min_length=2, max_length=2000) + + class PlatformFulfillmentCompleteRequest(BaseModel): note: str = Field(default="", max_length=1000) diff --git a/web/backend/services/external_order_source.py b/web/backend/services/external_order_source.py index 8f348c1..7d1e4e8 100644 --- a/web/backend/services/external_order_source.py +++ b/web/backend/services/external_order_source.py @@ -290,6 +290,8 @@ def _normalize_pending_row(row: dict[str, Any]) -> dict[str, Any]: "sku_name": str(row.get("sku_name") or ""), "internal_sku_key": internal_sku_key, "quantity": int(row.get("quantity") or 1), + "fulfillment_status": str(row.get("fulfillment_status") or ""), + "fulfillment_issue_code": str(row.get("fulfillment_issue_code") or ""), "spec_json": row.get("spec_json"), "item_updated_at": row.get("item_updated_at"), } diff --git a/web/backend/services/platform_fulfillment/service.py b/web/backend/services/platform_fulfillment/service.py index d8d3d50..6a15c8f 100644 --- a/web/backend/services/platform_fulfillment/service.py +++ b/web/backend/services/platform_fulfillment/service.py @@ -26,6 +26,7 @@ from ...models import ( PlatformFulfillmentTask, User, ) +from ...permissions import ROLE_LABELS from ..account_binding import ( binding_role_from_result, pending_binding_role_from_result, @@ -1053,6 +1054,16 @@ def get_task_detail(db: Session, task_id: int) -> dict[str, Any]: .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 {} return { "task": _task_out(db, task, include_qr=True), "events": [ @@ -1061,6 +1072,24 @@ def get_task_detail(db: Session, task_id: int) -> dict[str, Any]: "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": event.detail_json or {}, "createdAt": event.created_at, } @@ -2244,6 +2273,9 @@ def cancel_task( raise HTTPException(status_code=409, detail="已完成任务不能取消") account_id = task.account_id lease_id = task.lease_id + previous_execution_status = task.execution_status + previous_binding_status = task.binding_status + previous_exchange_status = task.exchange_status lease = ( db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() if task.lease_id @@ -2288,6 +2320,9 @@ def cancel_task( actor_id=current.id, detail={ "reason": task.last_error, + "previousExecutionStatus": previous_execution_status, + "previousBindingStatus": previous_binding_status, + "previousExchangeStatus": previous_exchange_status, "releasedAccountId": account_id, "releasedLeaseId": lease_id, "stoppedBatches": stopped_batches, @@ -2298,6 +2333,103 @@ def cancel_task( return get_task_detail(db, task.id) +def restore_cancelled_task( + db: Session, + *, + task_id: int, + current: User, + reason: str, +) -> dict[str, Any]: + """仅恢复人工误取消、且来源订单仍可履约的任务;不复用旧租约。""" + task = ( + db.query(PlatformFulfillmentTask) + .filter(PlatformFulfillmentTask.id == int(task_id)) + .with_for_update() + .first() + ) + if task is None: + raise HTTPException(status_code=404, detail="直播账号履约任务不存在") + if task.execution_status != "cancelled": + raise HTTPException(status_code=409, detail="只有已取消任务可以恢复") + if task.issue_code == "source_cancelled": + raise HTTPException(status_code=409, detail="来源订单已取消,不能恢复") + manual_cancel = ( + db.query(PlatformFulfillmentEvent.id) + .filter( + PlatformFulfillmentEvent.task_id == task.id, + PlatformFulfillmentEvent.event_type == "task_cancelled", + PlatformFulfillmentEvent.actor_type == "user", + ) + .first() + ) + if manual_cancel is None: + raise HTTPException(status_code=409, detail="只有人工取消的任务可以恢复") + + try: + source = lookup_pending_manual_fulfillment(task.source_order_item_id) + except OrderLookupUnavailable as exc: + raise HTTPException(status_code=503, detail=f"订单源不可用:{exc}") from exc + if source is None: + raise HTTPException(status_code=409, detail="来源订单不存在或已不可履约") + if ( + str(source.get("order_status") or "") in {"refunded", "cancelled", "closed"} + or str(source.get("pay_status") or "") != "paid" + or str(source.get("fulfillment_issue_code") or "") + in {"user_refund", "platform_cancelled"} + ): + raise HTTPException(status_code=409, detail="来源订单已退款、关闭或取消,不能恢复") + + restore_reason = reason.strip() + if len(restore_reason) < 2: + raise HTTPException(status_code=400, detail="请填写恢复原因") + + mapping = _mapping_for_sku(db, task.internal_sku_key) + _apply_mapping(task, mapping) + task.account_id = None + task.lease_id = None + task.bind_task_id = None + task.exchange_task_id = None + task.binding_status = "not_started" + task.exchange_status = "not_started" + task.completed_at = None + task.next_allocate_at = _now() if task.execution_status == "ready" else None + task.operator_id = current.id + task.updated_at = _now() + + restored_collab = ( + db.query(DouyuExternalOrder) + .filter(DouyuExternalOrder.source_task_id == task.id) + .first() + ) + restored_collab_status = "" + if restored_collab is not None and restored_collab.status == "void": + restored_collab.status = "incomplete" + restored_collab.void_reason = "" + restored_collab.updated_by = current.id + restored_collab.updated_at = _now() + restored_collab.version = int(restored_collab.version or 0) + 1 + restored_collab_status = restored_collab.status + + _append_event( + db, + task.id, + "task_restored", + actor_type="user", + actor_id=current.id, + detail={ + "reason": restore_reason, + "restoredExecutionStatus": task.execution_status, + "restoredCollabOrderId": ( + int(restored_collab.id) if restored_collab is not None else None + ), + "restoredCollabStatus": restored_collab_status, + }, + ) + _emit_order_site_binding_state(db, task.id) + db.commit() + return get_task_detail(db, task.id) + + __all__ = [ "allocate_task", "cancel_task", @@ -2313,6 +2445,7 @@ __all__ = [ "refresh_exchange_eligibility", "release_task_account", "reset_task_binding", + "restore_cancelled_task", "start_binding", "sync_order_item_ids", "sync_order_snapshot", diff --git a/web/frontend/src/api/platformFulfillment.ts b/web/frontend/src/api/platformFulfillment.ts index 694e146..9a0b084 100644 --- a/web/frontend/src/api/platformFulfillment.ts +++ b/web/frontend/src/api/platformFulfillment.ts @@ -108,4 +108,9 @@ export const platformFulfillmentApi = { `/platform-fulfillment/tasks/${taskId}/cancel`, { reason }, ), + restore: (taskId: number, reason: string) => + api.post( + `/platform-fulfillment/tasks/${taskId}/restore`, + { reason }, + ), }; diff --git a/web/frontend/src/api/types.ts b/web/frontend/src/api/types.ts index 34dd31d..6fb1c30 100644 --- a/web/frontend/src/api/types.ts +++ b/web/frontend/src/api/types.ts @@ -2229,6 +2229,9 @@ export interface PlatformFulfillmentEvent { eventType: string; actorType: string; actorId: string; + actorName: string; + actorRole: string; + actorRoleLabel: string; detail: Record; createdAt: string; } diff --git a/web/frontend/src/pages/PlatformFulfillmentPage.tsx b/web/frontend/src/pages/PlatformFulfillmentPage.tsx index 234db72..acee6fb 100644 --- a/web/frontend/src/pages/PlatformFulfillmentPage.tsx +++ b/web/frontend/src/pages/PlatformFulfillmentPage.tsx @@ -76,7 +76,7 @@ const EXCHANGE_STATUS_LABELS: Record = { const ACTOR_TYPE_LABELS: Record = { system: '系统', - user: '运营', + user: '操作人', customer: '客户', connector: '连接器', }; @@ -97,6 +97,7 @@ const EVENT_LABELS: Record = { manual_exchange_completed: '人工兑换完成', marked_manual_required: '转人工处理', task_cancelled: '任务已取消', + task_restored: '恢复已取消任务', }; const ISSUE_LABELS: Record = { @@ -111,6 +112,7 @@ const ISSUE_LABELS: Record = { customer_role_cooldown: '游戏角色仍在换绑冷却期', lease_expired: '账号租约已过期', manual_required: '需要人工处理', + source_cancelled: '来源订单已取消', }; const DOUYU_ACTION_LABELS: Record = { @@ -184,7 +186,7 @@ function eventLabel(value: string) { function eventColor(value: string) { if (value.includes('failed') || value.includes('cancelled')) return 'red'; if (value.includes('manual_required')) return 'orange'; - if (value.includes('completed') || value.includes('allocated')) return 'green'; + if (value.includes('completed') || value.includes('allocated') || value.includes('restored')) return 'green'; return 'blue'; } @@ -226,6 +228,10 @@ function eventDescription(event: { eventType: string; detail: Record(null); + const [restoreTarget, setRestoreTarget] = useState(null); + const [restoreReason, setRestoreReason] = useState(''); + const [restoring, setRestoring] = useState(false); const [selectedRowKeys, setSelectedRowKeys] = useState([]); const [selectedId, setSelectedId] = useState(null); const [detail, setDetail] = useState(null); @@ -492,7 +501,7 @@ export default function PlatformFulfillmentPage() { Modal.confirm({ title: '确认取消履约任务?', content: - '取消后会立即停止当前绑定或兑换任务,释放已占用的斗鱼账号,并通知订单侧更新为已取消。该操作不可撤销。', + '取消后会立即停止当前绑定或兑换任务,释放已占用的斗鱼账号,并通知订单侧更新为已取消。若属误操作,仅超级管理员可核对来源订单后恢复。', okText: '确认取消并释放账号', okButtonProps: { danger: true }, cancelText: '返回', @@ -503,6 +512,29 @@ export default function PlatformFulfillmentPage() { }); }; + const restoreTask = async () => { + if (!restoreTarget) return; + const reason = restoreReason.trim(); + if (reason.length < 2) { + message.warning('请填写恢复原因'); + return; + } + setRestoring(true); + try { + const result = await platformFulfillmentApi.restore(restoreTarget.id, reason); + setDetail(result); + setSelectedId(result.task.id); + setRestoreTarget(null); + setRestoreReason(''); + await loadTasks(); + message.success('任务已恢复并重新进入履约队列'); + } catch (error) { + message.error(getErrorMessage(error)); + } finally { + setRestoring(false); + } + }; + const runDouyuAccountAction = async (taskType: string) => { if (!selected?.account) { message.warning('当前履约任务还没有分配斗鱼账号'); @@ -866,11 +898,27 @@ export default function PlatformFulfillmentPage() { 重置角色资料 ) : null} - {selected.executionStatus !== 'completed' && selected.executionStatus !== 'cancelled' ? ( + {can('platform_fulfillment:cancel') && + selected.executionStatus !== 'completed' && + selected.executionStatus !== 'cancelled' ? ( ) : null} + {can('platform_fulfillment:restore') && + selected.executionStatus === 'cancelled' && + selected.issueCode !== 'source_cancelled' ? ( + + ) : null} ) : null; @@ -1166,8 +1214,10 @@ export default function PlatformFulfillmentPage() { {eventLabel(event.eventType)} {eventDescription(event)} - {formatTime(event.createdAt)} · {ACTOR_TYPE_LABELS[event.actorType] || '系统'} - {event.actorId ? ` · 操作人 ${event.actorId}` : ''} + {formatTime(event.createdAt)} ·{' '} + {event.actorRoleLabel || ACTOR_TYPE_LABELS[event.actorType] || '系统'} + {event.actorName ? ` · ${event.actorName}` : ''} + {event.actorId ? ` · ID ${event.actorId}` : ''} ), @@ -1228,6 +1278,36 @@ export default function PlatformFulfillmentPage() { + void restoreTask()} + onCancel={() => { + setRestoreTarget(null); + setRestoreReason(''); + }} + > + + + setRestoreReason(event.target.value)} + /> + + +