fix(douyu): 统一外部协作账号租约

This commit is contained in:
yml
2026-11-19 16:03:17 +08:00
parent acd27bde67
commit dd48175b4a
8 changed files with 1248 additions and 79 deletions
@@ -82,6 +82,7 @@ def _matching_mode() -> str:
mode = os.getenv("PLATFORM_FULFILLMENT_MATCH_MODE", "hybrid").strip().lower()
return mode if mode in {"legacy", "hybrid", "capability"} else "hybrid"
_SYNC_LOCK = Lock()
_AUTO_SYNC_LOCK = Lock()
_AUTO_SYNC_LAST_ATTEMPT = float("-inf")
@@ -150,7 +151,9 @@ def _upsert_order_snapshot(
) -> tuple[PlatformFulfillmentTask | None, bool, bool]:
"""应用一条订单项快照,返回 (task, created, ignored)。"""
item_id = str(
_snapshot_value(snapshot, "sourceOrderItemId", "source_order_item_id", default="")
_snapshot_value(
snapshot, "sourceOrderItemId", "source_order_item_id", default=""
)
).strip()
if not item_id:
return None, False, True
@@ -177,11 +180,7 @@ def _upsert_order_snapshot(
return None, False, True
cutoff = _order_match_started_at(db)
match_basis_at = paid_at or order_created_at
if (
match_basis_at is not None
and cutoff is not None
and match_basis_at < cutoff
):
if match_basis_at is not None and cutoff is not None and match_basis_at < cutoff:
return None, False, True
task = (
@@ -303,21 +302,11 @@ def _upsert_order_snapshot(
default=task.source_fulfillment_id,
)
)
task.provider = str(
_snapshot_value(snapshot, "provider", default=task.provider)
)
task.shop_id = str(
_snapshot_value(snapshot, "shopId", "shop_id", default="")
)
task.shop_name = str(
_snapshot_value(snapshot, "shopName", "shop_name", default="")
)
task.sku_code = str(
_snapshot_value(snapshot, "skuCode", "sku_code", default="")
)
task.sku_name = str(
_snapshot_value(snapshot, "skuName", "sku_name", default="")
)
task.provider = str(_snapshot_value(snapshot, "provider", default=task.provider))
task.shop_id = str(_snapshot_value(snapshot, "shopId", "shop_id", default=""))
task.shop_name = str(_snapshot_value(snapshot, "shopName", "shop_name", default=""))
task.sku_code = str(_snapshot_value(snapshot, "skuCode", "sku_code", default=""))
task.sku_name = str(_snapshot_value(snapshot, "skuName", "sku_name", default=""))
task.internal_sku_key = str(
_snapshot_value(
snapshot,
@@ -453,7 +442,9 @@ def sync_order_item_ids(
updated = 0
ignored = 0
task_ids: list[int] = []
for item_id in dict.fromkeys(str(item or "").strip() for item in source_order_item_ids):
for item_id in dict.fromkeys(
str(item or "").strip() for item in source_order_item_ids
):
if not item_id:
ignored += 1
continue
@@ -461,7 +452,9 @@ def sync_order_item_ids(
if snapshot is None:
ignored += 1
continue
mapping = mapping_by_sku.get(str(snapshot.get("internal_sku_key") or "").strip())
mapping = mapping_by_sku.get(
str(snapshot.get("internal_sku_key") or "").strip()
)
task, was_created, was_ignored = _upsert_order_snapshot(
db,
snapshot,
@@ -765,6 +758,31 @@ def _load_task(db: Session, task_id: int) -> PlatformFulfillmentTask:
return task
def _retain_lease_for_active_collab(
db: Session,
*,
task: PlatformFulfillmentTask,
lease: AccountLease | None,
current: User,
reason: str,
) -> AccountLease | None:
"""平台释放账号前,把仍在活动的协作单占用接续到同一租约。"""
if lease is None or not task.account_id:
return None
from ..douyu_collab_service import retain_lease_for_active_collab
return retain_lease_for_active_collab(
db,
account_id=int(task.account_id),
holder_user_id=int(current.id),
current=current,
lease=lease,
source_task_id=int(task.id),
reason=reason,
commit=False,
)
def _apply_mapping(
task: PlatformFulfillmentTask,
mapping: PlatformCommodityMapping | None,
@@ -892,10 +910,10 @@ def _sync_pending_tasks(
task.scope = SCOPE_ELITE
task.source_snapshot_json = _jsonable(row)
task.updated_at = _now()
if (
task.account_id is None
and task.execution_status in {"pending_mapping", "ready"}
):
if task.account_id is None and task.execution_status in {
"pending_mapping",
"ready",
}:
_apply_mapping(task, mapping)
if task.execution_status == "ready" and task.account_id is None:
task.next_allocate_at = _now()
@@ -1135,13 +1153,16 @@ def get_task_detail(db: Session, task_id: int) -> dict[str, Any]:
actor_ids = {
int(event.actor_id)
for event in events
if event.actor_type == "user"
and str(event.actor_id or "").isdigit()
if event.actor_type == "user" and str(event.actor_id or "").isdigit()
}
actors = {
int(user.id): user
for user in db.query(User).filter(User.id.in_(actor_ids)).all()
} if actor_ids else {}
actors = (
{
int(user.id): user
for user in db.query(User).filter(User.id.in_(actor_ids)).all()
}
if actor_ids
else {}
)
return {
"task": _task_out(db, task, include_qr=True),
"events": [
@@ -1154,19 +1175,16 @@ def get_task_detail(db: Session, task_id: int) -> dict[str, Any]:
actors[int(event.actor_id)].deleted_username
or actors[int(event.actor_id)].username
)
if str(event.actor_id or "").isdigit()
and int(event.actor_id) in actors
if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors
else "",
"actorRole": actors[int(event.actor_id)].role
if str(event.actor_id or "").isdigit()
and int(event.actor_id) in actors
if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors
else "",
"actorRoleLabel": ROLE_LABELS.get(
actors[int(event.actor_id)].role,
actors[int(event.actor_id)].role,
)
if str(event.actor_id or "").isdigit()
and int(event.actor_id) in actors
if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors
else "",
"detail": event.detail_json or {},
"createdAt": event.created_at,
@@ -1542,9 +1560,7 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
availability=(
AVAILABILITY_LIMITED if limited else AVAILABILITY_AVAILABLE
),
blocking_reason=(
"该账号已达此商品兑换上限" if limited else ""
),
blocking_reason=("该账号已达此商品兑换上限" if limited else ""),
raw_status="1" if limited else "0",
observed_at=live_state.checked_at,
source="live_check",
@@ -1742,7 +1758,15 @@ def release_task_account(
if task.lease_id
else None
)
release_lease(db, lease, reason=reason)
retained = _retain_lease_for_active_collab(
db,
task=task,
lease=lease,
current=current,
reason="platform_released_to_collab",
)
if retained is None:
release_lease(db, lease, reason=reason, commit=False)
task.account_id = None
task.lease_id = None
task.bind_task_id = None
@@ -2057,7 +2081,7 @@ def reconcile_binding_state_outbox(
PlatformFulfillmentTask.id > normalized_after,
PlatformFulfillmentTask.execution_status.notin_(
["completed", "cancelled"]
)
),
)
.order_by(PlatformFulfillmentTask.id.asc())
.limit(batch_size)
@@ -2297,7 +2321,20 @@ def complete_manual_exchange(
task.last_error = ""
task.issue_code = ""
task.updated_at = _now()
release_lease(db, lease, reason="manual_exchange_completed")
retained = _retain_lease_for_active_collab(
db,
task=task,
lease=lease,
current=current,
reason="platform_completed_but_collab_active",
)
if retained is None:
release_lease(
db,
lease,
reason="manual_exchange_completed",
commit=False,
)
_append_event(
db,
task.id,
@@ -2378,7 +2415,20 @@ def cancel_task(
linked_task.status = "stopped"
linked_task.message = "履约任务已取消"
linked_task.finished_at = _now()
release_lease(db, lease, reason="platform_fulfillment_cancelled")
retained = _retain_lease_for_active_collab(
db,
task=task,
lease=lease,
current=current,
reason="platform_cancelled_but_collab_active",
)
if retained is None:
release_lease(
db,
lease,
reason="platform_fulfillment_cancelled",
commit=False,
)
task.account_id = None
task.lease_id = None
task.bind_task_id = None
@@ -2455,7 +2505,9 @@ def restore_cancelled_task(
or str(source.get("fulfillment_issue_code") or "")
in {"user_refund", "platform_cancelled"}
):
raise HTTPException(status_code=409, detail="来源订单已退款、关闭或取消,不能恢复")
raise HTTPException(
status_code=409, detail="来源订单已退款、关闭或取消,不能恢复"
)
restore_reason = reason.strip()
if len(restore_reason) < 2:
@@ -2537,7 +2589,20 @@ def release_task_to_manual(
if task.lease_id
else None
)
release_lease(db, lease, reason="platform_fulfillment_manual")
retained = _retain_lease_for_active_collab(
db,
task=task,
lease=lease,
current=current,
reason="platform_release_to_manual",
)
if retained is None:
release_lease(
db,
lease,
reason="platform_fulfillment_manual",
commit=False,
)
task.account_id = None
task.lease_id = None
task.bind_task_id = None