feat(fulfillment): 自动选号并补充精英宝典操作
- 增加直播履约自动选号 worker、重试与任务扫描 - 履约详情复用斗鱼任务能力开通宝典、充值和兑换皮肤 - 补充自动选号与精英宝典操作测试
This commit is contained in:
@@ -524,6 +524,68 @@ class TestBindingAndCompletion(_Base):
|
|||||||
assert detail["task"]["issueCode"] == ""
|
assert detail["task"]["issueCode"] == ""
|
||||||
assert detail["task"]["lastError"] == ""
|
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):
|
def test_list_hides_qr_but_detail_returns_it(self):
|
||||||
task = self._allocated()
|
task = self._allocated()
|
||||||
bind_task = DouyuTask(
|
bind_task = DouyuTask(
|
||||||
|
|||||||
@@ -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}
|
||||||
@@ -105,6 +105,10 @@ async def lifespan(app: FastAPI):
|
|||||||
start_integration_outbox_worker,
|
start_integration_outbox_worker,
|
||||||
stop_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 (
|
from .services.platform_fulfillment.reconciler import (
|
||||||
start_platform_fulfillment_reconciler,
|
start_platform_fulfillment_reconciler,
|
||||||
stop_platform_fulfillment_reconciler,
|
stop_platform_fulfillment_reconciler,
|
||||||
@@ -112,9 +116,11 @@ async def lifespan(app: FastAPI):
|
|||||||
|
|
||||||
start_integration_outbox_worker()
|
start_integration_outbox_worker()
|
||||||
start_platform_fulfillment_reconciler()
|
start_platform_fulfillment_reconciler()
|
||||||
|
start_platform_fulfillment_auto_allocator()
|
||||||
try:
|
try:
|
||||||
yield
|
yield
|
||||||
finally:
|
finally:
|
||||||
|
stop_platform_fulfillment_auto_allocator()
|
||||||
stop_platform_fulfillment_reconciler()
|
stop_platform_fulfillment_reconciler()
|
||||||
stop_integration_outbox_worker()
|
stop_integration_outbox_worker()
|
||||||
stop_scheduler()
|
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": "账号正在补充积分,请稍后重试",
|
"points_short": "账号正在补充积分,请稍后重试",
|
||||||
"commodity_limit_reached": "当前商品暂时无法兑换,请联系客服",
|
"commodity_limit_reached": "当前商品暂时无法兑换,请联系客服",
|
||||||
"binding_failed": "暂未识别到绑定角色,请继续使用当前二维码完成扫码",
|
"binding_failed": "暂未识别到绑定角色,请继续使用当前二维码完成扫码",
|
||||||
|
"account_role_cooldown": "当前绑定账号暂不可换绑,请截图本页面并联系客服处理",
|
||||||
|
"customer_role_cooldown": "该游戏角色仍在换绑冷却期,请截图本页面并联系客服处理",
|
||||||
"eligibility_check_failed": "状态查询异常,请稍后刷新",
|
"eligibility_check_failed": "状态查询异常,请稍后刷新",
|
||||||
"manual_required": "当前需要人工处理,请联系客服",
|
"manual_required": "当前需要人工处理,请联系客服",
|
||||||
}
|
}
|
||||||
return messages.get(task.issue_code, "") if task.issue_code else ""
|
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]:
|
def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
|
||||||
"""面向前端客户页的安全绑定快照,不包含账号、CK、积分和租约。"""
|
"""面向前端客户页的安全绑定快照,不包含账号、CK、积分和租约。"""
|
||||||
task = _load_task(db, task_id)
|
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"}:
|
if bind_task.status in {"failed", "error", "stopped"}:
|
||||||
task.binding_status = "failed"
|
task.binding_status = "failed"
|
||||||
task.execution_status = "manual_required"
|
task.execution_status = "manual_required"
|
||||||
task.issue_code = "binding_failed"
|
task.issue_code = _binding_failure_issue(bind_task, result)
|
||||||
task.last_error = bind_task.message or "绑定任务失败"
|
task.last_error = _customer_task_message(task)
|
||||||
elif bool(result.get("bind_confirmed")):
|
elif bool(result.get("bind_confirmed")):
|
||||||
task.binding_status = "bound"
|
task.binding_status = "bound"
|
||||||
task.execution_status = "bound"
|
task.execution_status = "bound"
|
||||||
@@ -1119,6 +1137,21 @@ def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]:
|
|||||||
)
|
)
|
||||||
if after != before:
|
if after != before:
|
||||||
task.updated_at = _now()
|
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)
|
_emit_order_site_binding_state(db, task.id)
|
||||||
db.commit()
|
db.commit()
|
||||||
return get_task_detail(db, task.id)
|
return get_task_detail(db, task.id)
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
import { useCallback, useEffect, useState } from 'react';
|
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 { 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 type { ColumnsType } from 'antd/es/table';
|
||||||
import { douyuApi, platformFulfillmentApi } from '../api/modules';
|
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 { getErrorMessage } from '../utils/error';
|
||||||
import { message } from '../utils/antdMessage';
|
import { message } from '../utils/antdMessage';
|
||||||
import { formatTime } from '../utils/time';
|
import { formatTime } from '../utils/time';
|
||||||
@@ -73,6 +75,7 @@ const EVENT_LABELS: Record<string, string> = {
|
|||||||
account_released: '释放履约账号',
|
account_released: '释放履约账号',
|
||||||
binding_started: '开始绑定游戏角色',
|
binding_started: '开始绑定游戏角色',
|
||||||
binding_confirm_started: '提交角色绑定确认',
|
binding_confirm_started: '提交角色绑定确认',
|
||||||
|
binding_failed: '游戏角色绑定失败',
|
||||||
eligibility_check_failed: '兑换资格查询失败',
|
eligibility_check_failed: '兑换资格查询失败',
|
||||||
exchange_eligibility_checked: '刷新兑换资格',
|
exchange_eligibility_checked: '刷新兑换资格',
|
||||||
manual_exchange_completed: '人工兑换完成',
|
manual_exchange_completed: '人工兑换完成',
|
||||||
@@ -88,10 +91,20 @@ const ISSUE_LABELS: Record<string, string> = {
|
|||||||
commodity_limit_reached: '商品已达限兑上限',
|
commodity_limit_reached: '商品已达限兑上限',
|
||||||
eligibility_check_failed: '资格查询失败',
|
eligibility_check_failed: '资格查询失败',
|
||||||
binding_failed: '绑定失败',
|
binding_failed: '绑定失败',
|
||||||
|
account_role_cooldown: '斗鱼账号仍在换绑冷却期',
|
||||||
|
customer_role_cooldown: '游戏角色仍在换绑冷却期',
|
||||||
lease_expired: '账号租约已过期',
|
lease_expired: '账号租约已过期',
|
||||||
manual_required: '需要人工处理',
|
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) {
|
function statusLabel(value: string) {
|
||||||
return STATUS_OPTIONS.find((item) => item.value === value)?.label || value;
|
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_started') return '已生成客户绑定二维码';
|
||||||
if (event.eventType === 'binding_confirm_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 '订单已进入直播账号履约工作台';
|
if (event.eventType === 'task_created') return '订单已进入直播账号履约工作台';
|
||||||
return '履约状态已更新';
|
return '履约状态已更新';
|
||||||
}
|
}
|
||||||
@@ -241,6 +257,12 @@ export default function PlatformFulfillmentPage() {
|
|||||||
const [leaseDurationMode, setLeaseDurationMode] = useState<'unlimited' | 'minutes' | 'hours'>('unlimited');
|
const [leaseDurationMode, setLeaseDurationMode] = useState<'unlimited' | 'minutes' | 'hours'>('unlimited');
|
||||||
const [leaseDurationValue, setLeaseDurationValue] = useState<number | null>(60);
|
const [leaseDurationValue, setLeaseDurationValue] = useState<number | null>(60);
|
||||||
const [savingSettings, setSavingSettings] = useState(false);
|
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) => {
|
const loadTasks = useCallback(async (silent = false) => {
|
||||||
if (!silent) setLoading(true);
|
if (!silent) setLoading(true);
|
||||||
@@ -302,8 +324,30 @@ export default function PlatformFulfillmentPage() {
|
|||||||
return () => window.clearInterval(timer);
|
return () => window.clearInterval(timer);
|
||||||
}, [loadDetail, selectedId]);
|
}, [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 selected = detail?.task || null;
|
||||||
const qrValue = selected?.bindTask?.qrUrl || '';
|
const qrValue = selected?.bindTask?.qrUrl || '';
|
||||||
|
const douyuActionQrValue = douyuActionTask ? taskQrUrl(douyuActionTask) : '';
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (qrValue) setQrOpen(true);
|
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) => {
|
const openMapping = async (task?: PlatformFulfillmentTask) => {
|
||||||
setMappingSku(task?.internalSkuKey || '');
|
setMappingSku(task?.internalSkuKey || '');
|
||||||
setMappingGoodsId(task?.commodityId || '');
|
setMappingGoodsId(task?.commodityId || '');
|
||||||
@@ -536,7 +625,7 @@ export default function PlatformFulfillmentPage() {
|
|||||||
) : null}
|
) : null}
|
||||||
{task.executionStatus === 'ready' ? (
|
{task.executionStatus === 'ready' ? (
|
||||||
<Button size="small" type="primary" icon={<UserSwitchOutlined />} onClick={() => void runTaskAction(() => platformFulfillmentApi.allocate(task.id))}>
|
<Button size="small" type="primary" icon={<UserSwitchOutlined />} onClick={() => void runTaskAction(() => platformFulfillmentApi.allocate(task.id))}>
|
||||||
自动选号
|
人工重试选号
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
{task.executionStatus === 'allocated' ? (
|
{task.executionStatus === 'allocated' ? (
|
||||||
@@ -593,7 +682,7 @@ export default function PlatformFulfillmentPage() {
|
|||||||
<Title level={4} style={{ margin: 0 }}>
|
<Title level={4} style={{ margin: 0 }}>
|
||||||
直播账号履约工作台
|
直播账号履约工作台
|
||||||
</Title>
|
</Title>
|
||||||
<Text type="secondary">读取 order_site 人工订单,客户扫码绑定游戏角色,运营使用斗鱼账号人工兑换。</Text>
|
<Text type="secondary">系统自动检测账号并选号;只有缺货、CK 异常或资格失败时转人工处理。客户扫码绑定后,运营可直接开通宝典、充值或兑换皮肤。</Text>
|
||||||
</div>
|
</div>
|
||||||
<Space wrap>
|
<Space wrap>
|
||||||
<Tag>账号租约:{leaseDurationLabel(settings?.leaseDurationMinutes)}</Tag>
|
<Tag>账号租约:{leaseDurationLabel(settings?.leaseDurationMinutes)}</Tag>
|
||||||
@@ -759,6 +848,85 @@ export default function PlatformFulfillmentPage() {
|
|||||||
</Card>
|
</Card>
|
||||||
</div>
|
</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="当前操作">
|
<Card size="small" title="当前操作">
|
||||||
{actionButtons}
|
{actionButtons}
|
||||||
</Card>
|
</Card>
|
||||||
@@ -789,6 +957,37 @@ export default function PlatformFulfillmentPage() {
|
|||||||
)}
|
)}
|
||||||
</Drawer>
|
</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)}>
|
<Modal open={qrOpen && Boolean(qrValue)} title="客户扫码绑定游戏角色" footer={null} onCancel={() => setQrOpen(false)}>
|
||||||
<Space direction="vertical" align="center" style={{ width: '100%' }}>
|
<Space direction="vertical" align="center" style={{ width: '100%' }}>
|
||||||
{qrValue ? <QRCode value={qrValue} size={260} /> : null}
|
{qrValue ? <QRCode value={qrValue} size={260} /> : null}
|
||||||
|
|||||||
Reference in New Issue
Block a user