feat(fulfillment): 自动选号并补充精英宝典操作

- 增加直播履约自动选号 worker、重试与任务扫描
- 履约详情复用斗鱼任务能力开通宝典、充值和兑换皮肤
- 补充自动选号与精英宝典操作测试
This commit is contained in:
yml
2026-11-18 10:59:20 +08:00
parent bba3d9dac9
commit 8ba6379687
6 changed files with 501 additions and 6 deletions
+6
View File
@@ -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()
@@ -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)
@@ -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)
@@ -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<string, string> = {
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<string, string> = {
commodity_limit_reached: '商品已达限兑上限',
eligibility_check_failed: '资格查询失败',
binding_failed: '绑定失败',
account_role_cooldown: '斗鱼账号仍在换绑冷却期',
customer_role_cooldown: '游戏角色仍在换绑冷却期',
lease_expired: '账号租约已过期',
manual_required: '需要人工处理',
};
const DOUYU_ACTION_LABELS: Record<string, string> = {
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<string, unk
}
if (event.eventType === 'binding_started') return '已生成客户绑定二维码';
if (event.eventType === 'binding_confirm_started') return '已提交游戏角色绑定确认';
if (event.eventType === 'binding_failed') {
return String(detail.rawError || issueLabel(String(detail.issueCode || 'binding_failed')));
}
if (event.eventType === 'task_created') return '订单已进入直播账号履约工作台';
return '履约状态已更新';
}
@@ -241,6 +257,12 @@ export default function PlatformFulfillmentPage() {
const [leaseDurationMode, setLeaseDurationMode] = useState<'unlimited' | 'minutes' | 'hours'>('unlimited');
const [leaseDurationValue, setLeaseDurationValue] = useState<number | null>(60);
const [savingSettings, setSavingSettings] = useState(false);
const [douyuActionLoading, setDouyuActionLoading] = useState('');
const [douyuActionType, setDouyuActionType] = useState('');
const [douyuActionBatchId, setDouyuActionBatchId] = useState('');
const [douyuActionTask, setDouyuActionTask] = useState<DouyuTaskItem | null>(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<string, unknown> = {};
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' ? (
<Button size="small" type="primary" icon={<UserSwitchOutlined />} onClick={() => void runTaskAction(() => platformFulfillmentApi.allocate(task.id))}>
自动选号
人工重试选号
</Button>
) : null}
{task.executionStatus === 'allocated' ? (
@@ -593,7 +682,7 @@ export default function PlatformFulfillmentPage() {
<Title level={4} style={{ margin: 0 }}>
直播账号履约工作台
</Title>
<Text type="secondary">读取 order_site 人工订单,客户扫码绑定游戏角色,运营使用斗鱼账号人工兑换。</Text>
<Text type="secondary">系统自动检测账号并选号;只有缺货、CK 异常或资格失败时转人工处理。客户扫码绑定后,运营可直接开通宝典、充值或兑换皮肤。</Text>
</div>
<Space wrap>
<Tag>账号租约:{leaseDurationLabel(settings?.leaseDurationMinutes)}</Tag>
@@ -759,6 +848,85 @@ export default function PlatformFulfillmentPage() {
</Card>
</div>
<Card size="small" title="精英宝典操作">
<Space direction="vertical" size={12} style={{ width: '100%' }}>
<Text type="secondary">
直接复用斗鱼精英宝典工作台任务,作用于当前履约账号;开通和充值会在任务窗口展示支付二维码。
</Text>
<Space wrap>
<Button
icon={<ReloadOutlined />}
disabled={!selected.account || !can('douyu:task')}
loading={douyuActionLoading === 'query_elite_status'}
onClick={() => void runDouyuAccountAction('query_elite_status')}
>
查询宝典状态
</Button>
<Button
type="primary"
icon={<CreditCardOutlined />}
disabled={!selected.account || !can('douyu:task')}
loading={douyuActionLoading === 'create_elite_qr'}
onClick={() => void runDouyuAccountAction('create_elite_qr')}
>
开通精英宝典
</Button>
</Space>
<Space wrap>
<Space.Compact>
<InputNumber
min={1}
precision={0}
value={goldAmount}
onChange={(value) => setGoldAmount(Number(value) || 1)}
addonBefore="鱼翅"
style={{ width: 150 }}
/>
<Button
icon={<CreditCardOutlined />}
disabled={!selected.account || !can('douyu:task')}
loading={douyuActionLoading === 'create_gold_qr'}
onClick={() => void runDouyuAccountAction('create_gold_qr')}
>
充值鱼翅
</Button>
</Space.Compact>
<Space.Compact>
<InputNumber
min={1}
precision={0}
value={giftCount}
onChange={(value) => setGiftCount(Number(value) || 1)}
addonBefore="数量"
style={{ width: 130 }}
/>
<Button
icon={<GiftOutlined />}
disabled={!selected.account || !can('douyu:task')}
loading={douyuActionLoading === 'donate_elite_gift'}
onClick={() => void runDouyuAccountAction('donate_elite_gift')}
>
赠送精英令
</Button>
</Space.Compact>
<Button
type="primary"
icon={<ShoppingOutlined />}
disabled={
!selected.account ||
!can('douyu:task') ||
!selected.commodityId ||
selected.exchangeStatus !== 'eligible'
}
loading={douyuActionLoading === 'exchange_goods'}
onClick={() => void runDouyuAccountAction('exchange_goods')}
>
兑换当前订单皮肤
</Button>
</Space>
</Space>
</Card>
<Card size="small" title="当前操作">
{actionButtons}
</Card>
@@ -789,6 +957,37 @@ export default function PlatformFulfillmentPage() {
)}
</Drawer>
<Modal
open={Boolean(douyuActionBatchId)}
title={DOUYU_ACTION_LABELS[douyuActionType] || '斗鱼精英宝典操作'}
footer={
<Button onClick={closeDouyuAction}>
关闭
</Button>
}
onCancel={closeDouyuAction}
width={520}
>
<Space direction="vertical" size={14} style={{ width: '100%', alignItems: 'center' }}>
{douyuActionTask ? (
<>
<Tag color={TASK_STATUS_COLORS[douyuActionTask.status] || 'default'}>
{TASK_STATUS_LABELS[douyuActionTask.status] || douyuActionTask.status}
</Tag>
<Text>{douyuActionTask.message || '任务执行中'}</Text>
{douyuActionQrValue ? (
<QRCode value={douyuActionQrValue} size={260} />
) : null}
{douyuActionType === 'exchange_goods' && douyuActionTask.status === 'success' ? (
<ExchangeResultImage task={douyuActionTask} />
) : null}
</>
) : (
<Text type="secondary">任务已提交,正在等待斗鱼执行器返回结果...</Text>
)}
</Space>
</Modal>
<Modal open={qrOpen && Boolean(qrValue)} title="客户扫码绑定游戏角色" footer={null} onCancel={() => setQrOpen(false)}>
<Space direction="vertical" align="center" style={{ width: '100%' }}>
{qrValue ? <QRCode value={qrValue} size={260} /> : null}