From 8ba6379687e6f126bbfc149128df1fb1bebbe8de Mon Sep 17 00:00:00 2001 From: yml Date: Tue, 17 Nov 2026 21:51:05 +0800 Subject: [PATCH] =?UTF-8?q?feat(fulfillment):=20=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E9=80=89=E5=8F=B7=E5=B9=B6=E8=A1=A5=E5=85=85=E7=B2=BE=E8=8B=B1?= =?UTF-8?q?=E5=AE=9D=E5=85=B8=E6=93=8D=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 增加直播履约自动选号 worker、重试与任务扫描 - 履约详情复用斗鱼任务能力开通宝典、充值和兑换皮肤 - 补充自动选号与精英宝典操作测试 --- tests/test_platform_fulfillment.py | 62 ++++++ ...est_platform_fulfillment_auto_allocator.py | 56 +++++ web/backend/main.py | 6 + .../platform_fulfillment/auto_allocator.py | 139 ++++++++++++ .../services/platform_fulfillment/service.py | 37 +++- .../src/pages/PlatformFulfillmentPage.tsx | 207 +++++++++++++++++- 6 files changed, 501 insertions(+), 6 deletions(-) create mode 100644 tests/test_platform_fulfillment_auto_allocator.py create mode 100644 web/backend/services/platform_fulfillment/auto_allocator.py diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index 943c0ad..8fb8187 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -524,6 +524,68 @@ class TestBindingAndCompletion(_Base): assert detail["task"]["issueCode"] == "" assert detail["task"]["lastError"] == "" + def test_refresh_binding_classifies_customer_role_cooldown(self): + task = self._allocated() + bind_task = DouyuTask( + batch_id="bind-customer-cooldown", + account_id=task.account_id, + account_assigned_to=self.admin_id, + task_type="confirm_bind", + handbook_scope="elite", + status="failed", + message="待绑定游戏账号(测试角色)未到换绑时间,请重新换账号扫码绑定", + result={ + "bind_phase": "confirm_failed", + "role_name": "测试角色", + "bind_ready_for_confirm": True, + "bind_confirmed": False, + }, + created_by=self.admin_id, + ) + self.session.add(bind_task) + self.session.flush() + task.bind_task_id = bind_task.id + task.binding_status = "role_ready" + task.execution_status = "role_ready" + self.session.commit() + + detail = service.refresh_binding(self.session, task_id=task.id) + + assert detail["task"]["issueCode"] == "customer_role_cooldown" + assert detail["task"]["bindingStatus"] == "failed" + assert detail["task"]["executionStatus"] == "manual_required" + assert "截图" in detail["task"]["lastError"] + assert "联系客服" in detail["task"]["lastError"] + + def test_refresh_binding_classifies_account_role_cooldown(self): + task = self._allocated() + bind_task = DouyuTask( + batch_id="bind-account-cooldown", + account_id=task.account_id, + account_assigned_to=self.admin_id, + task_type="get_bind_qr", + handbook_scope="elite", + status="failed", + message="当前角色 暂不能换绑,剩余 3天", + result={ + "bind_phase": "change_waiting", + "change_role_wait_time": 259200, + }, + created_by=self.admin_id, + ) + self.session.add(bind_task) + self.session.flush() + task.bind_task_id = bind_task.id + task.binding_status = "preparing" + task.execution_status = "waiting_bind" + self.session.commit() + + detail = service.refresh_binding(self.session, task_id=task.id) + + assert detail["task"]["issueCode"] == "account_role_cooldown" + assert detail["task"]["executionStatus"] == "manual_required" + assert "截图" in detail["task"]["lastError"] + def test_list_hides_qr_but_detail_returns_it(self): task = self._allocated() bind_task = DouyuTask( diff --git a/tests/test_platform_fulfillment_auto_allocator.py b/tests/test_platform_fulfillment_auto_allocator.py new file mode 100644 index 0000000..7b1f51b --- /dev/null +++ b/tests/test_platform_fulfillment_auto_allocator.py @@ -0,0 +1,56 @@ +"""直播账号履约自动选号 worker。""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta +from unittest.mock import patch + +from web.backend.models import PlatformFulfillmentTask, User +from web.backend.services.platform_fulfillment import auto_allocator + + +def test_auto_allocator_only_scans_ready_unassigned_tasks(db): + actor = User(username="auto-alloc-actor", password_hash="h", role="super_admin") + ready = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="1", + source_order_item_id="1", + platform_order_id="AUTO-1", + internal_sku_key="skin", + commodity_id="commodity-1", + execution_status="ready", + binding_status="not_started", + exchange_status="not_started", + updated_at=datetime.now(UTC) - timedelta(minutes=2), + ) + mapped_pending = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="2", + source_order_item_id="2", + platform_order_id="AUTO-2", + internal_sku_key="skin", + commodity_id="commodity-1", + execution_status="pending_mapping", + binding_status="not_started", + exchange_status="not_started", + updated_at=datetime.now(UTC) - timedelta(minutes=2), + ) + db.add_all([actor, ready, mapped_pending]) + db.commit() + + calls: list[int] = [] + with ( + patch.object(auto_allocator.service, "_integration_actor", return_value=actor), + patch.object( + auto_allocator.service, + "allocate_task", + side_effect=lambda _db, *, task_id, current: ( + calls.append(task_id) + or {"task": {"account": {"id": 9}}} + ), + ), + ): + result = auto_allocator.run_auto_allocation_once(db, limit=10) + + assert calls == [ready.id] + assert result == {"checked": 1, "allocated": 1, "failed": 0} diff --git a/web/backend/main.py b/web/backend/main.py index 4739f27..85885a8 100644 --- a/web/backend/main.py +++ b/web/backend/main.py @@ -105,6 +105,10 @@ async def lifespan(app: FastAPI): start_integration_outbox_worker, stop_integration_outbox_worker, ) + from .services.platform_fulfillment.auto_allocator import ( + start_platform_fulfillment_auto_allocator, + stop_platform_fulfillment_auto_allocator, + ) from .services.platform_fulfillment.reconciler import ( start_platform_fulfillment_reconciler, stop_platform_fulfillment_reconciler, @@ -112,9 +116,11 @@ async def lifespan(app: FastAPI): start_integration_outbox_worker() start_platform_fulfillment_reconciler() + start_platform_fulfillment_auto_allocator() try: yield finally: + stop_platform_fulfillment_auto_allocator() stop_platform_fulfillment_reconciler() stop_integration_outbox_worker() stop_scheduler() diff --git a/web/backend/services/platform_fulfillment/auto_allocator.py b/web/backend/services/platform_fulfillment/auto_allocator.py new file mode 100644 index 0000000..7b52dc8 --- /dev/null +++ b/web/backend/services/platform_fulfillment/auto_allocator.py @@ -0,0 +1,139 @@ +"""自动为待处理直播账号履约任务选号;异常任务保留给人工处理。""" + +from __future__ import annotations + +import os +import threading +from datetime import UTC, datetime, timedelta +from typing import Any + +from loguru import logger +from sqlalchemy.orm import Session + +from ...database import SessionLocal +from ...models import PlatformFulfillmentTask +from . import service + +DEFAULT_INTERVAL_SECONDS = 20 +DEFAULT_BATCH_SIZE = 2 +DEFAULT_RETRY_SECONDS = 45 + +_stop_event = threading.Event() +_thread: threading.Thread | None = None +_lock = threading.Lock() + + +def _env_int(name: str, default: int, minimum: int, maximum: int) -> int: + try: + value = int(os.getenv(name, str(default))) + except ValueError: + return default + return max(minimum, min(maximum, value)) + + +def run_auto_allocation_once( + db: Session, + *, + limit: int | None = None, + now: datetime | None = None, +) -> dict[str, int]: + """扫描 ready 且尚未分配账号的任务,逐笔调用统一选号逻辑。""" + moment = now or datetime.now(UTC) + batch_size = limit or _env_int( + "PLATFORM_FULFILLMENT_AUTO_ALLOCATE_BATCH", + DEFAULT_BATCH_SIZE, + 1, + 20, + ) + retry_seconds = _env_int( + "PLATFORM_FULFILLMENT_AUTO_ALLOCATE_RETRY_SECONDS", + DEFAULT_RETRY_SECONDS, + 10, + 3600, + ) + candidates = ( + db.query(PlatformFulfillmentTask) + .filter( + PlatformFulfillmentTask.execution_status == "ready", + PlatformFulfillmentTask.account_id.is_(None), + PlatformFulfillmentTask.commodity_id != "", + PlatformFulfillmentTask.updated_at + <= moment - timedelta(seconds=retry_seconds), + ) + .order_by(PlatformFulfillmentTask.updated_at.asc()) + .limit(batch_size) + .all() + ) + if not candidates: + return {"checked": 0, "allocated": 0, "failed": 0} + + actor = service._integration_actor(db) + allocated = 0 + failed = 0 + for task in candidates: + try: + detail: dict[str, Any] = service.allocate_task( + db, + task_id=int(task.id), + current=actor, + ) + if detail.get("task", {}).get("account"): + allocated += 1 + else: + failed += 1 + except Exception as exc: # noqa: BLE001 - 单个任务异常不能中断整批 + db.rollback() + failed += 1 + logger.warning( + "直播账号履约自动选号失败 task_id={}: {}", task.id, exc + ) + return { + "checked": len(candidates), + "allocated": allocated, + "failed": failed, + } + + +def _run() -> None: + interval = _env_int( + "PLATFORM_FULFILLMENT_AUTO_ALLOCATE_SECONDS", + DEFAULT_INTERVAL_SECONDS, + 5, + 3600, + ) + while not _stop_event.wait(interval): + db = SessionLocal() + try: + result = run_auto_allocation_once(db) + if result["checked"]: + logger.info("直播账号履约自动选号: {}", result) + except Exception as exc: # noqa: BLE001 - worker 不能因单轮异常退出 + db.rollback() + logger.warning("直播账号履约自动选号轮次失败: {}", exc) + finally: + db.close() + + +def start_platform_fulfillment_auto_allocator() -> bool: + global _thread + with _lock: + if _thread is not None and _thread.is_alive(): + return False + _stop_event.clear() + _thread = threading.Thread( + target=_run, + name="platform-fulfillment-auto-allocator", + daemon=True, + ) + _thread.start() + return True + + +def stop_platform_fulfillment_auto_allocator() -> None: + global _thread + _stop_event.set() + with _lock: + thread = _thread + _thread = None + if thread is not None and thread.is_alive(): + thread.join(timeout=3) diff --git a/web/backend/services/platform_fulfillment/service.py b/web/backend/services/platform_fulfillment/service.py index 326c05d..db8d669 100644 --- a/web/backend/services/platform_fulfillment/service.py +++ b/web/backend/services/platform_fulfillment/service.py @@ -560,12 +560,30 @@ def _customer_task_message(task: PlatformFulfillmentTask) -> str: "points_short": "账号正在补充积分,请稍后重试", "commodity_limit_reached": "当前商品暂时无法兑换,请联系客服", "binding_failed": "暂未识别到绑定角色,请继续使用当前二维码完成扫码", + "account_role_cooldown": "当前绑定账号暂不可换绑,请截图本页面并联系客服处理", + "customer_role_cooldown": "该游戏角色仍在换绑冷却期,请截图本页面并联系客服处理", "eligibility_check_failed": "状态查询异常,请稍后刷新", "manual_required": "当前需要人工处理,请联系客服", } return messages.get(task.issue_code, "") if task.issue_code else "" +def _binding_failure_issue(bind_task: DouyuTask, result: dict[str, Any]) -> str: + phase = str(result.get("bind_phase") or "") + message = str(bind_task.message or "") + if phase == "change_waiting" or "暂不能换绑" in message: + task_issue = "account_role_cooldown" + elif phase == "confirm_failed" or "待绑定游戏账号" in message or "未到换绑时间" in message: + task_issue = "customer_role_cooldown" + else: + return "binding_failed" + messages = { + "account_role_cooldown": "当前绑定账号暂不可换绑,请截图本页面并联系客服处理", + "customer_role_cooldown": "该游戏角色仍在换绑冷却期,请截图本页面并联系客服处理", + } + return task_issue if messages.get(task_issue) else "binding_failed" + + def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]: """面向前端客户页的安全绑定快照,不包含账号、CK、积分和租约。""" task = _load_task(db, task_id) @@ -1093,8 +1111,8 @@ def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]: if bind_task.status in {"failed", "error", "stopped"}: task.binding_status = "failed" task.execution_status = "manual_required" - task.issue_code = "binding_failed" - task.last_error = bind_task.message or "绑定任务失败" + task.issue_code = _binding_failure_issue(bind_task, result) + task.last_error = _customer_task_message(task) elif bool(result.get("bind_confirmed")): task.binding_status = "bound" task.execution_status = "bound" @@ -1119,6 +1137,21 @@ def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]: ) if after != before: task.updated_at = _now() + if task.issue_code in { + "account_role_cooldown", + "customer_role_cooldown", + }: + _append_event( + db, + task.id, + "binding_failed", + detail={ + "issueCode": task.issue_code, + "bindTaskId": bind_task.id, + "bindPhase": str(result.get("bind_phase") or ""), + "rawError": str(bind_task.message or "")[:1000], + }, + ) _emit_order_site_binding_state(db, task.id) db.commit() return get_task_detail(db, task.id) diff --git a/web/frontend/src/pages/PlatformFulfillmentPage.tsx b/web/frontend/src/pages/PlatformFulfillmentPage.tsx index fe1cb78..5d47e61 100644 --- a/web/frontend/src/pages/PlatformFulfillmentPage.tsx +++ b/web/frontend/src/pages/PlatformFulfillmentPage.tsx @@ -1,9 +1,11 @@ import { useCallback, useEffect, useState } from 'react'; import { Alert, Button, Card, Descriptions, Drawer, Empty, Input, InputNumber, Modal, QRCode, Segmented, Select, Space, Switch, Table, Tabs, Tag, Timeline, Typography } from 'antd'; -import { CheckCircleOutlined, CopyOutlined, LinkOutlined, QrcodeOutlined, ReloadOutlined, SettingOutlined, SyncOutlined, UserSwitchOutlined } from '@ant-design/icons'; +import { CheckCircleOutlined, CopyOutlined, CreditCardOutlined, GiftOutlined, LinkOutlined, QrcodeOutlined, ReloadOutlined, SettingOutlined, ShoppingOutlined, SyncOutlined, UserSwitchOutlined } from '@ant-design/icons'; import type { ColumnsType } from 'antd/es/table'; import { douyuApi, platformFulfillmentApi } from '../api/modules'; -import type { DouyuGoodsItem, PlatformFulfillmentDetail, PlatformFulfillmentMapping, PlatformFulfillmentSettings, PlatformFulfillmentTask } from '../api/modules'; +import type { DouyuGoodsItem, DouyuTaskItem, PlatformFulfillmentDetail, PlatformFulfillmentMapping, PlatformFulfillmentSettings, PlatformFulfillmentTask } from '../api/modules'; +import ExchangeResultImage from '../components/ExchangeResultImage'; +import { TASK_STATUS_COLORS, TASK_STATUS_LABELS, taskQrUrl } from './douyu-tasks/config'; import { getErrorMessage } from '../utils/error'; import { message } from '../utils/antdMessage'; import { formatTime } from '../utils/time'; @@ -73,6 +75,7 @@ const EVENT_LABELS: Record = { account_released: '释放履约账号', binding_started: '开始绑定游戏角色', binding_confirm_started: '提交角色绑定确认', + binding_failed: '游戏角色绑定失败', eligibility_check_failed: '兑换资格查询失败', exchange_eligibility_checked: '刷新兑换资格', manual_exchange_completed: '人工兑换完成', @@ -88,10 +91,20 @@ const ISSUE_LABELS: Record = { commodity_limit_reached: '商品已达限兑上限', eligibility_check_failed: '资格查询失败', binding_failed: '绑定失败', + account_role_cooldown: '斗鱼账号仍在换绑冷却期', + customer_role_cooldown: '游戏角色仍在换绑冷却期', lease_expired: '账号租约已过期', manual_required: '需要人工处理', }; +const DOUYU_ACTION_LABELS: Record = { + query_elite_status: '查询精英宝典', + create_elite_qr: '开通精英宝典', + create_gold_qr: '充值鱼翅', + donate_elite_gift: '赠送精英令', + exchange_goods: '兑换订单皮肤', +}; + function statusLabel(value: string) { return STATUS_OPTIONS.find((item) => item.value === value)?.label || value; } @@ -195,6 +208,9 @@ function eventDescription(event: { eventType: string; detail: Record('unlimited'); const [leaseDurationValue, setLeaseDurationValue] = useState(60); const [savingSettings, setSavingSettings] = useState(false); + const [douyuActionLoading, setDouyuActionLoading] = useState(''); + const [douyuActionType, setDouyuActionType] = useState(''); + const [douyuActionBatchId, setDouyuActionBatchId] = useState(''); + const [douyuActionTask, setDouyuActionTask] = useState(null); + const [goldAmount, setGoldAmount] = useState(30); + const [giftCount, setGiftCount] = useState(1); const loadTasks = useCallback(async (silent = false) => { if (!silent) setLoading(true); @@ -302,8 +324,30 @@ export default function PlatformFulfillmentPage() { return () => window.clearInterval(timer); }, [loadDetail, selectedId]); + useEffect(() => { + if (!douyuActionBatchId) return; + let stopped = false; + const loadActionTask = async () => { + try { + const items = await douyuApi.listTasks('elite', douyuActionBatchId); + if (!stopped) setDouyuActionTask(items[0] || null); + } catch { + // 保持当前任务快照,下一轮继续。 + } + }; + void loadActionTask(); + const timer = window.setInterval(() => { + if (document.visibilityState === 'visible') void loadActionTask(); + }, 2000); + return () => { + stopped = true; + window.clearInterval(timer); + }; + }, [douyuActionBatchId]); + const selected = detail?.task || null; const qrValue = selected?.bindTask?.qrUrl || ''; + const douyuActionQrValue = douyuActionTask ? taskQrUrl(douyuActionTask) : ''; useEffect(() => { if (qrValue) setQrOpen(true); @@ -334,6 +378,51 @@ export default function PlatformFulfillmentPage() { } }; + const runDouyuAccountAction = async (taskType: string) => { + if (!selected?.account) { + message.warning('当前履约任务还没有分配斗鱼账号'); + return; + } + if (!can('douyu:task')) { + message.warning('当前账号没有斗鱼任务执行权限'); + return; + } + if (taskType === 'exchange_goods' && !selected.commodityId) { + message.warning('当前订单还没有配置斗鱼商品映射'); + return; + } + const payload: Record = {}; + if (taskType === 'create_gold_qr') payload.amount = Math.max(1, Number(goldAmount) || 1); + if (taskType === 'donate_elite_gift') payload.gift_count = Math.max(1, Number(giftCount) || 1); + if (taskType === 'exchange_goods') payload.commodity_id = selected.commodityId; + + setDouyuActionLoading(taskType); + setDouyuActionTask(null); + try { + const result = await douyuApi.createTasks({ + account_ids: [selected.account.id], + task_type: taskType, + handbook_scope: 'elite', + concurrency: 1, + payload, + }); + setDouyuActionType(taskType); + setDouyuActionBatchId(result.batch_id); + message.success(`${DOUYU_ACTION_LABELS[taskType] || '斗鱼任务'}已提交`); + } catch (error) { + message.error(getErrorMessage(error)); + } finally { + setDouyuActionLoading(''); + } + }; + + const closeDouyuAction = () => { + setDouyuActionBatchId(''); + setDouyuActionTask(null); + if (selectedId) void loadDetail(selectedId, true); + void loadTasks(); + }; + const openMapping = async (task?: PlatformFulfillmentTask) => { setMappingSku(task?.internalSkuKey || ''); setMappingGoodsId(task?.commodityId || ''); @@ -536,7 +625,7 @@ export default function PlatformFulfillmentPage() { ) : null} {task.executionStatus === 'ready' ? ( ) : null} {task.executionStatus === 'allocated' ? ( @@ -593,7 +682,7 @@ export default function PlatformFulfillmentPage() { 直播账号履约工作台 - 读取 order_site 人工订单,客户扫码绑定游戏角色,运营使用斗鱼账号人工兑换。 + 系统自动检测账号并选号;只有缺货、CK 异常或资格失败时转人工处理。客户扫码绑定后,运营可直接开通宝典、充值或兑换皮肤。 账号租约:{leaseDurationLabel(settings?.leaseDurationMinutes)} @@ -759,6 +848,85 @@ export default function PlatformFulfillmentPage() { + + + + 直接复用斗鱼精英宝典工作台任务,作用于当前履约账号;开通和充值会在任务窗口展示支付二维码。 + + + + + + + + setGoldAmount(Number(value) || 1)} + addonBefore="鱼翅" + style={{ width: 150 }} + /> + + + + setGiftCount(Number(value) || 1)} + addonBefore="数量" + style={{ width: 130 }} + /> + + + + + + + {actionButtons} @@ -789,6 +957,37 @@ export default function PlatformFulfillmentPage() { )} + + 关闭 + + } + onCancel={closeDouyuAction} + width={520} + > + + {douyuActionTask ? ( + <> + + {TASK_STATUS_LABELS[douyuActionTask.status] || douyuActionTask.status} + + {douyuActionTask.message || '任务执行中'} + {douyuActionQrValue ? ( + + ) : null} + {douyuActionType === 'exchange_goods' && douyuActionTask.status === 'success' ? ( + + ) : null} + + ) : ( + 任务已提交,正在等待斗鱼执行器返回结果... + )} + + + setQrOpen(false)}> {qrValue ? : null}