Files
live-hub-py/web/backend/services/douyu_collab_sync.py
T

372 lines
12 KiB
Python

"""直播账号履约任务向斗鱼外部单协作的幂等投影。"""
from __future__ import annotations
from collections.abc import Sequence
from typing import Any
from loguru import logger
from sqlalchemy.orm import Session
from ..models import (
Account,
DouyuExternalOrder,
DouyuGoodsSnapshot,
DouyuTask,
PlatformCommodityMapping,
PlatformFulfillmentTask,
User,
)
from .account_events_service import EVENT_COLLAB_SYNCED
from .audit_service import record_account_action, record_audit
from .douyu_binding import BINDING_VIEW_CONFIRMED, resolve_douyu_binding
from .douyu_collab_common import (
POINTS_THRESHOLD_DEFAULT,
SOURCE_TYPE_PLATFORM_FULFILLMENT,
STATUS_DONE,
STATUS_INCOMPLETE,
STATUS_VOID,
CollabError,
_mark_order_succeeded,
_now,
_text,
_to_int,
)
from .douyu_collab_leases import _sync_order_lease
from .douyu_collab_shops import ensure_shops_registered, resolve_shop_name
def _platform_fulfillment_gift(
db: Session,
task: PlatformFulfillmentTask,
) -> tuple[str, str, int | None]:
"""解析履约任务对应的斗鱼商品,优先显式映射,再回退到商品快照。"""
mapping = (
db.query(PlatformCommodityMapping)
.filter(PlatformCommodityMapping.id == task.commodity_mapping_id)
.first()
if task.commodity_mapping_id
else None
)
snapshot = (
db.query(DouyuGoodsSnapshot)
.filter(DouyuGoodsSnapshot.commodity_id == task.commodity_id)
.first()
if task.commodity_id
else None
)
name = _text(
(mapping.goods_name if mapping else "")
or (snapshot.name if snapshot else "")
or task.sku_name,
max_length=128,
)
commodity_id = _text(
task.commodity_id
or (mapping.commodity_id if mapping else "")
or (snapshot.commodity_id if snapshot else ""),
max_length=64,
)
required_points = _to_int(task.required_points)
if required_points is None and mapping is not None:
required_points = _to_int(mapping.required_points)
if required_points is None and snapshot is not None:
required_points = _to_int(snapshot.score)
return name, commodity_id, required_points
def _platform_fulfillment_order_no(task: PlatformFulfillmentTask) -> str:
"""外部协作单直接使用 order_site 的真实平台订单号。"""
order_no = _text(task.platform_order_id)
if not order_no:
raise CollabError("履约任务缺少平台订单号", code="platform_order_no_required")
if len(order_no) > 64:
raise CollabError(
"平台订单号超过协作单号长度限制",
code="platform_order_no_too_long",
)
return order_no
def _apply_platform_fulfillment_binding(
db: Session,
order: DouyuExternalOrder,
task: PlatformFulfillmentTask,
*,
overwrite: bool,
) -> None:
"""把履约任务已确认的本地绑定结果投影到协作单,不额外联网。"""
bind_task = (
db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first()
if task.bind_task_id
else None
)
if bind_task is None:
return
binding = resolve_douyu_binding(
bind_task,
account=db.get(Account, int(task.account_id)) if task.account_id else None,
)
if binding.status != BINDING_VIEW_CONFIRMED:
return
role = binding.confirmed_role_name
if overwrite or not order.bind_game_role:
order.bind_game_role = _text(role, max_length=128)
channel = binding.confirmed_channel
if channel and (overwrite or not order.bind_game_channel):
order.bind_game_channel = _text(channel, max_length=128)
if overwrite or not order.bind_snapshot_at:
order.bind_snapshot_at = _now()
def _apply_platform_fulfillment_status(
order: DouyuExternalOrder,
task: PlatformFulfillmentTask,
*,
created: bool,
) -> None:
"""只做不会倒退的状态映射,保留协作台里人工推进的中间状态。"""
if created:
if task.execution_status == "completed":
order.status = STATUS_DONE
order.done_at = order.done_at or task.completed_at or _now()
_mark_order_succeeded(order, order.done_at)
elif task.execution_status == "cancelled":
order.status = STATUS_VOID
order.void_reason = order.void_reason or "直播履约任务已取消"
else:
order.status = STATUS_INCOMPLETE
return
if task.execution_status == "completed" and order.status not in (
STATUS_DONE,
STATUS_VOID,
):
order.status = STATUS_DONE
order.done_at = order.done_at or task.completed_at or _now()
_mark_order_succeeded(order, order.done_at)
elif task.execution_status == "cancelled" and order.status != STATUS_VOID:
order.status = STATUS_VOID
order.void_reason = order.void_reason or "直播履约任务已取消"
def sync_platform_fulfillment_order(
db: Session,
current: User,
task: PlatformFulfillmentTask,
*,
commit: bool = True,
) -> tuple[DouyuExternalOrder, str]:
"""把一条直播履约任务幂等同步为斗鱼外部协作单。"""
if task.source_system != "order_site":
raise CollabError("仅支持同步 order_site 履约任务", code="source_unsupported")
order = (
db.query(DouyuExternalOrder)
.filter(DouyuExternalOrder.source_task_id == task.id)
.first()
)
order_no = _platform_fulfillment_order_no(task)
created = order is None
order_by_no = (
db.query(DouyuExternalOrder)
.filter(DouyuExternalOrder.order_no == order_no)
.first()
)
if order is not None and order_by_no is not None and order_by_no.id != order.id:
raise CollabError(
f"平台订单号 {order_no} 已关联其他履约任务",
code="order_no_conflict",
)
if order is None and order_by_no is not None:
if order_by_no.source_task_id not in (None, task.id):
raise CollabError(
f"平台订单号 {order_no} 已关联其他履约任务",
code="order_no_conflict",
)
order = order_by_no
created = False
now = _now()
account = (
db.query(Account).filter(Account.id == task.account_id).first()
if task.account_id
else None
)
gift_name, commodity_id, required_points = _platform_fulfillment_gift(db, task)
if order is None:
order = DouyuExternalOrder(
order_no=order_no,
source_type=SOURCE_TYPE_PLATFORM_FULFILLMENT,
source_task_id=task.id,
status=STATUS_INCOMPLETE,
points_threshold=POINTS_THRESHOLD_DEFAULT,
owner_id=current.id,
created_by=current.id,
version=0,
created_at=now,
)
db.add(order)
order.order_no = order_no
order.source_type = SOURCE_TYPE_PLATFORM_FULFILLMENT
order.source_task_id = int(task.id)
order.source_order_id = _text(task.source_order_id, max_length=64)
order.source_order_item_id = _text(task.source_order_item_id, max_length=64)
order.source_platform_order_id = _text(task.platform_order_id, max_length=128)
order.last_synced_at = now
order.updated_by = current.id
order.updated_at = now
shop_original_name = _text(task.shop_name or task.shop_id, max_length=128)
ensure_shops_registered(db, current, [shop_original_name])
order.shop = resolve_shop_name(db, shop_original_name)[:64]
order.shop_original_name = shop_original_name
order.gift_name = gift_name
order.commodity_id = commodity_id
order.required_points = required_points
if account is not None and (
created or (order.account_id is None and not order.account_username)
):
order.account_id = int(account.id)
order.account_username = _text(account.username, max_length=128)
order.account_uid = _text(account.uid, max_length=32)
order.account_nickname = _text(account.nickname, max_length=128)
_apply_platform_fulfillment_binding(
db,
order,
task,
overwrite=created,
)
_apply_platform_fulfillment_status(order, task, created=created)
order.version = int(order.version or 0) + 1
db.flush()
_sync_order_lease(
db,
current,
order,
reason="douyu_collab_sync_terminal",
)
audit_detail = {
"taskId": int(task.id),
"orderNo": order.order_no,
"created": created,
"status": order.status,
}
linked_account = (
db.query(Account).filter(Account.id == order.account_id).first()
if order.account_id
else None
)
if linked_account is not None:
record_account_action(
db,
current,
account=linked_account,
action="douyu:collab:sync_from_platform_fulfillment",
event_type=EVENT_COLLAB_SYNCED,
title=f"同步外部单协作:{order.order_no}",
target=f"douyu_external_order:{order.id}",
detail=audit_detail,
)
else:
record_audit(
db,
current,
action="douyu:collab:sync_from_platform_fulfillment",
target=f"douyu_external_order:{order.id}",
detail=audit_detail,
)
if commit:
db.commit()
db.refresh(order)
return order, "created" if created else "updated"
def sync_platform_fulfillment_orders(
db: Session,
current: User,
*,
task_ids: Sequence[int],
commit: bool = True,
) -> dict[str, Any]:
"""批量同步履约任务;单条失败回滚自己的 SAVEPOINT,不拖垮整批。"""
requested_ids = list(dict.fromkeys(int(item) for item in task_ids if item))
tasks = (
db.query(PlatformFulfillmentTask)
.filter(PlatformFulfillmentTask.id.in_(requested_ids))
.all()
if requested_ids
else []
)
tasks_by_id = {int(task.id): task for task in tasks}
result = {
"requested": len(requested_ids),
"created": 0,
"updated": 0,
"skipped": 0,
"failed": 0,
"items": [],
}
for task_id in requested_ids:
task = tasks_by_id.get(task_id)
if task is None:
result["skipped"] += 1
result["items"].append(
{
"taskId": task_id,
"action": "skipped",
"reason": "履约任务不存在",
"collabOrderId": None,
"orderNo": "",
}
)
continue
try:
with db.begin_nested():
order, action = sync_platform_fulfillment_order(
db,
current,
task,
commit=False,
)
result[action] += 1
result["items"].append(
{
"taskId": task_id,
"action": action,
"reason": "",
"collabOrderId": int(order.id),
"orderNo": order.order_no,
}
)
except CollabError as exc:
result["failed"] += 1
result["items"].append(
{
"taskId": task_id,
"action": "failed",
"reason": exc.detail,
"collabOrderId": None,
"orderNo": "",
}
)
except Exception: # noqa: BLE001 - 批量边界需隔离单条未知故障
logger.exception("同步直播履约任务 {} 到斗鱼外部协作失败", task_id)
result["failed"] += 1
result["items"].append(
{
"taskId": task_id,
"action": "failed",
"reason": "同步失败,请稍后重试",
"collabOrderId": None,
"orderNo": "",
}
)
if commit:
db.commit()
return result