feat(fulfillment): 支持手动同步斗鱼外部单协作
This commit is contained in:
@@ -39,7 +39,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 = "20261118_0093"
|
HEAD_REVISION = "20261118_0094"
|
||||||
|
|
||||||
# 迁移新增、但不声明在模型里的复合查询索引。
|
# 迁移新增、但不声明在模型里的复合查询索引。
|
||||||
EXTRA_INDEXES = (
|
EXTRA_INDEXES = (
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ from web.backend.models import (
|
|||||||
AccountEvent,
|
AccountEvent,
|
||||||
AccountLease,
|
AccountLease,
|
||||||
AutomationJob,
|
AutomationJob,
|
||||||
|
DouyuExternalOrder,
|
||||||
DouyuGoodsSnapshot,
|
DouyuGoodsSnapshot,
|
||||||
DouyuTask,
|
DouyuTask,
|
||||||
IntegrationOutbox,
|
IntegrationOutbox,
|
||||||
@@ -25,6 +26,8 @@ from web.backend.models import (
|
|||||||
PlatformFulfillmentTask,
|
PlatformFulfillmentTask,
|
||||||
User,
|
User,
|
||||||
)
|
)
|
||||||
|
from web.backend.schemas import DouyuCollabOrderOut
|
||||||
|
from web.backend.services import douyu_collab_service as collab
|
||||||
from web.backend.services.automation.jobs import (
|
from web.backend.services.automation.jobs import (
|
||||||
platform_fulfillment_lease_reaper as reaper,
|
platform_fulfillment_lease_reaper as reaper,
|
||||||
)
|
)
|
||||||
@@ -438,6 +441,247 @@ class TestSyncAndMapping(_Base):
|
|||||||
assert task.required_points == 1280
|
assert task.required_points == 1280
|
||||||
|
|
||||||
|
|
||||||
|
class TestFulfillmentCollabSync(_Base):
|
||||||
|
def _task_with_account(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
execution_status: str = "ready",
|
||||||
|
) -> PlatformFulfillmentTask:
|
||||||
|
task = self.task()
|
||||||
|
account = self.account("collab-sync-account")
|
||||||
|
task.account_id = account.id
|
||||||
|
task.execution_status = execution_status
|
||||||
|
self.session.commit()
|
||||||
|
return task
|
||||||
|
|
||||||
|
def test_manual_sync_creates_projected_collab_order(self):
|
||||||
|
task = self._task_with_account()
|
||||||
|
mapping = self.session.query(PlatformCommodityMapping).one()
|
||||||
|
mapping.goods_name = "套装-兔兔白日梦(斗鱼)"
|
||||||
|
self.session.add(
|
||||||
|
DouyuGoodsSnapshot(
|
||||||
|
commodity_id=COMMODITY,
|
||||||
|
name="不应覆盖显式映射",
|
||||||
|
score=999,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
bind_task = DouyuTask(
|
||||||
|
batch_id="collab-sync-bind",
|
||||||
|
account_id=task.account_id,
|
||||||
|
task_type="get_bind_qr",
|
||||||
|
handbook_scope="elite",
|
||||||
|
status="success",
|
||||||
|
result={
|
||||||
|
"role_name": "已确认角色",
|
||||||
|
"bind_confirmed": True,
|
||||||
|
"area_name": "微信",
|
||||||
|
"plat_name": "苹果(iOS)",
|
||||||
|
},
|
||||||
|
created_by=self.admin_id,
|
||||||
|
)
|
||||||
|
self.session.add(bind_task)
|
||||||
|
self.session.flush()
|
||||||
|
task.bind_task_id = bind_task.id
|
||||||
|
self.session.commit()
|
||||||
|
|
||||||
|
order, action = collab.sync_platform_fulfillment_order(
|
||||||
|
self.session,
|
||||||
|
self.admin,
|
||||||
|
task,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert action == "created"
|
||||||
|
assert order.order_no == f"PF{task.id}"
|
||||||
|
assert order.source_type == "platform_fulfillment"
|
||||||
|
assert order.source_task_id == task.id
|
||||||
|
assert order.source_order_id == task.source_order_id
|
||||||
|
assert order.source_order_item_id == task.source_order_item_id
|
||||||
|
assert order.source_platform_order_id == task.platform_order_id
|
||||||
|
assert order.last_synced_at is not None
|
||||||
|
assert order.shop == task.shop_name
|
||||||
|
assert order.gift_name == "套装-兔兔白日梦(斗鱼)"
|
||||||
|
assert order.commodity_id == COMMODITY
|
||||||
|
assert order.required_points == 1280
|
||||||
|
assert order.account_id == task.account_id
|
||||||
|
assert order.account_username == "collab-sync-account"
|
||||||
|
assert order.bind_game_role == "已确认角色"
|
||||||
|
assert order.bind_game_channel == "微信 / 苹果(iOS)"
|
||||||
|
assert order.status == collab.STATUS_INCOMPLETE
|
||||||
|
payload = DouyuCollabOrderOut.model_validate(
|
||||||
|
collab.serialize_one(self.session, order)
|
||||||
|
).model_dump()
|
||||||
|
assert payload["source_task_id"] == task.id
|
||||||
|
assert payload["source_platform_order_id"] == task.platform_order_id
|
||||||
|
assert (
|
||||||
|
self.session.query(AccountEvent)
|
||||||
|
.filter(AccountEvent.event_type == "collab_synced")
|
||||||
|
.count()
|
||||||
|
== 1
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_manual_sync_does_not_clear_account_added_in_collab(self):
|
||||||
|
task = self.task()
|
||||||
|
order, _ = collab.sync_platform_fulfillment_order(
|
||||||
|
self.session,
|
||||||
|
self.admin,
|
||||||
|
task,
|
||||||
|
)
|
||||||
|
account = self.account("manual-collab-account")
|
||||||
|
order.account_id = account.id
|
||||||
|
order.account_username = account.username
|
||||||
|
self.session.commit()
|
||||||
|
|
||||||
|
synced, _ = collab.sync_platform_fulfillment_order(
|
||||||
|
self.session,
|
||||||
|
self.admin,
|
||||||
|
task,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert synced.account_id == account.id
|
||||||
|
assert synced.account_username == account.username
|
||||||
|
|
||||||
|
def test_manual_sync_is_idempotent_and_preserves_human_fields(self):
|
||||||
|
task = self._task_with_account()
|
||||||
|
order, _ = collab.sync_platform_fulfillment_order(
|
||||||
|
self.session,
|
||||||
|
self.admin,
|
||||||
|
task,
|
||||||
|
)
|
||||||
|
other_owner = User(
|
||||||
|
username="collab-owner",
|
||||||
|
password_hash="h",
|
||||||
|
role="operator",
|
||||||
|
)
|
||||||
|
self.session.add(other_owner)
|
||||||
|
self.session.commit()
|
||||||
|
order.owner_id = other_owner.id
|
||||||
|
order.fish_fin_balance = 321
|
||||||
|
order.points_balance = 654
|
||||||
|
order.points_check_message = "人工核账快照"
|
||||||
|
order.remark = "客服人工备注"
|
||||||
|
self.session.commit()
|
||||||
|
|
||||||
|
synced, action = collab.sync_platform_fulfillment_order(
|
||||||
|
self.session,
|
||||||
|
self.admin,
|
||||||
|
task,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert action == "updated"
|
||||||
|
assert self.session.query(DouyuExternalOrder).count() == 1
|
||||||
|
assert synced.id == order.id
|
||||||
|
assert synced.owner_id == other_owner.id
|
||||||
|
assert synced.fish_fin_balance == 321
|
||||||
|
assert synced.points_balance == 654
|
||||||
|
assert synced.points_check_message == "人工核账快照"
|
||||||
|
assert synced.remark == "客服人工备注"
|
||||||
|
|
||||||
|
def test_manual_sync_maps_only_safe_terminal_statuses(self):
|
||||||
|
task = self._task_with_account()
|
||||||
|
order, _ = collab.sync_platform_fulfillment_order(
|
||||||
|
self.session,
|
||||||
|
self.admin,
|
||||||
|
task,
|
||||||
|
)
|
||||||
|
order.status = collab.STATUS_TO_RECHARGE
|
||||||
|
self.session.commit()
|
||||||
|
|
||||||
|
task.execution_status = "completed"
|
||||||
|
task.completed_at = NOW
|
||||||
|
self.session.commit()
|
||||||
|
order, _ = collab.sync_platform_fulfillment_order(
|
||||||
|
self.session,
|
||||||
|
self.admin,
|
||||||
|
task,
|
||||||
|
)
|
||||||
|
assert order.status == collab.STATUS_DONE
|
||||||
|
assert order.done_at == NOW
|
||||||
|
|
||||||
|
cancelled = PlatformFulfillmentTask(
|
||||||
|
source_system="order_site",
|
||||||
|
source_order_id="200",
|
||||||
|
source_order_item_id="201",
|
||||||
|
source_fulfillment_id="301",
|
||||||
|
platform_order_id="ORDER-201",
|
||||||
|
sku_code=INTERNAL_SKU,
|
||||||
|
sku_name=INTERNAL_SKU,
|
||||||
|
internal_sku_key=INTERNAL_SKU,
|
||||||
|
commodity_mapping_id=task.commodity_mapping_id,
|
||||||
|
commodity_id=COMMODITY,
|
||||||
|
required_points=1280,
|
||||||
|
execution_status="cancelled",
|
||||||
|
paid_at=NOW,
|
||||||
|
created_at=NOW,
|
||||||
|
updated_at=NOW,
|
||||||
|
)
|
||||||
|
self.session.add(cancelled)
|
||||||
|
self.session.commit()
|
||||||
|
cancelled_order, action = collab.sync_platform_fulfillment_order(
|
||||||
|
self.session,
|
||||||
|
self.admin,
|
||||||
|
cancelled,
|
||||||
|
)
|
||||||
|
assert action == "created"
|
||||||
|
assert cancelled_order.status == collab.STATUS_VOID
|
||||||
|
assert cancelled_order.void_reason == "直播履约任务已取消"
|
||||||
|
|
||||||
|
def test_manual_sync_batch_reports_created_and_missing(self):
|
||||||
|
first = self.task()
|
||||||
|
second = PlatformFulfillmentTask(
|
||||||
|
source_system="order_site",
|
||||||
|
source_order_id="300",
|
||||||
|
source_order_item_id="301",
|
||||||
|
source_fulfillment_id="401",
|
||||||
|
platform_order_id="ORDER-301",
|
||||||
|
sku_code=INTERNAL_SKU,
|
||||||
|
sku_name=INTERNAL_SKU,
|
||||||
|
internal_sku_key=INTERNAL_SKU,
|
||||||
|
commodity_mapping_id=first.commodity_mapping_id,
|
||||||
|
commodity_id=COMMODITY,
|
||||||
|
required_points=1280,
|
||||||
|
execution_status="ready",
|
||||||
|
paid_at=NOW,
|
||||||
|
created_at=NOW,
|
||||||
|
updated_at=NOW,
|
||||||
|
)
|
||||||
|
self.session.add(second)
|
||||||
|
self.session.commit()
|
||||||
|
|
||||||
|
result = collab.sync_platform_fulfillment_orders(
|
||||||
|
self.session,
|
||||||
|
self.admin,
|
||||||
|
task_ids=[first.id, second.id, 99999999],
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result["requested"] == 3
|
||||||
|
assert result["created"] == 2
|
||||||
|
assert result["updated"] == 0
|
||||||
|
assert result["skipped"] == 1
|
||||||
|
assert result["failed"] == 0
|
||||||
|
assert [item["action"] for item in result["items"]] == [
|
||||||
|
"created",
|
||||||
|
"created",
|
||||||
|
"skipped",
|
||||||
|
]
|
||||||
|
|
||||||
|
def test_task_list_exposes_linked_collab_order(self):
|
||||||
|
task = self._task_with_account()
|
||||||
|
order, _ = collab.sync_platform_fulfillment_order(
|
||||||
|
self.session,
|
||||||
|
self.admin,
|
||||||
|
task,
|
||||||
|
)
|
||||||
|
|
||||||
|
listed = service.list_tasks(self.session)
|
||||||
|
|
||||||
|
assert listed["items"][0]["collabOrder"] == {
|
||||||
|
"id": order.id,
|
||||||
|
"orderNo": order.order_no,
|
||||||
|
"status": collab.STATUS_INCOMPLETE,
|
||||||
|
"lastSyncedAt": order.last_synced_at,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
class TestSnapshotSync(_Base):
|
class TestSnapshotSync(_Base):
|
||||||
def snapshot(self, **overrides):
|
def snapshot(self, **overrides):
|
||||||
payload = {
|
payload = {
|
||||||
|
|||||||
@@ -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(
|
owner_id: Mapped[int | None] = mapped_column(
|
||||||
ForeignKey("users.id"), nullable=True, index=True
|
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 不落本表)----
|
# ---- 内部斗鱼账号(CK 不落本表)----
|
||||||
account_id: Mapped[int | None] = mapped_column(
|
account_id: Mapped[int | None] = mapped_column(
|
||||||
@@ -713,6 +734,14 @@ class DouyuExternalOrder(Base):
|
|||||||
UTCDateTime, default=_utcnow, onupdate=_utcnow, index=True
|
UTCDateTime, default=_utcnow, onupdate=_utcnow, index=True
|
||||||
)
|
)
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
Index(
|
||||||
|
"uq_douyu_external_source_task",
|
||||||
|
"source_task_id",
|
||||||
|
unique=True,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class DouyuExternalOrderMetric(Base):
|
class DouyuExternalOrderMetric(Base):
|
||||||
"""斗鱼协作单的鱼翅/积分/兑换记录快照(只追加,不存 CK)。"""
|
"""斗鱼协作单的鱼翅/积分/兑换记录快照(只追加,不存 CK)。"""
|
||||||
|
|||||||
@@ -11,12 +11,15 @@ from ..database import get_db
|
|||||||
from ..deps import require_permission
|
from ..deps import require_permission
|
||||||
from ..models import User
|
from ..models import User
|
||||||
from ..schemas import (
|
from ..schemas import (
|
||||||
|
PlatformFulfillmentCollabSyncRequest,
|
||||||
PlatformFulfillmentCompleteRequest,
|
PlatformFulfillmentCompleteRequest,
|
||||||
PlatformFulfillmentMappingUpsert,
|
PlatformFulfillmentMappingUpsert,
|
||||||
PlatformFulfillmentReasonRequest,
|
PlatformFulfillmentReasonRequest,
|
||||||
PlatformFulfillmentSettingsUpdate,
|
PlatformFulfillmentSettingsUpdate,
|
||||||
)
|
)
|
||||||
|
from ..services import douyu_collab_service
|
||||||
from ..services.audit_service import record_audit
|
from ..services.audit_service import record_audit
|
||||||
|
from ..services.douyu_collab_events import collab_events
|
||||||
from ..services.platform_fulfillment import service
|
from ..services.platform_fulfillment import service
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/platform-fulfillment", tags=["直播账号履约"])
|
router = APIRouter(prefix="/api/platform-fulfillment", tags=["直播账号履约"])
|
||||||
@@ -95,6 +98,26 @@ def sync_tasks(
|
|||||||
return result
|
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}")
|
@router.get("/tasks/{task_id}")
|
||||||
def get_task(
|
def get_task(
|
||||||
task_id: int,
|
task_id: int,
|
||||||
|
|||||||
@@ -1598,6 +1598,10 @@ class PlatformFulfillmentCustomerSessionBatchRequest(BaseModel):
|
|||||||
task_ids: list[int] = Field(default_factory=list, max_length=100)
|
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):
|
class DouyuTaskBatchRequest(BaseModel):
|
||||||
account_ids: list[int]
|
account_ids: list[int]
|
||||||
task_type: str
|
task_type: str
|
||||||
@@ -2667,6 +2671,12 @@ class DouyuCollabOrderOut(BaseModel):
|
|||||||
shop: str = ""
|
shop: str = ""
|
||||||
owner_id: int | None = None
|
owner_id: int | None = None
|
||||||
owner_name: str = ""
|
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_id: int | None = None
|
||||||
account_username: str = ""
|
account_username: str = ""
|
||||||
|
|||||||
@@ -77,6 +77,7 @@ EVENT_TASK_STOPPED = "task_stopped" # 斗鱼账号任务停止/中断
|
|||||||
EVENT_QUERY_COMPLETED = "query_completed" # 同步查询完成(含部分失败)
|
EVENT_QUERY_COMPLETED = "query_completed" # 同步查询完成(含部分失败)
|
||||||
EVENT_LEASE_ACQUIRED = "lease_acquired" # 分配履约账号使用权
|
EVENT_LEASE_ACQUIRED = "lease_acquired" # 分配履约账号使用权
|
||||||
EVENT_LEASE_RELEASED = "lease_released" # 释放履约账号使用权
|
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 datetime import UTC, datetime
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
from loguru import logger
|
||||||
from sqlalchemy import func, or_
|
from sqlalchemy import func, or_
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
@@ -31,9 +32,14 @@ from ..models import (
|
|||||||
DouyuExternalOrder,
|
DouyuExternalOrder,
|
||||||
DouyuExternalOrderMetric,
|
DouyuExternalOrderMetric,
|
||||||
DouyuGoodsSnapshot,
|
DouyuGoodsSnapshot,
|
||||||
|
DouyuTask,
|
||||||
|
PlatformCommodityMapping,
|
||||||
|
PlatformFulfillmentTask,
|
||||||
User,
|
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 .business_events import record_account_query
|
||||||
from .collab_common import apply_order_visibility, count_archived
|
from .collab_common import apply_order_visibility, count_archived
|
||||||
from .douyu_activity_query import (
|
from .douyu_activity_query import (
|
||||||
@@ -97,6 +103,8 @@ STATUS_FLOW: tuple[str, ...] = (
|
|||||||
STATUS_DONE,
|
STATUS_DONE,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
SOURCE_TYPE_PLATFORM_FULFILLMENT = "platform_fulfillment"
|
||||||
|
|
||||||
STAGE_INDEX = {
|
STAGE_INDEX = {
|
||||||
STATUS_INCOMPLETE: 0,
|
STATUS_INCOMPLETE: 0,
|
||||||
STATUS_TO_RECHARGE: 1,
|
STATUS_TO_RECHARGE: 1,
|
||||||
@@ -667,6 +675,292 @@ def create_order(
|
|||||||
return 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(
|
def update_order(
|
||||||
db: Session,
|
db: Session,
|
||||||
current: User,
|
current: User,
|
||||||
@@ -1792,6 +2086,12 @@ def serialize_order(
|
|||||||
"shop": order.shop or "",
|
"shop": order.shop or "",
|
||||||
"owner_id": order.owner_id,
|
"owner_id": order.owner_id,
|
||||||
"owner_name": users.get(int(order.owner_id), "") if order.owner_id else "",
|
"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_id": order.account_id,
|
||||||
"account_username": order.account_username or "",
|
"account_username": order.account_username or "",
|
||||||
"account_uid": order.account_uid or "",
|
"account_uid": order.account_uid or "",
|
||||||
@@ -1927,6 +2227,9 @@ def _apply_order_filters(
|
|||||||
DouyuExternalOrder.bind_game_role.ilike(pattern),
|
DouyuExternalOrder.bind_game_role.ilike(pattern),
|
||||||
DouyuExternalOrder.shop.ilike(pattern),
|
DouyuExternalOrder.shop.ilike(pattern),
|
||||||
DouyuExternalOrder.remark.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
|
return query
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ from sqlalchemy.orm import Session
|
|||||||
from ...models import (
|
from ...models import (
|
||||||
Account,
|
Account,
|
||||||
AccountLease,
|
AccountLease,
|
||||||
|
DouyuExternalOrder,
|
||||||
DouyuGoodsSnapshot,
|
DouyuGoodsSnapshot,
|
||||||
DouyuTask,
|
DouyuTask,
|
||||||
PlatformCommodityMapping,
|
PlatformCommodityMapping,
|
||||||
@@ -949,6 +950,11 @@ def _task_out(
|
|||||||
if task.bind_task_id
|
if task.bind_task_id
|
||||||
else None
|
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 {}
|
bind_result = (bind_task.result or {}) if bind_task else {}
|
||||||
# 外层只消费共享绑定规则,不再自己比较角色名或 bindAct。
|
# 外层只消费共享绑定规则,不再自己比较角色名或 bindAct。
|
||||||
pending_role = pending_binding_role_from_result(bind_result)
|
pending_role = pending_binding_role_from_result(bind_result)
|
||||||
@@ -982,6 +988,16 @@ def _task_out(
|
|||||||
"paidAt": task.paid_at,
|
"paidAt": task.paid_at,
|
||||||
"createdAt": task.created_at,
|
"createdAt": task.created_at,
|
||||||
"updatedAt": task.updated_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": (
|
"account": (
|
||||||
{
|
{
|
||||||
"id": account.id,
|
"id": account.id,
|
||||||
|
|||||||
@@ -31,6 +31,12 @@ export interface DouyuCollabOrder {
|
|||||||
shop: string;
|
shop: string;
|
||||||
owner_id: number | null;
|
owner_id: number | null;
|
||||||
owner_name: string;
|
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_id: number | null;
|
||||||
account_username: string;
|
account_username: string;
|
||||||
account_uid: string;
|
account_uid: string;
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import api from './client';
|
import api from './client';
|
||||||
import type {
|
import type {
|
||||||
PlatformFulfillmentDetail,
|
PlatformFulfillmentDetail,
|
||||||
|
PlatformFulfillmentCollabSyncResult,
|
||||||
PlatformFulfillmentListResponse,
|
PlatformFulfillmentListResponse,
|
||||||
PlatformFulfillmentMapping,
|
PlatformFulfillmentMapping,
|
||||||
PlatformFulfillmentSettings,
|
PlatformFulfillmentSettings,
|
||||||
@@ -38,6 +39,11 @@ export const platformFulfillmentApi = {
|
|||||||
null,
|
null,
|
||||||
{ params: { limit } },
|
{ params: { limit } },
|
||||||
),
|
),
|
||||||
|
syncCollab: (taskIds: number[]) =>
|
||||||
|
api.post<PlatformFulfillmentCollabSyncResult, PlatformFulfillmentCollabSyncResult>(
|
||||||
|
'/platform-fulfillment/tasks/sync-collab',
|
||||||
|
{ task_ids: taskIds },
|
||||||
|
),
|
||||||
getTask: (taskId: number) =>
|
getTask: (taskId: number) =>
|
||||||
api.get<PlatformFulfillmentDetail, PlatformFulfillmentDetail>(
|
api.get<PlatformFulfillmentDetail, PlatformFulfillmentDetail>(
|
||||||
`/platform-fulfillment/tasks/${taskId}`,
|
`/platform-fulfillment/tasks/${taskId}`,
|
||||||
|
|||||||
@@ -2213,6 +2213,12 @@ export interface PlatformFulfillmentTask {
|
|||||||
paidAt: string | null;
|
paidAt: string | null;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
|
collabOrder: {
|
||||||
|
id: number;
|
||||||
|
orderNo: string;
|
||||||
|
status: string;
|
||||||
|
lastSyncedAt: string | null;
|
||||||
|
} | null;
|
||||||
account: PlatformFulfillmentAccount | null;
|
account: PlatformFulfillmentAccount | null;
|
||||||
lease: { id: number; status: string; expiresAt: string | null } | null;
|
lease: { id: number; status: string; expiresAt: string | null } | null;
|
||||||
bindTask: PlatformFulfillmentBindTask | null;
|
bindTask: PlatformFulfillmentBindTask | null;
|
||||||
@@ -2248,3 +2254,20 @@ export interface PlatformFulfillmentListResponse {
|
|||||||
items: PlatformFulfillmentTask[];
|
items: PlatformFulfillmentTask[];
|
||||||
pagination: { page: number; pageSize: number; total: number };
|
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' },
|
task_stopped: { label: '任务停止', color: 'orange' },
|
||||||
query_completed: { label: '查询完成', color: 'blue' },
|
query_completed: { label: '查询完成', color: 'blue' },
|
||||||
lease_acquired: { label: '账号占用', color: 'cyan' },
|
lease_acquired: { label: '账号占用', color: 'cyan' },
|
||||||
|
collab_synced: { label: '外部协作同步', color: 'geekblue' },
|
||||||
lease_released: { label: '账号释放', color: 'default' },
|
lease_released: { label: '账号释放', color: 'default' },
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1089,6 +1089,9 @@ export default function DouyuCollabPage() {
|
|||||||
<Text strong copyable={{ text: value }}>
|
<Text strong copyable={{ text: value }}>
|
||||||
{value}
|
{value}
|
||||||
</Text>
|
</Text>
|
||||||
|
{row.source_type === 'platform_fulfillment' && (
|
||||||
|
<Tag color="cyan">履约同步 · #{row.source_task_id}</Tag>
|
||||||
|
)}
|
||||||
{row.status === 'void' && <Tag color="error">已作废:{row.void_reason || '-'}</Tag>}
|
{row.status === 'void' && <Tag color="error">已作废:{row.void_reason || '-'}</Tag>}
|
||||||
</Space>
|
</Space>
|
||||||
),
|
),
|
||||||
@@ -2218,6 +2221,19 @@ export default function DouyuCollabPage() {
|
|||||||
<Descriptions.Item label="状态">
|
<Descriptions.Item label="状态">
|
||||||
<Tag color={STATUS_META[detail.status]?.color}>{detail.status_label}</Tag>
|
<Tag color={STATUS_META[detail.status]?.color}>{detail.status_label}</Tag>
|
||||||
</Descriptions.Item>
|
</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_username || '-'}</Descriptions.Item>
|
||||||
<Descriptions.Item label="账号昵称">{detail.account_nickname || '-'}</Descriptions.Item>
|
<Descriptions.Item label="账号昵称">{detail.account_nickname || '-'}</Descriptions.Item>
|
||||||
<Descriptions.Item label="绑定角色">{detail.bind_game_role || '-'}</Descriptions.Item>
|
<Descriptions.Item label="绑定角色">{detail.bind_game_role || '-'}</Descriptions.Item>
|
||||||
|
|||||||
@@ -43,6 +43,17 @@ const STATUS_COLORS: Record<string, string> = {
|
|||||||
cancelled: 'default',
|
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> = {
|
const BINDING_STATUS_LABELS: Record<string, string> = {
|
||||||
not_started: '未开始',
|
not_started: '未开始',
|
||||||
preparing: '准备中',
|
preparing: '准备中',
|
||||||
@@ -121,6 +132,10 @@ function exchangeStatusLabel(value: string) {
|
|||||||
return EXCHANGE_STATUS_LABELS[value] || '未知状态';
|
return EXCHANGE_STATUS_LABELS[value] || '未知状态';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function collabStatusLabel(value: string) {
|
||||||
|
return COLLAB_STATUS_LABELS[value] || value || '-';
|
||||||
|
}
|
||||||
|
|
||||||
function issueLabel(value: string) {
|
function issueLabel(value: string) {
|
||||||
if (!value) return '-';
|
if (!value) return '-';
|
||||||
return ISSUE_LABELS[value] || '其他处理事项';
|
return ISSUE_LABELS[value] || '其他处理事项';
|
||||||
@@ -254,6 +269,8 @@ export default function PlatformFulfillmentPage() {
|
|||||||
const [total, setTotal] = useState(0);
|
const [total, setTotal] = useState(0);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [syncing, setSyncing] = 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 [selectedId, setSelectedId] = useState<number | null>(null);
|
||||||
const [detail, setDetail] = useState<PlatformFulfillmentDetail | null>(null);
|
const [detail, setDetail] = useState<PlatformFulfillmentDetail | null>(null);
|
||||||
const [detailLoading, setDetailLoading] = useState(false);
|
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>) => {
|
const runTaskAction = async (action: () => Promise<PlatformFulfillmentDetail>) => {
|
||||||
try {
|
try {
|
||||||
const result = await action();
|
const result = await action();
|
||||||
@@ -669,6 +730,22 @@ export default function PlatformFulfillmentPage() {
|
|||||||
</Space>
|
</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: '更新时间',
|
title: '更新时间',
|
||||||
dataIndex: 'updatedAt',
|
dataIndex: 'updatedAt',
|
||||||
@@ -778,6 +855,14 @@ export default function PlatformFulfillmentPage() {
|
|||||||
<Button icon={<LinkOutlined />} disabled={!can('platform_fulfillment:admin')} onClick={() => void openMapping()}>
|
<Button icon={<LinkOutlined />} disabled={!can('platform_fulfillment:admin')} onClick={() => void openMapping()}>
|
||||||
商品映射
|
商品映射
|
||||||
</Button>
|
</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 type="primary" loading={syncing} icon={<SyncOutlined />} onClick={() => void sync()}>
|
||||||
同步待履约订单
|
同步待履约订单
|
||||||
</Button>
|
</Button>
|
||||||
@@ -815,7 +900,11 @@ export default function PlatformFulfillmentPage() {
|
|||||||
loading={loading}
|
loading={loading}
|
||||||
columns={columns}
|
columns={columns}
|
||||||
dataSource={rows}
|
dataSource={rows}
|
||||||
scroll={{ x: 1600 }}
|
rowSelection={{
|
||||||
|
selectedRowKeys,
|
||||||
|
onChange: setSelectedRowKeys,
|
||||||
|
}}
|
||||||
|
scroll={{ x: 1900 }}
|
||||||
pagination={{
|
pagination={{
|
||||||
current: page,
|
current: page,
|
||||||
pageSize,
|
pageSize,
|
||||||
@@ -891,6 +980,11 @@ export default function PlatformFulfillmentPage() {
|
|||||||
<Descriptions.Item label="所需积分">{selected.requiredPoints ?? '-'}</Descriptions.Item>
|
<Descriptions.Item label="所需积分">{selected.requiredPoints ?? '-'}</Descriptions.Item>
|
||||||
<Descriptions.Item label="执行状态">{statusLabel(selected.executionStatus)}</Descriptions.Item>
|
<Descriptions.Item label="执行状态">{statusLabel(selected.executionStatus)}</Descriptions.Item>
|
||||||
<Descriptions.Item label="绑定状态">{bindingStatusLabel(selected.bindingStatus)}</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="兑换状态">{exchangeStatusLabel(selected.exchangeStatus)}</Descriptions.Item>
|
||||||
<Descriptions.Item label="处理提示">{issueLabel(selected.issueCode)}</Descriptions.Item>
|
<Descriptions.Item label="处理提示">{issueLabel(selected.issueCode)}</Descriptions.Item>
|
||||||
</Descriptions>
|
</Descriptions>
|
||||||
|
|||||||
Reference in New Issue
Block a user