feat(fulfillment): 新增直播账号履约工作台

This commit is contained in:
yml
2026-11-17 14:44:28 +08:00
parent f8a35ec224
commit 1ca768eba5
30 changed files with 3729 additions and 27 deletions
@@ -22,6 +22,12 @@ from .jobs.douyu_tasks_retention import (
from .jobs.douyu_tasks_retention import (
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 run_points_expire_check
from .scheduler import (
@@ -43,6 +49,7 @@ __all__ = [
"CK_HEALTH_KEY",
"CK_RELOGIN_KEY",
"DOUYU_TASKS_RETENTION_KEY",
"PLATFORM_FULFILLMENT_LEASE_REAPER_KEY",
"POINTS_EXPIRE_KEY",
"JobSpec",
"automation_enabled",
@@ -57,6 +64,7 @@ __all__ = [
"run_douyu_tasks_retention",
"run_due_jobs",
"run_job_now",
"run_platform_fulfillment_lease_reaper",
"run_points_expire_check",
"scheduler_status",
"start_scheduler",
@@ -140,3 +148,14 @@ def register_default_jobs() -> None:
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_AUTO_FULFILLED = "auto_fulfilled"
ROUTE_WORKER_PLATFORM = "worker_platform"
PLATFORM_FULFILLMENT_SOURCE = "order_site"
# 发货方内部行:同一订单号下与真实店铺行成对出现,其 sku_code 是内部编码
# (如 suit_shadow_gothic),不能用来回显给买家。
@@ -151,6 +152,102 @@ def _fetch_rows(order_no: str) -> list[dict[str, Any]]:
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:
"""订单号维度的聚合判定:任一行已处理即算已处理。"""
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",
]