feat(fulfillment): 增加订单匹配起算时间
This commit is contained in:
@@ -158,6 +158,7 @@ def _fetch_pending_manual_fulfillments(
|
||||
limit: int = 100,
|
||||
*,
|
||||
internal_sku_keys: list[str] | None = None,
|
||||
paid_at_from: datetime | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""读取最近的人工渠道待履约订单项。
|
||||
|
||||
@@ -172,8 +173,11 @@ def _fetch_pending_manual_fulfillments(
|
||||
if not sku_keys:
|
||||
return []
|
||||
engine = _get_engine()
|
||||
paid_at_filter = (
|
||||
"AND o.paid_at >= :paid_at_from" if paid_at_from is not None else ""
|
||||
)
|
||||
sql = text(
|
||||
"""
|
||||
f"""
|
||||
SELECT o.id AS source_order_id,
|
||||
o.platform_order_id,
|
||||
o.provider,
|
||||
@@ -204,6 +208,7 @@ def _fetch_pending_manual_fulfillments(
|
||||
AND f.status = 'assigned'
|
||||
AND o.pay_status = 'paid'
|
||||
AND o.order_status NOT IN ('refunded', 'cancelled', 'closed')
|
||||
{paid_at_filter}
|
||||
AND oi.quantity = 1
|
||||
AND COALESCE(f.issue_code, '') NOT IN ('user_refund', 'platform_cancelled')
|
||||
AND COALESCE(
|
||||
@@ -218,14 +223,17 @@ def _fetch_pending_manual_fulfillments(
|
||||
)
|
||||
try:
|
||||
with engine.connect() as conn:
|
||||
params: dict[str, Any] = {
|
||||
"limit": max(1, min(limit, 500)),
|
||||
"internal_sku_keys": sku_keys,
|
||||
}
|
||||
if paid_at_from is not None:
|
||||
params["paid_at_from"] = paid_at_from
|
||||
return [
|
||||
dict(row)
|
||||
for row in conn.execute(
|
||||
sql,
|
||||
{
|
||||
"limit": max(1, min(limit, 500)),
|
||||
"internal_sku_keys": sku_keys,
|
||||
},
|
||||
params,
|
||||
).mappings()
|
||||
]
|
||||
except Exception as exc:
|
||||
@@ -237,6 +245,7 @@ def list_pending_manual_fulfillments(
|
||||
limit: int = 100,
|
||||
*,
|
||||
internal_sku_keys: list[str] | None = None,
|
||||
paid_at_from: datetime | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""返回最近的人工渠道待履约订单项快照。"""
|
||||
if not _enabled():
|
||||
@@ -252,6 +261,7 @@ def list_pending_manual_fulfillments(
|
||||
for row in _fetch_pending_manual_fulfillments(
|
||||
limit=limit,
|
||||
internal_sku_keys=sku_keys,
|
||||
paid_at_from=paid_at_from,
|
||||
):
|
||||
internal_sku_key = str(
|
||||
row.get("manual_sku_key")
|
||||
|
||||
@@ -51,18 +51,19 @@ def run_auto_allocation_once(
|
||||
10,
|
||||
3600,
|
||||
)
|
||||
candidates = (
|
||||
db.query(PlatformFulfillmentTask)
|
||||
.filter(
|
||||
PlatformFulfillmentTask.execution_status == "ready",
|
||||
PlatformFulfillmentTask.account_id.is_(None),
|
||||
PlatformFulfillmentTask.commodity_id != "",
|
||||
PlatformFulfillmentTask.updated_at
|
||||
<= moment - timedelta(seconds=retry_seconds),
|
||||
query = db.query(PlatformFulfillmentTask).filter(
|
||||
PlatformFulfillmentTask.execution_status == "ready",
|
||||
PlatformFulfillmentTask.account_id.is_(None),
|
||||
PlatformFulfillmentTask.commodity_id != "",
|
||||
PlatformFulfillmentTask.updated_at <= moment - timedelta(seconds=retry_seconds),
|
||||
)
|
||||
match_started_at = service._order_match_started_at(db)
|
||||
if match_started_at is not None:
|
||||
query = query.filter(
|
||||
PlatformFulfillmentTask.created_at >= match_started_at,
|
||||
)
|
||||
.order_by(PlatformFulfillmentTask.updated_at.asc())
|
||||
.limit(batch_size)
|
||||
.all()
|
||||
candidates = (
|
||||
query.order_by(PlatformFulfillmentTask.updated_at.asc()).limit(batch_size).all()
|
||||
)
|
||||
if not candidates:
|
||||
return {"checked": 0, "allocated": 0, "failed": 0}
|
||||
@@ -84,9 +85,7 @@ def run_auto_allocation_once(
|
||||
except Exception as exc: # noqa: BLE001 - 单个任务异常不能中断整批
|
||||
db.rollback()
|
||||
failed += 1
|
||||
logger.warning(
|
||||
"直播账号履约自动选号失败 task_id={}: {}", task.id, exc
|
||||
)
|
||||
logger.warning("直播账号履约自动选号失败 task_id={}: {}", task.id, exc)
|
||||
return {
|
||||
"checked": len(candidates),
|
||||
"allocated": allocated,
|
||||
|
||||
@@ -94,18 +94,24 @@ def _mapping_for_sku(
|
||||
|
||||
|
||||
def get_settings(db: Session) -> dict[str, Any]:
|
||||
now = _now()
|
||||
row = (
|
||||
db.query(PlatformFulfillmentSetting)
|
||||
.filter(PlatformFulfillmentSetting.id == 1)
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
row = PlatformFulfillmentSetting(id=1, lease_duration_minutes=None)
|
||||
row = PlatformFulfillmentSetting(
|
||||
id=1,
|
||||
lease_duration_minutes=None,
|
||||
order_match_started_at=now,
|
||||
)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return {
|
||||
"leaseDurationMinutes": row.lease_duration_minutes,
|
||||
"orderMatchStartedAt": _jsonable(row.order_match_started_at),
|
||||
"updatedAt": _jsonable(row.updated_at),
|
||||
}
|
||||
|
||||
@@ -114,6 +120,7 @@ def update_settings(
|
||||
db: Session,
|
||||
*,
|
||||
lease_duration_minutes: int | None,
|
||||
order_match_started_at: datetime | None = None,
|
||||
current: User,
|
||||
) -> dict[str, Any]:
|
||||
row = (
|
||||
@@ -121,10 +128,15 @@ def update_settings(
|
||||
.filter(PlatformFulfillmentSetting.id == 1)
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
row = PlatformFulfillmentSetting(id=1)
|
||||
db.add(row)
|
||||
now = _now()
|
||||
if row is None:
|
||||
row = PlatformFulfillmentSetting(
|
||||
id=1,
|
||||
order_match_started_at=order_match_started_at or now,
|
||||
)
|
||||
db.add(row)
|
||||
elif order_match_started_at is not None:
|
||||
row.order_match_started_at = order_match_started_at
|
||||
row.lease_duration_minutes = lease_duration_minutes
|
||||
row.updated_by = current.id
|
||||
row.updated_at = now
|
||||
@@ -145,6 +157,7 @@ def update_settings(
|
||||
db.commit()
|
||||
return {
|
||||
"leaseDurationMinutes": row.lease_duration_minutes,
|
||||
"orderMatchStartedAt": _jsonable(row.order_match_started_at),
|
||||
"updatedAt": _jsonable(row.updated_at),
|
||||
}
|
||||
|
||||
@@ -153,6 +166,15 @@ def _lease_duration_minutes(db: Session) -> int | None:
|
||||
return get_settings(db)["leaseDurationMinutes"]
|
||||
|
||||
|
||||
def _order_match_started_at(db: Session) -> datetime | None:
|
||||
row = (
|
||||
db.query(PlatformFulfillmentSetting)
|
||||
.filter(PlatformFulfillmentSetting.id == 1)
|
||||
.first()
|
||||
)
|
||||
return row.order_match_started_at if row is not None else None
|
||||
|
||||
|
||||
def _integration_actor(db: Session) -> User:
|
||||
raw_user_id = os.getenv("PLATFORM_FULFILLMENT_INTEGRATION_ACTOR_ID", "").strip()
|
||||
query = db.query(User).filter(User.is_active.is_(True))
|
||||
@@ -184,6 +206,11 @@ def _find_customer_task(
|
||||
PlatformFulfillmentTask.source_system == "order_site",
|
||||
PlatformFulfillmentTask.source_order_item_id == item_id,
|
||||
)
|
||||
match_started_at = _order_match_started_at(db)
|
||||
if match_started_at is not None:
|
||||
query = query.filter(
|
||||
PlatformFulfillmentTask.created_at >= match_started_at,
|
||||
)
|
||||
order_no = str(platform_order_id or "").strip()
|
||||
if order_no:
|
||||
query = query.filter(PlatformFulfillmentTask.platform_order_id == order_no)
|
||||
@@ -283,6 +310,7 @@ def _sync_pending_tasks(
|
||||
commit: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""只拉取已配置商品映射的人工待履约订单项并生成本地作业。"""
|
||||
match_started_at = _order_match_started_at(db)
|
||||
mappings = (
|
||||
db.query(PlatformCommodityMapping)
|
||||
.filter(
|
||||
@@ -310,6 +338,7 @@ def _sync_pending_tasks(
|
||||
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
|
||||
@@ -384,6 +413,7 @@ def _sync_pending_tasks(
|
||||
"updated": updated,
|
||||
"skippedUnmapped": skipped_unmapped,
|
||||
"configuredSkuCount": len(mappings_by_sku),
|
||||
"orderMatchStartedAt": _jsonable(match_started_at),
|
||||
}
|
||||
|
||||
|
||||
@@ -432,6 +462,11 @@ def list_tasks(
|
||||
page_size: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
query = db.query(PlatformFulfillmentTask)
|
||||
match_started_at = _order_match_started_at(db)
|
||||
if match_started_at is not None:
|
||||
query = query.filter(
|
||||
PlatformFulfillmentTask.created_at >= match_started_at,
|
||||
)
|
||||
query = query.filter(
|
||||
or_(
|
||||
PlatformFulfillmentTask.commodity_mapping_id.isnot(None),
|
||||
@@ -845,16 +880,18 @@ def upsert_mapping(
|
||||
row.updated_at = _now()
|
||||
db.flush()
|
||||
|
||||
pending = (
|
||||
db.query(PlatformFulfillmentTask)
|
||||
.filter(
|
||||
PlatformFulfillmentTask.internal_sku_key == sku_key,
|
||||
PlatformFulfillmentTask.execution_status.in_(
|
||||
["pending_mapping", "ready", "manual_required"]
|
||||
),
|
||||
)
|
||||
.all()
|
||||
match_started_at = _order_match_started_at(db)
|
||||
pending = db.query(PlatformFulfillmentTask).filter(
|
||||
PlatformFulfillmentTask.internal_sku_key == sku_key,
|
||||
PlatformFulfillmentTask.execution_status.in_(
|
||||
["pending_mapping", "ready", "manual_required"]
|
||||
),
|
||||
)
|
||||
if match_started_at is not None:
|
||||
pending = pending.filter(
|
||||
PlatformFulfillmentTask.created_at >= match_started_at,
|
||||
)
|
||||
pending = pending.all()
|
||||
for task in pending:
|
||||
_apply_mapping(task, row if row.enabled else None)
|
||||
task.updated_at = _now()
|
||||
|
||||
Reference in New Issue
Block a user