feat(fulfillment): 支持手动同步斗鱼外部单协作
This commit is contained in:
@@ -0,0 +1,137 @@
|
||||
"""斗鱼外部单协作关联直播履约来源。
|
||||
|
||||
手工协作单保持 ``source_type=manual``;从直播履约同步的订单通过唯一
|
||||
``source_task_id`` 幂等关联,重复点击同步不会生成重复订单。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261118_0094"
|
||||
down_revision: str | None = "20261118_0093"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
TABLE = "douyu_external_orders"
|
||||
INDEX = "uq_douyu_external_source_task"
|
||||
FOREIGN_KEY = "fk_douyu_external_orders_source_task"
|
||||
|
||||
|
||||
def _column_exists(name: str) -> bool:
|
||||
return bool(
|
||||
op.get_bind()
|
||||
.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()
|
||||
)
|
||||
|
||||
|
||||
def _index_exists(name: str) -> bool:
|
||||
return bool(
|
||||
op.get_bind()
|
||||
.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()
|
||||
)
|
||||
|
||||
|
||||
def _foreign_key_exists(name: str) -> bool:
|
||||
return any(
|
||||
item.get("name") == name
|
||||
for item in sa.inspect(op.get_bind()).get_foreign_keys(TABLE)
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
if not _column_exists("source_type"):
|
||||
op.add_column(
|
||||
TABLE,
|
||||
sa.Column(
|
||||
"source_type",
|
||||
sa.String(length=24),
|
||||
nullable=False,
|
||||
server_default="manual",
|
||||
),
|
||||
)
|
||||
if not _column_exists("source_task_id"):
|
||||
op.add_column(
|
||||
TABLE,
|
||||
sa.Column("source_task_id", sa.BigInteger(), nullable=True),
|
||||
)
|
||||
if not _column_exists("source_order_id"):
|
||||
op.add_column(
|
||||
TABLE,
|
||||
sa.Column(
|
||||
"source_order_id",
|
||||
sa.String(length=64),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
)
|
||||
if not _column_exists("source_order_item_id"):
|
||||
op.add_column(
|
||||
TABLE,
|
||||
sa.Column(
|
||||
"source_order_item_id",
|
||||
sa.String(length=64),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
)
|
||||
if not _column_exists("source_platform_order_id"):
|
||||
op.add_column(
|
||||
TABLE,
|
||||
sa.Column(
|
||||
"source_platform_order_id",
|
||||
sa.String(length=128),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
)
|
||||
if not _column_exists("last_synced_at"):
|
||||
op.add_column(
|
||||
TABLE,
|
||||
sa.Column("last_synced_at", sa.DateTime(), nullable=True),
|
||||
)
|
||||
if not _index_exists(INDEX):
|
||||
op.create_index(INDEX, TABLE, ["source_task_id"], unique=True)
|
||||
if not _foreign_key_exists(FOREIGN_KEY):
|
||||
op.create_foreign_key(
|
||||
FOREIGN_KEY,
|
||||
TABLE,
|
||||
"platform_fulfillment_tasks",
|
||||
["source_task_id"],
|
||||
["id"],
|
||||
ondelete="SET NULL",
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
if _foreign_key_exists(FOREIGN_KEY):
|
||||
op.drop_constraint(FOREIGN_KEY, TABLE, type_="foreignkey")
|
||||
if _index_exists(INDEX):
|
||||
op.drop_index(INDEX, table_name=TABLE)
|
||||
for column in (
|
||||
"last_synced_at",
|
||||
"source_platform_order_id",
|
||||
"source_order_item_id",
|
||||
"source_order_id",
|
||||
"source_task_id",
|
||||
"source_type",
|
||||
):
|
||||
if _column_exists(column):
|
||||
op.drop_column(TABLE, column)
|
||||
@@ -630,6 +630,27 @@ class DouyuExternalOrder(Base):
|
||||
owner_id: Mapped[int | None] = mapped_column(
|
||||
ForeignKey("users.id"), nullable=True, index=True
|
||||
)
|
||||
# ---- 来源关联(手工协作单为空)----
|
||||
source_type: Mapped[str] = mapped_column(
|
||||
String(24), nullable=False, default="manual", server_default="manual"
|
||||
)
|
||||
source_task_id: Mapped[int | None] = mapped_column(
|
||||
BigInteger,
|
||||
ForeignKey("platform_fulfillment_tasks.id", ondelete="SET NULL"),
|
||||
nullable=True,
|
||||
)
|
||||
source_order_id: Mapped[str] = mapped_column(
|
||||
String(64), nullable=False, default="", server_default=""
|
||||
)
|
||||
source_order_item_id: Mapped[str] = mapped_column(
|
||||
String(64), nullable=False, default="", server_default=""
|
||||
)
|
||||
source_platform_order_id: Mapped[str] = mapped_column(
|
||||
String(128), nullable=False, default="", server_default=""
|
||||
)
|
||||
last_synced_at: Mapped[datetime | None] = mapped_column(
|
||||
UTCDateTime, nullable=True
|
||||
)
|
||||
|
||||
# ---- 内部斗鱼账号(CK 不落本表)----
|
||||
account_id: Mapped[int | None] = mapped_column(
|
||||
@@ -713,6 +734,14 @@ class DouyuExternalOrder(Base):
|
||||
UTCDateTime, default=_utcnow, onupdate=_utcnow, index=True
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
Index(
|
||||
"uq_douyu_external_source_task",
|
||||
"source_task_id",
|
||||
unique=True,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class DouyuExternalOrderMetric(Base):
|
||||
"""斗鱼协作单的鱼翅/积分/兑换记录快照(只追加,不存 CK)。"""
|
||||
|
||||
@@ -11,12 +11,15 @@ from ..database import get_db
|
||||
from ..deps import require_permission
|
||||
from ..models import User
|
||||
from ..schemas import (
|
||||
PlatformFulfillmentCollabSyncRequest,
|
||||
PlatformFulfillmentCompleteRequest,
|
||||
PlatformFulfillmentMappingUpsert,
|
||||
PlatformFulfillmentReasonRequest,
|
||||
PlatformFulfillmentSettingsUpdate,
|
||||
)
|
||||
from ..services import douyu_collab_service
|
||||
from ..services.audit_service import record_audit
|
||||
from ..services.douyu_collab_events import collab_events
|
||||
from ..services.platform_fulfillment import service
|
||||
|
||||
router = APIRouter(prefix="/api/platform-fulfillment", tags=["直播账号履约"])
|
||||
@@ -95,6 +98,26 @@ def sync_tasks(
|
||||
return result
|
||||
|
||||
|
||||
@router.post("/tasks/sync-collab")
|
||||
def sync_tasks_to_douyu_collab(
|
||||
req: PlatformFulfillmentCollabSyncRequest,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("platform_fulfillment:use")),
|
||||
) -> dict[str, Any]:
|
||||
result = douyu_collab_service.sync_platform_fulfillment_orders(
|
||||
db,
|
||||
current,
|
||||
task_ids=req.task_ids,
|
||||
)
|
||||
if result["created"] or result["updated"]:
|
||||
collab_events.publish(
|
||||
scope="orders",
|
||||
action="order.sync_from_platform_fulfillment",
|
||||
actor_id=int(current.id),
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/tasks/{task_id}")
|
||||
def get_task(
|
||||
task_id: int,
|
||||
|
||||
@@ -1598,6 +1598,10 @@ class PlatformFulfillmentCustomerSessionBatchRequest(BaseModel):
|
||||
task_ids: list[int] = Field(default_factory=list, max_length=100)
|
||||
|
||||
|
||||
class PlatformFulfillmentCollabSyncRequest(BaseModel):
|
||||
task_ids: list[int] = Field(..., min_length=1, max_length=100)
|
||||
|
||||
|
||||
class DouyuTaskBatchRequest(BaseModel):
|
||||
account_ids: list[int]
|
||||
task_type: str
|
||||
@@ -2667,6 +2671,12 @@ class DouyuCollabOrderOut(BaseModel):
|
||||
shop: str = ""
|
||||
owner_id: int | None = None
|
||||
owner_name: str = ""
|
||||
source_type: str = "manual"
|
||||
source_task_id: int | None = None
|
||||
source_order_id: str = ""
|
||||
source_order_item_id: str = ""
|
||||
source_platform_order_id: str = ""
|
||||
last_synced_at: datetime | None = None
|
||||
|
||||
account_id: int | None = None
|
||||
account_username: str = ""
|
||||
|
||||
@@ -77,6 +77,7 @@ EVENT_TASK_STOPPED = "task_stopped" # 斗鱼账号任务停止/中断
|
||||
EVENT_QUERY_COMPLETED = "query_completed" # 同步查询完成(含部分失败)
|
||||
EVENT_LEASE_ACQUIRED = "lease_acquired" # 分配履约账号使用权
|
||||
EVENT_LEASE_RELEASED = "lease_released" # 释放履约账号使用权
|
||||
EVENT_COLLAB_SYNCED = "collab_synced" # 直播履约任务同步到外部单协作
|
||||
|
||||
# 有符号金额的事件类型(用于页面「累计充值/累计消耗」):
|
||||
# 充值为正、兑换为负,其余不计入金额统计。
|
||||
|
||||
@@ -17,6 +17,7 @@ from collections.abc import Mapping, Sequence
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from loguru import logger
|
||||
from sqlalchemy import func, or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -31,9 +32,14 @@ from ..models import (
|
||||
DouyuExternalOrder,
|
||||
DouyuExternalOrderMetric,
|
||||
DouyuGoodsSnapshot,
|
||||
DouyuTask,
|
||||
PlatformCommodityMapping,
|
||||
PlatformFulfillmentTask,
|
||||
User,
|
||||
)
|
||||
from .audit_service import record_audit
|
||||
from .account_binding import binding_channel, binding_role_from_result
|
||||
from .account_events_service import EVENT_COLLAB_SYNCED
|
||||
from .audit_service import record_account_action, record_audit
|
||||
from .business_events import record_account_query
|
||||
from .collab_common import apply_order_visibility, count_archived
|
||||
from .douyu_activity_query import (
|
||||
@@ -97,6 +103,8 @@ STATUS_FLOW: tuple[str, ...] = (
|
||||
STATUS_DONE,
|
||||
)
|
||||
|
||||
SOURCE_TYPE_PLATFORM_FULFILLMENT = "platform_fulfillment"
|
||||
|
||||
STAGE_INDEX = {
|
||||
STATUS_INCOMPLETE: 0,
|
||||
STATUS_TO_RECHARGE: 1,
|
||||
@@ -667,6 +675,292 @@ def create_order(
|
||||
return order
|
||||
|
||||
|
||||
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 _apply_platform_fulfillment_binding(
|
||||
db: Session,
|
||||
order: DouyuExternalOrder,
|
||||
task: PlatformFulfillmentTask,
|
||||
) -> None:
|
||||
"""把履约任务已确认的本地绑定结果投影到协作单,不额外联网。"""
|
||||
bind_task = (
|
||||
db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first()
|
||||
if task.bind_task_id
|
||||
else None
|
||||
)
|
||||
result = bind_task.result if bind_task and isinstance(bind_task.result, dict) else None
|
||||
role = binding_role_from_result(result)
|
||||
if not role:
|
||||
return
|
||||
order.bind_game_role = _text(role, max_length=128)
|
||||
channel = binding_channel(result)
|
||||
if channel:
|
||||
order.bind_game_channel = _text(channel, max_length=128)
|
||||
order.bind_snapshot_at = order.bind_snapshot_at or _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()
|
||||
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()
|
||||
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]:
|
||||
"""把一条直播履约任务幂等同步为斗鱼外部协作单。
|
||||
|
||||
这里只复制本地已确认的数据,不调用斗鱼接口,也不覆盖协作台上人工维护的
|
||||
负责人、余额、核账快照和备注。``source_task_id`` 是幂等键。
|
||||
"""
|
||||
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()
|
||||
)
|
||||
created = order is None
|
||||
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_no = f"PF{task.id}"
|
||||
occupied = (
|
||||
db.query(DouyuExternalOrder)
|
||||
.filter(DouyuExternalOrder.order_no == order_no)
|
||||
.first()
|
||||
)
|
||||
if occupied is not None:
|
||||
raise CollabError(
|
||||
f"协作单号 {order_no} 已被其他订单占用",
|
||||
code="order_no_conflict",
|
||||
)
|
||||
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.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
|
||||
order.shop = _text(task.shop_name or task.shop_id, max_length=64)
|
||||
order.gift_name = gift_name
|
||||
order.commodity_id = commodity_id
|
||||
order.required_points = required_points
|
||||
if account is not None:
|
||||
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)
|
||||
_apply_platform_fulfillment_status(order, task, created=created)
|
||||
order.version = int(order.version or 0) + 1
|
||||
db.flush()
|
||||
|
||||
audit_detail = {
|
||||
"taskId": int(task.id),
|
||||
"orderNo": order.order_no,
|
||||
"created": created,
|
||||
"status": order.status,
|
||||
}
|
||||
if account is not None:
|
||||
record_account_action(
|
||||
db,
|
||||
current,
|
||||
account=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
|
||||
|
||||
|
||||
def update_order(
|
||||
db: Session,
|
||||
current: User,
|
||||
@@ -1792,6 +2086,12 @@ def serialize_order(
|
||||
"shop": order.shop or "",
|
||||
"owner_id": order.owner_id,
|
||||
"owner_name": users.get(int(order.owner_id), "") if order.owner_id else "",
|
||||
"source_type": order.source_type or "manual",
|
||||
"source_task_id": order.source_task_id,
|
||||
"source_order_id": order.source_order_id or "",
|
||||
"source_order_item_id": order.source_order_item_id or "",
|
||||
"source_platform_order_id": order.source_platform_order_id or "",
|
||||
"last_synced_at": order.last_synced_at,
|
||||
"account_id": order.account_id,
|
||||
"account_username": order.account_username or "",
|
||||
"account_uid": order.account_uid or "",
|
||||
@@ -1927,6 +2227,9 @@ def _apply_order_filters(
|
||||
DouyuExternalOrder.bind_game_role.ilike(pattern),
|
||||
DouyuExternalOrder.shop.ilike(pattern),
|
||||
DouyuExternalOrder.remark.ilike(pattern),
|
||||
DouyuExternalOrder.source_order_id.ilike(pattern),
|
||||
DouyuExternalOrder.source_order_item_id.ilike(pattern),
|
||||
DouyuExternalOrder.source_platform_order_id.ilike(pattern),
|
||||
)
|
||||
)
|
||||
return query
|
||||
|
||||
@@ -17,6 +17,7 @@ from sqlalchemy.orm import Session
|
||||
from ...models import (
|
||||
Account,
|
||||
AccountLease,
|
||||
DouyuExternalOrder,
|
||||
DouyuGoodsSnapshot,
|
||||
DouyuTask,
|
||||
PlatformCommodityMapping,
|
||||
@@ -949,6 +950,11 @@ def _task_out(
|
||||
if task.bind_task_id
|
||||
else None
|
||||
)
|
||||
collab_order = (
|
||||
db.query(DouyuExternalOrder)
|
||||
.filter(DouyuExternalOrder.source_task_id == task.id)
|
||||
.first()
|
||||
)
|
||||
bind_result = (bind_task.result or {}) if bind_task else {}
|
||||
# 外层只消费共享绑定规则,不再自己比较角色名或 bindAct。
|
||||
pending_role = pending_binding_role_from_result(bind_result)
|
||||
@@ -982,6 +988,16 @@ def _task_out(
|
||||
"paidAt": task.paid_at,
|
||||
"createdAt": task.created_at,
|
||||
"updatedAt": task.updated_at,
|
||||
"collabOrder": (
|
||||
{
|
||||
"id": collab_order.id,
|
||||
"orderNo": collab_order.order_no,
|
||||
"status": collab_order.status,
|
||||
"lastSyncedAt": collab_order.last_synced_at,
|
||||
}
|
||||
if collab_order
|
||||
else None
|
||||
),
|
||||
"account": (
|
||||
{
|
||||
"id": account.id,
|
||||
|
||||
@@ -31,6 +31,12 @@ export interface DouyuCollabOrder {
|
||||
shop: string;
|
||||
owner_id: number | null;
|
||||
owner_name: string;
|
||||
source_type: string;
|
||||
source_task_id: number | null;
|
||||
source_order_id: string;
|
||||
source_order_item_id: string;
|
||||
source_platform_order_id: string;
|
||||
last_synced_at: string | null;
|
||||
account_id: number | null;
|
||||
account_username: string;
|
||||
account_uid: string;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import api from './client';
|
||||
import type {
|
||||
PlatformFulfillmentDetail,
|
||||
PlatformFulfillmentCollabSyncResult,
|
||||
PlatformFulfillmentListResponse,
|
||||
PlatformFulfillmentMapping,
|
||||
PlatformFulfillmentSettings,
|
||||
@@ -38,6 +39,11 @@ export const platformFulfillmentApi = {
|
||||
null,
|
||||
{ params: { limit } },
|
||||
),
|
||||
syncCollab: (taskIds: number[]) =>
|
||||
api.post<PlatformFulfillmentCollabSyncResult, PlatformFulfillmentCollabSyncResult>(
|
||||
'/platform-fulfillment/tasks/sync-collab',
|
||||
{ task_ids: taskIds },
|
||||
),
|
||||
getTask: (taskId: number) =>
|
||||
api.get<PlatformFulfillmentDetail, PlatformFulfillmentDetail>(
|
||||
`/platform-fulfillment/tasks/${taskId}`,
|
||||
|
||||
@@ -2213,6 +2213,12 @@ export interface PlatformFulfillmentTask {
|
||||
paidAt: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
collabOrder: {
|
||||
id: number;
|
||||
orderNo: string;
|
||||
status: string;
|
||||
lastSyncedAt: string | null;
|
||||
} | null;
|
||||
account: PlatformFulfillmentAccount | null;
|
||||
lease: { id: number; status: string; expiresAt: string | null } | null;
|
||||
bindTask: PlatformFulfillmentBindTask | null;
|
||||
@@ -2248,3 +2254,20 @@ export interface PlatformFulfillmentListResponse {
|
||||
items: PlatformFulfillmentTask[];
|
||||
pagination: { page: number; pageSize: number; total: number };
|
||||
}
|
||||
|
||||
export interface PlatformFulfillmentCollabSyncItem {
|
||||
taskId: number;
|
||||
action: 'created' | 'updated' | 'skipped' | 'failed';
|
||||
reason: string;
|
||||
collabOrderId: number | null;
|
||||
orderNo: string;
|
||||
}
|
||||
|
||||
export interface PlatformFulfillmentCollabSyncResult {
|
||||
requested: number;
|
||||
created: number;
|
||||
updated: number;
|
||||
skipped: number;
|
||||
failed: number;
|
||||
items: PlatformFulfillmentCollabSyncItem[];
|
||||
}
|
||||
|
||||
@@ -43,6 +43,7 @@ const EVENT_STYLE: Record<string, { label: string; color: string }> = {
|
||||
task_stopped: { label: '任务停止', color: 'orange' },
|
||||
query_completed: { label: '查询完成', color: 'blue' },
|
||||
lease_acquired: { label: '账号占用', color: 'cyan' },
|
||||
collab_synced: { label: '外部协作同步', color: 'geekblue' },
|
||||
lease_released: { label: '账号释放', color: 'default' },
|
||||
};
|
||||
|
||||
|
||||
@@ -1089,6 +1089,9 @@ export default function DouyuCollabPage() {
|
||||
<Text strong copyable={{ text: value }}>
|
||||
{value}
|
||||
</Text>
|
||||
{row.source_type === 'platform_fulfillment' && (
|
||||
<Tag color="cyan">履约同步 · #{row.source_task_id}</Tag>
|
||||
)}
|
||||
{row.status === 'void' && <Tag color="error">已作废:{row.void_reason || '-'}</Tag>}
|
||||
</Space>
|
||||
),
|
||||
@@ -2218,6 +2221,19 @@ export default function DouyuCollabPage() {
|
||||
<Descriptions.Item label="状态">
|
||||
<Tag color={STATUS_META[detail.status]?.color}>{detail.status_label}</Tag>
|
||||
</Descriptions.Item>
|
||||
{detail.source_type === 'platform_fulfillment' ? (
|
||||
<>
|
||||
<Descriptions.Item label="履约任务">
|
||||
#{detail.source_task_id ?? '-'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="来源订单">
|
||||
{detail.source_platform_order_id || detail.source_order_id || '-'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="最近同步" span={2}>
|
||||
{detail.last_synced_at ? formatTime(detail.last_synced_at) : '-'}
|
||||
</Descriptions.Item>
|
||||
</>
|
||||
) : null}
|
||||
<Descriptions.Item label="斗鱼账号">{detail.account_username || '-'}</Descriptions.Item>
|
||||
<Descriptions.Item label="账号昵称">{detail.account_nickname || '-'}</Descriptions.Item>
|
||||
<Descriptions.Item label="绑定角色">{detail.bind_game_role || '-'}</Descriptions.Item>
|
||||
|
||||
@@ -43,6 +43,17 @@ const STATUS_COLORS: Record<string, string> = {
|
||||
cancelled: 'default',
|
||||
};
|
||||
|
||||
const COLLAB_STATUS_LABELS: Record<string, string> = {
|
||||
incomplete: '待补资料',
|
||||
to_recharge: '待充值',
|
||||
recharged: '已充值',
|
||||
scripted: '已上脚本',
|
||||
done: '抢购成功',
|
||||
points_error: '积分异常',
|
||||
failed: '抢购失败',
|
||||
void: '已作废',
|
||||
};
|
||||
|
||||
const BINDING_STATUS_LABELS: Record<string, string> = {
|
||||
not_started: '未开始',
|
||||
preparing: '准备中',
|
||||
@@ -121,6 +132,10 @@ function exchangeStatusLabel(value: string) {
|
||||
return EXCHANGE_STATUS_LABELS[value] || '未知状态';
|
||||
}
|
||||
|
||||
function collabStatusLabel(value: string) {
|
||||
return COLLAB_STATUS_LABELS[value] || value || '-';
|
||||
}
|
||||
|
||||
function issueLabel(value: string) {
|
||||
if (!value) return '-';
|
||||
return ISSUE_LABELS[value] || '其他处理事项';
|
||||
@@ -254,6 +269,8 @@ export default function PlatformFulfillmentPage() {
|
||||
const [total, setTotal] = useState(0);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [syncing, setSyncing] = useState(false);
|
||||
const [collabSyncing, setCollabSyncing] = useState(false);
|
||||
const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
|
||||
const [selectedId, setSelectedId] = useState<number | null>(null);
|
||||
const [detail, setDetail] = useState<PlatformFulfillmentDetail | null>(null);
|
||||
const [detailLoading, setDetailLoading] = useState(false);
|
||||
@@ -381,6 +398,50 @@ export default function PlatformFulfillmentPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const syncCollab = async () => {
|
||||
const taskIds = selectedRowKeys.map(Number).filter((value) => Number.isInteger(value));
|
||||
if (taskIds.length === 0) {
|
||||
message.warning('请先勾选要同步的履约任务');
|
||||
return;
|
||||
}
|
||||
setCollabSyncing(true);
|
||||
try {
|
||||
const result = await platformFulfillmentApi.syncCollab(taskIds);
|
||||
const summary = `外部协作同步完成:新增 ${result.created},更新 ${result.updated}`;
|
||||
if (result.failed || result.skipped) {
|
||||
message.warning(`${summary},跳过 ${result.skipped},失败 ${result.failed}`);
|
||||
const problems = result.items.filter(
|
||||
(item) => item.action === 'failed' || item.action === 'skipped',
|
||||
);
|
||||
Modal.warning({
|
||||
title: '部分履约任务未同步',
|
||||
width: 560,
|
||||
content: (
|
||||
<Space direction="vertical" size={4}>
|
||||
{problems.slice(0, 20).map((item) => (
|
||||
<Text key={`${item.taskId}-${item.action}`} type="secondary">
|
||||
#{item.taskId}:{item.reason || '未同步'}
|
||||
</Text>
|
||||
))}
|
||||
{problems.length > 20 ? (
|
||||
<Text type="secondary">另有 {problems.length - 20} 条未显示</Text>
|
||||
) : null}
|
||||
</Space>
|
||||
),
|
||||
});
|
||||
} else {
|
||||
message.success(summary);
|
||||
}
|
||||
setSelectedRowKeys([]);
|
||||
await loadTasks();
|
||||
if (selectedId) await loadDetail(selectedId, true);
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setCollabSyncing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const runTaskAction = async (action: () => Promise<PlatformFulfillmentDetail>) => {
|
||||
try {
|
||||
const result = await action();
|
||||
@@ -669,6 +730,22 @@ export default function PlatformFulfillmentPage() {
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '外部协作',
|
||||
key: 'collab',
|
||||
width: 150,
|
||||
render: (_, task) =>
|
||||
task.collabOrder ? (
|
||||
<Space direction="vertical" size={2}>
|
||||
<Tag color={task.collabOrder.status === 'done' ? 'success' : 'blue'}>
|
||||
{collabStatusLabel(task.collabOrder.status)}
|
||||
</Tag>
|
||||
<Text copyable={{ text: task.collabOrder.orderNo }}>{task.collabOrder.orderNo}</Text>
|
||||
</Space>
|
||||
) : (
|
||||
<Text type="secondary">未同步</Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '更新时间',
|
||||
dataIndex: 'updatedAt',
|
||||
@@ -778,6 +855,14 @@ export default function PlatformFulfillmentPage() {
|
||||
<Button icon={<LinkOutlined />} disabled={!can('platform_fulfillment:admin')} onClick={() => void openMapping()}>
|
||||
商品映射
|
||||
</Button>
|
||||
<Button
|
||||
icon={<LinkOutlined />}
|
||||
loading={collabSyncing}
|
||||
disabled={!can('platform_fulfillment:use') || selectedRowKeys.length === 0}
|
||||
onClick={() => void syncCollab()}
|
||||
>
|
||||
同步外部单协作{selectedRowKeys.length > 0 ? `(${selectedRowKeys.length})` : ''}
|
||||
</Button>
|
||||
<Button type="primary" loading={syncing} icon={<SyncOutlined />} onClick={() => void sync()}>
|
||||
同步待履约订单
|
||||
</Button>
|
||||
@@ -815,7 +900,11 @@ export default function PlatformFulfillmentPage() {
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={rows}
|
||||
scroll={{ x: 1600 }}
|
||||
rowSelection={{
|
||||
selectedRowKeys,
|
||||
onChange: setSelectedRowKeys,
|
||||
}}
|
||||
scroll={{ x: 1900 }}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize,
|
||||
@@ -891,6 +980,11 @@ export default function PlatformFulfillmentPage() {
|
||||
<Descriptions.Item label="所需积分">{selected.requiredPoints ?? '-'}</Descriptions.Item>
|
||||
<Descriptions.Item label="执行状态">{statusLabel(selected.executionStatus)}</Descriptions.Item>
|
||||
<Descriptions.Item label="绑定状态">{bindingStatusLabel(selected.bindingStatus)}</Descriptions.Item>
|
||||
<Descriptions.Item label="外部协作单" span={2}>
|
||||
{selected.collabOrder
|
||||
? `${selected.collabOrder.orderNo} · ${collabStatusLabel(selected.collabOrder.status)}`
|
||||
: '未同步'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="兑换状态">{exchangeStatusLabel(selected.exchangeStatus)}</Descriptions.Item>
|
||||
<Descriptions.Item label="处理提示">{issueLabel(selected.issueCode)}</Descriptions.Item>
|
||||
</Descriptions>
|
||||
|
||||
Reference in New Issue
Block a user