542 lines
16 KiB
Python
542 lines
16 KiB
Python
"""订单快照同步与待履约任务生成。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import threading
|
|
import time
|
|
from datetime import datetime
|
|
from typing import Any
|
|
|
|
from fastapi import HTTPException
|
|
from sqlalchemy.orm import Session
|
|
|
|
from ...models import (
|
|
PlatformCommodityMapping,
|
|
PlatformFulfillmentTask,
|
|
)
|
|
from ..external_order_source import (
|
|
OrderLookupUnavailable,
|
|
list_pending_manual_fulfillments,
|
|
lookup_pending_manual_fulfillment,
|
|
)
|
|
from .common import (
|
|
AUTO_SYNC_INTERVAL_SECONDS,
|
|
SCOPE_ELITE,
|
|
TARGET_PLATFORM,
|
|
_jsonable,
|
|
_now,
|
|
_order_match_started_at,
|
|
_order_snapshot_from_event,
|
|
_parse_snapshot_datetime,
|
|
_snapshot_value,
|
|
)
|
|
from .mappings import _apply_mapping
|
|
from .outbox import _emit_order_site_binding_state
|
|
from .runtime import (
|
|
_append_event,
|
|
_apply_task_lease_policy,
|
|
)
|
|
|
|
_SYNC_LOCK = threading.Lock()
|
|
_AUTO_SYNC_LOCK = threading.Lock()
|
|
_AUTO_SYNC_LAST_ATTEMPT = float("-inf")
|
|
|
|
|
|
def _upsert_order_snapshot(
|
|
db: Session,
|
|
snapshot: dict[str, Any],
|
|
*,
|
|
mapping: PlatformCommodityMapping | None,
|
|
) -> tuple[PlatformFulfillmentTask | None, bool, bool]:
|
|
"""应用一条订单项快照,返回 (task, created, ignored)。"""
|
|
item_id = str(
|
|
_snapshot_value(
|
|
snapshot, "sourceOrderItemId", "source_order_item_id", default=""
|
|
)
|
|
).strip()
|
|
if not item_id:
|
|
return None, False, True
|
|
|
|
paid_at = _parse_snapshot_datetime(
|
|
_snapshot_value(snapshot, "paidAt", "paid_at", default=None)
|
|
)
|
|
order_created_at = _parse_snapshot_datetime(
|
|
_snapshot_value(
|
|
snapshot,
|
|
"orderCreatedAt",
|
|
"order_created_at",
|
|
default=None,
|
|
)
|
|
)
|
|
order_status = str(
|
|
_snapshot_value(snapshot, "orderStatus", "order_status", default="")
|
|
)
|
|
pay_status = str(
|
|
_snapshot_value(snapshot, "payStatus", "pay_status", default="paid")
|
|
)
|
|
terminal_order = order_status in {"refunded", "cancelled", "closed"}
|
|
if not terminal_order and pay_status != "paid":
|
|
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:
|
|
return None, False, True
|
|
|
|
task = (
|
|
db.query(PlatformFulfillmentTask)
|
|
.filter(
|
|
PlatformFulfillmentTask.source_system == "order_site",
|
|
PlatformFulfillmentTask.source_order_item_id == item_id,
|
|
)
|
|
.first()
|
|
)
|
|
created = task is None
|
|
if task is None:
|
|
task = PlatformFulfillmentTask(
|
|
source_system="order_site",
|
|
source_order_id=str(
|
|
_snapshot_value(
|
|
snapshot,
|
|
"sourceOrderId",
|
|
"source_order_id",
|
|
"orderId",
|
|
default="",
|
|
)
|
|
),
|
|
source_order_item_id=item_id,
|
|
source_fulfillment_id=str(
|
|
_snapshot_value(
|
|
snapshot,
|
|
"sourceFulfillmentId",
|
|
"source_fulfillment_id",
|
|
"fulfillmentId",
|
|
default="",
|
|
)
|
|
),
|
|
target_platform=TARGET_PLATFORM,
|
|
scope=SCOPE_ELITE,
|
|
created_at=_now(),
|
|
updated_at=_now(),
|
|
)
|
|
db.add(task)
|
|
db.flush()
|
|
_append_event(
|
|
db,
|
|
task.id,
|
|
"task_created",
|
|
detail={
|
|
"platformOrderId": _snapshot_value(
|
|
snapshot, "platformOrderId", "platform_order_id", default=""
|
|
)
|
|
},
|
|
)
|
|
|
|
before = (
|
|
task.platform_order_id,
|
|
task.source_order_id,
|
|
task.source_fulfillment_id,
|
|
task.provider,
|
|
task.shop_id,
|
|
task.shop_name,
|
|
task.sku_code,
|
|
task.sku_name,
|
|
task.internal_sku_key,
|
|
task.quantity,
|
|
task.order_amount_fen,
|
|
task.paid_at,
|
|
task.execution_status,
|
|
task.commodity_mapping_id,
|
|
task.commodity_id,
|
|
task.required_points,
|
|
task.issue_code,
|
|
)
|
|
if task.execution_status in {"completed", "cancelled"}:
|
|
task.source_snapshot_json = _jsonable(snapshot)
|
|
return task, created, False
|
|
|
|
previous_execution_status = task.execution_status
|
|
terminal = (
|
|
terminal_order
|
|
or _snapshot_value(
|
|
snapshot,
|
|
"fulfillmentStatus",
|
|
"fulfillment_status",
|
|
default="",
|
|
)
|
|
== "archived"
|
|
or _snapshot_value(
|
|
snapshot,
|
|
"configEnabled",
|
|
"config_enabled",
|
|
default=True,
|
|
)
|
|
is False
|
|
or _snapshot_value(
|
|
snapshot,
|
|
"douyuFulfillmentEnabled",
|
|
"douyu_fulfillment_enabled",
|
|
default=True,
|
|
)
|
|
is False
|
|
)
|
|
|
|
task.platform_order_id = str(
|
|
_snapshot_value(snapshot, "platformOrderId", "platform_order_id", default="")
|
|
)
|
|
task.source_order_id = str(
|
|
_snapshot_value(
|
|
snapshot,
|
|
"sourceOrderId",
|
|
"source_order_id",
|
|
"orderId",
|
|
default=task.source_order_id,
|
|
)
|
|
)
|
|
task.source_fulfillment_id = str(
|
|
_snapshot_value(
|
|
snapshot,
|
|
"sourceFulfillmentId",
|
|
"source_fulfillment_id",
|
|
"fulfillmentId",
|
|
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.internal_sku_key = str(
|
|
_snapshot_value(
|
|
snapshot,
|
|
"internalSkuKey",
|
|
"internal_sku_key",
|
|
default="",
|
|
)
|
|
).strip()
|
|
task.quantity = max(
|
|
1,
|
|
int(_snapshot_value(snapshot, "quantity", default=1) or 1),
|
|
)
|
|
task.order_amount_fen = int(
|
|
_snapshot_value(
|
|
snapshot,
|
|
"revenueAmountFen",
|
|
"revenue_amount_fen",
|
|
"totalAmountFen",
|
|
"total_amount",
|
|
default=0,
|
|
)
|
|
or 0
|
|
)
|
|
task.paid_at = paid_at
|
|
task.source_snapshot_json = _jsonable(snapshot)
|
|
task.updated_at = _now()
|
|
|
|
if terminal:
|
|
task.execution_status = "cancelled"
|
|
task.issue_code = "source_cancelled"
|
|
task.last_error = "订单已关闭或直播履约配置已停用"
|
|
task.next_allocate_at = None
|
|
# 订单源头取消/关闭后不再保留执行账号;统一策略会立即释放租约。
|
|
_apply_task_lease_policy(db, task)
|
|
else:
|
|
# 订单快照会被重复投递。只有未分配任务从「待映射」进入「待分配」时
|
|
# 才允许改生命周期状态;已分配任务不能被快照更新打回 pending。
|
|
update_execution_status = task.account_id is None and (
|
|
previous_execution_status == "pending_mapping" or mapping is None
|
|
)
|
|
_apply_mapping(
|
|
task,
|
|
mapping,
|
|
update_execution_status=update_execution_status,
|
|
)
|
|
if task.account_id is not None:
|
|
task.next_allocate_at = None
|
|
elif task.execution_status == "ready":
|
|
if previous_execution_status != "ready" or task.next_allocate_at is None:
|
|
task.next_allocate_at = _now()
|
|
else:
|
|
task.next_allocate_at = None
|
|
|
|
after = (
|
|
task.platform_order_id,
|
|
task.source_order_id,
|
|
task.source_fulfillment_id,
|
|
task.provider,
|
|
task.shop_id,
|
|
task.shop_name,
|
|
task.sku_code,
|
|
task.sku_name,
|
|
task.internal_sku_key,
|
|
task.quantity,
|
|
task.order_amount_fen,
|
|
task.paid_at,
|
|
task.execution_status,
|
|
task.commodity_mapping_id,
|
|
task.commodity_id,
|
|
task.required_points,
|
|
task.issue_code,
|
|
)
|
|
changed = created or before != after
|
|
if changed:
|
|
_emit_order_site_binding_state(db, task.id)
|
|
return task, created, False
|
|
|
|
|
|
def _mapping_map(db: Session) -> dict[str, PlatformCommodityMapping]:
|
|
rows = (
|
|
db.query(PlatformCommodityMapping)
|
|
.filter(
|
|
PlatformCommodityMapping.target_platform == TARGET_PLATFORM,
|
|
PlatformCommodityMapping.enabled.is_(True),
|
|
PlatformCommodityMapping.archived_at.is_(None),
|
|
)
|
|
.order_by(PlatformCommodityMapping.updated_at.desc())
|
|
.all()
|
|
)
|
|
result: dict[str, PlatformCommodityMapping] = {}
|
|
for row in rows:
|
|
sku_key = str(row.internal_sku_key or "").strip()
|
|
if sku_key and sku_key not in result:
|
|
result[sku_key] = row
|
|
return result
|
|
|
|
|
|
def sync_order_snapshot(
|
|
db: Session,
|
|
payload: dict[str, Any],
|
|
*,
|
|
commit: bool = True,
|
|
) -> dict[str, Any]:
|
|
"""消费 order_site 订单项快照;正常路径不再读取 order_site 数据库。"""
|
|
snapshot = _order_snapshot_from_event(payload)
|
|
mapping_by_sku = _mapping_map(db)
|
|
mapping = mapping_by_sku.get(
|
|
str(
|
|
_snapshot_value(
|
|
snapshot,
|
|
"internalSkuKey",
|
|
"internal_sku_key",
|
|
default="",
|
|
)
|
|
).strip()
|
|
)
|
|
task, created, ignored = _upsert_order_snapshot(db, snapshot, mapping=mapping)
|
|
if commit:
|
|
db.commit()
|
|
return {
|
|
"fetched": 1,
|
|
"created": int(created),
|
|
"updated": int(task is not None and not created),
|
|
"ignored": int(ignored),
|
|
"taskIds": [int(task.id)] if task is not None else [],
|
|
}
|
|
|
|
|
|
def sync_order_item_ids(
|
|
db: Session,
|
|
source_order_item_ids: list[str],
|
|
*,
|
|
commit: bool = True,
|
|
) -> dict[str, Any]:
|
|
"""兼容旧版事件:只定向读取明确订单项,不再走最近 500 条窗口。"""
|
|
mapping_by_sku = _mapping_map(db)
|
|
created = 0
|
|
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
|
|
):
|
|
if not item_id:
|
|
ignored += 1
|
|
continue
|
|
snapshot = lookup_pending_manual_fulfillment(item_id)
|
|
if snapshot is None:
|
|
ignored += 1
|
|
continue
|
|
mapping = mapping_by_sku.get(
|
|
str(snapshot.get("internal_sku_key") or "").strip()
|
|
)
|
|
task, was_created, was_ignored = _upsert_order_snapshot(
|
|
db,
|
|
snapshot,
|
|
mapping=mapping,
|
|
)
|
|
if task is None:
|
|
ignored += int(was_ignored)
|
|
continue
|
|
created += int(was_created)
|
|
updated += int(not was_created)
|
|
task_ids.append(int(task.id))
|
|
if commit:
|
|
db.commit()
|
|
return {
|
|
"fetched": len(task_ids),
|
|
"created": created,
|
|
"updated": updated,
|
|
"ignored": ignored,
|
|
"taskIds": task_ids,
|
|
}
|
|
|
|
|
|
def _sync_pending_tasks(
|
|
db: Session,
|
|
*,
|
|
limit: int = 100,
|
|
commit: bool = True,
|
|
) -> dict[str, Any]:
|
|
"""只拉取已配置商品映射的人工待履约订单项并生成本地作业。"""
|
|
match_started_at = _order_match_started_at(db)
|
|
mappings = (
|
|
db.query(PlatformCommodityMapping)
|
|
.filter(
|
|
PlatformCommodityMapping.target_platform == TARGET_PLATFORM,
|
|
PlatformCommodityMapping.enabled.is_(True),
|
|
)
|
|
.all()
|
|
)
|
|
mappings_by_sku = {
|
|
str(mapping.internal_sku_key or "").strip(): mapping
|
|
for mapping in mappings
|
|
if str(mapping.internal_sku_key or "").strip()
|
|
}
|
|
if not mappings_by_sku:
|
|
if commit:
|
|
db.commit()
|
|
return {
|
|
"fetched": 0,
|
|
"created": 0,
|
|
"updated": 0,
|
|
"skippedUnmapped": 0,
|
|
"configuredSkuCount": 0,
|
|
}
|
|
try:
|
|
rows = list_pending_manual_fulfillments(
|
|
limit=limit,
|
|
internal_sku_keys=list(mappings_by_sku),
|
|
paid_at_from=match_started_at,
|
|
)
|
|
except OrderLookupUnavailable as exc:
|
|
raise HTTPException(status_code=503, detail=f"订单源不可用:{exc}") from exc
|
|
|
|
created = 0
|
|
updated = 0
|
|
skipped_unmapped = 0
|
|
task_ids: list[int] = []
|
|
for row in rows:
|
|
item_id = str(row.get("source_order_item_id") or "")
|
|
if not item_id:
|
|
continue
|
|
internal_sku_key = str(row.get("internal_sku_key") or "").strip()
|
|
mapping = mappings_by_sku.get(internal_sku_key)
|
|
if mapping is None:
|
|
skipped_unmapped += 1
|
|
continue
|
|
task = (
|
|
db.query(PlatformFulfillmentTask)
|
|
.filter(
|
|
PlatformFulfillmentTask.source_system == "order_site",
|
|
PlatformFulfillmentTask.source_order_item_id == item_id,
|
|
)
|
|
.first()
|
|
)
|
|
if task is None:
|
|
task = PlatformFulfillmentTask(
|
|
source_system="order_site",
|
|
source_order_id=str(row.get("source_order_id") or ""),
|
|
source_order_item_id=item_id,
|
|
source_fulfillment_id=str(row.get("source_fulfillment_id") or ""),
|
|
created_at=_now(),
|
|
updated_at=_now(),
|
|
)
|
|
db.add(task)
|
|
db.flush()
|
|
created += 1
|
|
_append_event(
|
|
db,
|
|
task.id,
|
|
"task_created",
|
|
detail={"platformOrderId": row.get("platform_order_id")},
|
|
)
|
|
else:
|
|
updated += 1
|
|
|
|
if task.execution_status in {"completed", "cancelled"}:
|
|
continue
|
|
task.platform_order_id = str(row.get("platform_order_id") or "")
|
|
task.provider = str(row.get("provider") or "")
|
|
task.shop_id = str(row.get("shop_id") or "")
|
|
task.shop_name = str(row.get("shop_name") or "")
|
|
task.sku_code = str(row.get("sku_code") or "")
|
|
task.sku_name = str(row.get("sku_name") or "")
|
|
task.internal_sku_key = internal_sku_key
|
|
task.quantity = 1
|
|
if isinstance(row.get("paid_at"), datetime):
|
|
task.paid_at = row["paid_at"]
|
|
task.order_amount_fen = int(
|
|
row.get("revenue_amount_fen") or row.get("total_amount") or 0
|
|
)
|
|
task.target_platform = TARGET_PLATFORM
|
|
task.scope = SCOPE_ELITE
|
|
task.source_snapshot_json = _jsonable(row)
|
|
task.updated_at = _now()
|
|
if task.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()
|
|
_emit_order_site_binding_state(db, task.id)
|
|
task_ids.append(int(task.id))
|
|
|
|
if commit:
|
|
db.commit()
|
|
return {
|
|
"fetched": len(rows),
|
|
"created": created,
|
|
"updated": updated,
|
|
"skippedUnmapped": skipped_unmapped,
|
|
"configuredSkuCount": len(mappings_by_sku),
|
|
"orderMatchStartedAt": _jsonable(match_started_at),
|
|
"taskIds": task_ids,
|
|
}
|
|
|
|
|
|
def sync_pending_tasks(
|
|
db: Session,
|
|
*,
|
|
limit: int = 100,
|
|
commit: bool = True,
|
|
) -> dict[str, Any]:
|
|
"""串行同步订单,避免自动同步与人工同步并发创建重复任务。"""
|
|
with _SYNC_LOCK:
|
|
return _sync_pending_tasks(db, limit=limit, commit=commit)
|
|
|
|
|
|
def sync_pending_tasks_if_due(
|
|
db: Session,
|
|
*,
|
|
limit: int = 100,
|
|
now: float | None = None,
|
|
) -> dict[str, Any] | None:
|
|
"""工作台读取时自动同步;按进程节流,不阻塞每 5 秒一次的列表轮询。"""
|
|
global _AUTO_SYNC_LAST_ATTEMPT
|
|
|
|
if not _AUTO_SYNC_LOCK.acquire(blocking=False):
|
|
return None
|
|
try:
|
|
current = time.monotonic() if now is None else now
|
|
if current - _AUTO_SYNC_LAST_ATTEMPT < AUTO_SYNC_INTERVAL_SECONDS:
|
|
return None
|
|
_AUTO_SYNC_LAST_ATTEMPT = current
|
|
try:
|
|
return sync_pending_tasks(db, limit=limit)
|
|
except Exception:
|
|
_AUTO_SYNC_LAST_ATTEMPT = float("-inf")
|
|
raise
|
|
finally:
|
|
_AUTO_SYNC_LOCK.release()
|