From 86b586b96d03c2f3481a8aeeda02d8b575dc2e4c Mon Sep 17 00:00:00 2001 From: yml Date: Wed, 18 Nov 2026 22:14:16 +0800 Subject: [PATCH] =?UTF-8?q?fix(fulfillment):=20=E4=BF=9D=E6=8C=81=E5=A4=96?= =?UTF-8?q?=E9=83=A8=E5=8D=8F=E4=BD=9C=E4=BA=BA=E5=B7=A5=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=B9=B6=E6=94=AF=E6=8C=81=E8=BD=AC=E4=BA=BA=E5=B7=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/test_platform_fulfillment.py | 102 ++++++++++++++++++ web/backend/routers/platform_fulfillment.py | 24 +++++ web/backend/services/douyu_collab_service.py | 30 ++++-- .../services/platform_fulfillment/service.py | 70 +++++++++++- web/frontend/src/api/platformFulfillment.ts | 5 + .../src/pages/PlatformFulfillmentPage.tsx | 85 ++++++++++++++- 6 files changed, 302 insertions(+), 14 deletions(-) diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index 8c501ef..ca0cf1b 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -607,6 +607,36 @@ class TestFulfillmentCollabSync(_Base): assert synced.source_task_id == task.id assert synced.remark == "人工备注保留" + def test_manual_sync_preserves_existing_collab_account_and_role(self): + task = self.task() + task_account = self.account("task-account") + manual_account = self.account("manual-account") + task.account_id = task_account.id + manual = DouyuExternalOrder( + order_no=task.platform_order_id, + account_id=manual_account.id, + account_username=manual_account.username, + bind_game_role="人工绑定角色", + bind_game_channel="手工渠道", + status="to_recharge", + ) + self.session.add(manual) + self.session.commit() + + synced, action = collab.sync_platform_fulfillment_order( + self.session, + self.admin, + task, + ) + + assert action == "updated" + assert synced.id == manual.id + assert synced.account_id == manual_account.id + assert synced.account_username == manual_account.username + assert synced.bind_game_role == "人工绑定角色" + assert synced.bind_game_channel == "手工渠道" + assert synced.status == "to_recharge" + def test_manual_sync_maps_only_safe_terminal_statuses(self): task = self._task_with_account() order, _ = collab.sync_platform_fulfillment_order( @@ -1460,6 +1490,48 @@ class TestBindingAndCompletion(_Base): assert exc_info.value.status_code == 409 assert "来源订单已取消" in str(exc_info.value.detail) + def test_restore_rejects_active_external_collab(self, monkeypatch): + task = self.task() + service.cancel_task( + self.session, + task_id=task.id, + current=self.admin, + reason="客服误点取消", + ) + account = self.account("active-collab-account") + self.session.add( + DouyuExternalOrder( + order_no=task.platform_order_id, + source_type="platform_fulfillment", + source_task_id=task.id, + account_id=account.id, + account_username=account.username, + bind_game_role="人工已绑定", + status="to_recharge", + ) + ) + self.session.commit() + monkeypatch.setattr( + service, + "lookup_pending_manual_fulfillment", + lambda _item_id: { + "order_status": "paid", + "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_restore_rejects_terminal_source_order(self, monkeypatch): task = self.task() service.cancel_task( @@ -1553,6 +1625,36 @@ class TestBindingAndCompletion(_Base): self.session.refresh(task) assert task.execution_status == "cancelled" + def test_release_to_manual_releases_lease_without_reallocating(self): + task = self._allocated() + account_id = task.account_id + lease_id = task.lease_id + + detail = service.release_task_to_manual( + self.session, + task_id=task.id, + current=self.admin, + reason="以外部单协作人工处理为准", + ) + + self.session.refresh(task) + lease = self.session.query(AccountLease).filter_by(id=lease_id).one() + assert detail["task"]["executionStatus"] == "manual_required" + assert task.account_id is None + assert task.lease_id is None + assert task.next_allocate_at is None + assert task.issue_code == "manual_required" + assert task.last_error == "以外部单协作人工处理为准" + assert lease.status == "released" + assert lease.release_reason == "platform_fulfillment_manual" + event = ( + self.session.query(PlatformFulfillmentEvent) + .filter_by(task_id=task.id, event_type="released_to_manual") + .one() + ) + assert event.detail_json["releasedAccountId"] == account_id + assert event.detail_json["releasedLeaseId"] == lease_id + def test_refresh_binding_maps_role_ready(self, monkeypatch): notified: list[int] = [] monkeypatch.setattr( diff --git a/web/backend/routers/platform_fulfillment.py b/web/backend/routers/platform_fulfillment.py index 3d9e553..4e3d557 100644 --- a/web/backend/routers/platform_fulfillment.py +++ b/web/backend/routers/platform_fulfillment.py @@ -315,6 +315,30 @@ def release_task( return result +@router.post("/tasks/{task_id}/release-manual") +def release_task_to_manual( + task_id: int, + req: PlatformFulfillmentReasonRequest, + db: Session = Depends(get_db), + current: User = Depends(require_permission("platform_fulfillment:use")), +) -> dict[str, Any]: + result = service.release_task_to_manual( + db, + task_id=task_id, + current=current, + reason=req.reason, + ) + record_audit( + db, + current, + action="platform_fulfillment:release_to_manual", + target=f"platform_fulfillment_task:{task_id}", + detail={"reason": req.reason}, + ) + db.commit() + return result + + @router.post("/tasks/{task_id}/manual") def mark_manual( task_id: int, diff --git a/web/backend/services/douyu_collab_service.py b/web/backend/services/douyu_collab_service.py index 21882eb..b66af61 100644 --- a/web/backend/services/douyu_collab_service.py +++ b/web/backend/services/douyu_collab_service.py @@ -731,6 +731,8 @@ def _apply_platform_fulfillment_binding( db: Session, order: DouyuExternalOrder, task: PlatformFulfillmentTask, + *, + overwrite: bool, ) -> None: """把履约任务已确认的本地绑定结果投影到协作单,不额外联网。""" bind_task = ( @@ -742,11 +744,13 @@ def _apply_platform_fulfillment_binding( role = binding_role_from_result(result) if not role: return - order.bind_game_role = _text(role, max_length=128) + if overwrite or not order.bind_game_role: + order.bind_game_role = _text(role, max_length=128) channel = binding_channel(result) - if channel: + if channel and (overwrite or not order.bind_game_channel): order.bind_game_channel = _text(channel, max_length=128) - order.bind_snapshot_at = order.bind_snapshot_at or _now() + if overwrite or not order.bind_snapshot_at: + order.bind_snapshot_at = _now() def _apply_platform_fulfillment_status( @@ -855,12 +859,19 @@ def sync_platform_fulfillment_order( order.gift_name = gift_name order.commodity_id = commodity_id order.required_points = required_points - if account is not None: + if account is not None and ( + created or (order.account_id is None and not order.account_username) + ): 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_binding( + db, + order, + task, + overwrite=created, + ) _apply_platform_fulfillment_status(order, task, created=created) order.version = int(order.version or 0) + 1 db.flush() @@ -871,11 +882,16 @@ def sync_platform_fulfillment_order( "created": created, "status": order.status, } - if account is not None: + linked_account = ( + db.query(Account).filter(Account.id == order.account_id).first() + if order.account_id + else None + ) + if linked_account is not None: record_account_action( db, current, - account=account, + account=linked_account, action="douyu:collab:sync_from_platform_fulfillment", event_type=EVENT_COLLAB_SYNCED, title=f"同步外部单协作:{order.order_no}", diff --git a/web/backend/services/platform_fulfillment/service.py b/web/backend/services/platform_fulfillment/service.py index 6a15c8f..1851584 100644 --- a/web/backend/services/platform_fulfillment/service.py +++ b/web/backend/services/platform_fulfillment/service.py @@ -2383,6 +2383,21 @@ def restore_cancelled_task( if len(restore_reason) < 2: raise HTTPException(status_code=400, detail="请填写恢复原因") + restored_collab = ( + db.query(DouyuExternalOrder) + .filter(DouyuExternalOrder.source_task_id == task.id) + .first() + ) + if restored_collab is not None and ( + restored_collab.status not in {"incomplete", "void"} + or restored_collab.bind_game_role + or restored_collab.home_images + ): + raise HTTPException( + status_code=409, + detail="关联外部协作单已在人工处理,请继续使用外部协作单", + ) + mapping = _mapping_for_sku(db, task.internal_sku_key) _apply_mapping(task, mapping) task.account_id = None @@ -2396,11 +2411,6 @@ def restore_cancelled_task( 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" @@ -2430,6 +2440,55 @@ def restore_cancelled_task( return get_task_detail(db, task.id) +def release_task_to_manual( + db: Session, + *, + task_id: int, + current: User, + reason: str, +) -> dict[str, Any]: + """释放履约账号并转人工,不再进入自动选号。""" + task = _load_task(db, task_id) + if task.execution_status in {"completed", "cancelled"}: + raise HTTPException(status_code=409, detail="已结束任务不能转人工") + manual_reason = reason.strip()[:2000] or "以外部单协作人工处理为准" + account_id = task.account_id + lease_id = task.lease_id + lease = ( + db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() + if task.lease_id + else None + ) + release_lease(db, lease, reason="platform_fulfillment_manual") + task.account_id = None + task.lease_id = None + task.bind_task_id = None + task.exchange_task_id = None + task.execution_status = "manual_required" + task.binding_status = "not_started" + task.exchange_status = "not_started" + task.issue_code = "manual_required" + task.next_allocate_at = None + task.operator_id = current.id + task.last_error = manual_reason + task.updated_at = _now() + _append_event( + db, + task.id, + "released_to_manual", + actor_type="user", + actor_id=current.id, + detail={ + "reason": manual_reason, + "releasedAccountId": account_id, + "releasedLeaseId": lease_id, + }, + ) + _emit_order_site_binding_state(db, task.id) + db.commit() + return get_task_detail(db, task.id) + + __all__ = [ "allocate_task", "cancel_task", @@ -2444,6 +2503,7 @@ __all__ = [ "refresh_binding", "refresh_exchange_eligibility", "release_task_account", + "release_task_to_manual", "reset_task_binding", "restore_cancelled_task", "start_binding", diff --git a/web/frontend/src/api/platformFulfillment.ts b/web/frontend/src/api/platformFulfillment.ts index 9a0b084..b4a4f72 100644 --- a/web/frontend/src/api/platformFulfillment.ts +++ b/web/frontend/src/api/platformFulfillment.ts @@ -98,6 +98,11 @@ export const platformFulfillmentApi = { api.post( `/platform-fulfillment/tasks/${taskId}/release`, ), + releaseToManual: (taskId: number, reason: string) => + api.post( + `/platform-fulfillment/tasks/${taskId}/release-manual`, + { reason }, + ), markManual: (taskId: number, reason = '') => api.post( `/platform-fulfillment/tasks/${taskId}/manual`, diff --git a/web/frontend/src/pages/PlatformFulfillmentPage.tsx b/web/frontend/src/pages/PlatformFulfillmentPage.tsx index acee6fb..d2e318d 100644 --- a/web/frontend/src/pages/PlatformFulfillmentPage.tsx +++ b/web/frontend/src/pages/PlatformFulfillmentPage.tsx @@ -96,6 +96,7 @@ const EVENT_LABELS: Record = { exchange_eligibility_checked: '刷新兑换资格', manual_exchange_completed: '人工兑换完成', marked_manual_required: '转人工处理', + released_to_manual: '释放账号并转人工', task_cancelled: '任务已取消', task_restored: '恢复已取消任务', }; @@ -185,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('manual_required') || value.includes('released_to_manual')) return 'orange'; if (value.includes('completed') || value.includes('allocated') || value.includes('restored')) return 'green'; return 'blue'; } @@ -225,6 +226,9 @@ function eventDescription(event: { eventType: string; detail: Record(null); const [restoreReason, setRestoreReason] = useState(''); const [restoring, setRestoring] = useState(false); + const [manualReleaseTarget, setManualReleaseTarget] = useState(null); + const [manualReleaseReason, setManualReleaseReason] = useState(''); + const [manualReleasing, setManualReleasing] = useState(false); const [selectedRowKeys, setSelectedRowKeys] = useState([]); const [selectedId, setSelectedId] = useState(null); const [detail, setDetail] = useState(null); @@ -535,6 +542,32 @@ export default function PlatformFulfillmentPage() { } }; + const releaseTaskToManual = async () => { + if (!manualReleaseTarget) return; + const reason = manualReleaseReason.trim(); + if (reason.length < 2) { + message.warning('请填写转人工原因'); + return; + } + setManualReleasing(true); + try { + const result = await platformFulfillmentApi.releaseToManual( + manualReleaseTarget.id, + reason, + ); + setDetail(result); + setSelectedId(result.task.id); + setManualReleaseTarget(null); + setManualReleaseReason(''); + await loadTasks(); + message.success('账号已释放,任务已转人工处理'); + } catch (error) { + message.error(getErrorMessage(error)); + } finally { + setManualReleasing(false); + } + }; + const runDouyuAccountAction = async (taskType: string) => { if (!selected?.account) { message.warning('当前履约任务还没有分配斗鱼账号'); @@ -892,7 +925,25 @@ export default function PlatformFulfillmentPage() { 查看二维码 ) : null} - {selected.account ? : null} + {selected.account ? ( + + ) : null} + {selected.account && + selected.executionStatus !== 'completed' && + selected.executionStatus !== 'cancelled' && + can('platform_fulfillment:use') ? ( + + ) : null} {canResetBinding(selected) ? (