feat(fulfillment): 新增直播账号履约工作台
This commit is contained in:
@@ -141,5 +141,10 @@ WORKER_SMS_CODE_TTL_SECONDS=300
|
|||||||
WORKER_SMS_COOLDOWN_SECONDS=60
|
WORKER_SMS_COOLDOWN_SECONDS=60
|
||||||
WORKER_SMS_DAILY_LIMIT=10
|
WORKER_SMS_DAILY_LIMIT=10
|
||||||
|
|
||||||
|
# order_site 只读订单库(直播账号履约工作台)
|
||||||
|
ORDER_SITE_DATABASE_URL=
|
||||||
|
ORDER_SITE_LOOKUP_ENABLED=false
|
||||||
|
ORDER_SITE_LOOKUP_TIMEOUT_SECONDS=3
|
||||||
|
|
||||||
# Uvicorn reload(开发模式设为 true,生产环境保持 false)
|
# Uvicorn reload(开发模式设为 true,生产环境保持 false)
|
||||||
UVICORN_RELOAD=false
|
UVICORN_RELOAD=false
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
## 能做什么
|
## 能做什么
|
||||||
|
|
||||||
- **斗鱼**:极验滑块自动过验、邮箱验证码、批量登录与 CK 检测/重登;精英宝典 / 电竞手册 / 和平小店三套工作台(绑定、开通、充值、兑换);鱼翅可由微信二维码或供应商直充。
|
- **斗鱼**:极验滑块自动过验、邮箱验证码、批量登录与 CK 检测/重登;精英宝典 / 电竞手册 / 和平小店三套工作台(绑定、开通、充值、兑换);直播账号履约工作台支持从 order_site 读取人工订单、客户扫码绑定斗鱼账号并人工兑换;鱼翅可由微信二维码或供应商直充。
|
||||||
- **虎牙**:Cookie / 密码 / App / 短信登录、自动注册、设备绑定、精英宝典、浏览器人工兑换;网页运行 Cookie 与 App 原始凭据(`raw_cookie`)分离,可从原始凭据重建网页 Cookie。
|
- **虎牙**:Cookie / 密码 / App / 短信登录、自动注册、设备绑定、精英宝典、浏览器人工兑换;网页运行 Cookie 与 App 原始凭据(`raw_cookie`)分离,可从原始凭据重建网页 Cookie。
|
||||||
- **应用宝**:和平精英点券扫码登录、选区服角色、支付二维码。Worker 合在 Web 容器内,只监听 `127.0.0.1:8810`。
|
- **应用宝**:和平精英点券扫码登录、选区服角色、支付二维码。Worker 合在 Web 容器内,只监听 `127.0.0.1:8810`。
|
||||||
- **权限**:超级管理员 / 运营 / 客服;可按权限点覆盖。客服只看分配给自己的账号,虎牙侧默认开放精英宝典(含外部 CK 导入)与浏览器兑换。
|
- **权限**:超级管理员 / 运营 / 客服;可按权限点覆盖。客服只看分配给自己的账号,虎牙侧默认开放精英宝典(含外部 CK 导入)与浏览器兑换。
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
- [小X分身虎牙 CK 提取](虎牙/分身CK提取.md):ADB、WebView Cookie 与 cred0 解密提取流程。
|
- [小X分身虎牙 CK 提取](虎牙/分身CK提取.md):ADB、WebView Cookie 与 cred0 解密提取流程。
|
||||||
- [精英宝典 HAR 提取](虎牙/HAR提取CK与积分中心.md):HAR 中的完整 CK、积分中心和商品结构。
|
- [精英宝典 HAR 提取](虎牙/HAR提取CK与积分中心.md):HAR 中的完整 CK、积分中心和商品结构。
|
||||||
- [皮肤准入映射分析](皮肤准入映射分析.md):快手皮肤订单到斗鱼商品的覆盖与映射边界。
|
- [皮肤准入映射分析](皮肤准入映射分析.md):快手皮肤订单到斗鱼商品的覆盖与映射边界。
|
||||||
|
- [直播账号履约工作台](直播账号履约工作台.md):order_site 人工订单、斗鱼账号租约、客户扫码绑定和人工兑换。
|
||||||
|
|
||||||
## 协议与逆向证据
|
## 协议与逆向证据
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
# 直播账号履约工作台
|
||||||
|
|
||||||
|
更新时间:2026-11-17
|
||||||
|
|
||||||
|
## 目标
|
||||||
|
|
||||||
|
从 `order_site` 只读获取人工渠道待履约订单,由系统选择内部斗鱼账号,
|
||||||
|
客户扫码绑定游戏角色,运营人工完成精英宝典兑换。
|
||||||
|
|
||||||
|
首期边界:
|
||||||
|
|
||||||
|
- 只支持斗鱼精英宝典
|
||||||
|
- 每笔订单项固定 1 件
|
||||||
|
- 客户扫码绑定游戏角色
|
||||||
|
- 不做自动充值
|
||||||
|
- 不做自动兑换
|
||||||
|
- 不向 `order_site` 回写状态
|
||||||
|
- 退款、取消由运营人工处理
|
||||||
|
|
||||||
|
## 数据边界
|
||||||
|
|
||||||
|
- `order_site` 是订单、支付、退款和人工履约状态的真源。
|
||||||
|
- `live-hub` 只通过 `external_order_source.py` 读取订单数据库。
|
||||||
|
- `live-hub` 的履约作业记录在 `platform_fulfillment_tasks`。
|
||||||
|
- 内部 SKU 与斗鱼商品必须显式配置 `platform_commodity_mappings`。
|
||||||
|
- CK 始终保存在原有账号字段中,不进入履约任务接口。
|
||||||
|
|
||||||
|
## 操作流程
|
||||||
|
|
||||||
|
1. 在“直播账号履约工作台”点击“同步待履约订单”。
|
||||||
|
2. 为待映射商品选择斗鱼商品和积分价格。
|
||||||
|
3. 点击“自动选号”,系统按 CK、积分、开通状态、租约、365 天限兑和
|
||||||
|
换绑冷却筛选账号。
|
||||||
|
4. 点击“生成二维码”,让客户扫码绑定游戏角色。
|
||||||
|
5. 角色出现后点击“确认绑定”。
|
||||||
|
6. 点击“刷新兑换资格”,核对限兑、积分和精英宝典开通状态。
|
||||||
|
7. 运营在斗鱼侧人工完成兑换。
|
||||||
|
8. 回到工作台点击“完成”,系统释放账号租约并记录操作时间线。
|
||||||
|
|
||||||
|
## 环境
|
||||||
|
|
||||||
|
读取 `order_site` 需要:
|
||||||
|
|
||||||
|
```dotenv
|
||||||
|
ORDER_SITE_DATABASE_URL=postgresql://...
|
||||||
|
ORDER_SITE_LOOKUP_ENABLED=true
|
||||||
|
```
|
||||||
|
|
||||||
|
数据库账号必须是只读账号。跨库 SQL 只允许出现在
|
||||||
|
`web/backend/services/external_order_source.py`。
|
||||||
|
|
||||||
|
## 权限
|
||||||
|
|
||||||
|
- `platform_fulfillment:view`
|
||||||
|
- `platform_fulfillment:use`
|
||||||
|
- `platform_fulfillment:admin`
|
||||||
|
|
||||||
|
## 暂不实现
|
||||||
|
|
||||||
|
- `order_site` 状态回写接口
|
||||||
|
- 自动充值鱼翅
|
||||||
|
- 自动兑换
|
||||||
|
- 多数量拆分
|
||||||
|
- 电竞手册、和平小店、虎牙和微博
|
||||||
+2
-1
@@ -20,7 +20,8 @@ dependencies = [
|
|||||||
"python-multipart>=0.0.9",
|
"python-multipart>=0.0.9",
|
||||||
"alembic>=1.18.4",
|
"alembic>=1.18.4",
|
||||||
"websockets>=16.0",
|
"websockets>=16.0",
|
||||||
"onnxruntime>=1.18.0",
|
# macOS Intel wheels end at 1.23.x; newer releases only cover arm64 on macOS.
|
||||||
|
"onnxruntime>=1.18.0,<1.24",
|
||||||
"scipy>=1.13.0",
|
"scipy>=1.13.0",
|
||||||
"pyexecjs>=1.5.1",
|
"pyexecjs>=1.5.1",
|
||||||
"pymysql>=1.1,<2",
|
"pymysql>=1.1,<2",
|
||||||
|
|||||||
@@ -11,8 +11,9 @@ import os
|
|||||||
import time
|
import time
|
||||||
from collections.abc import Iterator
|
from collections.abc import Iterator
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from datetime import UTC, datetime
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
|
import pytest
|
||||||
from sqlalchemy.orm import sessionmaker
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
|
||||||
import web.backend.database as database_module
|
import web.backend.database as database_module
|
||||||
@@ -30,8 +31,15 @@ def _force_non_utc_timezone(name: str = "Asia/Shanghai") -> Iterator[None]:
|
|||||||
只有开发机(UTC+8)才现形 —— 而「只在某些机器上失败」的测试等于没有测试。
|
只有开发机(UTC+8)才现形 —— 而「只在某些机器上失败」的测试等于没有测试。
|
||||||
"""
|
"""
|
||||||
previous = os.environ.get("TZ")
|
previous = os.environ.get("TZ")
|
||||||
|
can_change_tz = hasattr(time, "tzset")
|
||||||
os.environ["TZ"] = name
|
os.environ["TZ"] = name
|
||||||
time.tzset()
|
if can_change_tz:
|
||||||
|
time.tzset()
|
||||||
|
elif (datetime.now().astimezone().utcoffset() or timedelta()) == timedelta():
|
||||||
|
os.environ.pop("TZ", None)
|
||||||
|
if previous is not None:
|
||||||
|
os.environ["TZ"] = previous
|
||||||
|
pytest.skip("当前 Python 运行时缺少 time.tzset,且宿主机为 UTC")
|
||||||
try:
|
try:
|
||||||
yield
|
yield
|
||||||
finally:
|
finally:
|
||||||
@@ -39,7 +47,8 @@ def _force_non_utc_timezone(name: str = "Asia/Shanghai") -> Iterator[None]:
|
|||||||
os.environ.pop("TZ", None)
|
os.environ.pop("TZ", None)
|
||||||
else:
|
else:
|
||||||
os.environ["TZ"] = previous
|
os.environ["TZ"] = previous
|
||||||
time.tzset()
|
if can_change_tz:
|
||||||
|
time.tzset()
|
||||||
|
|
||||||
|
|
||||||
class _Base:
|
class _Base:
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ TESTS_DIR = Path(__file__).resolve().parent
|
|||||||
PROJECT_ROOT = TESTS_DIR.parent
|
PROJECT_ROOT = TESTS_DIR.parent
|
||||||
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
|
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
|
||||||
|
|
||||||
HEAD_REVISION = "20261113_0082"
|
HEAD_REVISION = "20261117_0084"
|
||||||
|
|
||||||
# 迁移新增、但不声明在模型里的复合查询索引。
|
# 迁移新增、但不声明在模型里的复合查询索引。
|
||||||
EXTRA_INDEXES = (
|
EXTRA_INDEXES = (
|
||||||
|
|||||||
@@ -0,0 +1,399 @@
|
|||||||
|
"""直播账号履约:订单同步、映射、选号、绑码状态和人工完成。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from tests.support.db import get_test_engine, make_test_session
|
||||||
|
from web.backend.models import (
|
||||||
|
Account,
|
||||||
|
AccountLease,
|
||||||
|
AutomationJob,
|
||||||
|
DouyuGoodsSnapshot,
|
||||||
|
DouyuTask,
|
||||||
|
PlatformCommodityMapping,
|
||||||
|
PlatformFulfillmentTask,
|
||||||
|
User,
|
||||||
|
)
|
||||||
|
from web.backend.services.automation.jobs import platform_fulfillment_lease_reaper as reaper
|
||||||
|
from web.backend.services.platform_fulfillment import account_selector, service
|
||||||
|
|
||||||
|
NOW = datetime.now(UTC).replace(microsecond=0)
|
||||||
|
COMMODITY = "20260120QYOOB_bag10"
|
||||||
|
INTERNAL_SKU = "套装-兔兔白日梦"
|
||||||
|
|
||||||
|
|
||||||
|
class _Base:
|
||||||
|
def setup_method(self):
|
||||||
|
self.engine = get_test_engine()
|
||||||
|
self.session = make_test_session(self.engine)
|
||||||
|
self.admin = User(
|
||||||
|
username="pf-admin",
|
||||||
|
password_hash="h",
|
||||||
|
role="super_admin",
|
||||||
|
)
|
||||||
|
self.session.add(self.admin)
|
||||||
|
self.session.commit()
|
||||||
|
self.admin_id = self.admin.id
|
||||||
|
|
||||||
|
def teardown_method(self):
|
||||||
|
self.session.close()
|
||||||
|
|
||||||
|
def account(
|
||||||
|
self,
|
||||||
|
name: str,
|
||||||
|
*,
|
||||||
|
points: int = 2000,
|
||||||
|
opened: bool = True,
|
||||||
|
role_available_at: datetime | None = None,
|
||||||
|
) -> Account:
|
||||||
|
row = Account(
|
||||||
|
username=name,
|
||||||
|
password="p",
|
||||||
|
email=f"{name}@example.com",
|
||||||
|
email_password="ep",
|
||||||
|
status="active",
|
||||||
|
ck_check_status="valid",
|
||||||
|
cookie="PHPSESSID=x",
|
||||||
|
elite_opened=opened,
|
||||||
|
points=points,
|
||||||
|
gold_balance=100,
|
||||||
|
auto_managed=True,
|
||||||
|
role_change_available_at=role_available_at,
|
||||||
|
)
|
||||||
|
self.session.add(row)
|
||||||
|
self.session.commit()
|
||||||
|
return row
|
||||||
|
|
||||||
|
def mapping(self, enabled: bool = True) -> PlatformCommodityMapping:
|
||||||
|
row = PlatformCommodityMapping(
|
||||||
|
target_platform="douyu",
|
||||||
|
internal_sku_key=INTERNAL_SKU,
|
||||||
|
commodity_id=COMMODITY,
|
||||||
|
goods_name=INTERNAL_SKU,
|
||||||
|
required_points=1280,
|
||||||
|
scope="elite",
|
||||||
|
enabled=enabled,
|
||||||
|
created_by=self.admin_id,
|
||||||
|
created_at=NOW,
|
||||||
|
updated_at=NOW,
|
||||||
|
)
|
||||||
|
self.session.add(row)
|
||||||
|
self.session.commit()
|
||||||
|
return row
|
||||||
|
|
||||||
|
def task(self, *, mapped: bool = True) -> PlatformFulfillmentTask:
|
||||||
|
mapping = self.mapping() if mapped else None
|
||||||
|
row = PlatformFulfillmentTask(
|
||||||
|
source_system="order_site",
|
||||||
|
source_order_id="100",
|
||||||
|
source_order_item_id="101",
|
||||||
|
source_fulfillment_id="201",
|
||||||
|
platform_order_id="ORDER-101",
|
||||||
|
provider="91kaquan",
|
||||||
|
shop_id="shop-1",
|
||||||
|
shop_name="测试店",
|
||||||
|
sku_code=INTERNAL_SKU,
|
||||||
|
sku_name=INTERNAL_SKU,
|
||||||
|
internal_sku_key=INTERNAL_SKU,
|
||||||
|
quantity=1,
|
||||||
|
order_amount_fen=9900,
|
||||||
|
target_platform="douyu",
|
||||||
|
scope="elite",
|
||||||
|
commodity_mapping_id=mapping.id if mapping else None,
|
||||||
|
commodity_id=COMMODITY if mapping else "",
|
||||||
|
required_points=1280 if mapping else None,
|
||||||
|
binding_status="not_started",
|
||||||
|
execution_status="ready" if mapping else "pending_mapping",
|
||||||
|
exchange_status="not_started",
|
||||||
|
source_snapshot_json={"order_no": "ORDER-101"},
|
||||||
|
created_at=NOW,
|
||||||
|
updated_at=NOW,
|
||||||
|
)
|
||||||
|
self.session.add(row)
|
||||||
|
self.session.commit()
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
class TestSyncAndMapping(_Base):
|
||||||
|
def test_sync_creates_pending_mapping_task(self, monkeypatch):
|
||||||
|
monkeypatch.setattr(
|
||||||
|
service,
|
||||||
|
"list_pending_manual_fulfillments",
|
||||||
|
lambda limit: [
|
||||||
|
{
|
||||||
|
"source_system": "order_site",
|
||||||
|
"source_order_id": "100",
|
||||||
|
"source_order_item_id": "101",
|
||||||
|
"source_fulfillment_id": "201",
|
||||||
|
"platform_order_id": "ORDER-101",
|
||||||
|
"provider": "91kaquan",
|
||||||
|
"shop_id": "shop-1",
|
||||||
|
"shop_name": "测试店",
|
||||||
|
"sku_code": INTERNAL_SKU,
|
||||||
|
"sku_name": INTERNAL_SKU,
|
||||||
|
"internal_sku_key": INTERNAL_SKU,
|
||||||
|
"quantity": 1,
|
||||||
|
"revenue_amount_fen": 9900,
|
||||||
|
"total_amount": 9900,
|
||||||
|
"paid_at": NOW,
|
||||||
|
"item_updated_at": NOW,
|
||||||
|
}
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
result = service.sync_pending_tasks(self.session, limit=10)
|
||||||
|
|
||||||
|
assert result["created"] == 1
|
||||||
|
task = self.session.query(PlatformFulfillmentTask).one()
|
||||||
|
assert task.execution_status == "pending_mapping"
|
||||||
|
assert task.internal_sku_key == INTERNAL_SKU
|
||||||
|
assert task.order_amount_fen == 9900
|
||||||
|
|
||||||
|
def test_sync_is_idempotent_and_applies_mapping(self, monkeypatch):
|
||||||
|
self.mapping()
|
||||||
|
monkeypatch.setattr(
|
||||||
|
service,
|
||||||
|
"list_pending_manual_fulfillments",
|
||||||
|
lambda limit: [
|
||||||
|
{
|
||||||
|
"source_order_id": "100",
|
||||||
|
"source_order_item_id": "101",
|
||||||
|
"source_fulfillment_id": "201",
|
||||||
|
"platform_order_id": "ORDER-101",
|
||||||
|
"provider": "91kaquan",
|
||||||
|
"shop_id": "shop-1",
|
||||||
|
"shop_name": "测试店",
|
||||||
|
"sku_code": INTERNAL_SKU,
|
||||||
|
"sku_name": INTERNAL_SKU,
|
||||||
|
"internal_sku_key": INTERNAL_SKU,
|
||||||
|
"quantity": 1,
|
||||||
|
"revenue_amount_fen": 9900,
|
||||||
|
"total_amount": 9900,
|
||||||
|
"paid_at": NOW,
|
||||||
|
"item_updated_at": NOW,
|
||||||
|
}
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
first = service.sync_pending_tasks(self.session, limit=10)
|
||||||
|
second = service.sync_pending_tasks(self.session, limit=10)
|
||||||
|
|
||||||
|
assert first["created"] == 1
|
||||||
|
assert second["created"] == 0
|
||||||
|
assert self.session.query(PlatformFulfillmentTask).count() == 1
|
||||||
|
task = self.session.query(PlatformFulfillmentTask).one()
|
||||||
|
assert task.execution_status == "ready"
|
||||||
|
assert task.commodity_id == COMMODITY
|
||||||
|
|
||||||
|
def test_upsert_mapping_advances_existing_task(self):
|
||||||
|
task = self.task(mapped=False)
|
||||||
|
self.session.add(
|
||||||
|
DouyuGoodsSnapshot(
|
||||||
|
commodity_id=COMMODITY,
|
||||||
|
name=INTERNAL_SKU,
|
||||||
|
score=1280,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.session.commit()
|
||||||
|
|
||||||
|
service.upsert_mapping(
|
||||||
|
self.session,
|
||||||
|
internal_sku_key=INTERNAL_SKU,
|
||||||
|
commodity_id=COMMODITY,
|
||||||
|
goods_name="",
|
||||||
|
required_points=None,
|
||||||
|
enabled=True,
|
||||||
|
current=self.admin,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.session.refresh(task)
|
||||||
|
assert task.execution_status == "ready"
|
||||||
|
assert task.commodity_id == COMMODITY
|
||||||
|
assert task.required_points == 1280
|
||||||
|
|
||||||
|
|
||||||
|
class TestAccountSelection(_Base):
|
||||||
|
def test_eligible_account_excludes_cooldown_and_uses_least_points(self):
|
||||||
|
self.account("small", points=1300)
|
||||||
|
self.account("large", points=9000)
|
||||||
|
self.account(
|
||||||
|
"cooldown",
|
||||||
|
points=1400,
|
||||||
|
role_available_at=NOW + timedelta(days=1),
|
||||||
|
)
|
||||||
|
|
||||||
|
candidates = account_selector.eligible_accounts(
|
||||||
|
self.session,
|
||||||
|
commodity_id=COMMODITY,
|
||||||
|
required_points=1280,
|
||||||
|
now=NOW,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert [row.username for row in candidates] == ["small", "large"]
|
||||||
|
|
||||||
|
def test_lease_is_unique_per_account(self):
|
||||||
|
account = self.account("leased")
|
||||||
|
candidate = account_selector.eligible_accounts(
|
||||||
|
self.session,
|
||||||
|
commodity_id=COMMODITY,
|
||||||
|
required_points=1280,
|
||||||
|
now=NOW,
|
||||||
|
)[0]
|
||||||
|
|
||||||
|
first = account_selector.lease_account(
|
||||||
|
self.session,
|
||||||
|
candidate=candidate,
|
||||||
|
holder_user_id=self.admin_id,
|
||||||
|
task_id=1,
|
||||||
|
commodity_id=COMMODITY,
|
||||||
|
now=NOW,
|
||||||
|
)
|
||||||
|
second = account_selector.lease_account(
|
||||||
|
self.session,
|
||||||
|
candidate=candidate,
|
||||||
|
holder_user_id=self.admin_id,
|
||||||
|
task_id=2,
|
||||||
|
commodity_id=COMMODITY,
|
||||||
|
now=NOW,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert first is not None
|
||||||
|
assert second is None
|
||||||
|
assert self.session.query(AccountLease).filter_by(account_id=account.id).count() == 1
|
||||||
|
|
||||||
|
def test_allocate_and_release_task(self):
|
||||||
|
account = self.account("allocated")
|
||||||
|
task = self.task()
|
||||||
|
|
||||||
|
detail = service.allocate_task(
|
||||||
|
self.session,
|
||||||
|
task_id=task.id,
|
||||||
|
current=self.admin,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert detail["task"]["account"]["id"] == account.id
|
||||||
|
assert detail["task"]["executionStatus"] == "allocated"
|
||||||
|
lease = self.session.query(AccountLease).one()
|
||||||
|
assert lease.purpose == "platform_fulfillment"
|
||||||
|
assert lease.status == "active"
|
||||||
|
|
||||||
|
released = service.release_task_account(
|
||||||
|
self.session,
|
||||||
|
task_id=task.id,
|
||||||
|
current=self.admin,
|
||||||
|
)
|
||||||
|
assert released["task"]["executionStatus"] == "ready"
|
||||||
|
self.session.refresh(lease)
|
||||||
|
assert lease.status == "released"
|
||||||
|
|
||||||
|
|
||||||
|
class TestBindingAndCompletion(_Base):
|
||||||
|
def _allocated(self):
|
||||||
|
self.account("bind-account")
|
||||||
|
task = self.task()
|
||||||
|
service.allocate_task(self.session, task_id=task.id, current=self.admin)
|
||||||
|
self.session.refresh(task)
|
||||||
|
return task
|
||||||
|
|
||||||
|
def test_refresh_binding_maps_role_ready(self):
|
||||||
|
task = self._allocated()
|
||||||
|
bind_task = DouyuTask(
|
||||||
|
batch_id="bind-1",
|
||||||
|
account_id=task.account_id,
|
||||||
|
account_assigned_to=self.admin_id,
|
||||||
|
task_type="get_bind_qr",
|
||||||
|
handbook_scope="elite",
|
||||||
|
status="success",
|
||||||
|
result={"url": "https://example.com/qr", "role_name": "测试角色"},
|
||||||
|
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"]["bindingStatus"] == "role_ready"
|
||||||
|
assert detail["task"]["bindTask"]["roleName"] == "测试角色"
|
||||||
|
|
||||||
|
def test_list_hides_qr_but_detail_returns_it(self):
|
||||||
|
task = self._allocated()
|
||||||
|
bind_task = DouyuTask(
|
||||||
|
batch_id="bind-qr",
|
||||||
|
account_id=task.account_id,
|
||||||
|
account_assigned_to=self.admin_id,
|
||||||
|
task_type="get_bind_qr",
|
||||||
|
handbook_scope="elite",
|
||||||
|
status="running",
|
||||||
|
result={"url": "https://example.com/private-qr"},
|
||||||
|
created_by=self.admin_id,
|
||||||
|
)
|
||||||
|
self.session.add(bind_task)
|
||||||
|
self.session.flush()
|
||||||
|
task.bind_task_id = bind_task.id
|
||||||
|
task.binding_status = "qr_pending"
|
||||||
|
task.execution_status = "waiting_bind"
|
||||||
|
self.session.commit()
|
||||||
|
|
||||||
|
listed = service.list_tasks(self.session)
|
||||||
|
detail = service.get_task_detail(self.session, task.id)
|
||||||
|
|
||||||
|
assert listed["items"][0]["bindTask"]["qrUrl"] == ""
|
||||||
|
assert detail["task"]["bindTask"]["qrUrl"] == "https://example.com/private-qr"
|
||||||
|
|
||||||
|
def test_manual_completion_requires_bound_and_releases_lease(self):
|
||||||
|
task = self._allocated()
|
||||||
|
task.binding_status = "bound"
|
||||||
|
task.execution_status = "bound"
|
||||||
|
task.exchange_status = "eligible"
|
||||||
|
self.session.commit()
|
||||||
|
|
||||||
|
detail = service.complete_manual_exchange(
|
||||||
|
self.session,
|
||||||
|
task_id=task.id,
|
||||||
|
current=self.admin,
|
||||||
|
note="人工兑换完成",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert detail["task"]["executionStatus"] == "completed"
|
||||||
|
assert detail["task"]["exchangeStatus"] == "manual_done"
|
||||||
|
lease = self.session.query(AccountLease).one()
|
||||||
|
assert lease.status == "released"
|
||||||
|
|
||||||
|
def test_expired_lease_moves_unfinished_task_to_manual(self):
|
||||||
|
task = self._allocated()
|
||||||
|
lease = self.session.query(AccountLease).one()
|
||||||
|
lease.expires_at = NOW - timedelta(minutes=1)
|
||||||
|
self.session.commit()
|
||||||
|
|
||||||
|
job = AutomationJob(key=reaper.JOB_KEY, batch_size=100)
|
||||||
|
result = reaper.run_platform_fulfillment_lease_reaper(
|
||||||
|
self.session,
|
||||||
|
job,
|
||||||
|
now=NOW,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.session.refresh(task)
|
||||||
|
assert result["expired"] == 1
|
||||||
|
assert task.execution_status == "manual_required"
|
||||||
|
assert task.issue_code == "lease_expired"
|
||||||
|
|
||||||
|
def test_completion_rejects_limited_exchange(self):
|
||||||
|
task = self._allocated()
|
||||||
|
task.binding_status = "bound"
|
||||||
|
task.execution_status = "manual_required"
|
||||||
|
task.exchange_status = "limited"
|
||||||
|
self.session.commit()
|
||||||
|
|
||||||
|
with pytest.raises(Exception):
|
||||||
|
service.complete_manual_exchange(
|
||||||
|
self.session,
|
||||||
|
task_id=task.id,
|
||||||
|
current=self.admin,
|
||||||
|
)
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
version = 1
|
version = 1
|
||||||
revision = 3
|
revision = 5
|
||||||
requires-python = "==3.12.*"
|
requires-python = "==3.12.*"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -191,6 +191,18 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
|
{ url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "coloredlogs"
|
||||||
|
version = "15.0.1"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "humanfriendly" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/cc/c7/eed8f27100517e8c0e6b923d5f0845d0cb99763da6fdee00478f91db7325/coloredlogs-15.0.1.tar.gz", hash = "sha256:7c991aa71a4577af2f82600d8f8f3a89f936baeaf9b50a9c197da014e5bf16b0", size = 278520, upload-time = "2021-06-11T10:22:45.202Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/a7/06/3d6badcf13db419e25b07041d9c7b4a2c331d3f4e7134445ec5df57714cd/coloredlogs-15.0.1-py2.py3-none-any.whl", hash = "sha256:612ee75c546f53e92e70049c9dbfcc18c935a2b9a53b66085ce9ef6a6e5c0934", size = 46018, upload-time = "2021-06-11T10:22:42.561Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cryptography"
|
name = "cryptography"
|
||||||
version = "49.0.0"
|
version = "49.0.0"
|
||||||
@@ -328,6 +340,18 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/05/0b/4240efeb672751ee5b9b380cb0e3fdc050bc05f68adc7a8aefc4fcd9a69a/httptools-0.8.0-cp312-cp312-win_amd64.whl", hash = "sha256:cd96f29b4bab1d42fa6e3d008711c75e0f79e94e06827330160e3a304227f150", size = 90918, upload-time = "2026-05-25T22:17:15.155Z" },
|
{ url = "https://files.pythonhosted.org/packages/05/0b/4240efeb672751ee5b9b380cb0e3fdc050bc05f68adc7a8aefc4fcd9a69a/httptools-0.8.0-cp312-cp312-win_amd64.whl", hash = "sha256:cd96f29b4bab1d42fa6e3d008711c75e0f79e94e06827330160e3a304227f150", size = 90918, upload-time = "2026-05-25T22:17:15.155Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "humanfriendly"
|
||||||
|
version = "10.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "pyreadline3", marker = "sys_platform == 'win32'" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/cc/3f/2c29224acb2e2df4d2046e4c73ee2662023c58ff5b113c4c1adac0886c43/humanfriendly-10.0.tar.gz", hash = "sha256:6b0b831ce8f15f7300721aa49829fc4e83921a9a301cc7f606be6686a2288ddc", size = 360702, upload-time = "2021-09-17T21:40:43.31Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/f0/0f/310fb31e39e2d734ccaa2c0fb981ee41f7bd5056ce9bc29b2248bd569169/humanfriendly-10.0-py2.py3-none-any.whl", hash = "sha256:1697e1a8a8f550fd43c2865cd84542fc175a61dcb779b6fee18cf6b6ccba1477", size = 86794, upload-time = "2021-09-17T21:40:39.897Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "idna"
|
name = "idna"
|
||||||
version = "3.18"
|
version = "3.18"
|
||||||
@@ -401,7 +425,7 @@ requires-dist = [
|
|||||||
{ name = "fastapi", specifier = ">=0.110.0" },
|
{ name = "fastapi", specifier = ">=0.110.0" },
|
||||||
{ name = "loguru", specifier = ">=0.7.0" },
|
{ name = "loguru", specifier = ">=0.7.0" },
|
||||||
{ name = "numpy", specifier = ">=1.24.0" },
|
{ name = "numpy", specifier = ">=1.24.0" },
|
||||||
{ name = "onnxruntime", specifier = ">=1.18.0" },
|
{ name = "onnxruntime", specifier = ">=1.18.0,<1.24" },
|
||||||
{ name = "opencv-python-headless", specifier = ">=4.8.0" },
|
{ name = "opencv-python-headless", specifier = ">=4.8.0" },
|
||||||
{ name = "pillow", specifier = ">=10.0.0" },
|
{ name = "pillow", specifier = ">=10.0.0" },
|
||||||
{ name = "psycopg", extras = ["binary"], specifier = ">=3.2,<4" },
|
{ name = "psycopg", extras = ["binary"], specifier = ">=3.2,<4" },
|
||||||
@@ -470,6 +494,15 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/e5/f1/216fc1bbfd74011693a4fd837e7026152e89c4bcf3e77b6692fba9923123/markupsafe-3.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:35add3b638a5d900e807944a078b51922212fb3dedb01633a8defc4b01a3c85f", size = 13906, upload-time = "2025-09-27T18:36:40.689Z" },
|
{ url = "https://files.pythonhosted.org/packages/e5/f1/216fc1bbfd74011693a4fd837e7026152e89c4bcf3e77b6692fba9923123/markupsafe-3.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:35add3b638a5d900e807944a078b51922212fb3dedb01633a8defc4b01a3c85f", size = 13906, upload-time = "2025-09-27T18:36:40.689Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "mpmath"
|
||||||
|
version = "1.3.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/e0/47/dd32fa426cc72114383ac549964eecb20ecfd886d1e5ccf5340b55b02f57/mpmath-1.3.0.tar.gz", hash = "sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f", size = 508106, upload-time = "2023-03-07T16:47:11.061Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198, upload-time = "2023-03-07T16:47:09.197Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "nodeenv"
|
name = "nodeenv"
|
||||||
version = "1.10.0"
|
version = "1.10.0"
|
||||||
@@ -500,20 +533,22 @@ wheels = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "onnxruntime"
|
name = "onnxruntime"
|
||||||
version = "1.27.0"
|
version = "1.23.2"
|
||||||
source = { registry = "https://pypi.org/simple" }
|
source = { registry = "https://pypi.org/simple" }
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
{ name = "coloredlogs" },
|
||||||
{ name = "flatbuffers" },
|
{ name = "flatbuffers" },
|
||||||
{ name = "numpy" },
|
{ name = "numpy" },
|
||||||
{ name = "packaging" },
|
{ name = "packaging" },
|
||||||
{ name = "protobuf" },
|
{ name = "protobuf" },
|
||||||
|
{ name = "sympy" },
|
||||||
]
|
]
|
||||||
wheels = [
|
wheels = [
|
||||||
{ url = "https://files.pythonhosted.org/packages/c3/b7/dd3a524ed93a820dff1af902d0412957ab12499953333e9daa01af5bc480/onnxruntime-1.27.0-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:a14c2ce45312def86b77aea651f46565e45960cf5f0721bfdff449165086ab76", size = 18433506, upload-time = "2026-06-15T22:43:47.026Z" },
|
{ url = "https://files.pythonhosted.org/packages/1b/9e/f748cd64161213adeef83d0cb16cb8ace1e62fa501033acdd9f9341fff57/onnxruntime-1.23.2-cp312-cp312-macosx_13_0_arm64.whl", hash = "sha256:b8f029a6b98d3cf5be564d52802bb50a8489ab73409fa9db0bf583eabb7c2321", size = 17195929, upload-time = "2025-10-22T03:47:36.24Z" },
|
||||||
{ url = "https://files.pythonhosted.org/packages/84/86/c3b6b17745a1997d784dadc9bd88d713d2e6721139a5a0e885b28cfb79b1/onnxruntime-1.27.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c6fddce0539a4898c7bef35b052ffd37935b2190e35488eab99ce91887743ea1", size = 16438140, upload-time = "2026-06-15T22:42:40.666Z" },
|
{ url = "https://files.pythonhosted.org/packages/91/9d/a81aafd899b900101988ead7fb14974c8a58695338ab6a0f3d6b0100f30b/onnxruntime-1.23.2-cp312-cp312-macosx_13_0_x86_64.whl", hash = "sha256:218295a8acae83905f6f1aed8cacb8e3eb3bd7513a13fe4ba3b2664a19fc4a6b", size = 19157705, upload-time = "2025-10-22T03:46:40.415Z" },
|
||||||
{ url = "https://files.pythonhosted.org/packages/26/81/24dd9b31b0fb912ee19ca53ac1c9764bfd79d58a2ccef564eb693be831a5/onnxruntime-1.27.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7c65a7438632d55dfbc8a02ee60bd6cf7dd9d1ba05a43d4b851452f32338e194", size = 18658316, upload-time = "2026-06-15T22:43:04.012Z" },
|
{ url = "https://files.pythonhosted.org/packages/3c/35/4e40f2fba272a6698d62be2cd21ddc3675edfc1a4b9ddefcc4648f115315/onnxruntime-1.23.2-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:76ff670550dc23e58ea9bc53b5149b99a44e63b34b524f7b8547469aaa0dcb8c", size = 15226915, upload-time = "2025-10-22T03:46:27.773Z" },
|
||||||
{ url = "https://files.pythonhosted.org/packages/4f/88/8ec9db1a4d126bb8b758992beb40d1249df171917d75f44a327eb5f20dda/onnxruntime-1.27.0-cp312-cp312-win_amd64.whl", hash = "sha256:20c321cf187ba496e648acf6b4cf90b4d398b0d17c2a77fdaeba365b908cc1c1", size = 13358769, upload-time = "2026-06-15T22:43:34.581Z" },
|
{ url = "https://files.pythonhosted.org/packages/ef/88/9cc25d2bafe6bc0d4d3c1db3ade98196d5b355c0b273e6a5dc09c5d5d0d5/onnxruntime-1.23.2-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0f9b4ae77f8e3c9bee50c27bc1beede83f786fe1d52e99ac85aa8d65a01e9b77", size = 17382649, upload-time = "2025-10-22T03:47:02.782Z" },
|
||||||
{ url = "https://files.pythonhosted.org/packages/ae/9f/fdad359dfcba7e7cd8815569b304a596531d4efa77a75d77f8b4981891a2/onnxruntime-1.27.0-cp312-cp312-win_arm64.whl", hash = "sha256:d0d1f68868e2ef30ef70998ba9bbbc5c305e9b17041e3936751c1b8aa6aade06", size = 13104440, upload-time = "2026-06-15T22:43:22.893Z" },
|
{ url = "https://files.pythonhosted.org/packages/c0/b4/569d298f9fc4d286c11c45e85d9ffa9e877af12ace98af8cab52396e8f46/onnxruntime-1.23.2-cp312-cp312-win_amd64.whl", hash = "sha256:25de5214923ce941a3523739d34a520aac30f21e631de53bba9174dc9c004435", size = 13470528, upload-time = "2025-10-22T03:47:28.106Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -731,6 +766,15 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/c4/bd/2534e130295c8cfd4f0a2e31623baab7502278f1e97bcfe61db75656a77f/pymysql-1.2.0-py3-none-any.whl", hash = "sha256:62169ce6d5510f08e140c5e7990ee884a9764024e4a9a27b2cc11f1099322ae0", size = 45716, upload-time = "2026-05-19T08:26:20.974Z" },
|
{ url = "https://files.pythonhosted.org/packages/c4/bd/2534e130295c8cfd4f0a2e31623baab7502278f1e97bcfe61db75656a77f/pymysql-1.2.0-py3-none-any.whl", hash = "sha256:62169ce6d5510f08e140c5e7990ee884a9764024e4a9a27b2cc11f1099322ae0", size = 45716, upload-time = "2026-05-19T08:26:20.974Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pyreadline3"
|
||||||
|
version = "3.5.6"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/b6/6d/f94028646d7bbe6d9d873c47ee7c246f2d29129d253f0d96cb6fcab70733/pyreadline3-3.5.6.tar.gz", hash = "sha256:61e53218b99656091ddb077df9e71f25850e72e030b6183b39c9b7e6e4f4a9bf", size = 100368, upload-time = "2026-05-14T17:55:04.471Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/f7/5e/35c856e186b74678c24927847ad9895a51f1bc02a0c6126477a6c6040064/pyreadline3-3.5.6-py3-none-any.whl", hash = "sha256:8449b734232e42a5dcd74048e39b60db2839a4c38cf3ae2bf7707d58b5389c0d", size = 85243, upload-time = "2026-05-14T17:55:03.262Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pyright"
|
name = "pyright"
|
||||||
version = "1.1.411"
|
version = "1.1.411"
|
||||||
@@ -977,6 +1021,18 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/ec/bb/2799cc2ede3ed41131f8975621e7213dfc7ef4acbbaadfa440f32500c370/starlette-1.3.1-py3-none-any.whl", hash = "sha256:c7372aae11c3c3f26a42df7bd626cec2f47d03483d261d369516a615a53714c6", size = 73632, upload-time = "2026-06-12T09:23:10.017Z" },
|
{ url = "https://files.pythonhosted.org/packages/ec/bb/2799cc2ede3ed41131f8975621e7213dfc7ef4acbbaadfa440f32500c370/starlette-1.3.1-py3-none-any.whl", hash = "sha256:c7372aae11c3c3f26a42df7bd626cec2f47d03483d261d369516a615a53714c6", size = 73632, upload-time = "2026-06-12T09:23:10.017Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "sympy"
|
||||||
|
version = "1.14.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "mpmath" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921, upload-time = "2025-04-27T18:05:01.611Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/a2/09/77d55d46fd61b4a135c444fc97158ef34a095e5681d0a6c10b75bf356191/sympy-1.14.0-py3-none-any.whl", hash = "sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", size = 6299353, upload-time = "2025-04-27T18:04:59.103Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "typing-extensions"
|
name = "typing-extensions"
|
||||||
version = "4.15.0"
|
version = "4.15.0"
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ from .routers import (
|
|||||||
files,
|
files,
|
||||||
huya,
|
huya,
|
||||||
login,
|
login,
|
||||||
|
platform_fulfillment,
|
||||||
proxy,
|
proxy,
|
||||||
users,
|
users,
|
||||||
weibo,
|
weibo,
|
||||||
@@ -171,6 +172,7 @@ app.include_router(weibo.router)
|
|||||||
app.include_router(weibo_collab.router)
|
app.include_router(weibo_collab.router)
|
||||||
app.include_router(douyu.router)
|
app.include_router(douyu.router)
|
||||||
app.include_router(douyu_collab.router)
|
app.include_router(douyu_collab.router)
|
||||||
|
app.include_router(platform_fulfillment.router)
|
||||||
app.include_router(yyb.router)
|
app.include_router(yyb.router)
|
||||||
app.include_router(audit.router)
|
app.include_router(audit.router)
|
||||||
app.include_router(automation.router)
|
app.include_router(automation.router)
|
||||||
|
|||||||
@@ -0,0 +1,163 @@
|
|||||||
|
"""账号租约 `account_leases` + `accounts.role_change_available_at` + 操作人索引
|
||||||
|
|
||||||
|
配套文档:`docs/设计-账号自动分配与回收.md`(§3.2 表结构、§4 换绑冷却、§3.14 流水)。
|
||||||
|
|
||||||
|
三件事:
|
||||||
|
|
||||||
|
1. **`account_leases`** —— 归属(`assigned_to`,管理员/运营的维护责任)与
|
||||||
|
使用权(租约,客服临时占用)分离。核心是生成列 `active_account_id`
|
||||||
|
加唯一索引 `uq_lease_active_account`:一个账号同时只能有一个**有效**租约,
|
||||||
|
并发抢号由数据库裁决(撞唯一键即换候选),不需要应用层加锁。
|
||||||
|
2. **`accounts.role_change_available_at`** —— `change_role_wait_time` 是接口原文的
|
||||||
|
「剩余秒数」,落库即过期;换绑判定需要的是**绝对时刻**。电竞手册复用既有的
|
||||||
|
`esports_can_change_time`(本来就是绝对时刻),不另开副本。
|
||||||
|
3. **`ix_account_events_actor_occurred`** —— 池化后客服不再持有账号,
|
||||||
|
「某客服这段时间做了什么」只能按 `actor_id` 查;此前没有可用索引。
|
||||||
|
|
||||||
|
**可重跑**:应用启动时会自动跑迁移,所以每个动作都带存在性守卫。
|
||||||
|
|
||||||
|
**回退**:drop 表、drop 列、drop 索引。租约是运行期状态,回退即丢失 ——
|
||||||
|
但账号与任务数据不受影响(`assigned_to`、`douyu_tasks` 一律没动)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "20261117_0083"
|
||||||
|
down_revision: str | None = "20261113_0082"
|
||||||
|
branch_labels: str | None = None
|
||||||
|
depends_on: str | None = None
|
||||||
|
|
||||||
|
TABLE = "account_leases"
|
||||||
|
ACCOUNT_COLUMN = "role_change_available_at"
|
||||||
|
ACTOR_INDEX = "ix_account_events_actor_occurred"
|
||||||
|
|
||||||
|
#: 「一个账号同时只能有一个有效租约」的数据库级保证。
|
||||||
|
ACTIVE_ACCOUNT_EXPR = "CASE WHEN status = 'active' THEN account_id ELSE NULL END"
|
||||||
|
|
||||||
|
|
||||||
|
def _table_exists(name: str) -> bool:
|
||||||
|
conn = op.get_bind()
|
||||||
|
count = conn.execute(
|
||||||
|
sa.text(
|
||||||
|
"SELECT COUNT(*) FROM information_schema.tables "
|
||||||
|
"WHERE table_schema = DATABASE() AND table_name = :name"
|
||||||
|
),
|
||||||
|
{"name": name},
|
||||||
|
).scalar()
|
||||||
|
return bool(count)
|
||||||
|
|
||||||
|
|
||||||
|
def _column_exists(table: str, name: str) -> bool:
|
||||||
|
conn = op.get_bind()
|
||||||
|
count = conn.execute(
|
||||||
|
sa.text(
|
||||||
|
"SELECT COUNT(*) FROM information_schema.columns "
|
||||||
|
"WHERE table_schema = DATABASE() "
|
||||||
|
"AND table_name = :table AND column_name = :name"
|
||||||
|
),
|
||||||
|
{"table": table, "name": name},
|
||||||
|
).scalar()
|
||||||
|
return bool(count)
|
||||||
|
|
||||||
|
|
||||||
|
def _index_exists(table: str, name: str) -> bool:
|
||||||
|
conn = op.get_bind()
|
||||||
|
count = conn.execute(
|
||||||
|
sa.text(
|
||||||
|
"SELECT COUNT(*) FROM information_schema.statistics "
|
||||||
|
"WHERE table_schema = DATABASE() "
|
||||||
|
"AND table_name = :table AND index_name = :name"
|
||||||
|
),
|
||||||
|
{"table": table, "name": name},
|
||||||
|
).scalar()
|
||||||
|
return bool(count)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
if not _table_exists(TABLE):
|
||||||
|
op.create_table(
|
||||||
|
TABLE,
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("account_id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("holder_user_id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"scope", sa.String(length=16), nullable=False, server_default="elite"
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"purpose",
|
||||||
|
sa.String(length=24),
|
||||||
|
nullable=False,
|
||||||
|
server_default="exchange",
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"commodity_id", sa.String(length=64), nullable=False, server_default=""
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"batch_id", sa.String(length=64), nullable=False, server_default=""
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"status", sa.String(length=16), nullable=False, server_default="active"
|
||||||
|
),
|
||||||
|
sa.Column("leased_at", sa.DateTime(), nullable=False),
|
||||||
|
sa.Column("expires_at", sa.DateTime(), nullable=False),
|
||||||
|
sa.Column("released_at", sa.DateTime(), nullable=True),
|
||||||
|
sa.Column(
|
||||||
|
"release_reason",
|
||||||
|
sa.String(length=64),
|
||||||
|
nullable=False,
|
||||||
|
server_default="",
|
||||||
|
),
|
||||||
|
# ⚠️ 生成列必须排在 account_id / status 之后:MySQL 只允许生成列
|
||||||
|
# 引用它前面已定义的列。
|
||||||
|
sa.Column(
|
||||||
|
"active_account_id",
|
||||||
|
sa.Integer(),
|
||||||
|
sa.Computed(ACTIVE_ACCOUNT_EXPR, persisted=True),
|
||||||
|
nullable=True,
|
||||||
|
),
|
||||||
|
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["account_id"], ["accounts.id"], name="fk_lease_account"
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["holder_user_id"], ["users.id"], name="fk_lease_holder"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
if not _index_exists(TABLE, "uq_lease_active_account"):
|
||||||
|
op.create_index(
|
||||||
|
"uq_lease_active_account", TABLE, ["active_account_id"], unique=True
|
||||||
|
)
|
||||||
|
if not _index_exists(TABLE, "ix_leases_holder_status"):
|
||||||
|
op.create_index("ix_leases_holder_status", TABLE, ["holder_user_id", "status"])
|
||||||
|
if not _index_exists(TABLE, "ix_leases_status_expires"):
|
||||||
|
op.create_index("ix_leases_status_expires", TABLE, ["status", "expires_at"])
|
||||||
|
if not _index_exists(TABLE, "ix_account_leases_account_id"):
|
||||||
|
op.create_index("ix_account_leases_account_id", TABLE, ["account_id"])
|
||||||
|
|
||||||
|
if not _column_exists("accounts", ACCOUNT_COLUMN):
|
||||||
|
op.add_column(
|
||||||
|
"accounts",
|
||||||
|
sa.Column(
|
||||||
|
ACCOUNT_COLUMN,
|
||||||
|
sa.DateTime(),
|
||||||
|
nullable=True,
|
||||||
|
comment="精英宝典可换绑时刻(绝对时间);换绑冷却只记录不拦截",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
if not _index_exists("account_events", ACTOR_INDEX):
|
||||||
|
op.create_index(ACTOR_INDEX, "account_events", ["actor_id", "occurred_at"])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
if _index_exists("account_events", ACTOR_INDEX):
|
||||||
|
op.drop_index(ACTOR_INDEX, table_name="account_events")
|
||||||
|
if _column_exists("accounts", ACCOUNT_COLUMN):
|
||||||
|
op.drop_column("accounts", ACCOUNT_COLUMN)
|
||||||
|
if _table_exists(TABLE):
|
||||||
|
op.drop_table(TABLE)
|
||||||
@@ -0,0 +1,252 @@
|
|||||||
|
"""直播账号履约:SKU 映射、履约作业与事件
|
||||||
|
|
||||||
|
Revision ID: 20261117_0084
|
||||||
|
Revises: 20261117_0083
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "20261117_0084"
|
||||||
|
down_revision: str | None = "20261117_0083"
|
||||||
|
branch_labels: str | None = None
|
||||||
|
depends_on: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def _table_exists(table: str) -> bool:
|
||||||
|
return bool(
|
||||||
|
op.get_bind()
|
||||||
|
.execute(
|
||||||
|
sa.text(
|
||||||
|
"SELECT COUNT(*) FROM information_schema.tables "
|
||||||
|
"WHERE table_schema = DATABASE() AND table_name = :table"
|
||||||
|
),
|
||||||
|
{"table": table},
|
||||||
|
)
|
||||||
|
.scalar()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _index_exists(index: str) -> bool:
|
||||||
|
return bool(
|
||||||
|
op.get_bind()
|
||||||
|
.execute(
|
||||||
|
sa.text(
|
||||||
|
"SELECT COUNT(*) FROM information_schema.statistics "
|
||||||
|
"WHERE table_schema = DATABASE() AND index_name = :index"
|
||||||
|
),
|
||||||
|
{"index": index},
|
||||||
|
)
|
||||||
|
.scalar()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
if not _table_exists("platform_commodity_mappings"):
|
||||||
|
op.create_table(
|
||||||
|
"platform_commodity_mappings",
|
||||||
|
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"target_platform",
|
||||||
|
sa.String(length=16),
|
||||||
|
nullable=False,
|
||||||
|
server_default="douyu",
|
||||||
|
),
|
||||||
|
sa.Column("internal_sku_key", sa.String(length=255), nullable=False),
|
||||||
|
sa.Column("commodity_id", sa.String(length=64), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"goods_name", sa.String(length=255), nullable=False, server_default=""
|
||||||
|
),
|
||||||
|
sa.Column("required_points", sa.Integer(), nullable=True),
|
||||||
|
sa.Column(
|
||||||
|
"scope", sa.String(length=16), nullable=False, server_default="elite"
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"enabled", sa.Boolean(), nullable=False, server_default=sa.text("1")
|
||||||
|
),
|
||||||
|
sa.Column("created_by", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||||
|
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(["created_by"], ["users.id"]),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
sa.UniqueConstraint(
|
||||||
|
"target_platform",
|
||||||
|
"internal_sku_key",
|
||||||
|
name="uq_platform_commodity_mapping_sku",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
if not _index_exists("ix_platform_commodity_mapping_enabled"):
|
||||||
|
op.create_index(
|
||||||
|
"ix_platform_commodity_mapping_enabled",
|
||||||
|
"platform_commodity_mappings",
|
||||||
|
["target_platform", "enabled"],
|
||||||
|
)
|
||||||
|
|
||||||
|
if not _table_exists("platform_fulfillment_tasks"):
|
||||||
|
op.create_table(
|
||||||
|
"platform_fulfillment_tasks",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"source_system",
|
||||||
|
sa.String(length=32),
|
||||||
|
nullable=False,
|
||||||
|
server_default="order_site",
|
||||||
|
),
|
||||||
|
sa.Column("source_order_id", sa.String(length=64), nullable=False),
|
||||||
|
sa.Column("source_order_item_id", sa.String(length=64), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"source_fulfillment_id",
|
||||||
|
sa.String(length=64),
|
||||||
|
nullable=False,
|
||||||
|
server_default="",
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"platform_order_id",
|
||||||
|
sa.String(length=128),
|
||||||
|
nullable=False,
|
||||||
|
server_default="",
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"provider", sa.String(length=32), nullable=False, server_default=""
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"shop_id", sa.String(length=64), nullable=False, server_default=""
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"shop_name", sa.String(length=255), nullable=False, server_default=""
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"sku_code", sa.String(length=255), nullable=False, server_default=""
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"sku_name", sa.String(length=512), nullable=False, server_default=""
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"internal_sku_key",
|
||||||
|
sa.String(length=255),
|
||||||
|
nullable=False,
|
||||||
|
server_default="",
|
||||||
|
),
|
||||||
|
sa.Column("quantity", sa.Integer(), nullable=False, server_default="1"),
|
||||||
|
sa.Column(
|
||||||
|
"order_amount_fen", sa.Integer(), nullable=False, server_default="0"
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"target_platform",
|
||||||
|
sa.String(length=16),
|
||||||
|
nullable=False,
|
||||||
|
server_default="douyu",
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"scope", sa.String(length=16), nullable=False, server_default="elite"
|
||||||
|
),
|
||||||
|
sa.Column("commodity_mapping_id", sa.Integer(), nullable=True),
|
||||||
|
sa.Column(
|
||||||
|
"commodity_id", sa.String(length=64), nullable=False, server_default=""
|
||||||
|
),
|
||||||
|
sa.Column("required_points", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("account_id", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("lease_id", sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column("bind_task_id", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("exchange_task_id", sa.Integer(), nullable=True),
|
||||||
|
sa.Column(
|
||||||
|
"binding_status",
|
||||||
|
sa.String(length=24),
|
||||||
|
nullable=False,
|
||||||
|
server_default="not_started",
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"execution_status",
|
||||||
|
sa.String(length=24),
|
||||||
|
nullable=False,
|
||||||
|
server_default="pending_mapping",
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"exchange_status",
|
||||||
|
sa.String(length=24),
|
||||||
|
nullable=False,
|
||||||
|
server_default="not_started",
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"issue_code", sa.String(length=64), nullable=False, server_default=""
|
||||||
|
),
|
||||||
|
sa.Column("last_error", sa.Text(), nullable=False),
|
||||||
|
sa.Column("source_snapshot_json", sa.JSON(), nullable=True),
|
||||||
|
sa.Column("operator_id", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("completed_at", sa.DateTime(), nullable=True),
|
||||||
|
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||||
|
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["commodity_mapping_id"],
|
||||||
|
["platform_commodity_mappings.id"],
|
||||||
|
ondelete="SET NULL",
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["account_id"], ["accounts.id"], ondelete="SET NULL"
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["lease_id"], ["account_leases.id"], ondelete="SET NULL"
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["bind_task_id"], ["douyu_tasks.id"], ondelete="SET NULL"
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["exchange_task_id"], ["douyu_tasks.id"], ondelete="SET NULL"
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(["operator_id"], ["users.id"], ondelete="SET NULL"),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
sa.UniqueConstraint(
|
||||||
|
"source_system",
|
||||||
|
"source_order_item_id",
|
||||||
|
name="uq_platform_fulfillment_source_item",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
for name, columns in (
|
||||||
|
("ix_platform_fulfillment_tasks_internal_sku_key", ["internal_sku_key"]),
|
||||||
|
("ix_platform_fulfillment_tasks_account_id", ["account_id"]),
|
||||||
|
("ix_platform_fulfillment_status_updated", ["execution_status", "updated_at"]),
|
||||||
|
("ix_platform_fulfillment_order", ["source_order_id", "source_order_item_id"]),
|
||||||
|
):
|
||||||
|
if not _index_exists(name):
|
||||||
|
op.create_index(name, "platform_fulfillment_tasks", columns)
|
||||||
|
|
||||||
|
if not _table_exists("platform_fulfillment_events"):
|
||||||
|
op.create_table(
|
||||||
|
"platform_fulfillment_events",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("task_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("event_type", sa.String(length=64), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"actor_type",
|
||||||
|
sa.String(length=16),
|
||||||
|
nullable=False,
|
||||||
|
server_default="system",
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"actor_id", sa.String(length=64), nullable=False, server_default=""
|
||||||
|
),
|
||||||
|
sa.Column("detail_json", sa.JSON(), nullable=True),
|
||||||
|
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["task_id"], ["platform_fulfillment_tasks.id"], ondelete="CASCADE"
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
)
|
||||||
|
for name, columns in (
|
||||||
|
("ix_platform_fulfillment_events_task_id", ["task_id"]),
|
||||||
|
("ix_platform_fulfillment_events_task_created", ["task_id", "created_at"]),
|
||||||
|
):
|
||||||
|
if not _index_exists(name):
|
||||||
|
op.create_index(name, "platform_fulfillment_events", columns)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
for table in (
|
||||||
|
"platform_fulfillment_events",
|
||||||
|
"platform_fulfillment_tasks",
|
||||||
|
"platform_commodity_mappings",
|
||||||
|
):
|
||||||
|
if _table_exists(table):
|
||||||
|
op.drop_table(table)
|
||||||
@@ -161,6 +161,14 @@ class Account(Base):
|
|||||||
# S6 拆解时差点把这个信息丢掉,所以补成独立布尔列。
|
# S6 拆解时差点把这个信息丢掉,所以补成独立布尔列。
|
||||||
esports_opened: Mapped[bool | None] = mapped_column(Boolean, nullable=True)
|
esports_opened: Mapped[bool | None] = mapped_column(Boolean, nullable=True)
|
||||||
change_role_wait_time: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
change_role_wait_time: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||||
|
# 精英宝典**可换绑时刻**(绝对时间)。`change_role_wait_time` 是接口原文的
|
||||||
|
# 「剩余秒数」,落库那一刻就开始过期 —— 过几天再读它,既不知道是不是还在冷却,
|
||||||
|
# 也不知道什么时候能换绑。所以每次写入时同时记下 `now + wait_time`。
|
||||||
|
# 不同活动的换绑冷却不同,因此**按作用域分列**(电竞手册用既有的
|
||||||
|
# `esports_can_change_time`,它本来就是绝对时刻,不另开副本)。
|
||||||
|
role_change_available_at: Mapped[datetime | None] = mapped_column(
|
||||||
|
UTCDateTime, nullable=True
|
||||||
|
)
|
||||||
# 精英宝典开通状态(getUserInfo 的 manualType / expireTime)。
|
# 精英宝典开通状态(getUserInfo 的 manualType / expireTime)。
|
||||||
# 光看积分区分不了「开通后积分花完」和「从未开通」,必须单独落库。
|
# 光看积分区分不了「开通后积分花完」和「从未开通」,必须单独落库。
|
||||||
elite_opened: Mapped[bool | None] = mapped_column(Boolean, nullable=True)
|
elite_opened: Mapped[bool | None] = mapped_column(Boolean, nullable=True)
|
||||||
@@ -1623,6 +1631,270 @@ class AccountEvent(Base):
|
|||||||
"subject_key",
|
"subject_key",
|
||||||
"occurred_at",
|
"occurred_at",
|
||||||
),
|
),
|
||||||
|
# 「某个客服这段时间做了什么」——池化后客服不再持有账号,
|
||||||
|
# 这条是管理侧追责与对账的主查询路径,此前没有任何索引可用。
|
||||||
|
Index("ix_account_events_actor_occurred", "actor_id", "occurred_at"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AccountLease(Base):
|
||||||
|
"""账号租约:谁在**此刻**可以使用这个账号。
|
||||||
|
|
||||||
|
## 为什么要有它
|
||||||
|
|
||||||
|
以前「能不能操作某账号」的唯一判据是 `accounts.assigned_to == 我`。
|
||||||
|
账号因此被**永久独占**:客服名下的账号积分花完了也不会流向别人,
|
||||||
|
管理员只能人工调拨。池化之后这层隐式互斥消失,必须有一个显式的
|
||||||
|
「临时使用权」——就是这张表。
|
||||||
|
|
||||||
|
## 归属与使用权分离
|
||||||
|
|
||||||
|
- `accounts.assigned_to` 收窄为**维护责任**(谁负责重登、开通、进货),
|
||||||
|
由管理员/运营承担,客服名下不再持有账号;
|
||||||
|
- `account_leases` 表示**此刻谁在用**,用完即释放。
|
||||||
|
|
||||||
|
## 一个账号同时只能有一个有效租约
|
||||||
|
|
||||||
|
靠生成列 `active_account_id` + 唯一索引在**数据库层**保证:非 active 时为 NULL,
|
||||||
|
MySQL 唯一索引允许多个 NULL,所以历史记录不受限。并发抢号由数据库裁决 ——
|
||||||
|
两个事务抢同一账号必有一个撞唯一键,捕获后换下一个候选即可,不需要应用层加锁。
|
||||||
|
|
||||||
|
⚠️ `active_account_id` 必须声明在 `account_id` 与 `status` **之后**:
|
||||||
|
MySQL 要求生成列只能引用它前面已定义的列。
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = "account_leases"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
|
||||||
|
account_id: Mapped[int] = mapped_column(
|
||||||
|
ForeignKey("accounts.id"), nullable=False, index=True
|
||||||
|
)
|
||||||
|
holder_user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
||||||
|
# 作用域:elite / esports / peace(与 douyu_tasks.handbook_scope 同域)
|
||||||
|
scope: Mapped[str] = mapped_column(String(16), nullable=False, default="elite")
|
||||||
|
purpose: Mapped[str] = mapped_column(
|
||||||
|
String(24), nullable=False, default="exchange", server_default="exchange"
|
||||||
|
)
|
||||||
|
commodity_id: Mapped[str] = mapped_column(
|
||||||
|
String(64), nullable=False, default="", server_default=""
|
||||||
|
)
|
||||||
|
batch_id: Mapped[str] = mapped_column(
|
||||||
|
String(64), nullable=False, default="", server_default=""
|
||||||
|
)
|
||||||
|
# active / released / expired
|
||||||
|
status: Mapped[str] = mapped_column(
|
||||||
|
String(16), nullable=False, default="active", server_default="active"
|
||||||
|
)
|
||||||
|
leased_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
|
||||||
|
# TTL 兜底:进程重启、页面关掉都能靠它把租约收回来。
|
||||||
|
expires_at: Mapped[datetime] = mapped_column(UTCDateTime, nullable=False)
|
||||||
|
released_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||||
|
release_reason: Mapped[str] = mapped_column(
|
||||||
|
String(64), nullable=False, default="", server_default=""
|
||||||
|
)
|
||||||
|
# 生成列:active 时等于 account_id,其余为 NULL。唯一索引因此只约束「有效租约」。
|
||||||
|
active_account_id: Mapped[int | None] = mapped_column(
|
||||||
|
Integer,
|
||||||
|
Computed(
|
||||||
|
"CASE WHEN status = 'active' THEN account_id ELSE NULL END",
|
||||||
|
persisted=True,
|
||||||
|
),
|
||||||
|
nullable=True,
|
||||||
|
)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
Index("uq_lease_active_account", "active_account_id", unique=True),
|
||||||
|
Index("ix_leases_holder_status", "holder_user_id", "status"),
|
||||||
|
Index("ix_leases_status_expires", "status", "expires_at"),
|
||||||
|
)
|
||||||
|
|
||||||
|
account: Mapped[Account] = relationship("Account")
|
||||||
|
holder: Mapped[User] = relationship("User")
|
||||||
|
|
||||||
|
|
||||||
|
class PlatformCommodityMapping(Base):
|
||||||
|
"""order_site 内部 SKU 到斗鱼商品的显式映射。"""
|
||||||
|
|
||||||
|
__tablename__ = "platform_commodity_mappings"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
target_platform: Mapped[str] = mapped_column(
|
||||||
|
String(16), nullable=False, default="douyu", server_default="douyu"
|
||||||
|
)
|
||||||
|
internal_sku_key: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||||
|
commodity_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
goods_name: Mapped[str] = mapped_column(
|
||||||
|
String(255), nullable=False, default="", server_default=""
|
||||||
|
)
|
||||||
|
required_points: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||||
|
scope: Mapped[str] = mapped_column(
|
||||||
|
String(16), nullable=False, default="elite", server_default="elite"
|
||||||
|
)
|
||||||
|
enabled: Mapped[bool] = mapped_column(
|
||||||
|
Boolean, nullable=False, default=True, server_default="1"
|
||||||
|
)
|
||||||
|
created_by: Mapped[int | None] = mapped_column(
|
||||||
|
ForeignKey("users.id"), nullable=True
|
||||||
|
)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(
|
||||||
|
UTCDateTime, default=_utcnow, onupdate=_utcnow
|
||||||
|
)
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint(
|
||||||
|
"target_platform",
|
||||||
|
"internal_sku_key",
|
||||||
|
name="uq_platform_commodity_mapping_sku",
|
||||||
|
),
|
||||||
|
Index(
|
||||||
|
"ix_platform_commodity_mapping_enabled",
|
||||||
|
"target_platform",
|
||||||
|
"enabled",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class PlatformFulfillmentTask(Base):
|
||||||
|
"""一笔 order_site 订单项在 live-hub 中的直播账号履约作业。"""
|
||||||
|
|
||||||
|
__tablename__ = "platform_fulfillment_tasks"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
|
||||||
|
source_system: Mapped[str] = mapped_column(
|
||||||
|
String(32), nullable=False, default="order_site", server_default="order_site"
|
||||||
|
)
|
||||||
|
source_order_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
source_order_item_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
source_fulfillment_id: Mapped[str] = mapped_column(
|
||||||
|
String(64), nullable=False, default="", server_default=""
|
||||||
|
)
|
||||||
|
platform_order_id: Mapped[str] = mapped_column(
|
||||||
|
String(128), nullable=False, default="", server_default=""
|
||||||
|
)
|
||||||
|
provider: Mapped[str] = mapped_column(
|
||||||
|
String(32), nullable=False, default="", server_default=""
|
||||||
|
)
|
||||||
|
shop_id: Mapped[str] = mapped_column(
|
||||||
|
String(64), nullable=False, default="", server_default=""
|
||||||
|
)
|
||||||
|
shop_name: Mapped[str] = mapped_column(
|
||||||
|
String(255), nullable=False, default="", server_default=""
|
||||||
|
)
|
||||||
|
sku_code: Mapped[str] = mapped_column(
|
||||||
|
String(255), nullable=False, default="", server_default=""
|
||||||
|
)
|
||||||
|
sku_name: Mapped[str] = mapped_column(
|
||||||
|
String(512), nullable=False, default="", server_default=""
|
||||||
|
)
|
||||||
|
internal_sku_key: Mapped[str] = mapped_column(
|
||||||
|
String(255), nullable=False, default="", server_default="", index=True
|
||||||
|
)
|
||||||
|
quantity: Mapped[int] = mapped_column(
|
||||||
|
Integer, nullable=False, default=1, server_default="1"
|
||||||
|
)
|
||||||
|
order_amount_fen: Mapped[int] = mapped_column(
|
||||||
|
Integer, nullable=False, default=0, server_default="0"
|
||||||
|
)
|
||||||
|
target_platform: Mapped[str] = mapped_column(
|
||||||
|
String(16), nullable=False, default="douyu", server_default="douyu"
|
||||||
|
)
|
||||||
|
scope: Mapped[str] = mapped_column(
|
||||||
|
String(16), nullable=False, default="elite", server_default="elite"
|
||||||
|
)
|
||||||
|
commodity_mapping_id: Mapped[int | None] = mapped_column(
|
||||||
|
ForeignKey("platform_commodity_mappings.id", ondelete="SET NULL"),
|
||||||
|
nullable=True,
|
||||||
|
)
|
||||||
|
commodity_id: Mapped[str] = mapped_column(
|
||||||
|
String(64), nullable=False, default="", server_default=""
|
||||||
|
)
|
||||||
|
required_points: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||||
|
account_id: Mapped[int | None] = mapped_column(
|
||||||
|
ForeignKey("accounts.id", ondelete="SET NULL"), nullable=True, index=True
|
||||||
|
)
|
||||||
|
lease_id: Mapped[int | None] = mapped_column(
|
||||||
|
ForeignKey("account_leases.id", ondelete="SET NULL"), nullable=True
|
||||||
|
)
|
||||||
|
bind_task_id: Mapped[int | None] = mapped_column(
|
||||||
|
ForeignKey("douyu_tasks.id", ondelete="SET NULL"), nullable=True
|
||||||
|
)
|
||||||
|
exchange_task_id: Mapped[int | None] = mapped_column(
|
||||||
|
ForeignKey("douyu_tasks.id", ondelete="SET NULL"), nullable=True
|
||||||
|
)
|
||||||
|
binding_status: Mapped[str] = mapped_column(
|
||||||
|
String(24), nullable=False, default="not_started", server_default="not_started"
|
||||||
|
)
|
||||||
|
execution_status: Mapped[str] = mapped_column(
|
||||||
|
String(24),
|
||||||
|
nullable=False,
|
||||||
|
default="pending_mapping",
|
||||||
|
server_default="pending_mapping",
|
||||||
|
)
|
||||||
|
exchange_status: Mapped[str] = mapped_column(
|
||||||
|
String(24), nullable=False, default="not_started", server_default="not_started"
|
||||||
|
)
|
||||||
|
issue_code: Mapped[str] = mapped_column(
|
||||||
|
String(64), nullable=False, default="", server_default=""
|
||||||
|
)
|
||||||
|
last_error: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||||
|
source_snapshot_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||||
|
operator_id: Mapped[int | None] = mapped_column(
|
||||||
|
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
|
||||||
|
)
|
||||||
|
completed_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(
|
||||||
|
UTCDateTime, default=_utcnow, onupdate=_utcnow
|
||||||
|
)
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint(
|
||||||
|
"source_system",
|
||||||
|
"source_order_item_id",
|
||||||
|
name="uq_platform_fulfillment_source_item",
|
||||||
|
),
|
||||||
|
Index(
|
||||||
|
"ix_platform_fulfillment_status_updated",
|
||||||
|
"execution_status",
|
||||||
|
"updated_at",
|
||||||
|
),
|
||||||
|
Index(
|
||||||
|
"ix_platform_fulfillment_order",
|
||||||
|
"source_order_id",
|
||||||
|
"source_order_item_id",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class PlatformFulfillmentEvent(Base):
|
||||||
|
"""直播账号履约作业事件,只追加。"""
|
||||||
|
|
||||||
|
__tablename__ = "platform_fulfillment_events"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
|
||||||
|
task_id: Mapped[int] = mapped_column(
|
||||||
|
ForeignKey("platform_fulfillment_tasks.id", ondelete="CASCADE"),
|
||||||
|
nullable=False,
|
||||||
|
index=True,
|
||||||
|
)
|
||||||
|
event_type: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
actor_type: Mapped[str] = mapped_column(
|
||||||
|
String(16), nullable=False, default="system", server_default="system"
|
||||||
|
)
|
||||||
|
actor_id: Mapped[str] = mapped_column(
|
||||||
|
String(64), nullable=False, default="", server_default=""
|
||||||
|
)
|
||||||
|
detail_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
Index(
|
||||||
|
"ix_platform_fulfillment_events_task_created",
|
||||||
|
"task_id",
|
||||||
|
"created_at",
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -37,6 +37,10 @@ PERMISSIONS = {
|
|||||||
"douyu:collab:manage": "删除斗鱼外部单协作",
|
"douyu:collab:manage": "删除斗鱼外部单协作",
|
||||||
# CK 是凭据:导到剪贴板 = 把凭据带出系统,单独一个点,默认只给运营
|
# CK 是凭据:导到剪贴板 = 把凭据带出系统,单独一个点,默认只给运营
|
||||||
"douyu:collab:ck_export": "导出斗鱼外部单协作账号的 CK(写剪贴板)",
|
"douyu:collab:ck_export": "导出斗鱼外部单协作账号的 CK(写剪贴板)",
|
||||||
|
# 直播账号履约:order_site 订单由内部斗鱼账号完成游戏角色绑定和人工兑换
|
||||||
|
"platform_fulfillment:view": "查看直播账号履约任务",
|
||||||
|
"platform_fulfillment:use": "分配账号、绑定角色和处理直播账号履约",
|
||||||
|
"platform_fulfillment:admin": "维护直播账号履约商品映射",
|
||||||
"yyb:session": "应用宝扫码登录与角色查询",
|
"yyb:session": "应用宝扫码登录与角色查询",
|
||||||
"yyb:recharge": "应用宝充值与付款",
|
"yyb:recharge": "应用宝充值与付款",
|
||||||
"yyb:manage": "接管并操作他人的应用宝任务",
|
"yyb:manage": "接管并操作他人的应用宝任务",
|
||||||
@@ -113,6 +117,9 @@ ROLE_PERMISSIONS = {
|
|||||||
"douyu:collab:edit",
|
"douyu:collab:edit",
|
||||||
"douyu:collab:manage",
|
"douyu:collab:manage",
|
||||||
"douyu:collab:ck_export",
|
"douyu:collab:ck_export",
|
||||||
|
"platform_fulfillment:view",
|
||||||
|
"platform_fulfillment:use",
|
||||||
|
"platform_fulfillment:admin",
|
||||||
"yyb:session",
|
"yyb:session",
|
||||||
"yyb:recharge",
|
"yyb:recharge",
|
||||||
"yyb:manage",
|
"yyb:manage",
|
||||||
@@ -164,6 +171,8 @@ ROLE_PERMISSIONS = {
|
|||||||
"douyu:task",
|
"douyu:task",
|
||||||
"douyu:collab:view",
|
"douyu:collab:view",
|
||||||
"douyu:collab:edit",
|
"douyu:collab:edit",
|
||||||
|
"platform_fulfillment:view",
|
||||||
|
"platform_fulfillment:use",
|
||||||
"yyb:session",
|
"yyb:session",
|
||||||
"yyb:history",
|
"yyb:history",
|
||||||
"weibo:view",
|
"weibo:view",
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import threading
|
|
||||||
from datetime import UTC, datetime
|
from datetime import UTC, datetime
|
||||||
from typing import Any, cast
|
from typing import Any, cast
|
||||||
|
|
||||||
@@ -54,6 +53,7 @@ from ..schemas import (
|
|||||||
from ..services.account_binding import bind_payload
|
from ..services.account_binding import bind_payload
|
||||||
from ..services.audit_service import record_audit
|
from ..services.audit_service import record_audit
|
||||||
from ..services.business_events import record_recharge
|
from ..services.business_events import record_recharge
|
||||||
|
from ..services.douyu_batch_launcher import start_douyu_batch
|
||||||
from ..services.douyu_runner import DouyuBatchRunner, douyu_batch_registry
|
from ..services.douyu_runner import DouyuBatchRunner, douyu_batch_registry
|
||||||
from ..services.douyu_service import (
|
from ..services.douyu_service import (
|
||||||
DOUYU_CONFIG_FIELDS,
|
DOUYU_CONFIG_FIELDS,
|
||||||
@@ -768,22 +768,12 @@ async def create_task_batch(
|
|||||||
)
|
)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|
||||||
log_queue = asyncio.Queue()
|
start_douyu_batch(
|
||||||
loop = asyncio.get_running_loop()
|
|
||||||
thread_db = SessionLocal()
|
|
||||||
runner = DouyuBatchRunner(
|
|
||||||
db=thread_db,
|
|
||||||
batch_id=batch_id,
|
batch_id=batch_id,
|
||||||
task_type=req.task_type,
|
task_type=req.task_type,
|
||||||
payload=req.payload,
|
payload=req.payload,
|
||||||
log_queue=log_queue,
|
|
||||||
loop=loop,
|
|
||||||
concurrency=req.concurrency,
|
concurrency=req.concurrency,
|
||||||
)
|
)
|
||||||
douyu_batch_registry.register(batch_id, log_queue, loop, runner)
|
|
||||||
|
|
||||||
thread = threading.Thread(target=runner.run, daemon=True)
|
|
||||||
thread.start()
|
|
||||||
|
|
||||||
return {"batch_id": batch_id, "count": count, "success": True}
|
return {"batch_id": batch_id, "count": count, "success": True}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,283 @@
|
|||||||
|
"""直播账号履约工作台 API。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Query
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from ..database import get_db
|
||||||
|
from ..deps import require_permission
|
||||||
|
from ..models import User
|
||||||
|
from ..schemas import (
|
||||||
|
PlatformFulfillmentCompleteRequest,
|
||||||
|
PlatformFulfillmentMappingUpsert,
|
||||||
|
PlatformFulfillmentReasonRequest,
|
||||||
|
)
|
||||||
|
from ..services.audit_service import record_audit
|
||||||
|
from ..services.platform_fulfillment import service
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/platform-fulfillment", tags=["直播账号履约"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/tasks")
|
||||||
|
def list_tasks(
|
||||||
|
status: str = Query("", max_length=32),
|
||||||
|
keyword: str = Query("", max_length=200),
|
||||||
|
page: int = Query(1, ge=1),
|
||||||
|
page_size: int = Query(20, ge=1, le=100),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current: User = Depends(require_permission("platform_fulfillment:view")),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
del current
|
||||||
|
return service.list_tasks(
|
||||||
|
db,
|
||||||
|
status=status,
|
||||||
|
keyword=keyword,
|
||||||
|
page=page,
|
||||||
|
page_size=page_size,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/sync")
|
||||||
|
def sync_tasks(
|
||||||
|
limit: int = Query(100, ge=1, le=500),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current: User = Depends(require_permission("platform_fulfillment:use")),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
result = service.sync_pending_tasks(db, limit=limit)
|
||||||
|
record_audit(
|
||||||
|
db,
|
||||||
|
current,
|
||||||
|
action="platform_fulfillment:sync",
|
||||||
|
target="order_site",
|
||||||
|
detail=result,
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/tasks/{task_id}")
|
||||||
|
def get_task(
|
||||||
|
task_id: int,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current: User = Depends(require_permission("platform_fulfillment:view")),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
del current
|
||||||
|
return service.get_task_detail(db, task_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/mappings")
|
||||||
|
def list_mappings(
|
||||||
|
keyword: str = Query("", max_length=200),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current: User = Depends(require_permission("platform_fulfillment:view")),
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
del current
|
||||||
|
return service.list_mappings(db, keyword=keyword)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/mappings")
|
||||||
|
def upsert_mapping(
|
||||||
|
req: PlatformFulfillmentMappingUpsert,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current: User = Depends(require_permission("platform_fulfillment:admin")),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
result = service.upsert_mapping(
|
||||||
|
db,
|
||||||
|
internal_sku_key=req.internal_sku_key,
|
||||||
|
commodity_id=req.commodity_id,
|
||||||
|
goods_name=req.goods_name,
|
||||||
|
required_points=req.required_points,
|
||||||
|
enabled=req.enabled,
|
||||||
|
current=current,
|
||||||
|
)
|
||||||
|
record_audit(
|
||||||
|
db,
|
||||||
|
current,
|
||||||
|
action="platform_fulfillment:mapping:upsert",
|
||||||
|
target=f"platform_commodity_mapping:{result['id']}",
|
||||||
|
detail=result,
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/tasks/{task_id}/allocate")
|
||||||
|
def allocate_task(
|
||||||
|
task_id: int,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current: User = Depends(require_permission("platform_fulfillment:use")),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
result = service.allocate_task(db, task_id=task_id, current=current)
|
||||||
|
record_audit(
|
||||||
|
db,
|
||||||
|
current,
|
||||||
|
action="platform_fulfillment:allocate",
|
||||||
|
target=f"platform_fulfillment_task:{task_id}",
|
||||||
|
detail={"accountId": result.get("task", {}).get("account", {})},
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/tasks/{task_id}/bind/start")
|
||||||
|
async def start_binding(
|
||||||
|
task_id: int,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current: User = Depends(require_permission("platform_fulfillment:use")),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
result = await service.start_binding(db, task_id=task_id, current=current)
|
||||||
|
record_audit(
|
||||||
|
db,
|
||||||
|
current,
|
||||||
|
action="platform_fulfillment:binding:start",
|
||||||
|
target=f"platform_fulfillment_task:{task_id}",
|
||||||
|
detail={"bindTaskId": result.get("task", {}).get("bindTask", {})},
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/tasks/{task_id}/bind/refresh")
|
||||||
|
def refresh_binding(
|
||||||
|
task_id: int,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current: User = Depends(require_permission("platform_fulfillment:use")),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
del current
|
||||||
|
return service.refresh_binding(db, task_id=task_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/tasks/{task_id}/bind/confirm")
|
||||||
|
async def confirm_binding(
|
||||||
|
task_id: int,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current: User = Depends(require_permission("platform_fulfillment:use")),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
result = await service.confirm_binding(db, task_id=task_id, current=current)
|
||||||
|
record_audit(
|
||||||
|
db,
|
||||||
|
current,
|
||||||
|
action="platform_fulfillment:binding:confirm",
|
||||||
|
target=f"platform_fulfillment_task:{task_id}",
|
||||||
|
detail={"confirmTaskId": result.get("task", {}).get("bindTask", {})},
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/tasks/{task_id}/eligibility/refresh")
|
||||||
|
def refresh_eligibility(
|
||||||
|
task_id: int,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current: User = Depends(require_permission("platform_fulfillment:use")),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
result = service.refresh_exchange_eligibility(
|
||||||
|
db, task_id=task_id, current=current
|
||||||
|
)
|
||||||
|
record_audit(
|
||||||
|
db,
|
||||||
|
current,
|
||||||
|
action="platform_fulfillment:eligibility:refresh",
|
||||||
|
target=f"platform_fulfillment_task:{task_id}",
|
||||||
|
detail={"exchangeStatus": result.get("task", {}).get("exchangeStatus")},
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/tasks/{task_id}/complete")
|
||||||
|
def complete_task(
|
||||||
|
task_id: int,
|
||||||
|
req: PlatformFulfillmentCompleteRequest,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current: User = Depends(require_permission("platform_fulfillment:use")),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
result = service.complete_manual_exchange(
|
||||||
|
db,
|
||||||
|
task_id=task_id,
|
||||||
|
current=current,
|
||||||
|
note=req.note,
|
||||||
|
)
|
||||||
|
record_audit(
|
||||||
|
db,
|
||||||
|
current,
|
||||||
|
action="platform_fulfillment:complete",
|
||||||
|
target=f"platform_fulfillment_task:{task_id}",
|
||||||
|
detail={"note": req.note},
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/tasks/{task_id}/release")
|
||||||
|
def release_task(
|
||||||
|
task_id: int,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current: User = Depends(require_permission("platform_fulfillment:use")),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
result = service.release_task_account(
|
||||||
|
db, task_id=task_id, current=current, reason="manual_release"
|
||||||
|
)
|
||||||
|
record_audit(
|
||||||
|
db,
|
||||||
|
current,
|
||||||
|
action="platform_fulfillment:release",
|
||||||
|
target=f"platform_fulfillment_task:{task_id}",
|
||||||
|
detail={},
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/tasks/{task_id}/manual")
|
||||||
|
def mark_manual(
|
||||||
|
task_id: int,
|
||||||
|
req: PlatformFulfillmentReasonRequest,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current: User = Depends(require_permission("platform_fulfillment:use")),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
result = service.mark_manual_required(
|
||||||
|
db,
|
||||||
|
task_id=task_id,
|
||||||
|
current=current,
|
||||||
|
reason=req.reason,
|
||||||
|
)
|
||||||
|
record_audit(
|
||||||
|
db,
|
||||||
|
current,
|
||||||
|
action="platform_fulfillment:manual_required",
|
||||||
|
target=f"platform_fulfillment_task:{task_id}",
|
||||||
|
detail={"reason": req.reason},
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/tasks/{task_id}/cancel")
|
||||||
|
def cancel_task(
|
||||||
|
task_id: int,
|
||||||
|
req: PlatformFulfillmentReasonRequest,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current: User = Depends(require_permission("platform_fulfillment:use")),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
result = service.cancel_task(
|
||||||
|
db,
|
||||||
|
task_id=task_id,
|
||||||
|
current=current,
|
||||||
|
reason=req.reason,
|
||||||
|
)
|
||||||
|
record_audit(
|
||||||
|
db,
|
||||||
|
current,
|
||||||
|
action="platform_fulfillment:cancel",
|
||||||
|
target=f"platform_fulfillment_task:{task_id}",
|
||||||
|
detail={"reason": req.reason},
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ["router"]
|
||||||
@@ -1560,6 +1560,22 @@ class DouyuConfigUpdate(BaseModel):
|
|||||||
skin_id: str | None = None
|
skin_id: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class PlatformFulfillmentMappingUpsert(BaseModel):
|
||||||
|
internal_sku_key: str = Field(..., min_length=1, max_length=255)
|
||||||
|
commodity_id: str = Field(..., min_length=1, max_length=64)
|
||||||
|
goods_name: str = Field(default="", max_length=255)
|
||||||
|
required_points: int | None = Field(default=None, ge=0)
|
||||||
|
enabled: bool = True
|
||||||
|
|
||||||
|
|
||||||
|
class PlatformFulfillmentReasonRequest(BaseModel):
|
||||||
|
reason: str = Field(default="", max_length=2000)
|
||||||
|
|
||||||
|
|
||||||
|
class PlatformFulfillmentCompleteRequest(BaseModel):
|
||||||
|
note: str = Field(default="", max_length=1000)
|
||||||
|
|
||||||
|
|
||||||
class DouyuTaskBatchRequest(BaseModel):
|
class DouyuTaskBatchRequest(BaseModel):
|
||||||
account_ids: list[int]
|
account_ids: list[int]
|
||||||
task_type: str
|
task_type: str
|
||||||
|
|||||||
@@ -22,6 +22,12 @@ from .jobs.douyu_tasks_retention import (
|
|||||||
from .jobs.douyu_tasks_retention import (
|
from .jobs.douyu_tasks_retention import (
|
||||||
run_douyu_tasks_retention,
|
run_douyu_tasks_retention,
|
||||||
)
|
)
|
||||||
|
from .jobs.platform_fulfillment_lease_reaper import (
|
||||||
|
JOB_KEY as PLATFORM_FULFILLMENT_LEASE_REAPER_KEY,
|
||||||
|
)
|
||||||
|
from .jobs.platform_fulfillment_lease_reaper import (
|
||||||
|
run_platform_fulfillment_lease_reaper,
|
||||||
|
)
|
||||||
from .jobs.points_expire import JOB_KEY as POINTS_EXPIRE_KEY
|
from .jobs.points_expire import JOB_KEY as POINTS_EXPIRE_KEY
|
||||||
from .jobs.points_expire import run_points_expire_check
|
from .jobs.points_expire import run_points_expire_check
|
||||||
from .scheduler import (
|
from .scheduler import (
|
||||||
@@ -43,6 +49,7 @@ __all__ = [
|
|||||||
"CK_HEALTH_KEY",
|
"CK_HEALTH_KEY",
|
||||||
"CK_RELOGIN_KEY",
|
"CK_RELOGIN_KEY",
|
||||||
"DOUYU_TASKS_RETENTION_KEY",
|
"DOUYU_TASKS_RETENTION_KEY",
|
||||||
|
"PLATFORM_FULFILLMENT_LEASE_REAPER_KEY",
|
||||||
"POINTS_EXPIRE_KEY",
|
"POINTS_EXPIRE_KEY",
|
||||||
"JobSpec",
|
"JobSpec",
|
||||||
"automation_enabled",
|
"automation_enabled",
|
||||||
@@ -57,6 +64,7 @@ __all__ = [
|
|||||||
"run_douyu_tasks_retention",
|
"run_douyu_tasks_retention",
|
||||||
"run_due_jobs",
|
"run_due_jobs",
|
||||||
"run_job_now",
|
"run_job_now",
|
||||||
|
"run_platform_fulfillment_lease_reaper",
|
||||||
"run_points_expire_check",
|
"run_points_expire_check",
|
||||||
"scheduler_status",
|
"scheduler_status",
|
||||||
"start_scheduler",
|
"start_scheduler",
|
||||||
@@ -140,3 +148,14 @@ def register_default_jobs() -> None:
|
|||||||
run=run_ck_health,
|
run=run_ck_health,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
register_job(
|
||||||
|
JobSpec(
|
||||||
|
key=PLATFORM_FULFILLMENT_LEASE_REAPER_KEY,
|
||||||
|
title="直播账号履约租约回收",
|
||||||
|
interval_seconds=60,
|
||||||
|
run_interval_seconds=60,
|
||||||
|
batch_size=500,
|
||||||
|
concurrency=1,
|
||||||
|
run=run_platform_fulfillment_lease_reaper,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
"""回收过期的直播账号履约租约。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from ....models import AccountLease, AutomationJob, PlatformFulfillmentTask
|
||||||
|
from ...platform_fulfillment.account_selector import (
|
||||||
|
expire_platform_fulfillment_leases,
|
||||||
|
)
|
||||||
|
|
||||||
|
JOB_KEY = "platform_fulfillment_lease_reaper"
|
||||||
|
|
||||||
|
|
||||||
|
def run_platform_fulfillment_lease_reaper(
|
||||||
|
db: Session,
|
||||||
|
job: AutomationJob,
|
||||||
|
*,
|
||||||
|
now: datetime | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
moment = now or datetime.now(UTC)
|
||||||
|
released_ids = {
|
||||||
|
lease_id
|
||||||
|
for (lease_id,) in db.query(AccountLease.id)
|
||||||
|
.filter(
|
||||||
|
AccountLease.purpose == "platform_fulfillment",
|
||||||
|
AccountLease.status == "active",
|
||||||
|
AccountLease.expires_at <= moment,
|
||||||
|
)
|
||||||
|
.limit(max(1, int(job.batch_size or 500)))
|
||||||
|
.all()
|
||||||
|
}
|
||||||
|
expired = expire_platform_fulfillment_leases(
|
||||||
|
db,
|
||||||
|
now=moment,
|
||||||
|
limit=max(1, int(job.batch_size or 500)),
|
||||||
|
)
|
||||||
|
affected = 0
|
||||||
|
if released_ids:
|
||||||
|
rows = (
|
||||||
|
db.query(PlatformFulfillmentTask)
|
||||||
|
.filter(PlatformFulfillmentTask.lease_id.in_(released_ids))
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
for task in rows:
|
||||||
|
if task.execution_status in {"completed", "cancelled"}:
|
||||||
|
continue
|
||||||
|
task.execution_status = "manual_required"
|
||||||
|
task.issue_code = "lease_expired"
|
||||||
|
task.last_error = "账号租约已过期,请重新分配账号"
|
||||||
|
task.updated_at = moment
|
||||||
|
affected += 1
|
||||||
|
db.commit()
|
||||||
|
return {
|
||||||
|
"scanned": expired,
|
||||||
|
"expired": expired,
|
||||||
|
"affected_tasks": affected,
|
||||||
|
"message": f"直播账号履约租约回收 {expired} 条",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ["JOB_KEY", "run_platform_fulfillment_lease_reaper"]
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
"""在后台线程启动斗鱼任务批次。
|
||||||
|
|
||||||
|
任务创建入口和执行入口分离,供旧工作台和直播账号履约共用同一套线程/注册表。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import threading
|
||||||
|
|
||||||
|
from web.backend.database import SessionLocal
|
||||||
|
|
||||||
|
from .douyu_runner import DouyuBatchRunner, douyu_batch_registry
|
||||||
|
|
||||||
|
|
||||||
|
def start_douyu_batch(
|
||||||
|
*,
|
||||||
|
batch_id: str,
|
||||||
|
task_type: str,
|
||||||
|
payload: dict,
|
||||||
|
concurrency: int,
|
||||||
|
) -> None:
|
||||||
|
"""必须在运行中的 asyncio 事件循环里调用。"""
|
||||||
|
log_queue = asyncio.Queue()
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
thread_db = SessionLocal()
|
||||||
|
runner = DouyuBatchRunner(
|
||||||
|
db=thread_db,
|
||||||
|
batch_id=batch_id,
|
||||||
|
task_type=task_type,
|
||||||
|
payload=payload,
|
||||||
|
log_queue=log_queue,
|
||||||
|
loop=loop,
|
||||||
|
concurrency=max(1, min(int(concurrency), 10)),
|
||||||
|
)
|
||||||
|
douyu_batch_registry.register(batch_id, log_queue, loop, runner)
|
||||||
|
threading.Thread(target=runner.run, daemon=True).start()
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ["start_douyu_batch"]
|
||||||
@@ -32,6 +32,7 @@ CACHE_TTL = timedelta(hours=24)
|
|||||||
ROUTE_UNHANDLED = "unhandled"
|
ROUTE_UNHANDLED = "unhandled"
|
||||||
ROUTE_AUTO_FULFILLED = "auto_fulfilled"
|
ROUTE_AUTO_FULFILLED = "auto_fulfilled"
|
||||||
ROUTE_WORKER_PLATFORM = "worker_platform"
|
ROUTE_WORKER_PLATFORM = "worker_platform"
|
||||||
|
PLATFORM_FULFILLMENT_SOURCE = "order_site"
|
||||||
|
|
||||||
# 发货方内部行:同一订单号下与真实店铺行成对出现,其 sku_code 是内部编码
|
# 发货方内部行:同一订单号下与真实店铺行成对出现,其 sku_code 是内部编码
|
||||||
# (如 suit_shadow_gothic),不能用来回显给买家。
|
# (如 suit_shadow_gothic),不能用来回显给买家。
|
||||||
@@ -151,6 +152,102 @@ def _fetch_rows(order_no: str) -> list[dict[str, Any]]:
|
|||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def _fetch_pending_manual_fulfillments(limit: int = 100) -> list[dict[str, Any]]:
|
||||||
|
"""读取最近的人工渠道待履约订单项。
|
||||||
|
|
||||||
|
是否由直播账号履约由 live-hub 本地商品映射决定,不修改 order_site 配置。
|
||||||
|
"""
|
||||||
|
engine = _get_engine()
|
||||||
|
sql = text(
|
||||||
|
"""
|
||||||
|
SELECT o.id AS source_order_id,
|
||||||
|
o.platform_order_id,
|
||||||
|
o.provider,
|
||||||
|
o.platform,
|
||||||
|
o.shop_id,
|
||||||
|
o.shop_name,
|
||||||
|
o.order_status,
|
||||||
|
o.pay_status,
|
||||||
|
o.total_amount,
|
||||||
|
o.paid_at,
|
||||||
|
o.updated_at AS order_updated_at,
|
||||||
|
oi.id AS source_order_item_id,
|
||||||
|
oi.sku_code,
|
||||||
|
oi.sku_name,
|
||||||
|
oi.quantity,
|
||||||
|
oi.revenue_amount_fen,
|
||||||
|
oi.manual_sku_key,
|
||||||
|
oi.spec_json,
|
||||||
|
oi.updated_at AS item_updated_at,
|
||||||
|
f.id AS source_fulfillment_id,
|
||||||
|
f.channel AS fulfillment_channel,
|
||||||
|
f.status AS fulfillment_status,
|
||||||
|
f.issue_code AS fulfillment_issue_code
|
||||||
|
FROM orders o
|
||||||
|
JOIN order_items oi ON oi.order_id = o.id
|
||||||
|
JOIN fulfillments f ON f.order_item_id = oi.id
|
||||||
|
WHERE f.channel = 'manual'
|
||||||
|
AND f.status = 'assigned'
|
||||||
|
AND o.pay_status = 'paid'
|
||||||
|
AND o.order_status NOT IN ('refunded', 'cancelled', 'closed')
|
||||||
|
AND oi.quantity = 1
|
||||||
|
AND COALESCE(f.issue_code, '') NOT IN ('user_refund', 'platform_cancelled')
|
||||||
|
ORDER BY oi.updated_at DESC NULLS LAST, oi.id DESC
|
||||||
|
LIMIT :limit
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with engine.connect() as conn:
|
||||||
|
return [
|
||||||
|
dict(row)
|
||||||
|
for row in conn.execute(
|
||||||
|
sql, {"limit": max(1, min(limit, 500))}
|
||||||
|
).mappings()
|
||||||
|
]
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning(f"查询 order_site 人工待履约订单失败:{exc}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def list_pending_manual_fulfillments(limit: int = 100) -> list[dict[str, Any]]:
|
||||||
|
"""返回最近的人工渠道待履约订单项快照。"""
|
||||||
|
if not _enabled():
|
||||||
|
raise OrderLookupUnavailable("外部订单查询未启用")
|
||||||
|
result: list[dict[str, Any]] = []
|
||||||
|
for row in _fetch_pending_manual_fulfillments(limit=limit):
|
||||||
|
internal_sku_key = str(
|
||||||
|
row.get("manual_sku_key")
|
||||||
|
or row.get("sku_name")
|
||||||
|
or row.get("sku_code")
|
||||||
|
or ""
|
||||||
|
).strip()
|
||||||
|
result.append(
|
||||||
|
{
|
||||||
|
"source_system": PLATFORM_FULFILLMENT_SOURCE,
|
||||||
|
"source_order_id": str(row.get("source_order_id") or ""),
|
||||||
|
"source_order_item_id": str(row.get("source_order_item_id") or ""),
|
||||||
|
"source_fulfillment_id": str(row.get("source_fulfillment_id") or ""),
|
||||||
|
"platform_order_id": str(row.get("platform_order_id") or ""),
|
||||||
|
"provider": str(row.get("provider") or ""),
|
||||||
|
"platform": str(row.get("platform") or ""),
|
||||||
|
"shop_id": str(row.get("shop_id") or ""),
|
||||||
|
"shop_name": str(row.get("shop_name") or ""),
|
||||||
|
"order_status": str(row.get("order_status") or ""),
|
||||||
|
"pay_status": str(row.get("pay_status") or ""),
|
||||||
|
"total_amount": int(row.get("total_amount") or 0),
|
||||||
|
"revenue_amount_fen": int(row.get("revenue_amount_fen") or 0),
|
||||||
|
"paid_at": row.get("paid_at"),
|
||||||
|
"sku_code": str(row.get("sku_code") or ""),
|
||||||
|
"sku_name": str(row.get("sku_name") or ""),
|
||||||
|
"internal_sku_key": internal_sku_key,
|
||||||
|
"quantity": int(row.get("quantity") or 1),
|
||||||
|
"spec_json": row.get("spec_json"),
|
||||||
|
"item_updated_at": row.get("item_updated_at"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
def _route_of(rows: list[dict[str, Any]]) -> str:
|
def _route_of(rows: list[dict[str, Any]]) -> str:
|
||||||
"""订单号维度的聚合判定:任一行已处理即算已处理。"""
|
"""订单号维度的聚合判定:任一行已处理即算已处理。"""
|
||||||
if any(row["has_fulfillment"] for row in rows):
|
if any(row["has_fulfillment"] for row in rows):
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
"""直播账号履约领域服务。"""
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
"""直播账号履约的账号筛选与租约。
|
||||||
|
|
||||||
|
只复用账号池中经过验证的筛选与数据库唯一约束,不引入自动充值、自动兑换
|
||||||
|
或多活动 scope。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
|
from sqlalchemy import or_, select
|
||||||
|
from sqlalchemy.exc import IntegrityError
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from ...models import Account, AccountEvent, AccountLease, User
|
||||||
|
|
||||||
|
VALIDATION_LEASE_MINUTES = 5
|
||||||
|
BINDING_LEASE_MINUTES = 120
|
||||||
|
EXCHANGE_COOLDOWN_DAYS = 365
|
||||||
|
POOL_OWNER_ROLES = ("super_admin", "operation")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class AccountCandidate:
|
||||||
|
account_id: int
|
||||||
|
username: str
|
||||||
|
nickname: str
|
||||||
|
points: int
|
||||||
|
gold_balance: int | None
|
||||||
|
points_expire_at: datetime | None
|
||||||
|
role_change_available_at: datetime | None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def display_name(self) -> str:
|
||||||
|
return self.nickname or self.username or f"#{self.account_id}"
|
||||||
|
|
||||||
|
|
||||||
|
def _now(now: datetime | None = None) -> datetime:
|
||||||
|
return now or datetime.now(UTC)
|
||||||
|
|
||||||
|
|
||||||
|
def eligible_accounts(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
commodity_id: str,
|
||||||
|
required_points: int,
|
||||||
|
now: datetime | None = None,
|
||||||
|
limit: int = 20,
|
||||||
|
) -> list[AccountCandidate]:
|
||||||
|
"""筛选能人工兑换指定精英宝典商品的账号。"""
|
||||||
|
moment = _now(now)
|
||||||
|
since = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS)
|
||||||
|
owner_ids = select(User.id).where(User.role.in_(POOL_OWNER_ROLES))
|
||||||
|
active_lease = (
|
||||||
|
select(AccountLease.id)
|
||||||
|
.where(AccountLease.active_account_id == Account.id)
|
||||||
|
.exists()
|
||||||
|
)
|
||||||
|
exchanged = (
|
||||||
|
select(AccountEvent.id)
|
||||||
|
.where(
|
||||||
|
AccountEvent.account_id == Account.id,
|
||||||
|
AccountEvent.event_type == "exchange",
|
||||||
|
AccountEvent.subject_key == commodity_id,
|
||||||
|
AccountEvent.occurred_at >= since,
|
||||||
|
)
|
||||||
|
.exists()
|
||||||
|
)
|
||||||
|
rows = (
|
||||||
|
db.query(Account)
|
||||||
|
.filter(
|
||||||
|
Account.status == "active",
|
||||||
|
Account.ck_check_status == "valid",
|
||||||
|
Account.cookie.isnot(None),
|
||||||
|
Account.cookie != "",
|
||||||
|
Account.auto_managed.is_(True),
|
||||||
|
Account.elite_opened.is_(True),
|
||||||
|
Account.points.isnot(None),
|
||||||
|
Account.points >= max(0, int(required_points)),
|
||||||
|
or_(Account.assigned_to.is_(None), Account.assigned_to.in_(owner_ids)),
|
||||||
|
~active_lease,
|
||||||
|
~exchanged,
|
||||||
|
or_(
|
||||||
|
Account.role_change_available_at.is_(None),
|
||||||
|
Account.role_change_available_at <= moment,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.order_by(
|
||||||
|
Account.points_expire_at.is_(None),
|
||||||
|
Account.points_expire_at.asc(),
|
||||||
|
Account.points.asc(),
|
||||||
|
Account.id.asc(),
|
||||||
|
)
|
||||||
|
.limit(max(1, min(int(limit), 100)))
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
return [
|
||||||
|
AccountCandidate(
|
||||||
|
account_id=row.id,
|
||||||
|
username=row.username,
|
||||||
|
nickname=row.nickname or "",
|
||||||
|
points=int(row.points or 0),
|
||||||
|
gold_balance=row.gold_balance,
|
||||||
|
points_expire_at=row.points_expire_at,
|
||||||
|
role_change_available_at=row.role_change_available_at,
|
||||||
|
)
|
||||||
|
for row in rows
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def lease_account(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
candidate: AccountCandidate,
|
||||||
|
holder_user_id: int,
|
||||||
|
task_id: int,
|
||||||
|
commodity_id: str,
|
||||||
|
ttl_minutes: int = VALIDATION_LEASE_MINUTES,
|
||||||
|
now: datetime | None = None,
|
||||||
|
) -> AccountLease | None:
|
||||||
|
"""尝试领取一个账号;撞唯一索引时返回 None。"""
|
||||||
|
moment = _now(now)
|
||||||
|
lease = AccountLease(
|
||||||
|
account_id=candidate.account_id,
|
||||||
|
holder_user_id=holder_user_id,
|
||||||
|
scope="elite",
|
||||||
|
purpose="platform_fulfillment",
|
||||||
|
commodity_id=commodity_id,
|
||||||
|
batch_id=f"pf:{task_id}",
|
||||||
|
status="active",
|
||||||
|
leased_at=moment,
|
||||||
|
expires_at=moment + timedelta(minutes=max(1, int(ttl_minutes))),
|
||||||
|
release_reason="",
|
||||||
|
created_at=moment,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with db.begin_nested():
|
||||||
|
db.add(lease)
|
||||||
|
db.flush()
|
||||||
|
except IntegrityError:
|
||||||
|
if lease in db:
|
||||||
|
db.expunge(lease)
|
||||||
|
return None
|
||||||
|
db.commit()
|
||||||
|
return lease
|
||||||
|
|
||||||
|
|
||||||
|
def renew_lease(
|
||||||
|
db: Session,
|
||||||
|
lease: AccountLease,
|
||||||
|
*,
|
||||||
|
ttl_minutes: int = BINDING_LEASE_MINUTES,
|
||||||
|
now: datetime | None = None,
|
||||||
|
) -> AccountLease:
|
||||||
|
if lease.status != "active":
|
||||||
|
raise ValueError("租约已结束,不能续期")
|
||||||
|
lease.expires_at = _now(now) + timedelta(minutes=max(1, int(ttl_minutes)))
|
||||||
|
db.commit()
|
||||||
|
return lease
|
||||||
|
|
||||||
|
|
||||||
|
def release_lease(
|
||||||
|
db: Session,
|
||||||
|
lease: AccountLease | None,
|
||||||
|
*,
|
||||||
|
reason: str,
|
||||||
|
now: datetime | None = None,
|
||||||
|
) -> bool:
|
||||||
|
if lease is None or lease.status != "active":
|
||||||
|
return False
|
||||||
|
lease.status = "released"
|
||||||
|
lease.released_at = _now(now)
|
||||||
|
lease.release_reason = str(reason or "")[:64]
|
||||||
|
db.commit()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def expire_platform_fulfillment_leases(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
now: datetime | None = None,
|
||||||
|
limit: int = 500,
|
||||||
|
) -> int:
|
||||||
|
moment = _now(now)
|
||||||
|
leases = (
|
||||||
|
db.query(AccountLease)
|
||||||
|
.filter(
|
||||||
|
AccountLease.purpose == "platform_fulfillment",
|
||||||
|
AccountLease.status == "active",
|
||||||
|
AccountLease.expires_at <= moment,
|
||||||
|
)
|
||||||
|
.order_by(AccountLease.id.asc())
|
||||||
|
.limit(max(1, int(limit)))
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
for lease in leases:
|
||||||
|
lease.status = "expired"
|
||||||
|
lease.released_at = moment
|
||||||
|
lease.release_reason = "ttl_expired"
|
||||||
|
if leases:
|
||||||
|
db.commit()
|
||||||
|
return len(leases)
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"BINDING_LEASE_MINUTES",
|
||||||
|
"EXCHANGE_COOLDOWN_DAYS",
|
||||||
|
"VALIDATION_LEASE_MINUTES",
|
||||||
|
"AccountCandidate",
|
||||||
|
"eligible_accounts",
|
||||||
|
"expire_platform_fulfillment_leases",
|
||||||
|
"lease_account",
|
||||||
|
"release_lease",
|
||||||
|
"renew_lease",
|
||||||
|
]
|
||||||
@@ -0,0 +1,915 @@
|
|||||||
|
"""直播账号履约作业服务:订单同步、映射、选号、绑码和人工完成。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from sqlalchemy import or_
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from core.douyu import DouyuActivityClient, DouyuActivityError
|
||||||
|
from core.douyu.cookie_utils import cookie_value
|
||||||
|
|
||||||
|
from ...models import (
|
||||||
|
Account,
|
||||||
|
AccountLease,
|
||||||
|
DouyuGoodsSnapshot,
|
||||||
|
DouyuTask,
|
||||||
|
PlatformCommodityMapping,
|
||||||
|
PlatformFulfillmentEvent,
|
||||||
|
PlatformFulfillmentTask,
|
||||||
|
User,
|
||||||
|
)
|
||||||
|
from ..douyu_batch_launcher import start_douyu_batch
|
||||||
|
from ..douyu_service import douyu_config_value, ensure_douyu_config
|
||||||
|
from ..external_order_source import (
|
||||||
|
OrderLookupUnavailable,
|
||||||
|
list_pending_manual_fulfillments,
|
||||||
|
)
|
||||||
|
from .account_selector import (
|
||||||
|
BINDING_LEASE_MINUTES,
|
||||||
|
VALIDATION_LEASE_MINUTES,
|
||||||
|
eligible_accounts,
|
||||||
|
lease_account,
|
||||||
|
release_lease,
|
||||||
|
renew_lease,
|
||||||
|
)
|
||||||
|
|
||||||
|
TARGET_PLATFORM = "douyu"
|
||||||
|
SCOPE_ELITE = "elite"
|
||||||
|
ACTIVE_STATUSES = {
|
||||||
|
"ready",
|
||||||
|
"allocated",
|
||||||
|
"waiting_bind",
|
||||||
|
"role_ready",
|
||||||
|
"binding_confirming",
|
||||||
|
"bound",
|
||||||
|
"manual_required",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _now() -> datetime:
|
||||||
|
return datetime.now(UTC)
|
||||||
|
|
||||||
|
|
||||||
|
def _jsonable(value: Any) -> Any:
|
||||||
|
if isinstance(value, datetime):
|
||||||
|
return value.isoformat()
|
||||||
|
if isinstance(value, dict):
|
||||||
|
return {str(key): _jsonable(item) for key, item in value.items()}
|
||||||
|
if isinstance(value, (list, tuple)):
|
||||||
|
return [_jsonable(item) for item in value]
|
||||||
|
if isinstance(value, (str, int, float, bool)) or value is None:
|
||||||
|
return value
|
||||||
|
return str(value)
|
||||||
|
|
||||||
|
|
||||||
|
def _mapping_for_sku(
|
||||||
|
db: Session, internal_sku_key: str
|
||||||
|
) -> PlatformCommodityMapping | None:
|
||||||
|
return (
|
||||||
|
db.query(PlatformCommodityMapping)
|
||||||
|
.filter(
|
||||||
|
PlatformCommodityMapping.target_platform == TARGET_PLATFORM,
|
||||||
|
PlatformCommodityMapping.internal_sku_key == internal_sku_key,
|
||||||
|
PlatformCommodityMapping.enabled.is_(True),
|
||||||
|
)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _append_event(
|
||||||
|
db: Session,
|
||||||
|
task_id: int,
|
||||||
|
event_type: str,
|
||||||
|
*,
|
||||||
|
actor_type: str = "system",
|
||||||
|
actor_id: int | str | None = None,
|
||||||
|
detail: dict[str, Any] | None = None,
|
||||||
|
) -> None:
|
||||||
|
db.add(
|
||||||
|
PlatformFulfillmentEvent(
|
||||||
|
task_id=task_id,
|
||||||
|
event_type=event_type,
|
||||||
|
actor_type=actor_type,
|
||||||
|
actor_id=str(actor_id or ""),
|
||||||
|
detail_json=detail or {},
|
||||||
|
created_at=_now(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _load_task(db: Session, task_id: int) -> PlatformFulfillmentTask:
|
||||||
|
task = db.query(PlatformFulfillmentTask).filter(
|
||||||
|
PlatformFulfillmentTask.id == int(task_id)
|
||||||
|
).first()
|
||||||
|
if task is None:
|
||||||
|
raise HTTPException(status_code=404, detail="直播账号履约任务不存在")
|
||||||
|
return task
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_mapping(
|
||||||
|
task: PlatformFulfillmentTask,
|
||||||
|
mapping: PlatformCommodityMapping | None,
|
||||||
|
) -> None:
|
||||||
|
if mapping is None:
|
||||||
|
task.commodity_mapping_id = None
|
||||||
|
task.commodity_id = ""
|
||||||
|
task.required_points = None
|
||||||
|
task.execution_status = "pending_mapping"
|
||||||
|
task.issue_code = "mapping_missing"
|
||||||
|
task.last_error = "内部 SKU 尚未配置斗鱼商品映射"
|
||||||
|
return
|
||||||
|
task.commodity_mapping_id = mapping.id
|
||||||
|
task.commodity_id = mapping.commodity_id
|
||||||
|
task.required_points = mapping.required_points
|
||||||
|
task.execution_status = "ready"
|
||||||
|
task.issue_code = ""
|
||||||
|
task.last_error = ""
|
||||||
|
|
||||||
|
|
||||||
|
def sync_pending_tasks(db: Session, *, limit: int = 100) -> dict[str, Any]:
|
||||||
|
"""从 order_site 拉取人工待履约订单项并幂等生成本地作业。"""
|
||||||
|
try:
|
||||||
|
rows = list_pending_manual_fulfillments(limit=limit)
|
||||||
|
except OrderLookupUnavailable as exc:
|
||||||
|
raise HTTPException(status_code=503, detail=f"订单源不可用:{exc}") from exc
|
||||||
|
|
||||||
|
created = 0
|
||||||
|
updated = 0
|
||||||
|
for row in rows:
|
||||||
|
item_id = str(row.get("source_order_item_id") or "")
|
||||||
|
if not item_id:
|
||||||
|
continue
|
||||||
|
task = (
|
||||||
|
db.query(PlatformFulfillmentTask)
|
||||||
|
.filter(
|
||||||
|
PlatformFulfillmentTask.source_system == "order_site",
|
||||||
|
PlatformFulfillmentTask.source_order_item_id == item_id,
|
||||||
|
)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if task is None:
|
||||||
|
task = PlatformFulfillmentTask(
|
||||||
|
source_system="order_site",
|
||||||
|
source_order_id=str(row.get("source_order_id") or ""),
|
||||||
|
source_order_item_id=item_id,
|
||||||
|
source_fulfillment_id=str(row.get("source_fulfillment_id") or ""),
|
||||||
|
created_at=_now(),
|
||||||
|
updated_at=_now(),
|
||||||
|
)
|
||||||
|
db.add(task)
|
||||||
|
db.flush()
|
||||||
|
created += 1
|
||||||
|
_append_event(
|
||||||
|
db,
|
||||||
|
task.id,
|
||||||
|
"task_created",
|
||||||
|
detail={"platformOrderId": row.get("platform_order_id")},
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
updated += 1
|
||||||
|
|
||||||
|
if task.execution_status in {"completed", "cancelled"}:
|
||||||
|
continue
|
||||||
|
task.platform_order_id = str(row.get("platform_order_id") or "")
|
||||||
|
task.provider = str(row.get("provider") or "")
|
||||||
|
task.shop_id = str(row.get("shop_id") or "")
|
||||||
|
task.shop_name = str(row.get("shop_name") or "")
|
||||||
|
task.sku_code = str(row.get("sku_code") or "")
|
||||||
|
task.sku_name = str(row.get("sku_name") or "")
|
||||||
|
task.internal_sku_key = str(row.get("internal_sku_key") or "")
|
||||||
|
task.quantity = 1
|
||||||
|
task.order_amount_fen = int(
|
||||||
|
row.get("revenue_amount_fen") or row.get("total_amount") or 0
|
||||||
|
)
|
||||||
|
task.target_platform = TARGET_PLATFORM
|
||||||
|
task.scope = SCOPE_ELITE
|
||||||
|
task.source_snapshot_json = _jsonable(row)
|
||||||
|
task.updated_at = _now()
|
||||||
|
if task.execution_status in {"pending_mapping", "ready"}:
|
||||||
|
_apply_mapping(task, _mapping_for_sku(db, task.internal_sku_key))
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
return {"fetched": len(rows), "created": created, "updated": updated}
|
||||||
|
|
||||||
|
|
||||||
|
def list_tasks(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
status: str = "",
|
||||||
|
keyword: str = "",
|
||||||
|
page: int = 1,
|
||||||
|
page_size: int = 20,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
query = db.query(PlatformFulfillmentTask)
|
||||||
|
if status:
|
||||||
|
if status == "unfinished":
|
||||||
|
query = query.filter(
|
||||||
|
PlatformFulfillmentTask.execution_status.notin_(
|
||||||
|
["completed", "cancelled"]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
query = query.filter(PlatformFulfillmentTask.execution_status == status)
|
||||||
|
text = keyword.strip()
|
||||||
|
if text:
|
||||||
|
pattern = f"%{text}%"
|
||||||
|
query = query.filter(
|
||||||
|
or_(
|
||||||
|
PlatformFulfillmentTask.platform_order_id.ilike(pattern),
|
||||||
|
PlatformFulfillmentTask.sku_name.ilike(pattern),
|
||||||
|
PlatformFulfillmentTask.sku_code.ilike(pattern),
|
||||||
|
PlatformFulfillmentTask.internal_sku_key.ilike(pattern),
|
||||||
|
PlatformFulfillmentTask.commodity_id.ilike(pattern),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
total = query.count()
|
||||||
|
rows = (
|
||||||
|
query.order_by(
|
||||||
|
PlatformFulfillmentTask.updated_at.desc(),
|
||||||
|
PlatformFulfillmentTask.id.desc(),
|
||||||
|
)
|
||||||
|
.offset((max(1, page) - 1) * max(1, page_size))
|
||||||
|
.limit(max(1, min(page_size, 100)))
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"items": [_task_out(db, row) for row in rows],
|
||||||
|
"pagination": {
|
||||||
|
"page": max(1, page),
|
||||||
|
"pageSize": max(1, page_size),
|
||||||
|
"total": total,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _task_out(
|
||||||
|
db: Session,
|
||||||
|
task: PlatformFulfillmentTask,
|
||||||
|
*,
|
||||||
|
include_qr: bool = False,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
account = (
|
||||||
|
db.query(Account).filter(Account.id == task.account_id).first()
|
||||||
|
if task.account_id
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
lease = (
|
||||||
|
db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
|
||||||
|
if task.lease_id
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
bind_task = (
|
||||||
|
db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first()
|
||||||
|
if task.bind_task_id
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
bind_result = (bind_task.result or {}) if bind_task else {}
|
||||||
|
return {
|
||||||
|
"id": task.id,
|
||||||
|
"sourceSystem": task.source_system,
|
||||||
|
"sourceOrderId": task.source_order_id,
|
||||||
|
"sourceOrderItemId": task.source_order_item_id,
|
||||||
|
"sourceFulfillmentId": task.source_fulfillment_id,
|
||||||
|
"platformOrderId": task.platform_order_id,
|
||||||
|
"provider": task.provider,
|
||||||
|
"shopId": task.shop_id,
|
||||||
|
"shopName": task.shop_name,
|
||||||
|
"skuCode": task.sku_code,
|
||||||
|
"skuName": task.sku_name,
|
||||||
|
"internalSkuKey": task.internal_sku_key,
|
||||||
|
"quantity": task.quantity,
|
||||||
|
"orderAmountFen": task.order_amount_fen,
|
||||||
|
"targetPlatform": task.target_platform,
|
||||||
|
"scope": task.scope,
|
||||||
|
"commodityMappingId": task.commodity_mapping_id,
|
||||||
|
"commodityId": task.commodity_id,
|
||||||
|
"requiredPoints": task.required_points,
|
||||||
|
"bindingStatus": task.binding_status,
|
||||||
|
"executionStatus": task.execution_status,
|
||||||
|
"exchangeStatus": task.exchange_status,
|
||||||
|
"issueCode": task.issue_code,
|
||||||
|
"lastError": task.last_error,
|
||||||
|
"operatorId": task.operator_id,
|
||||||
|
"completedAt": task.completed_at,
|
||||||
|
"createdAt": task.created_at,
|
||||||
|
"updatedAt": task.updated_at,
|
||||||
|
"account": (
|
||||||
|
{
|
||||||
|
"id": account.id,
|
||||||
|
"username": account.username,
|
||||||
|
"nickname": account.nickname or "",
|
||||||
|
"points": account.points,
|
||||||
|
"goldBalance": account.gold_balance,
|
||||||
|
"eliteOpened": account.elite_opened,
|
||||||
|
"ckCheckStatus": account.ck_check_status,
|
||||||
|
"roleBindStatus": account.role_bind_status,
|
||||||
|
"gameName": account.game_name,
|
||||||
|
"gameChannel": account.game_channel,
|
||||||
|
"roleChangeAvailableAt": account.role_change_available_at,
|
||||||
|
}
|
||||||
|
if account
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
"lease": (
|
||||||
|
{
|
||||||
|
"id": lease.id,
|
||||||
|
"status": lease.status,
|
||||||
|
"expiresAt": lease.expires_at,
|
||||||
|
}
|
||||||
|
if lease
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
"bindTask": (
|
||||||
|
{
|
||||||
|
"id": bind_task.id,
|
||||||
|
"taskType": bind_task.task_type,
|
||||||
|
"status": bind_task.status,
|
||||||
|
"message": bind_task.message,
|
||||||
|
"qrUrl": str(bind_result.get("url") or "") if include_qr else "",
|
||||||
|
"roleName": str(
|
||||||
|
bind_result.get("role_name")
|
||||||
|
or bind_result.get("current_role_name")
|
||||||
|
or ""
|
||||||
|
),
|
||||||
|
"areaName": str(bind_result.get("area_name") or ""),
|
||||||
|
"platName": str(bind_result.get("plat_name") or ""),
|
||||||
|
"bindPhase": str(bind_result.get("bind_phase") or ""),
|
||||||
|
"bindReadyForConfirm": bool(
|
||||||
|
bind_result.get("bind_ready_for_confirm")
|
||||||
|
),
|
||||||
|
"bindConfirmed": bool(bind_result.get("bind_confirmed")),
|
||||||
|
}
|
||||||
|
if bind_task
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def get_task_detail(db: Session, task_id: int) -> dict[str, Any]:
|
||||||
|
task = _load_task(db, task_id)
|
||||||
|
events = (
|
||||||
|
db.query(PlatformFulfillmentEvent)
|
||||||
|
.filter(PlatformFulfillmentEvent.task_id == task.id)
|
||||||
|
.order_by(PlatformFulfillmentEvent.id.desc())
|
||||||
|
.limit(200)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"task": _task_out(db, task, include_qr=True),
|
||||||
|
"events": [
|
||||||
|
{
|
||||||
|
"id": event.id,
|
||||||
|
"eventType": event.event_type,
|
||||||
|
"actorType": event.actor_type,
|
||||||
|
"actorId": event.actor_id,
|
||||||
|
"detail": event.detail_json or {},
|
||||||
|
"createdAt": event.created_at,
|
||||||
|
}
|
||||||
|
for event in events
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def list_mappings(db: Session, *, keyword: str = "") -> list[dict[str, Any]]:
|
||||||
|
query = db.query(PlatformCommodityMapping)
|
||||||
|
text = keyword.strip()
|
||||||
|
if text:
|
||||||
|
pattern = f"%{text}%"
|
||||||
|
query = query.filter(
|
||||||
|
or_(
|
||||||
|
PlatformCommodityMapping.internal_sku_key.ilike(pattern),
|
||||||
|
PlatformCommodityMapping.commodity_id.ilike(pattern),
|
||||||
|
PlatformCommodityMapping.goods_name.ilike(pattern),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
rows = query.order_by(PlatformCommodityMapping.updated_at.desc()).limit(300).all()
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"id": row.id,
|
||||||
|
"targetPlatform": row.target_platform,
|
||||||
|
"internalSkuKey": row.internal_sku_key,
|
||||||
|
"commodityId": row.commodity_id,
|
||||||
|
"goodsName": row.goods_name,
|
||||||
|
"requiredPoints": row.required_points,
|
||||||
|
"scope": row.scope,
|
||||||
|
"enabled": row.enabled,
|
||||||
|
"updatedAt": row.updated_at,
|
||||||
|
}
|
||||||
|
for row in rows
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def upsert_mapping(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
internal_sku_key: str,
|
||||||
|
commodity_id: str,
|
||||||
|
goods_name: str,
|
||||||
|
required_points: int | None,
|
||||||
|
enabled: bool,
|
||||||
|
current: User,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
sku_key = internal_sku_key.strip()
|
||||||
|
commodity = commodity_id.strip()
|
||||||
|
if not sku_key or not commodity:
|
||||||
|
raise HTTPException(status_code=400, detail="内部 SKU 和斗鱼商品 ID 不能为空")
|
||||||
|
goods = (
|
||||||
|
db.query(DouyuGoodsSnapshot)
|
||||||
|
.filter(DouyuGoodsSnapshot.commodity_id == commodity)
|
||||||
|
.order_by(DouyuGoodsSnapshot.id.desc())
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
row = (
|
||||||
|
db.query(PlatformCommodityMapping)
|
||||||
|
.filter(
|
||||||
|
PlatformCommodityMapping.target_platform == TARGET_PLATFORM,
|
||||||
|
PlatformCommodityMapping.internal_sku_key == sku_key,
|
||||||
|
)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if row is None:
|
||||||
|
row = PlatformCommodityMapping(
|
||||||
|
target_platform=TARGET_PLATFORM,
|
||||||
|
internal_sku_key=sku_key,
|
||||||
|
created_by=current.id,
|
||||||
|
created_at=_now(),
|
||||||
|
)
|
||||||
|
db.add(row)
|
||||||
|
row.commodity_id = commodity
|
||||||
|
row.goods_name = (goods_name or (goods.name if goods else "")).strip()
|
||||||
|
row.required_points = (
|
||||||
|
int(required_points)
|
||||||
|
if required_points is not None
|
||||||
|
else (int(goods.score) if goods and goods.score is not None else None)
|
||||||
|
)
|
||||||
|
row.scope = SCOPE_ELITE
|
||||||
|
row.enabled = bool(enabled)
|
||||||
|
row.updated_at = _now()
|
||||||
|
db.flush()
|
||||||
|
|
||||||
|
pending = (
|
||||||
|
db.query(PlatformFulfillmentTask)
|
||||||
|
.filter(
|
||||||
|
PlatformFulfillmentTask.internal_sku_key == sku_key,
|
||||||
|
PlatformFulfillmentTask.execution_status.in_(
|
||||||
|
["pending_mapping", "ready", "manual_required"]
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
for task in pending:
|
||||||
|
_apply_mapping(task, row if row.enabled else None)
|
||||||
|
task.updated_at = _now()
|
||||||
|
_append_event(
|
||||||
|
db,
|
||||||
|
task.id,
|
||||||
|
"mapping_updated",
|
||||||
|
actor_type="user",
|
||||||
|
actor_id=current.id,
|
||||||
|
detail={"commodityId": row.commodity_id, "enabled": row.enabled},
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
return next(item for item in list_mappings(db, keyword=sku_key) if item["id"] == row.id)
|
||||||
|
|
||||||
|
|
||||||
|
def allocate_task(
|
||||||
|
db: Session, *, task_id: int, current: User
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
task = _load_task(db, task_id)
|
||||||
|
if task.execution_status in {"completed", "cancelled"}:
|
||||||
|
raise HTTPException(status_code=409, detail="已结束任务不能重新分配账号")
|
||||||
|
if not task.commodity_id or not task.required_points:
|
||||||
|
raise HTTPException(status_code=409, detail="请先完成商品映射")
|
||||||
|
if task.account_id and task.lease_id:
|
||||||
|
lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
|
||||||
|
if lease and lease.status == "active":
|
||||||
|
return get_task_detail(db, task.id)
|
||||||
|
|
||||||
|
candidates = eligible_accounts(
|
||||||
|
db,
|
||||||
|
commodity_id=task.commodity_id,
|
||||||
|
required_points=task.required_points,
|
||||||
|
limit=20,
|
||||||
|
)
|
||||||
|
selected = None
|
||||||
|
lease = None
|
||||||
|
for candidate in candidates:
|
||||||
|
lease = lease_account(
|
||||||
|
db,
|
||||||
|
candidate=candidate,
|
||||||
|
holder_user_id=current.id,
|
||||||
|
task_id=task.id,
|
||||||
|
commodity_id=task.commodity_id,
|
||||||
|
ttl_minutes=VALIDATION_LEASE_MINUTES,
|
||||||
|
)
|
||||||
|
if lease is not None:
|
||||||
|
selected = candidate
|
||||||
|
break
|
||||||
|
if selected is None or lease is None:
|
||||||
|
task.execution_status = "ready"
|
||||||
|
task.issue_code = "no_eligible_account"
|
||||||
|
task.last_error = "当前没有满足 CK、积分、限兑和换绑条件的斗鱼账号"
|
||||||
|
task.updated_at = _now()
|
||||||
|
_append_event(db, task.id, "account_allocation_failed")
|
||||||
|
db.commit()
|
||||||
|
return get_task_detail(db, task.id)
|
||||||
|
|
||||||
|
task.account_id = selected.account_id
|
||||||
|
task.lease_id = lease.id
|
||||||
|
task.operator_id = current.id
|
||||||
|
task.execution_status = "allocated"
|
||||||
|
task.binding_status = "not_started"
|
||||||
|
task.exchange_status = "not_started"
|
||||||
|
task.issue_code = ""
|
||||||
|
task.last_error = ""
|
||||||
|
task.updated_at = _now()
|
||||||
|
_append_event(
|
||||||
|
db,
|
||||||
|
task.id,
|
||||||
|
"account_allocated",
|
||||||
|
actor_type="user",
|
||||||
|
actor_id=current.id,
|
||||||
|
detail={
|
||||||
|
"accountId": selected.account_id,
|
||||||
|
"accountName": selected.display_name,
|
||||||
|
"points": selected.points,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
return get_task_detail(db, task.id)
|
||||||
|
|
||||||
|
|
||||||
|
def release_task_account(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
task_id: int,
|
||||||
|
current: User,
|
||||||
|
reason: str = "manual_release",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
task = _load_task(db, task_id)
|
||||||
|
lease = (
|
||||||
|
db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
|
||||||
|
if task.lease_id
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
release_lease(db, lease, reason=reason)
|
||||||
|
task.account_id = None
|
||||||
|
task.lease_id = None
|
||||||
|
task.bind_task_id = None
|
||||||
|
task.execution_status = "ready"
|
||||||
|
task.binding_status = "not_started"
|
||||||
|
task.exchange_status = "not_started"
|
||||||
|
task.issue_code = ""
|
||||||
|
task.last_error = ""
|
||||||
|
task.updated_at = _now()
|
||||||
|
_append_event(
|
||||||
|
db,
|
||||||
|
task.id,
|
||||||
|
"account_released",
|
||||||
|
actor_type="user",
|
||||||
|
actor_id=current.id,
|
||||||
|
detail={"reason": reason},
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
return get_task_detail(db, task.id)
|
||||||
|
|
||||||
|
|
||||||
|
async def start_binding(
|
||||||
|
db: Session, *, task_id: int, current: User
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
task = _load_task(db, task_id)
|
||||||
|
if not task.account_id or not task.lease_id:
|
||||||
|
raise HTTPException(status_code=409, detail="请先分配账号")
|
||||||
|
lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
|
||||||
|
if lease is None or lease.status != "active":
|
||||||
|
raise HTTPException(status_code=409, detail="账号租约已失效,请重新分配")
|
||||||
|
if task.bind_task_id:
|
||||||
|
existing = db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first()
|
||||||
|
if existing and existing.status in {"planned", "pending", "running", "success"}:
|
||||||
|
return get_task_detail(db, task.id)
|
||||||
|
|
||||||
|
batch_id = f"pfbind-{task.id}-{uuid.uuid4().hex[:8]}"
|
||||||
|
bind_task = DouyuTask(
|
||||||
|
batch_id=batch_id,
|
||||||
|
account_id=task.account_id,
|
||||||
|
account_assigned_to=current.id,
|
||||||
|
task_type="get_bind_qr",
|
||||||
|
handbook_scope="elite",
|
||||||
|
status="planned",
|
||||||
|
message="等待生成绑定二维码",
|
||||||
|
result={"payload": {}},
|
||||||
|
created_by=current.id,
|
||||||
|
)
|
||||||
|
db.add(bind_task)
|
||||||
|
db.flush()
|
||||||
|
task.bind_task_id = bind_task.id
|
||||||
|
task.binding_status = "preparing"
|
||||||
|
task.execution_status = "waiting_bind"
|
||||||
|
task.operator_id = current.id
|
||||||
|
task.updated_at = _now()
|
||||||
|
renew_lease(
|
||||||
|
db,
|
||||||
|
lease,
|
||||||
|
ttl_minutes=BINDING_LEASE_MINUTES,
|
||||||
|
)
|
||||||
|
_append_event(
|
||||||
|
db,
|
||||||
|
task.id,
|
||||||
|
"binding_started",
|
||||||
|
actor_type="user",
|
||||||
|
actor_id=current.id,
|
||||||
|
detail={"bindTaskId": bind_task.id},
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
start_douyu_batch(
|
||||||
|
batch_id=batch_id,
|
||||||
|
task_type="get_bind_qr",
|
||||||
|
payload={},
|
||||||
|
concurrency=1,
|
||||||
|
)
|
||||||
|
return get_task_detail(db, task.id)
|
||||||
|
|
||||||
|
|
||||||
|
def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]:
|
||||||
|
task = _load_task(db, task_id)
|
||||||
|
if not task.bind_task_id:
|
||||||
|
return get_task_detail(db, task.id)
|
||||||
|
bind_task = db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first()
|
||||||
|
if bind_task is None:
|
||||||
|
return get_task_detail(db, task.id)
|
||||||
|
result = bind_task.result or {}
|
||||||
|
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 "绑定任务失败"
|
||||||
|
elif bool(result.get("bind_confirmed")):
|
||||||
|
task.binding_status = "bound"
|
||||||
|
task.execution_status = "bound"
|
||||||
|
task.issue_code = ""
|
||||||
|
task.last_error = ""
|
||||||
|
elif bool(result.get("bind_ready_for_confirm")) or result.get("role_name"):
|
||||||
|
task.binding_status = "role_ready"
|
||||||
|
task.execution_status = "role_ready"
|
||||||
|
task.issue_code = ""
|
||||||
|
task.last_error = ""
|
||||||
|
elif result.get("url"):
|
||||||
|
task.binding_status = "qr_pending"
|
||||||
|
task.execution_status = "waiting_bind"
|
||||||
|
task.updated_at = _now()
|
||||||
|
db.commit()
|
||||||
|
return get_task_detail(db, task.id)
|
||||||
|
|
||||||
|
|
||||||
|
async def confirm_binding(
|
||||||
|
db: Session, *, task_id: int, current: User
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
task = _load_task(db, task_id)
|
||||||
|
task = _load_task(db, refresh_binding(db, task_id=task.id)["task"]["id"])
|
||||||
|
if task.binding_status != "role_ready":
|
||||||
|
raise HTTPException(status_code=409, detail="当前没有待确认的游戏角色")
|
||||||
|
if not task.account_id or not task.lease_id:
|
||||||
|
raise HTTPException(status_code=409, detail="账号租约不存在")
|
||||||
|
lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
|
||||||
|
if lease is None or lease.status != "active":
|
||||||
|
raise HTTPException(status_code=409, detail="账号租约已失效")
|
||||||
|
|
||||||
|
batch_id = f"pfconfirm-{task.id}-{uuid.uuid4().hex[:8]}"
|
||||||
|
confirm_task = DouyuTask(
|
||||||
|
batch_id=batch_id,
|
||||||
|
account_id=task.account_id,
|
||||||
|
account_assigned_to=current.id,
|
||||||
|
task_type="confirm_bind",
|
||||||
|
handbook_scope="elite",
|
||||||
|
status="planned",
|
||||||
|
message="等待确认角色绑定",
|
||||||
|
result={"payload": {}},
|
||||||
|
created_by=current.id,
|
||||||
|
)
|
||||||
|
db.add(confirm_task)
|
||||||
|
db.flush()
|
||||||
|
task.bind_task_id = confirm_task.id
|
||||||
|
task.binding_status = "confirming"
|
||||||
|
task.execution_status = "binding_confirming"
|
||||||
|
task.operator_id = current.id
|
||||||
|
task.updated_at = _now()
|
||||||
|
renew_lease(db, lease, ttl_minutes=BINDING_LEASE_MINUTES)
|
||||||
|
_append_event(
|
||||||
|
db,
|
||||||
|
task.id,
|
||||||
|
"binding_confirm_started",
|
||||||
|
actor_type="user",
|
||||||
|
actor_id=current.id,
|
||||||
|
detail={"confirmTaskId": confirm_task.id},
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
start_douyu_batch(
|
||||||
|
batch_id=batch_id,
|
||||||
|
task_type="confirm_bind",
|
||||||
|
payload={},
|
||||||
|
concurrency=1,
|
||||||
|
)
|
||||||
|
return get_task_detail(db, task.id)
|
||||||
|
|
||||||
|
|
||||||
|
def refresh_exchange_eligibility(
|
||||||
|
db: Session, *, task_id: int, current: User
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
task = _load_task(db, task_id)
|
||||||
|
if task.binding_status != "bound":
|
||||||
|
raise HTTPException(status_code=409, detail="请先确认游戏角色绑定")
|
||||||
|
account = db.query(Account).filter(Account.id == task.account_id).first()
|
||||||
|
if account is None or not account.cookie:
|
||||||
|
raise HTTPException(status_code=409, detail="账号 CK 不可用")
|
||||||
|
config = ensure_douyu_config(db)
|
||||||
|
try:
|
||||||
|
client = DouyuActivityClient(cookie=str(account.cookie))
|
||||||
|
ctn = client.acf_ccn(refresh_subscribe=False)
|
||||||
|
user_info = client.elite_user_info(
|
||||||
|
manual_id=str(douyu_config_value("manual_id", config.manual_id)),
|
||||||
|
rid=str(douyu_config_value("rid", config.rid)),
|
||||||
|
)
|
||||||
|
account.elite_opened = bool(user_info.get("manual_type"))
|
||||||
|
uid = account.uid or cookie_value(str(account.cookie), "acf_uid")
|
||||||
|
points_result = client.query_points(uid=uid, ctn=ctn)
|
||||||
|
account.points = int(points_result.get("points") or 0)
|
||||||
|
result = client.query_limited_goods(
|
||||||
|
manual_id=str(douyu_config_value("manual_id", config.manual_id)),
|
||||||
|
rid=str(douyu_config_value("rid", config.rid)),
|
||||||
|
)
|
||||||
|
limited = result.get("limited_goods") or []
|
||||||
|
except DouyuActivityError as exc:
|
||||||
|
task.execution_status = "manual_required"
|
||||||
|
task.exchange_status = "check_failed"
|
||||||
|
task.issue_code = "eligibility_check_failed"
|
||||||
|
task.last_error = str(exc)
|
||||||
|
task.updated_at = _now()
|
||||||
|
_append_event(
|
||||||
|
db,
|
||||||
|
task.id,
|
||||||
|
"eligibility_check_failed",
|
||||||
|
actor_type="user",
|
||||||
|
actor_id=current.id,
|
||||||
|
detail={"error": str(exc)},
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
return get_task_detail(db, task.id)
|
||||||
|
|
||||||
|
limited_ids = {
|
||||||
|
str(item.get("commodityId") or item.get("commodity_id") or "")
|
||||||
|
for item in limited
|
||||||
|
if isinstance(item, dict)
|
||||||
|
}
|
||||||
|
limited_ids.discard("")
|
||||||
|
if task.commodity_id in limited_ids:
|
||||||
|
task.exchange_status = "limited"
|
||||||
|
task.issue_code = "commodity_limit_reached"
|
||||||
|
task.last_error = "该账号已达到此商品兑换上限"
|
||||||
|
elif not account.elite_opened:
|
||||||
|
task.exchange_status = "not_opened"
|
||||||
|
task.issue_code = "elite_not_opened"
|
||||||
|
task.last_error = "该账号精英宝典未开通"
|
||||||
|
elif task.required_points and int(account.points or 0) < int(task.required_points):
|
||||||
|
task.exchange_status = "points_short"
|
||||||
|
task.issue_code = "points_short"
|
||||||
|
task.last_error = "该账号精英积分不足,需人工充值"
|
||||||
|
else:
|
||||||
|
task.exchange_status = "eligible"
|
||||||
|
task.issue_code = ""
|
||||||
|
task.last_error = ""
|
||||||
|
task.execution_status = (
|
||||||
|
"manual_required" if task.exchange_status != "eligible" else "bound"
|
||||||
|
)
|
||||||
|
task.updated_at = _now()
|
||||||
|
account.updated_at = _now()
|
||||||
|
_append_event(
|
||||||
|
db,
|
||||||
|
task.id,
|
||||||
|
"exchange_eligibility_checked",
|
||||||
|
actor_type="user",
|
||||||
|
actor_id=current.id,
|
||||||
|
detail={
|
||||||
|
"exchangeStatus": task.exchange_status,
|
||||||
|
"limitedCount": len(limited_ids),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
return get_task_detail(db, task.id)
|
||||||
|
|
||||||
|
|
||||||
|
def complete_manual_exchange(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
task_id: int,
|
||||||
|
current: User,
|
||||||
|
note: str = "",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
task = _load_task(db, task_id)
|
||||||
|
if task.binding_status != "bound":
|
||||||
|
raise HTTPException(status_code=409, detail="游戏角色尚未确认绑定")
|
||||||
|
if task.exchange_status not in {"eligible", "manual_done"}:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=409,
|
||||||
|
detail="当前兑换资格不是可兑换状态,请先刷新检查结果",
|
||||||
|
)
|
||||||
|
lease = (
|
||||||
|
db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
|
||||||
|
if task.lease_id
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
task.exchange_status = "manual_done"
|
||||||
|
task.execution_status = "completed"
|
||||||
|
task.completed_at = _now()
|
||||||
|
task.operator_id = current.id
|
||||||
|
task.last_error = ""
|
||||||
|
task.issue_code = ""
|
||||||
|
task.updated_at = _now()
|
||||||
|
release_lease(db, lease, reason="manual_exchange_completed")
|
||||||
|
_append_event(
|
||||||
|
db,
|
||||||
|
task.id,
|
||||||
|
"manual_exchange_completed",
|
||||||
|
actor_type="user",
|
||||||
|
actor_id=current.id,
|
||||||
|
detail={"note": note[:1000]},
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
return get_task_detail(db, task.id)
|
||||||
|
|
||||||
|
|
||||||
|
def mark_manual_required(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
task_id: int,
|
||||||
|
current: User,
|
||||||
|
reason: str,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
task = _load_task(db, task_id)
|
||||||
|
task.execution_status = "manual_required"
|
||||||
|
task.operator_id = current.id
|
||||||
|
task.last_error = reason.strip()[:2000]
|
||||||
|
task.issue_code = task.issue_code or "manual_required"
|
||||||
|
task.updated_at = _now()
|
||||||
|
_append_event(
|
||||||
|
db,
|
||||||
|
task.id,
|
||||||
|
"marked_manual_required",
|
||||||
|
actor_type="user",
|
||||||
|
actor_id=current.id,
|
||||||
|
detail={"reason": task.last_error},
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
return get_task_detail(db, task.id)
|
||||||
|
|
||||||
|
|
||||||
|
def cancel_task(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
task_id: int,
|
||||||
|
current: User,
|
||||||
|
reason: str,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
task = _load_task(db, task_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_cancelled")
|
||||||
|
task.execution_status = "cancelled"
|
||||||
|
task.operator_id = current.id
|
||||||
|
task.last_error = reason.strip()[:2000]
|
||||||
|
task.updated_at = _now()
|
||||||
|
_append_event(
|
||||||
|
db,
|
||||||
|
task.id,
|
||||||
|
"task_cancelled",
|
||||||
|
actor_type="user",
|
||||||
|
actor_id=current.id,
|
||||||
|
detail={"reason": task.last_error},
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
return get_task_detail(db, task.id)
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"allocate_task",
|
||||||
|
"cancel_task",
|
||||||
|
"complete_manual_exchange",
|
||||||
|
"confirm_binding",
|
||||||
|
"get_task_detail",
|
||||||
|
"list_mappings",
|
||||||
|
"list_tasks",
|
||||||
|
"mark_manual_required",
|
||||||
|
"refresh_binding",
|
||||||
|
"refresh_exchange_eligibility",
|
||||||
|
"release_task_account",
|
||||||
|
"start_binding",
|
||||||
|
"sync_pending_tasks",
|
||||||
|
"upsert_mapping",
|
||||||
|
]
|
||||||
@@ -16,6 +16,7 @@ const AccountCheckPage = lazy(() => import('./pages/AccountCheckPage'));
|
|||||||
const AssignmentsPage = lazy(() => import('./pages/AssignmentsPage'));
|
const AssignmentsPage = lazy(() => import('./pages/AssignmentsPage'));
|
||||||
const LoginTasksPage = lazy(() => import('./pages/LoginTasksPage'));
|
const LoginTasksPage = lazy(() => import('./pages/LoginTasksPage'));
|
||||||
const ProxyPage = lazy(() => import('./pages/ProxyPage'));
|
const ProxyPage = lazy(() => import('./pages/ProxyPage'));
|
||||||
|
const PlatformFulfillmentPage = lazy(() => import('./pages/PlatformFulfillmentPage'));
|
||||||
const AutomationPage = lazy(() => import('./pages/AutomationPage'));
|
const AutomationPage = lazy(() => import('./pages/AutomationPage'));
|
||||||
const UsersPage = lazy(() => import('./pages/UsersPage'));
|
const UsersPage = lazy(() => import('./pages/UsersPage'));
|
||||||
const CookiePage = lazy(() => import('./pages/CookiePage'));
|
const CookiePage = lazy(() => import('./pages/CookiePage'));
|
||||||
@@ -99,6 +100,7 @@ function AppContent() {
|
|||||||
<Route path="douyu/esports" element={lazyRoute(<DouyuTasksPage key="esports" handbook="esports" />)} />
|
<Route path="douyu/esports" element={lazyRoute(<DouyuTasksPage key="esports" handbook="esports" />)} />
|
||||||
<Route path="douyu/peace" element={lazyRoute(<DouyuTasksPage key="peace" handbook="peace" />)} />
|
<Route path="douyu/peace" element={lazyRoute(<DouyuTasksPage key="peace" handbook="peace" />)} />
|
||||||
<Route path="douyu/collab" element={lazyRoute(<DouyuCollabPage />)} />
|
<Route path="douyu/collab" element={lazyRoute(<DouyuCollabPage />)} />
|
||||||
|
<Route path="platform-fulfillment" element={lazyRoute(<PlatformFulfillmentPage />)} />
|
||||||
<Route path="huya/accounts" element={lazyRoute(<HuyaAccountsPage />)} />
|
<Route path="huya/accounts" element={lazyRoute(<HuyaAccountsPage />)} />
|
||||||
<Route path="huya/device-bindings" element={lazyRoute(<HuyaDeviceBindingsPage />)} />
|
<Route path="huya/device-bindings" element={lazyRoute(<HuyaDeviceBindingsPage />)} />
|
||||||
<Route path="huya/register" element={lazyRoute(<HuyaRegisterPage />)} />
|
<Route path="huya/register" element={lazyRoute(<HuyaRegisterPage />)} />
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ export { douyuCollabApi } from './douyuCollab';
|
|||||||
export { fileApi } from './files';
|
export { fileApi } from './files';
|
||||||
export { huyaApi } from './huya';
|
export { huyaApi } from './huya';
|
||||||
export { loginApi } from './login';
|
export { loginApi } from './login';
|
||||||
|
export { platformFulfillmentApi } from './platformFulfillment';
|
||||||
export { proxyApi } from './proxy';
|
export { proxyApi } from './proxy';
|
||||||
export { userApi } from './users';
|
export { userApi } from './users';
|
||||||
export { weiboApi } from './weibo';
|
export { weiboApi } from './weibo';
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import api from './client';
|
||||||
|
import type {
|
||||||
|
PlatformFulfillmentDetail,
|
||||||
|
PlatformFulfillmentListResponse,
|
||||||
|
PlatformFulfillmentMapping,
|
||||||
|
} from './types';
|
||||||
|
|
||||||
|
export const platformFulfillmentApi = {
|
||||||
|
listTasks: (params: {
|
||||||
|
status?: string;
|
||||||
|
keyword?: string;
|
||||||
|
page?: number;
|
||||||
|
page_size?: number;
|
||||||
|
}) =>
|
||||||
|
api.get<PlatformFulfillmentListResponse, PlatformFulfillmentListResponse>(
|
||||||
|
'/platform-fulfillment/tasks',
|
||||||
|
{ params },
|
||||||
|
),
|
||||||
|
sync: (limit = 100) =>
|
||||||
|
api.post<{ fetched: number; created: number; updated: number }, { fetched: number; created: number; updated: number }>(
|
||||||
|
'/platform-fulfillment/sync',
|
||||||
|
null,
|
||||||
|
{ params: { limit } },
|
||||||
|
),
|
||||||
|
getTask: (taskId: number) =>
|
||||||
|
api.get<PlatformFulfillmentDetail, PlatformFulfillmentDetail>(
|
||||||
|
`/platform-fulfillment/tasks/${taskId}`,
|
||||||
|
),
|
||||||
|
listMappings: (keyword = '') =>
|
||||||
|
api.get<PlatformFulfillmentMapping[], PlatformFulfillmentMapping[]>(
|
||||||
|
'/platform-fulfillment/mappings',
|
||||||
|
{ params: { keyword } },
|
||||||
|
),
|
||||||
|
upsertMapping: (data: {
|
||||||
|
internal_sku_key: string;
|
||||||
|
commodity_id: string;
|
||||||
|
goods_name?: string;
|
||||||
|
required_points?: number | null;
|
||||||
|
enabled: boolean;
|
||||||
|
}) =>
|
||||||
|
api.put<PlatformFulfillmentMapping, PlatformFulfillmentMapping>(
|
||||||
|
'/platform-fulfillment/mappings',
|
||||||
|
data,
|
||||||
|
),
|
||||||
|
allocate: (taskId: number) =>
|
||||||
|
api.post<PlatformFulfillmentDetail, PlatformFulfillmentDetail>(
|
||||||
|
`/platform-fulfillment/tasks/${taskId}/allocate`,
|
||||||
|
),
|
||||||
|
startBinding: (taskId: number) =>
|
||||||
|
api.post<PlatformFulfillmentDetail, PlatformFulfillmentDetail>(
|
||||||
|
`/platform-fulfillment/tasks/${taskId}/bind/start`,
|
||||||
|
),
|
||||||
|
refreshBinding: (taskId: number) =>
|
||||||
|
api.post<PlatformFulfillmentDetail, PlatformFulfillmentDetail>(
|
||||||
|
`/platform-fulfillment/tasks/${taskId}/bind/refresh`,
|
||||||
|
),
|
||||||
|
confirmBinding: (taskId: number) =>
|
||||||
|
api.post<PlatformFulfillmentDetail, PlatformFulfillmentDetail>(
|
||||||
|
`/platform-fulfillment/tasks/${taskId}/bind/confirm`,
|
||||||
|
),
|
||||||
|
refreshEligibility: (taskId: number) =>
|
||||||
|
api.post<PlatformFulfillmentDetail, PlatformFulfillmentDetail>(
|
||||||
|
`/platform-fulfillment/tasks/${taskId}/eligibility/refresh`,
|
||||||
|
),
|
||||||
|
complete: (taskId: number, note = '') =>
|
||||||
|
api.post<PlatformFulfillmentDetail, PlatformFulfillmentDetail>(
|
||||||
|
`/platform-fulfillment/tasks/${taskId}/complete`,
|
||||||
|
{ note },
|
||||||
|
),
|
||||||
|
release: (taskId: number) =>
|
||||||
|
api.post<PlatformFulfillmentDetail, PlatformFulfillmentDetail>(
|
||||||
|
`/platform-fulfillment/tasks/${taskId}/release`,
|
||||||
|
),
|
||||||
|
markManual: (taskId: number, reason = '') =>
|
||||||
|
api.post<PlatformFulfillmentDetail, PlatformFulfillmentDetail>(
|
||||||
|
`/platform-fulfillment/tasks/${taskId}/manual`,
|
||||||
|
{ reason },
|
||||||
|
),
|
||||||
|
cancel: (taskId: number, reason = '') =>
|
||||||
|
api.post<PlatformFulfillmentDetail, PlatformFulfillmentDetail>(
|
||||||
|
`/platform-fulfillment/tasks/${taskId}/cancel`,
|
||||||
|
{ reason },
|
||||||
|
),
|
||||||
|
};
|
||||||
@@ -2103,3 +2103,96 @@ export interface HuyaCollabGiftCatalogUpdate {
|
|||||||
is_active?: boolean;
|
is_active?: boolean;
|
||||||
remark?: string;
|
remark?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface PlatformFulfillmentAccount {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
nickname: string;
|
||||||
|
points: number | null;
|
||||||
|
goldBalance: number | null;
|
||||||
|
eliteOpened: boolean | null;
|
||||||
|
ckCheckStatus: string;
|
||||||
|
roleBindStatus: string;
|
||||||
|
gameName: string;
|
||||||
|
gameChannel: string;
|
||||||
|
roleChangeAvailableAt: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PlatformFulfillmentBindTask {
|
||||||
|
id: number;
|
||||||
|
taskType: string;
|
||||||
|
status: string;
|
||||||
|
message: string;
|
||||||
|
qrUrl: string;
|
||||||
|
roleName: string;
|
||||||
|
areaName: string;
|
||||||
|
platName: string;
|
||||||
|
bindPhase: string;
|
||||||
|
bindReadyForConfirm: boolean;
|
||||||
|
bindConfirmed: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PlatformFulfillmentTask {
|
||||||
|
id: number;
|
||||||
|
sourceSystem: string;
|
||||||
|
sourceOrderId: string;
|
||||||
|
sourceOrderItemId: string;
|
||||||
|
sourceFulfillmentId: string;
|
||||||
|
platformOrderId: string;
|
||||||
|
provider: string;
|
||||||
|
shopId: string;
|
||||||
|
shopName: string;
|
||||||
|
skuCode: string;
|
||||||
|
skuName: string;
|
||||||
|
internalSkuKey: string;
|
||||||
|
quantity: number;
|
||||||
|
orderAmountFen: number;
|
||||||
|
targetPlatform: string;
|
||||||
|
scope: string;
|
||||||
|
commodityMappingId: number | null;
|
||||||
|
commodityId: string;
|
||||||
|
requiredPoints: number | null;
|
||||||
|
bindingStatus: string;
|
||||||
|
executionStatus: string;
|
||||||
|
exchangeStatus: string;
|
||||||
|
issueCode: string;
|
||||||
|
lastError: string;
|
||||||
|
operatorId: number | null;
|
||||||
|
completedAt: string | null;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
account: PlatformFulfillmentAccount | null;
|
||||||
|
lease: { id: number; status: string; expiresAt: string } | null;
|
||||||
|
bindTask: PlatformFulfillmentBindTask | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PlatformFulfillmentEvent {
|
||||||
|
id: number;
|
||||||
|
eventType: string;
|
||||||
|
actorType: string;
|
||||||
|
actorId: string;
|
||||||
|
detail: Record<string, unknown>;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PlatformFulfillmentDetail {
|
||||||
|
task: PlatformFulfillmentTask;
|
||||||
|
events: PlatformFulfillmentEvent[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PlatformFulfillmentMapping {
|
||||||
|
id: number;
|
||||||
|
targetPlatform: string;
|
||||||
|
internalSkuKey: string;
|
||||||
|
commodityId: string;
|
||||||
|
goodsName: string;
|
||||||
|
requiredPoints: number | null;
|
||||||
|
scope: string;
|
||||||
|
enabled: boolean;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PlatformFulfillmentListResponse {
|
||||||
|
items: PlatformFulfillmentTask[];
|
||||||
|
pagination: { page: number; pageSize: number; total: number };
|
||||||
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import {
|
|||||||
MenuFoldOutlined, MenuUnfoldOutlined, SwapOutlined,
|
MenuFoldOutlined, MenuUnfoldOutlined, SwapOutlined,
|
||||||
SunOutlined, MoonOutlined, DesktopOutlined, GiftOutlined, ApartmentOutlined, MobileOutlined, ShoppingCartOutlined,
|
SunOutlined, MoonOutlined, DesktopOutlined, GiftOutlined, ApartmentOutlined, MobileOutlined, ShoppingCartOutlined,
|
||||||
BookOutlined, TrophyOutlined, ShopOutlined, GlobalOutlined,
|
BookOutlined, TrophyOutlined, ShopOutlined, GlobalOutlined,
|
||||||
SafetyCertificateOutlined, FileSearchOutlined, RobotOutlined, FileExcelOutlined,
|
SafetyCertificateOutlined, FileSearchOutlined, RobotOutlined, FileExcelOutlined, ThunderboltOutlined,
|
||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
|
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
|
||||||
import { getUser, clearAuth, type AuthUser } from '../store/auth';
|
import { getUser, clearAuth, type AuthUser } from '../store/auth';
|
||||||
@@ -90,6 +90,9 @@ export default function MainLayout({ onLogout }: { onLogout?: () => void }) {
|
|||||||
if (can('douyu:collab:view')) {
|
if (can('douyu:collab:view')) {
|
||||||
douyuItems.push({ key: '/douyu/collab', label: '外部单协作', icon: <FileExcelOutlined /> });
|
douyuItems.push({ key: '/douyu/collab', label: '外部单协作', icon: <FileExcelOutlined /> });
|
||||||
}
|
}
|
||||||
|
if (can('platform_fulfillment:view')) {
|
||||||
|
douyuItems.push({ key: '/platform-fulfillment', label: '直播账号履约', icon: <ThunderboltOutlined /> });
|
||||||
|
}
|
||||||
|
|
||||||
// 虎牙:客服用浏览器兑换和精英宝典;管理员/运营显示完整入口
|
// 虎牙:客服用浏览器兑换和精英宝典;管理员/运营显示完整入口
|
||||||
if (can('huya:task')) {
|
if (can('huya:task')) {
|
||||||
|
|||||||
@@ -0,0 +1,644 @@
|
|||||||
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
|
import {
|
||||||
|
Alert,
|
||||||
|
Button,
|
||||||
|
Card,
|
||||||
|
Descriptions,
|
||||||
|
Drawer,
|
||||||
|
Empty,
|
||||||
|
Input,
|
||||||
|
InputNumber,
|
||||||
|
Modal,
|
||||||
|
QRCode,
|
||||||
|
Select,
|
||||||
|
Space,
|
||||||
|
Switch,
|
||||||
|
Table,
|
||||||
|
Tabs,
|
||||||
|
Tag,
|
||||||
|
Timeline,
|
||||||
|
Typography,
|
||||||
|
} from 'antd';
|
||||||
|
import {
|
||||||
|
CheckCircleOutlined,
|
||||||
|
CopyOutlined,
|
||||||
|
LinkOutlined,
|
||||||
|
QrcodeOutlined,
|
||||||
|
ReloadOutlined,
|
||||||
|
SyncOutlined,
|
||||||
|
UserSwitchOutlined,
|
||||||
|
} from '@ant-design/icons';
|
||||||
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
|
import { douyuApi, platformFulfillmentApi } from '../api/modules';
|
||||||
|
import type {
|
||||||
|
DouyuGoodsItem,
|
||||||
|
PlatformFulfillmentDetail,
|
||||||
|
PlatformFulfillmentMapping,
|
||||||
|
PlatformFulfillmentTask,
|
||||||
|
} from '../api/modules';
|
||||||
|
import { getErrorMessage } from '../utils/error';
|
||||||
|
import { message } from '../utils/antdMessage';
|
||||||
|
import { formatTime } from '../utils/time';
|
||||||
|
import { getUser } from '../store/auth';
|
||||||
|
import { usePermissions } from '../hooks/usePermissions';
|
||||||
|
|
||||||
|
const { Text, Title } = Typography;
|
||||||
|
|
||||||
|
const STATUS_OPTIONS = [
|
||||||
|
{ value: '', label: '全部' },
|
||||||
|
{ value: 'pending_mapping', label: '待映射' },
|
||||||
|
{ value: 'ready', label: '待分配' },
|
||||||
|
{ value: 'allocated', label: '已分配' },
|
||||||
|
{ value: 'waiting_bind', label: '待扫码' },
|
||||||
|
{ value: 'role_ready', label: '待确认绑定' },
|
||||||
|
{ value: 'binding_confirming', label: '确认绑定中' },
|
||||||
|
{ value: 'bound', label: '待兑换' },
|
||||||
|
{ value: 'manual_required', label: '待人工' },
|
||||||
|
{ value: 'completed', label: '已完成' },
|
||||||
|
{ value: 'cancelled', label: '已取消' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const STATUS_COLORS: Record<string, string> = {
|
||||||
|
pending_mapping: 'orange',
|
||||||
|
ready: 'blue',
|
||||||
|
allocated: 'cyan',
|
||||||
|
waiting_bind: 'gold',
|
||||||
|
role_ready: 'purple',
|
||||||
|
binding_confirming: 'processing',
|
||||||
|
bound: 'green',
|
||||||
|
manual_required: 'red',
|
||||||
|
completed: 'success',
|
||||||
|
cancelled: 'default',
|
||||||
|
};
|
||||||
|
|
||||||
|
function statusLabel(value: string) {
|
||||||
|
return STATUS_OPTIONS.find((item) => item.value === value)?.label || value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function money(fen: number) {
|
||||||
|
return `¥${(Number(fen || 0) / 100).toFixed(2)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function PlatformFulfillmentPage() {
|
||||||
|
const user = getUser();
|
||||||
|
const { can } = usePermissions(user);
|
||||||
|
const [status, setStatus] = useState('');
|
||||||
|
const [keyword, setKeyword] = useState('');
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
const [pageSize, setPageSize] = useState(20);
|
||||||
|
const [rows, setRows] = useState<PlatformFulfillmentTask[]>([]);
|
||||||
|
const [total, setTotal] = useState(0);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [syncing, setSyncing] = useState(false);
|
||||||
|
const [selectedId, setSelectedId] = useState<number | null>(null);
|
||||||
|
const [detail, setDetail] = useState<PlatformFulfillmentDetail | null>(null);
|
||||||
|
const [detailLoading, setDetailLoading] = useState(false);
|
||||||
|
const [qrOpen, setQrOpen] = useState(false);
|
||||||
|
const [mappingOpen, setMappingOpen] = useState(false);
|
||||||
|
const [mappingSku, setMappingSku] = useState('');
|
||||||
|
const [mappingGoodsId, setMappingGoodsId] = useState('');
|
||||||
|
const [mappingPoints, setMappingPoints] = useState<number | null>(null);
|
||||||
|
const [mappingEnabled, setMappingEnabled] = useState(true);
|
||||||
|
const [goods, setGoods] = useState<DouyuGoodsItem[]>([]);
|
||||||
|
const [mappings, setMappings] = useState<PlatformFulfillmentMapping[]>([]);
|
||||||
|
|
||||||
|
const loadTasks = useCallback(async () => {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const result = await platformFulfillmentApi.listTasks({
|
||||||
|
status: status || undefined,
|
||||||
|
keyword: keyword.trim() || undefined,
|
||||||
|
page,
|
||||||
|
page_size: pageSize,
|
||||||
|
});
|
||||||
|
setRows(result.items);
|
||||||
|
setTotal(result.pagination.total);
|
||||||
|
} catch (error) {
|
||||||
|
message.error(getErrorMessage(error));
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [keyword, page, pageSize, status]);
|
||||||
|
|
||||||
|
const loadDetail = useCallback(async (taskId: number) => {
|
||||||
|
setDetailLoading(true);
|
||||||
|
try {
|
||||||
|
const result = await platformFulfillmentApi.getTask(taskId);
|
||||||
|
setDetail(result);
|
||||||
|
} catch (error) {
|
||||||
|
message.error(getErrorMessage(error));
|
||||||
|
} finally {
|
||||||
|
setDetailLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void loadTasks();
|
||||||
|
}, [loadTasks]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (selectedId) void loadDetail(selectedId);
|
||||||
|
}, [loadDetail, selectedId]);
|
||||||
|
|
||||||
|
const selected = detail?.task || null;
|
||||||
|
const qrValue = selected?.bindTask?.qrUrl || '';
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (qrValue) setQrOpen(true);
|
||||||
|
}, [qrValue]);
|
||||||
|
|
||||||
|
const sync = async () => {
|
||||||
|
setSyncing(true);
|
||||||
|
try {
|
||||||
|
const result = await platformFulfillmentApi.sync(200);
|
||||||
|
message.success(`同步完成:新增 ${result.created},更新 ${result.updated}`);
|
||||||
|
await loadTasks();
|
||||||
|
} catch (error) {
|
||||||
|
message.error(getErrorMessage(error));
|
||||||
|
} finally {
|
||||||
|
setSyncing(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const runTaskAction = async (action: () => Promise<PlatformFulfillmentDetail>) => {
|
||||||
|
try {
|
||||||
|
const result = await action();
|
||||||
|
setDetail(result);
|
||||||
|
setSelectedId(result.task.id);
|
||||||
|
await loadTasks();
|
||||||
|
message.success('操作已完成');
|
||||||
|
} catch (error) {
|
||||||
|
message.error(getErrorMessage(error));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const openMapping = async (task?: PlatformFulfillmentTask) => {
|
||||||
|
setMappingSku(task?.internalSkuKey || '');
|
||||||
|
setMappingGoodsId(task?.commodityId || '');
|
||||||
|
setMappingPoints(task?.requiredPoints ?? null);
|
||||||
|
setMappingEnabled(true);
|
||||||
|
setMappingOpen(true);
|
||||||
|
try {
|
||||||
|
const [goodsRows, mappingRows] = await Promise.all([
|
||||||
|
douyuApi.listGoods(),
|
||||||
|
platformFulfillmentApi.listMappings(task?.internalSkuKey || ''),
|
||||||
|
]);
|
||||||
|
setGoods(goodsRows);
|
||||||
|
setMappings(mappingRows);
|
||||||
|
} catch (error) {
|
||||||
|
message.error(getErrorMessage(error));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const selectGoods = (commodityId: string) => {
|
||||||
|
const item = goods.find((row) => row.commodity_id === commodityId);
|
||||||
|
setMappingGoodsId(commodityId);
|
||||||
|
if (item?.score != null) setMappingPoints(Number(item.score));
|
||||||
|
};
|
||||||
|
|
||||||
|
const saveMapping = async () => {
|
||||||
|
if (!mappingSku.trim() || !mappingGoodsId) {
|
||||||
|
message.warning('请填写内部 SKU 并选择斗鱼商品');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const item = goods.find((row) => row.commodity_id === mappingGoodsId);
|
||||||
|
try {
|
||||||
|
await platformFulfillmentApi.upsertMapping({
|
||||||
|
internal_sku_key: mappingSku.trim(),
|
||||||
|
commodity_id: mappingGoodsId,
|
||||||
|
goods_name: item?.name || '',
|
||||||
|
required_points: mappingPoints,
|
||||||
|
enabled: mappingEnabled,
|
||||||
|
});
|
||||||
|
message.success('商品映射已保存');
|
||||||
|
setMappings(await platformFulfillmentApi.listMappings(mappingSku.trim()));
|
||||||
|
await loadTasks();
|
||||||
|
} catch (error) {
|
||||||
|
message.error(getErrorMessage(error));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const columns: ColumnsType<PlatformFulfillmentTask> = [
|
||||||
|
{
|
||||||
|
title: '订单 / 商品',
|
||||||
|
key: 'order',
|
||||||
|
width: 280,
|
||||||
|
render: (_, task) => (
|
||||||
|
<Space direction="vertical" size={2}>
|
||||||
|
<Text strong>{task.platformOrderId || `#${task.sourceOrderId}`}</Text>
|
||||||
|
<Text>{task.skuName || task.internalSkuKey || '-'}</Text>
|
||||||
|
<Text type="secondary">
|
||||||
|
{task.provider || '-'} / {task.shopName || task.shopId || '-'}
|
||||||
|
</Text>
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '商品映射',
|
||||||
|
key: 'mapping',
|
||||||
|
width: 230,
|
||||||
|
render: (_, task) => (
|
||||||
|
<Space direction="vertical" size={2}>
|
||||||
|
<Text>{task.commodityId || '未映射'}</Text>
|
||||||
|
<Text type="secondary">
|
||||||
|
{task.requiredPoints != null ? `${task.requiredPoints} 积分` : '价格未知'}
|
||||||
|
</Text>
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '订单金额',
|
||||||
|
dataIndex: 'orderAmountFen',
|
||||||
|
width: 110,
|
||||||
|
render: (value: number) => money(value),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '账号',
|
||||||
|
key: 'account',
|
||||||
|
width: 190,
|
||||||
|
render: (_, task) =>
|
||||||
|
task.account ? (
|
||||||
|
<Space direction="vertical" size={2}>
|
||||||
|
<Text>{task.account.nickname || task.account.username}</Text>
|
||||||
|
<Text type="secondary">
|
||||||
|
积分 {task.account.points ?? '-'} · 鱼翅 {task.account.goldBalance ?? '-'}
|
||||||
|
</Text>
|
||||||
|
<Text type="secondary">
|
||||||
|
租约 {task.lease?.status || '-'} · {formatTime(task.lease?.expiresAt)}
|
||||||
|
</Text>
|
||||||
|
</Space>
|
||||||
|
) : (
|
||||||
|
<Text type="secondary">未分配</Text>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '绑定',
|
||||||
|
key: 'binding',
|
||||||
|
width: 180,
|
||||||
|
render: (_, task) => (
|
||||||
|
<Space direction="vertical" size={2}>
|
||||||
|
<Tag>{task.bindingStatus}</Tag>
|
||||||
|
<Text>{task.bindTask?.roleName || task.bindTask?.bindPhase || '-'}</Text>
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '状态',
|
||||||
|
key: 'status',
|
||||||
|
width: 150,
|
||||||
|
render: (_, task) => (
|
||||||
|
<Space direction="vertical" size={4}>
|
||||||
|
<Tag color={STATUS_COLORS[task.executionStatus] || 'default'}>
|
||||||
|
{statusLabel(task.executionStatus)}
|
||||||
|
</Tag>
|
||||||
|
<Text type="secondary">兑换:{task.exchangeStatus}</Text>
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '更新时间',
|
||||||
|
dataIndex: 'updatedAt',
|
||||||
|
width: 160,
|
||||||
|
render: (value: string) => formatTime(value),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
key: 'actions',
|
||||||
|
width: 330,
|
||||||
|
render: (_, task) => (
|
||||||
|
<Space wrap>
|
||||||
|
<Button size="small" onClick={() => setSelectedId(task.id)}>
|
||||||
|
详情
|
||||||
|
</Button>
|
||||||
|
{task.executionStatus === 'pending_mapping' ? (
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
type="primary"
|
||||||
|
icon={<LinkOutlined />}
|
||||||
|
disabled={!can('platform_fulfillment:admin')}
|
||||||
|
onClick={() => void openMapping(task)}
|
||||||
|
>
|
||||||
|
配置映射
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
{task.executionStatus === 'ready' ? (
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
type="primary"
|
||||||
|
icon={<UserSwitchOutlined />}
|
||||||
|
onClick={() =>
|
||||||
|
void runTaskAction(() => platformFulfillmentApi.allocate(task.id))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
自动选号
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
{task.executionStatus === 'allocated' ? (
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
type="primary"
|
||||||
|
icon={<QrcodeOutlined />}
|
||||||
|
onClick={() =>
|
||||||
|
void runTaskAction(() => platformFulfillmentApi.startBinding(task.id))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
生成二维码
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
{['waiting_bind', 'binding_confirming'].includes(task.executionStatus) ? (
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
icon={<ReloadOutlined />}
|
||||||
|
onClick={() =>
|
||||||
|
void runTaskAction(() => platformFulfillmentApi.refreshBinding(task.id))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
刷新绑定
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
{task.executionStatus === 'role_ready' ? (
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
type="primary"
|
||||||
|
icon={<CheckCircleOutlined />}
|
||||||
|
onClick={() =>
|
||||||
|
void runTaskAction(() => platformFulfillmentApi.confirmBinding(task.id))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
确认绑定
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
{task.executionStatus === 'bound' ? (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
icon={<SyncOutlined />}
|
||||||
|
onClick={() =>
|
||||||
|
void runTaskAction(() =>
|
||||||
|
platformFulfillmentApi.refreshEligibility(task.id),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
刷新兑换资格
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
type="primary"
|
||||||
|
disabled={task.exchangeStatus !== 'eligible'}
|
||||||
|
onClick={() =>
|
||||||
|
void runTaskAction(() =>
|
||||||
|
platformFulfillmentApi.complete(task.id, '人工兑换完成'),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
完成
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const actionButtons = selected ? (
|
||||||
|
<Space wrap>
|
||||||
|
{selected.bindTask?.qrUrl ? (
|
||||||
|
<Button icon={<QrcodeOutlined />} onClick={() => setQrOpen(true)}>
|
||||||
|
查看二维码
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
{selected.account ? (
|
||||||
|
<Button
|
||||||
|
onClick={() =>
|
||||||
|
void runTaskAction(() => platformFulfillmentApi.release(selected.id))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
释放账号
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
{selected.executionStatus !== 'completed' &&
|
||||||
|
selected.executionStatus !== 'cancelled' ? (
|
||||||
|
<Button
|
||||||
|
danger
|
||||||
|
onClick={() =>
|
||||||
|
void runTaskAction(() =>
|
||||||
|
platformFulfillmentApi.cancel(selected.id, '运营取消'),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
取消
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</Space>
|
||||||
|
) : null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Space direction="vertical" size={16} style={{ width: '100%' }}>
|
||||||
|
<Card size="small">
|
||||||
|
<Space align="start" style={{ width: '100%', justifyContent: 'space-between' }} wrap>
|
||||||
|
<div>
|
||||||
|
<Title level={4} style={{ margin: 0 }}>
|
||||||
|
直播账号履约工作台
|
||||||
|
</Title>
|
||||||
|
<Text type="secondary">
|
||||||
|
读取 order_site 人工订单,客户扫码绑定游戏角色,运营使用斗鱼账号人工兑换。
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
<Space wrap>
|
||||||
|
<Button icon={<LinkOutlined />} disabled={!can('platform_fulfillment:admin')} onClick={() => void openMapping()}>
|
||||||
|
商品映射
|
||||||
|
</Button>
|
||||||
|
<Button type="primary" loading={syncing} icon={<SyncOutlined />} onClick={() => void sync()}>
|
||||||
|
同步待履约订单
|
||||||
|
</Button>
|
||||||
|
</Space>
|
||||||
|
</Space>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card size="small">
|
||||||
|
<Space wrap style={{ marginBottom: 16 }}>
|
||||||
|
<Input.Search
|
||||||
|
allowClear
|
||||||
|
placeholder="订单号 / SKU / 商品 ID"
|
||||||
|
value={keyword}
|
||||||
|
onChange={(event) => {
|
||||||
|
setKeyword(event.target.value);
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
style={{ width: 300 }}
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
value={status}
|
||||||
|
options={STATUS_OPTIONS}
|
||||||
|
onChange={(value) => {
|
||||||
|
setStatus(value);
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
style={{ width: 150 }}
|
||||||
|
/>
|
||||||
|
<Button icon={<ReloadOutlined />} onClick={() => void loadTasks()}>
|
||||||
|
刷新
|
||||||
|
</Button>
|
||||||
|
</Space>
|
||||||
|
<Table<PlatformFulfillmentTask>
|
||||||
|
rowKey="id"
|
||||||
|
loading={loading}
|
||||||
|
columns={columns}
|
||||||
|
dataSource={rows}
|
||||||
|
scroll={{ x: 1500 }}
|
||||||
|
pagination={{
|
||||||
|
current: page,
|
||||||
|
pageSize,
|
||||||
|
total,
|
||||||
|
showSizeChanger: true,
|
||||||
|
onChange: (nextPage, nextSize) => {
|
||||||
|
setPage(nextPage);
|
||||||
|
setPageSize(nextSize);
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
locale={{ emptyText: <Empty description="暂无直播账号履约任务" /> }}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Drawer
|
||||||
|
open={Boolean(selectedId)}
|
||||||
|
width={760}
|
||||||
|
title={selected ? `履约详情 · ${selected.platformOrderId}` : '履约详情'}
|
||||||
|
onClose={() => setSelectedId(null)}
|
||||||
|
>
|
||||||
|
{detailLoading || !selected ? (
|
||||||
|
<Text type="secondary">加载中...</Text>
|
||||||
|
) : (
|
||||||
|
<Space direction="vertical" size={16} style={{ width: '100%' }}>
|
||||||
|
{selected.lastError ? (
|
||||||
|
<Alert type="warning" showIcon message={selected.lastError} />
|
||||||
|
) : null}
|
||||||
|
<Descriptions bordered size="small" column={2}>
|
||||||
|
<Descriptions.Item label="商品" span={2}>{selected.skuName}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="内部 SKU">{selected.internalSkuKey || '-'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="斗鱼商品">{selected.commodityId || '-'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="订单金额">{money(selected.orderAmountFen)}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="所需积分">{selected.requiredPoints ?? '-'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="执行状态">{statusLabel(selected.executionStatus)}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="绑定状态">{selected.bindingStatus}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="兑换状态">{selected.exchangeStatus}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="账号">
|
||||||
|
{selected.account?.nickname || selected.account?.username || '-'}
|
||||||
|
</Descriptions.Item>
|
||||||
|
</Descriptions>
|
||||||
|
<Card size="small" title="当前操作">
|
||||||
|
{actionButtons}
|
||||||
|
</Card>
|
||||||
|
<Card size="small" title="事件时间线">
|
||||||
|
<Timeline
|
||||||
|
items={(detail?.events || []).map((event) => ({
|
||||||
|
color: event.eventType.includes('failed') ? 'red' : 'blue',
|
||||||
|
children: (
|
||||||
|
<Space direction="vertical" size={2}>
|
||||||
|
<Text strong>{event.eventType}</Text>
|
||||||
|
<Text type="secondary">
|
||||||
|
{formatTime(event.createdAt)} · {event.actorType}
|
||||||
|
{event.actorId ? ` ${event.actorId}` : ''}
|
||||||
|
</Text>
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
</Space>
|
||||||
|
)}
|
||||||
|
</Drawer>
|
||||||
|
|
||||||
|
<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}
|
||||||
|
<Text type="secondary">
|
||||||
|
请客户使用对应游戏平台扫码。二维码只用于当前履约作业。
|
||||||
|
</Text>
|
||||||
|
<Button
|
||||||
|
icon={<CopyOutlined />}
|
||||||
|
onClick={() => {
|
||||||
|
void navigator.clipboard.writeText(qrValue).then(
|
||||||
|
() => message.success('二维码链接已复制'),
|
||||||
|
() => message.error('复制失败'),
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
复制二维码链接
|
||||||
|
</Button>
|
||||||
|
</Space>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
<Modal
|
||||||
|
open={mappingOpen}
|
||||||
|
title="斗鱼商品映射"
|
||||||
|
width={760}
|
||||||
|
okText="保存映射"
|
||||||
|
onOk={() => void saveMapping()}
|
||||||
|
onCancel={() => setMappingOpen(false)}
|
||||||
|
>
|
||||||
|
<Space direction="vertical" size={14} style={{ width: '100%' }}>
|
||||||
|
<Input
|
||||||
|
placeholder="内部 SKU,例如 套装-兔兔白日梦"
|
||||||
|
value={mappingSku}
|
||||||
|
onChange={(event) => setMappingSku(event.target.value)}
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
showSearch
|
||||||
|
optionFilterProp="label"
|
||||||
|
placeholder="选择斗鱼精英宝典商品"
|
||||||
|
value={mappingGoodsId || undefined}
|
||||||
|
onChange={selectGoods}
|
||||||
|
options={goods.map((item) => ({
|
||||||
|
value: item.commodity_id,
|
||||||
|
label: `${item.name || item.commodity_id} · ${item.score ?? '-'} 积分`,
|
||||||
|
}))}
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
/>
|
||||||
|
<Space>
|
||||||
|
<Text>所需积分</Text>
|
||||||
|
<InputNumber min={0} value={mappingPoints} onChange={(value) => setMappingPoints(value)} />
|
||||||
|
<Text>启用</Text>
|
||||||
|
<Switch checked={mappingEnabled} onChange={setMappingEnabled} />
|
||||||
|
</Space>
|
||||||
|
<Tabs
|
||||||
|
items={[
|
||||||
|
{
|
||||||
|
key: 'current',
|
||||||
|
label: '当前映射',
|
||||||
|
children: (
|
||||||
|
<Table<PlatformFulfillmentMapping>
|
||||||
|
rowKey="id"
|
||||||
|
size="small"
|
||||||
|
pagination={false}
|
||||||
|
dataSource={mappings}
|
||||||
|
columns={[
|
||||||
|
{ title: '内部 SKU', dataIndex: 'internalSkuKey' },
|
||||||
|
{ title: '商品', dataIndex: 'goodsName' },
|
||||||
|
{ title: '商品 ID', dataIndex: 'commodityId' },
|
||||||
|
{ title: '积分', dataIndex: 'requiredPoints' },
|
||||||
|
{
|
||||||
|
title: '状态',
|
||||||
|
dataIndex: 'enabled',
|
||||||
|
render: (value: boolean) => (
|
||||||
|
<Tag color={value ? 'green' : 'default'}>
|
||||||
|
{value ? '启用' : '停用'}
|
||||||
|
</Tag>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Space>
|
||||||
|
</Modal>
|
||||||
|
</Space>
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user