diff --git a/tests/test_douyu_payment_sessions.py b/tests/test_douyu_payment_sessions.py index 38d6a19..26b1ec9 100644 --- a/tests/test_douyu_payment_sessions.py +++ b/tests/test_douyu_payment_sessions.py @@ -1,11 +1,15 @@ +from datetime import UTC, datetime, timedelta + import pytest from fastapi import HTTPException from web.backend.models import Account, DouyuTask, User -from web.backend.routers.douyu import _require_batch_owner +from web.backend.routers.douyu import _prepare_task_batch, _require_batch_owner +from web.backend.schemas import DouyuTaskBatchRequest from web.backend.services.douyu_service import ( DouyuActivePaymentError, create_douyu_planned_tasks, + find_reusable_active_payment_task, ) @@ -144,3 +148,96 @@ def test_operation_cannot_stop_another_users_batch(db): assert exc_info.value.status_code == 403 _require_batch_owner(db, admin, batch_id) + + +def test_reuse_active_payment_reopens_unexpired_qr_and_skips_expired(db): + owner = _user(db, "payment-reopen-owner") + other = _user(db, "payment-reopen-other") + account = _account(db, "payment-reopen-acc") + db.commit() + + first = _prepare_task_batch( + DouyuTaskBatchRequest( + account_ids=[account.id], + task_type="create_elite_qr", + handbook_scope="elite", + reuse_active_payment=True, + ), + db, + owner, + ) + assert first["success"] is True + assert first.get("reused") is not True + + task = db.query(DouyuTask).filter(DouyuTask.batch_id == first["batch_id"]).one() + task.status = "running" + task.run_deadline_at = datetime.now(UTC) + timedelta(minutes=5) + task.result = {"pay_url": "https://pay.example.test/elite-qr"} + db.commit() + + reopened = _prepare_task_batch( + DouyuTaskBatchRequest( + account_ids=[account.id], + task_type="create_elite_qr", + handbook_scope="elite", + reuse_active_payment=True, + ), + db, + other, + ) + assert reopened["batch_id"] == first["batch_id"] + assert reopened["reused"] is True + assert reopened["count"] == 1 + assert db.query(DouyuTask).filter(DouyuTask.account_id == account.id).count() == 1 + + # 过期后的任务不再被复用 + task.run_deadline_at = datetime.now(UTC) - timedelta(seconds=10) + db.commit() + assert ( + find_reusable_active_payment_task( + db, + account.id, + task_type="create_elite_qr", + handbook_scope="elite", + ) + is None + ) + + # 鱼翅二维码按金额严格区分:同金额复用,不同金额不复用 + task.status = "stopped" + db.commit() + gold_first = _prepare_task_batch( + DouyuTaskBatchRequest( + account_ids=[account.id], + task_type="create_gold_qr", + handbook_scope="elite", + payload={"amount": 30}, + reuse_active_payment=True, + ), + db, + owner, + ) + gold_same = _prepare_task_batch( + DouyuTaskBatchRequest( + account_ids=[account.id], + task_type="create_gold_qr", + handbook_scope="elite", + payload={"amount": 30}, + reuse_active_payment=True, + ), + db, + owner, + ) + assert gold_same["batch_id"] == gold_first["batch_id"] + assert gold_same["reused"] is True + assert ( + find_reusable_active_payment_task( + db, + account.id, + task_type="create_gold_qr", + handbook_scope="elite", + recharge_channel="wechat_qr", + recharge_amount=60, + ) + is None + ) diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index d738724..5ee9e59 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -6908,3 +6908,24 @@ class TestAllocationPolicyAndSameRoleReuse(_Base): assert result["orphan_released"] == 1 assert orphan_lease.status == "released" assert shared_lease.status == "active" + + def test_manual_reason_preserves_specific_issue_codes(self): + task = self._create_commodity_task( + commodity_id=COMMODITY, + order_suffix="reason-1", + required_points=1280, + ) + task.execution_status = "manual_required" + task.binding_status = "failed" + for issue in ( + "customer_role_cooldown", + "account_role_cooldown", + "customer_role_bound_elsewhere", + "account_role_bound_elsewhere", + "role_changed", + "lease_expired", + ): + task.issue_code = issue + self.session.commit() + detail = service.get_task_detail(self.session, task.id) + assert detail["task"]["manualReason"] == issue diff --git a/web/backend/routers/douyu.py b/web/backend/routers/douyu.py index cf41330..13e5c53 100644 --- a/web/backend/routers/douyu.py +++ b/web/backend/routers/douyu.py @@ -118,6 +118,7 @@ from ..services.douyu_service import ( douyu_config_value, douyu_task_payload, ensure_douyu_config, + find_reusable_active_payment_task, visible_douyu_task_accounts, ) from ..services.execution_jobs import ( @@ -439,9 +440,7 @@ def _list_visible_tasks_for_admin( if batch_id: base_query = base_query.filter(DouyuTask.batch_id == batch_id) if account_scope_query is not None: - base_query = base_query.filter( - DouyuTask.account_id.in_(account_scope_query) - ) + base_query = base_query.filter(DouyuTask.account_id.in_(account_scope_query)) for query in _split_task_scope_query(base_query, handbook_scope): rows = query.order_by(DouyuTask.id.desc()).limit(take).all() task_ids.extend(int(row[0]) for row in rows) @@ -695,7 +694,9 @@ def _account_out(account: Account) -> DouyuTaskAccountOut: esports_change_role_wait_time=( account.esports_change_role_wait_time if esports_cooldown else 0 ), - esports_can_change_time=account.esports_can_change_time if esports_cooldown else None, + esports_can_change_time=account.esports_can_change_time + if esports_cooldown + else None, xpd_game_name=account.xpd_game_name or "", xpd_openid=account.xpd_openid or "", xpd_role_id=account.xpd_role_id or "", @@ -741,9 +742,7 @@ def _config_out(config: DouyuConfig) -> DouyuConfigOut: gold_recharge_channel=text("gold_recharge_channel"), gold_api_product_id=text("gold_api_product_id"), gold_api_account_template_name=text("gold_api_account_template_name"), - recharge_duplicate_confirm_minutes=number( - "recharge_duplicate_confirm_minutes" - ), + recharge_duplicate_confirm_minutes=number("recharge_duplicate_confirm_minutes"), gold_api_max_amount=number("gold_api_max_amount"), gift_id=text("gift_id"), skin_id=text("skin_id"), @@ -1351,8 +1350,7 @@ def _api_recharge_duplicate_guard( confirmation = ( db.query(DouyuRechargeConfirmation) .filter( - DouyuRechargeConfirmation.token - == req.recharge_confirmation_token, + DouyuRechargeConfirmation.token == req.recharge_confirmation_token, ) .with_for_update() .first() @@ -1411,9 +1409,7 @@ def _api_recharge_duplicate_guard( ) if not previous: return None - duplicate_account_ids = { - int(task.account_id) for task in previous - } + duplicate_account_ids = {int(task.account_id) for task in previous} account_rows = ( db.query(Account) .filter(Account.id.in_(duplicate_account_ids)) @@ -1432,8 +1428,7 @@ def _api_recharge_duplicate_guard( ) db.commit() names = [ - row.nickname or row.username or row.uid or f"#{row.id}" - for row in account_rows + row.nickname or row.username or row.uid or f"#{row.id}" for row in account_rows ] return { "batch_id": "", @@ -1517,9 +1512,31 @@ def _prepare_task_batch( else None ) if ( - req.task_type == "create_gold_qr" - and recharge_channel == "supplier_api" + req.reuse_active_payment + and len(req.account_ids) == 1 + and req.task_type in {"create_elite_qr", "create_esports_qr", "create_gold_qr"} + and not ( + req.task_type == "create_gold_qr" and recharge_channel == "supplier_api" + ) ): + reusable = find_reusable_active_payment_task( + db, + int(req.account_ids[0]), + task_type=req.task_type, + handbook_scope=req.handbook_scope, + recharge_channel=recharge_channel, + recharge_amount=recharge_amount, + ) + if reusable is not None: + return { + "batch_id": reusable.batch_id, + "count": 1, + "success": True, + "reused": True, + "message": "当前已有未过期的支付二维码,已重新打开", + } + + if req.task_type == "create_gold_qr" and recharge_channel == "supplier_api": guard = _api_recharge_duplicate_guard( db, req=req, @@ -1574,8 +1591,7 @@ def _prepare_task_batch( ): visible_accounts = visible_douyu_task_accounts(db, req.account_ids) inspections = [ - workbench_force_goods_inspection(db, acc) - for acc in visible_accounts + workbench_force_goods_inspection(db, acc) for acc in visible_accounts ] occupied_items = [item for item in inspections if item["occupied"]] blocked = next( @@ -1632,7 +1648,9 @@ def _prepare_task_batch( ) forced_pf_details: list[dict[str, Any]] = [] for douyu_task, account in forced_rows: - result_data = douyu_task.result if isinstance(douyu_task.result, dict) else {} + result_data = ( + douyu_task.result if isinstance(douyu_task.result, dict) else {} + ) raw_payload = result_data.get("payload") payload_meta = raw_payload if isinstance(raw_payload, dict) else {} pf_task_id = payload_meta.get("force_platform_task_id") @@ -1779,13 +1797,12 @@ def list_tasks( account_scope_query: Select | None = None if workbench_only: if not handbook_scope: - raise HTTPException(status_code=400, detail="工作台任务查询必须指定手册类型") - account_scope_query = ( - select(DouyuWorkbenchAccount.account_id) - .where( - DouyuWorkbenchAccount.user_id == current.id, - DouyuWorkbenchAccount.handbook_scope == handbook_scope, + raise HTTPException( + status_code=400, detail="工作台任务查询必须指定手册类型" ) + account_scope_query = select(DouyuWorkbenchAccount.account_id).where( + DouyuWorkbenchAccount.user_id == current.id, + DouyuWorkbenchAccount.handbook_scope == handbook_scope, ) if _can_view_all(current): @@ -2083,16 +2100,12 @@ async def ws_douyu_logs(websocket: WebSocket, batch_id: str): return continue if job is None or job.status in TERMINAL_STATUSES: - await websocket.send_json( - {"level": "result", "message": "批次已结束"} - ) + await websocket.send_json({"level": "result", "message": "批次已结束"}) return await asyncio.sleep(0.5) idle_seconds += 0.5 if idle_seconds >= 30: - await websocket.send_json( - {"level": "heartbeat", "message": ""} - ) + await websocket.send_json({"level": "heartbeat", "message": ""}) idle_seconds = 0 log_queue: asyncio.Queue = batch["log_queue"] diff --git a/web/backend/schemas.py b/web/backend/schemas.py index 7434b8f..95c6b01 100644 --- a/web/backend/schemas.py +++ b/web/backend/schemas.py @@ -1893,6 +1893,7 @@ class DouyuTaskBatchRequest(BaseModel): platform_task_id: int | None = Field(None, gt=0) recharge_confirmation_token: str | None = Field(None, max_length=64) force_occupied: bool = False + reuse_active_payment: bool = False class DouyuWorkbenchAccountsUpdate(BaseModel): diff --git a/web/backend/services/douyu_service.py b/web/backend/services/douyu_service.py index 0d263ec..9eca097 100644 --- a/web/backend/services/douyu_service.py +++ b/web/backend/services/douyu_service.py @@ -336,6 +336,62 @@ def _lock_payment_accounts( ) +def find_reusable_active_payment_task( + db: Session, + account_id: int, + *, + task_type: str, + handbook_scope: str, + recharge_channel: str = "", + recharge_amount: int | None = None, +) -> DouyuTask | None: + """查找同账号当前未过期的同类型支付任务,用于关闭二维码弹窗后重新打开。""" + if task_type not in DOUYU_ACTIVE_PAYMENT_TASK_TYPES: + return None + if task_type == "create_gold_qr" and recharge_channel == "supplier_api": + return None + locked = ( + db.query(Account.id) + .filter(Account.id == int(account_id), cookie_holding_filter()) + .with_for_update() + .first() + ) + if locked is None: + return None + conflict = ( + db.query(DouyuTask) + .filter( + DouyuTask.account_id == int(account_id), + DouyuTask.status.in_(DOUYU_ACTIVE_TASK_STATUSES), + DouyuTask.task_type.in_(DOUYU_ACTIVE_PAYMENT_TASK_TYPES), + ) + .order_by(DouyuTask.id.desc()) + .with_for_update() + .first() + ) + if conflict is None: + return None + if ( + str(conflict.task_type or "") != task_type + or str(conflict.handbook_scope or "") != handbook_scope + ): + return None + if task_type == "create_gold_qr" and ( + str(conflict.recharge_channel or "") != str(recharge_channel or "") + or conflict.recharge_amount != recharge_amount + ): + return None + if conflict.run_deadline_at is not None: + deadline = ( + conflict.run_deadline_at + if conflict.run_deadline_at.tzinfo is not None + else conflict.run_deadline_at.replace(tzinfo=UTC) + ) + if deadline <= datetime.now(UTC): + return None + return conflict + + def update_account_profile_from_cookie(account: Account, cookie: str) -> None: """从 Cookie 回填 uid/nickname。""" from .douyu_account_probe import update_identity_from_cookie @@ -405,10 +461,7 @@ def create_douyu_planned_tasks( "force_expected_role": inspection["account_role"], "force_platform_task_id": inspection["platform_task_id"], } - if ( - task_type in {"refresh_esports_goods", "refresh_xpd_goods"} - and accounts - ): + if task_type in {"refresh_esports_goods", "refresh_xpd_goods"} and accounts: # 商品快照是全局数据,一个可用 CK 足够;没有 CK 时前端无法选账号创建任务。 accounts = accounts[:1] diff --git a/web/backend/services/platform_fulfillment/classification.py b/web/backend/services/platform_fulfillment/classification.py index 3d44c5f..69fe911 100644 --- a/web/backend/services/platform_fulfillment/classification.py +++ b/web/backend/services/platform_fulfillment/classification.py @@ -73,16 +73,10 @@ def manual_reason(issue_code: str, exchange_status: str) -> str: return "elite_not_opened" if issue == "commodity_limit_reached" or exchange == "limited": return "limit_reached" - if issue in { - "binding_failed", - "account_role_cooldown", - "customer_role_cooldown", - "customer_role_bound_elsewhere", - "account_role_bound_elsewhere", - }: - return "binding_failed" - if issue in {"lease_expired", "manual_required"}: - return "account_cooldown" + if issue and issue != "manual_required": + return issue + if issue == "manual_required": + return "manual_required" return "other_manual" diff --git a/web/frontend/src/api/types.ts b/web/frontend/src/api/types.ts index 67cc58c..8928884 100644 --- a/web/frontend/src/api/types.ts +++ b/web/frontend/src/api/types.ts @@ -1026,6 +1026,7 @@ export interface DouyuTaskBatchRequest { platform_task_id?: number; recharge_confirmation_token?: string; force_occupied?: boolean; + reuse_active_payment?: boolean; } export interface DouyuOccupiedForceCandidate { @@ -1050,6 +1051,7 @@ export interface DouyuTaskBatchResult { account_names?: string[]; requires_force_confirmation?: boolean; occupied_accounts?: DouyuOccupiedForceCandidate[]; + reused?: boolean; message?: string; } diff --git a/web/frontend/src/pages/PlatformFulfillmentPage.tsx b/web/frontend/src/pages/PlatformFulfillmentPage.tsx index 395f7e2..21e76fb 100644 --- a/web/frontend/src/pages/PlatformFulfillmentPage.tsx +++ b/web/frontend/src/pages/PlatformFulfillmentPage.tsx @@ -114,10 +114,21 @@ const SALE_MODE_LABELS: Record = { const MANUAL_REASON_LABELS: Record = { points_short: '积分不足', elite_not_opened: '宝典未开通', - limit_reached: '已达限兑', - binding_failed: '绑定异常', - account_cooldown: '账号冷却', - other_manual: '其他人工', + limit_reached: '已达限兑上限', + binding_failed: '未识别到绑定角色', + binding_verify_failed: '斗鱼绑定复核未通过', + account_role_cooldown: '斗鱼号换绑冷却期', + customer_role_cooldown: '买家绑定角色冷却期', + customer_role_bound_elsewhere: '买家角色7天内已绑其他斗鱼号', + account_role_bound_elsewhere: '斗鱼号7天内已绑其他角色', + role_changed: '扫码角色已失效需重扫', + lease_expired: '账号租约已过期', + lease_expired_collab_handoff: '租约到期已转台账', + account_cooldown: '账号冷却 / 租约过期', + eligibility_check_failed: '兑换资格查询失败', + bundle_co_eligibility_missing: '缺少联合皮肤全资格账号', + manual_required: '需要人工处理', + other_manual: '其他人工处理', }; const SALE_MODE_TAB_STORAGE_KEY = 'platform_fulfillment_sale_mode_tab'; @@ -197,7 +208,7 @@ const EVENT_LABELS: Record = { const ISSUE_LABELS: Record = { mapping_missing: '商品映射缺失', no_eligible_account: '没有可分配账号', - bundle_co_eligibility_missing: '没有同时可兑联合皮肤的账号', + bundle_co_eligibility_missing: '缺少联合皮肤全资格账号', capability_cache_miss: '账号商品能力待补货', account_lease_conflict: '候选账号正被其他任务占用', account_pool_busy: '资格账号暂时全部占用', @@ -210,13 +221,16 @@ const ISSUE_LABELS: Record = { commodity_not_offered: '商品当前未上架', commodity_status_unknown: '商品资格状态未知', commodity_not_exchangeable: '商品当前不可兑换', - eligibility_check_failed: '资格查询失败', - binding_failed: '绑定失败', - account_role_cooldown: '斗鱼账号仍在换绑冷却期', - customer_role_cooldown: '游戏角色仍在换绑冷却期', - customer_role_bound_elsewhere: '用户角色 7 天内已绑定其他斗鱼账号', - account_role_bound_elsewhere: '斗鱼账号 7 天内已绑定其他角色', + eligibility_check_failed: '兑换资格查询失败', + binding_failed: '未识别到绑定角色', + binding_verify_failed: '斗鱼绑定复核未通过', + account_role_cooldown: '斗鱼号换绑冷却期', + customer_role_cooldown: '买家绑定角色冷却期', + customer_role_bound_elsewhere: '买家角色7天内已绑其他斗鱼号', + account_role_bound_elsewhere: '斗鱼号7天内已绑其他角色', + role_changed: '扫码角色已失效需重扫', lease_expired: '账号租约已过期', + lease_expired_collab_handoff: '租约到期已转台账', manual_required: '需要人工处理', source_cancelled: '来源订单已取消', }; @@ -1090,10 +1104,15 @@ export default function PlatformFulfillmentPage() { concurrency: 1, payload, platform_task_id: selected.id, + reuse_active_payment: ['create_elite_qr', 'create_gold_qr'].includes(taskType) || undefined, }); setDouyuActionType(taskType); setDouyuActionBatchId(result.batch_id); - message.success(`${DOUYU_ACTION_LABELS[taskType] || '斗鱼任务'}已提交`); + if (result.reused) { + message.info(result.message || '当前已有未过期的支付二维码,已重新打开'); + } else { + message.success(`${DOUYU_ACTION_LABELS[taskType] || '斗鱼任务'}已提交`); + } if (taskType === 'exchange_goods' && selectedId) { await loadDetail(selectedId, true); await loadTasks(true); @@ -1661,11 +1680,36 @@ export default function PlatformFulfillmentPage() { {statusLabel(task.executionStatus)} 兑换:{exchangeStatusLabel(task.exchangeStatus)} - {task.manualReason ? ( - - {MANUAL_REASON_LABELS[task.manualReason] || task.manualReason} - - ) : null} + {(() => { + const showIssue = + task.executionStatus === 'manual_required' + || Boolean(task.manualReason) + || task.bindingStatus === 'failed' + || (task.executionStatus === 'ready' && Boolean(task.issueCode)); + if (!showIssue) return null; + const code = + task.issueCode && task.issueCode !== 'manual_required' + ? task.issueCode + : task.manualReason; + const reasonText = + (code && (ISSUE_LABELS[code] || MANUAL_REASON_LABELS[code])) || ''; + const genericReason = + !code || ['binding_failed', 'manual_required', 'other_manual'].includes(code); + const displayText = + genericReason && task.lastError + ? task.lastError + : reasonText || task.lastError; + if (!displayText) return null; + return ( + + {displayText} + + ); + })()} ), }, @@ -2632,7 +2676,18 @@ export default function PlatformFulfillmentPage() { {douyuActionTask.message || '任务执行中'} {douyuActionQrValue ? ( - + <> + + {typeof douyuActionTask.result?.payment_deadline_at === 'string' && + douyuActionTask.result.payment_deadline_at ? ( + + 二维码有效期至:{formatTime(douyuActionTask.result.payment_deadline_at)} + + ) : null} + + 关闭弹窗不会中断后台到账查询;过期前再次点击按钮可重新打开当前二维码 + + ) : null} {douyuActionType === 'exchange_goods' && douyuActionTask.status === 'success' ? (