refactor(fulfillment): 拆分履约服务并修正换绑冷却分类
This commit is contained in:
@@ -0,0 +1,548 @@
|
||||
"""商品映射管理和映射变更后的任务重放。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy import func, or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...models import (
|
||||
DouyuGoodsSnapshot,
|
||||
PlatformCommodityMapping,
|
||||
PlatformFulfillmentTask,
|
||||
User,
|
||||
)
|
||||
from . import classification
|
||||
from .common import (
|
||||
SCOPE_ELITE,
|
||||
TARGET_PLATFORM,
|
||||
_apply_order_match_cutoff,
|
||||
_now,
|
||||
_order_match_started_at,
|
||||
)
|
||||
from .outbox import _emit_order_site_binding_state
|
||||
from .runtime import _append_event
|
||||
|
||||
|
||||
def _apply_mapping(
|
||||
task: PlatformFulfillmentTask,
|
||||
mapping: PlatformCommodityMapping | None,
|
||||
*,
|
||||
update_execution_status: bool = True,
|
||||
) -> None:
|
||||
if mapping is not None:
|
||||
snapshot_classification = (
|
||||
task.execution_status == "pending_mapping"
|
||||
or task.classification_source in {"", "unknown"}
|
||||
or task.sale_mode in {"", "unknown"}
|
||||
)
|
||||
task.commodity_mapping_id = mapping.id
|
||||
task.commodity_id = mapping.commodity_id
|
||||
task.required_points = mapping.required_points
|
||||
if snapshot_classification:
|
||||
task.sale_mode = classification.normalize_sale_mode(mapping.sale_mode)
|
||||
task.campaign_key = mapping.campaign_key
|
||||
task.campaign_name = mapping.campaign_name
|
||||
task.offer_available_from = mapping.available_from
|
||||
task.offer_available_until = mapping.available_until
|
||||
task.classification_source = (
|
||||
"mapping" if task.sale_mode != "unknown" else "unknown"
|
||||
)
|
||||
else:
|
||||
task.commodity_mapping_id = None
|
||||
task.commodity_id = ""
|
||||
task.required_points = None
|
||||
task.sale_mode = "unknown"
|
||||
task.campaign_key = ""
|
||||
task.campaign_name = ""
|
||||
task.offer_available_from = None
|
||||
task.offer_available_until = None
|
||||
task.classification_source = "unknown"
|
||||
if not update_execution_status:
|
||||
return
|
||||
if mapping is None:
|
||||
task.execution_status = "pending_mapping"
|
||||
task.issue_code = "mapping_missing"
|
||||
task.last_error = "内部 SKU 尚未配置斗鱼商品映射"
|
||||
return
|
||||
task.execution_status = "ready"
|
||||
task.issue_code = ""
|
||||
task.last_error = ""
|
||||
|
||||
|
||||
def _mapping_impact(db: Session, row: PlatformCommodityMapping) -> int:
|
||||
query = db.query(func.count(PlatformFulfillmentTask.id)).filter(
|
||||
PlatformFulfillmentTask.internal_sku_key == row.internal_sku_key,
|
||||
PlatformFulfillmentTask.account_id.is_(None),
|
||||
PlatformFulfillmentTask.execution_status.in_(
|
||||
["pending_mapping", "ready", "manual_required"]
|
||||
),
|
||||
)
|
||||
return int(query.scalar() or 0)
|
||||
|
||||
|
||||
def _mapping_out(
|
||||
db: Session,
|
||||
row: PlatformCommodityMapping,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, Any]:
|
||||
mode = classification.normalize_sale_mode(row.sale_mode)
|
||||
availability = classification.availability_state(
|
||||
sale_mode=mode,
|
||||
available_from=row.available_from,
|
||||
available_until=row.available_until,
|
||||
goods_status=row.goods_status,
|
||||
now=now,
|
||||
)
|
||||
return {
|
||||
"id": row.id,
|
||||
"targetPlatform": row.target_platform,
|
||||
"internalSkuKey": row.internal_sku_key,
|
||||
"campaignKey": row.campaign_key,
|
||||
"campaignName": row.campaign_name,
|
||||
"commodityId": row.commodity_id,
|
||||
"goodsName": row.goods_name,
|
||||
"requiredPoints": row.required_points,
|
||||
"scope": row.scope,
|
||||
"saleMode": mode,
|
||||
"availableFrom": row.available_from,
|
||||
"availableUntil": row.available_until,
|
||||
"releasedAt": row.released_at,
|
||||
"goodsStatus": row.goods_status,
|
||||
"availabilityState": availability,
|
||||
"enabled": row.enabled,
|
||||
"version": row.version,
|
||||
"archivedAt": row.archived_at,
|
||||
"affectedTasks": _mapping_impact(db, row),
|
||||
"updatedAt": row.updated_at,
|
||||
}
|
||||
|
||||
|
||||
def list_mappings(
|
||||
db: Session,
|
||||
*,
|
||||
keyword: str = "",
|
||||
sale_mode: str = "",
|
||||
enabled: bool | None = None,
|
||||
include_archived: bool = False,
|
||||
) -> list[dict[str, Any]]:
|
||||
query = db.query(PlatformCommodityMapping).filter(
|
||||
PlatformCommodityMapping.target_platform == TARGET_PLATFORM
|
||||
)
|
||||
if not include_archived:
|
||||
query = query.filter(PlatformCommodityMapping.archived_at.is_(None))
|
||||
if enabled is not None:
|
||||
query = query.filter(PlatformCommodityMapping.enabled.is_(enabled))
|
||||
if sale_mode:
|
||||
query = query.filter(
|
||||
PlatformCommodityMapping.sale_mode
|
||||
== classification.normalize_sale_mode(sale_mode)
|
||||
)
|
||||
text = keyword.strip()
|
||||
if text:
|
||||
pattern = f"%{text}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
PlatformCommodityMapping.internal_sku_key.ilike(pattern),
|
||||
PlatformCommodityMapping.commodity_id.ilike(pattern),
|
||||
PlatformCommodityMapping.goods_name.ilike(pattern),
|
||||
PlatformCommodityMapping.campaign_key.ilike(pattern),
|
||||
PlatformCommodityMapping.campaign_name.ilike(pattern),
|
||||
)
|
||||
)
|
||||
rows = (
|
||||
query.order_by(
|
||||
PlatformCommodityMapping.archived_at.asc(),
|
||||
PlatformCommodityMapping.enabled.desc(),
|
||||
PlatformCommodityMapping.updated_at.desc(),
|
||||
)
|
||||
.limit(500)
|
||||
.all()
|
||||
)
|
||||
now = datetime.now(UTC)
|
||||
return [_mapping_out(db, row, now=now) for row in rows]
|
||||
|
||||
|
||||
def _validate_mapping_window(
|
||||
available_from: datetime | None,
|
||||
available_until: datetime | None,
|
||||
) -> None:
|
||||
if (
|
||||
available_from is not None
|
||||
and available_until is not None
|
||||
and available_from >= available_until
|
||||
):
|
||||
raise HTTPException(status_code=400, detail="商品开放时间必须早于结束时间")
|
||||
|
||||
|
||||
def _disable_other_current_mappings(
|
||||
db: Session,
|
||||
*,
|
||||
row: PlatformCommodityMapping,
|
||||
) -> None:
|
||||
others = (
|
||||
db.query(PlatformCommodityMapping)
|
||||
.filter(
|
||||
PlatformCommodityMapping.id != row.id,
|
||||
PlatformCommodityMapping.target_platform == row.target_platform,
|
||||
PlatformCommodityMapping.internal_sku_key == row.internal_sku_key,
|
||||
PlatformCommodityMapping.enabled.is_(True),
|
||||
PlatformCommodityMapping.archived_at.is_(None),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for other in others:
|
||||
other.enabled = False
|
||||
other.version = int(other.version or 1) + 1
|
||||
other.updated_at = _now()
|
||||
|
||||
|
||||
def _reapply_mapping_tasks(
|
||||
db: Session,
|
||||
*,
|
||||
row: PlatformCommodityMapping,
|
||||
current: User,
|
||||
) -> None:
|
||||
pending = db.query(PlatformFulfillmentTask).filter(
|
||||
PlatformFulfillmentTask.internal_sku_key == row.internal_sku_key,
|
||||
PlatformFulfillmentTask.account_id.is_(None),
|
||||
PlatformFulfillmentTask.execution_status.in_(
|
||||
["pending_mapping", "ready", "manual_required"]
|
||||
),
|
||||
)
|
||||
pending = _apply_order_match_cutoff(pending, _order_match_started_at(db))
|
||||
task_ids: list[int] = []
|
||||
for task in pending.all():
|
||||
_apply_mapping(task, row if row.enabled else None)
|
||||
task.updated_at = _now()
|
||||
task.next_allocate_at = (
|
||||
_now()
|
||||
if task.execution_status == "ready" and task.account_id is None
|
||||
else None
|
||||
)
|
||||
_append_event(
|
||||
db,
|
||||
task.id,
|
||||
"mapping_updated",
|
||||
actor_type="user",
|
||||
actor_id=current.id,
|
||||
detail={
|
||||
"mappingId": row.id,
|
||||
"commodityId": row.commodity_id,
|
||||
"goodsName": row.goods_name,
|
||||
"saleMode": row.sale_mode,
|
||||
"campaignKey": row.campaign_key,
|
||||
"enabled": row.enabled,
|
||||
},
|
||||
)
|
||||
_emit_order_site_binding_state(db, task.id)
|
||||
task_ids.append(int(task.id))
|
||||
if task_ids:
|
||||
from .auto_allocator import wake_auto_allocator
|
||||
|
||||
wake_auto_allocator(task_ids)
|
||||
|
||||
|
||||
def _write_mapping(
|
||||
db: Session,
|
||||
row: PlatformCommodityMapping,
|
||||
*,
|
||||
internal_sku_key: str,
|
||||
campaign_key: str,
|
||||
campaign_name: str,
|
||||
commodity_id: str,
|
||||
goods_name: str,
|
||||
required_points: int | None,
|
||||
sale_mode: str,
|
||||
available_from: datetime | None,
|
||||
available_until: datetime | None,
|
||||
released_at: datetime | None,
|
||||
enabled: bool,
|
||||
current: User,
|
||||
) -> None:
|
||||
sku_key = internal_sku_key.strip()
|
||||
campaign = campaign_key.strip()
|
||||
commodity = commodity_id.strip()
|
||||
if not sku_key or not campaign or not commodity:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="内部 SKU、活动批次和斗鱼商品 ID 不能为空",
|
||||
)
|
||||
_validate_mapping_window(available_from, available_until)
|
||||
goods = (
|
||||
db.query(DouyuGoodsSnapshot)
|
||||
.filter(DouyuGoodsSnapshot.commodity_id == commodity)
|
||||
.order_by(DouyuGoodsSnapshot.id.desc())
|
||||
.first()
|
||||
)
|
||||
row.target_platform = TARGET_PLATFORM
|
||||
row.scope = SCOPE_ELITE
|
||||
row.internal_sku_key = sku_key
|
||||
row.campaign_key = campaign
|
||||
row.campaign_name = campaign_name.strip()
|
||||
row.commodity_id = commodity
|
||||
row.goods_name = (goods_name or (goods.name if goods else "")).strip()
|
||||
row.required_points = (
|
||||
int(required_points)
|
||||
if required_points is not None
|
||||
else (int(goods.score) if goods and goods.score is not None else None)
|
||||
)
|
||||
row.sale_mode = classification.normalize_sale_mode(sale_mode)
|
||||
row.available_from = available_from
|
||||
row.available_until = available_until
|
||||
row.released_at = released_at
|
||||
row.goods_status = str(goods.status if goods else "").strip()
|
||||
row.enabled = bool(enabled)
|
||||
row.updated_at = _now()
|
||||
row.version = max(1, int(row.version or 1))
|
||||
db.flush()
|
||||
if row.enabled:
|
||||
_disable_other_current_mappings(db, row=row)
|
||||
_reapply_mapping_tasks(db, row=row, current=current)
|
||||
db.commit()
|
||||
|
||||
|
||||
def create_mapping(
|
||||
db: Session,
|
||||
*,
|
||||
internal_sku_key: str,
|
||||
campaign_key: str,
|
||||
campaign_name: str,
|
||||
commodity_id: str,
|
||||
goods_name: str,
|
||||
required_points: int | None,
|
||||
sale_mode: str,
|
||||
available_from: datetime | None,
|
||||
available_until: datetime | None,
|
||||
released_at: datetime | None,
|
||||
enabled: bool,
|
||||
current: User,
|
||||
) -> dict[str, Any]:
|
||||
row = PlatformCommodityMapping(
|
||||
target_platform=TARGET_PLATFORM,
|
||||
scope=SCOPE_ELITE,
|
||||
internal_sku_key=internal_sku_key.strip(),
|
||||
campaign_key=campaign_key.strip(),
|
||||
commodity_id=commodity_id.strip(),
|
||||
created_by=current.id,
|
||||
created_at=_now(),
|
||||
updated_at=_now(),
|
||||
version=1,
|
||||
)
|
||||
duplicate = (
|
||||
db.query(PlatformCommodityMapping.id)
|
||||
.filter(
|
||||
PlatformCommodityMapping.target_platform == TARGET_PLATFORM,
|
||||
PlatformCommodityMapping.internal_sku_key == internal_sku_key.strip(),
|
||||
PlatformCommodityMapping.campaign_key == campaign_key.strip(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if duplicate:
|
||||
raise HTTPException(status_code=409, detail="该 SKU 的活动批次映射已存在")
|
||||
db.add(row)
|
||||
_write_mapping(
|
||||
db,
|
||||
row,
|
||||
internal_sku_key=internal_sku_key,
|
||||
campaign_key=campaign_key,
|
||||
campaign_name=campaign_name,
|
||||
commodity_id=commodity_id,
|
||||
goods_name=goods_name,
|
||||
required_points=required_points,
|
||||
sale_mode=sale_mode,
|
||||
available_from=available_from,
|
||||
available_until=available_until,
|
||||
released_at=released_at,
|
||||
enabled=enabled,
|
||||
current=current,
|
||||
)
|
||||
return _mapping_out(db, row)
|
||||
|
||||
|
||||
def update_mapping(
|
||||
db: Session,
|
||||
*,
|
||||
mapping_id: int,
|
||||
**values: Any,
|
||||
) -> dict[str, Any]:
|
||||
row = db.get(PlatformCommodityMapping, int(mapping_id))
|
||||
if row is None or row.target_platform != TARGET_PLATFORM:
|
||||
raise HTTPException(status_code=404, detail="商品映射不存在")
|
||||
if row.archived_at is not None:
|
||||
raise HTTPException(status_code=409, detail="已归档映射不能编辑,请先恢复")
|
||||
current = values.pop("current")
|
||||
duplicate = (
|
||||
db.query(PlatformCommodityMapping.id)
|
||||
.filter(
|
||||
PlatformCommodityMapping.id != row.id,
|
||||
PlatformCommodityMapping.target_platform == TARGET_PLATFORM,
|
||||
PlatformCommodityMapping.internal_sku_key
|
||||
== str(values.get("internal_sku_key") or "").strip(),
|
||||
PlatformCommodityMapping.campaign_key
|
||||
== str(values.get("campaign_key") or "").strip(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if duplicate:
|
||||
raise HTTPException(status_code=409, detail="该 SKU 的活动批次映射已存在")
|
||||
row.version = int(row.version or 1) + 1
|
||||
_write_mapping(db, row, current=current, **values)
|
||||
return _mapping_out(db, row)
|
||||
|
||||
|
||||
def set_mapping_enabled(
|
||||
db: Session,
|
||||
*,
|
||||
mapping_id: int,
|
||||
enabled: bool,
|
||||
current: User,
|
||||
) -> dict[str, Any]:
|
||||
row = db.get(PlatformCommodityMapping, int(mapping_id))
|
||||
if row is None or row.target_platform != TARGET_PLATFORM:
|
||||
raise HTTPException(status_code=404, detail="商品映射不存在")
|
||||
if row.archived_at is not None:
|
||||
raise HTTPException(status_code=409, detail="已归档映射不能启停,请先恢复")
|
||||
row.enabled = bool(enabled)
|
||||
row.version = int(row.version or 1) + 1
|
||||
row.updated_at = _now()
|
||||
db.flush()
|
||||
if enabled:
|
||||
_disable_other_current_mappings(db, row=row)
|
||||
_reapply_mapping_tasks(db, row=row, current=current)
|
||||
db.commit()
|
||||
return _mapping_out(db, row)
|
||||
|
||||
|
||||
def archive_mapping(
|
||||
db: Session,
|
||||
*,
|
||||
mapping_id: int,
|
||||
current: User,
|
||||
) -> dict[str, Any]:
|
||||
row = db.get(PlatformCommodityMapping, int(mapping_id))
|
||||
if row is None or row.target_platform != TARGET_PLATFORM:
|
||||
raise HTTPException(status_code=404, detail="商品映射不存在")
|
||||
row.enabled = False
|
||||
row.archived_at = _now()
|
||||
row.archived_by = current.id
|
||||
row.version = int(row.version or 1) + 1
|
||||
row.updated_at = _now()
|
||||
_reapply_mapping_tasks(db, row=row, current=current)
|
||||
db.commit()
|
||||
return _mapping_out(db, row)
|
||||
|
||||
|
||||
def restore_mapping(
|
||||
db: Session,
|
||||
*,
|
||||
mapping_id: int,
|
||||
) -> dict[str, Any]:
|
||||
row = db.get(PlatformCommodityMapping, int(mapping_id))
|
||||
if row is None or row.target_platform != TARGET_PLATFORM:
|
||||
raise HTTPException(status_code=404, detail="商品映射不存在")
|
||||
row.archived_at = None
|
||||
row.archived_by = None
|
||||
row.enabled = False
|
||||
row.version = int(row.version or 1) + 1
|
||||
row.updated_at = _now()
|
||||
db.commit()
|
||||
return _mapping_out(db, row)
|
||||
|
||||
|
||||
def delete_mapping(db: Session, *, mapping_id: int) -> None:
|
||||
row = db.get(PlatformCommodityMapping, int(mapping_id))
|
||||
if row is None or row.target_platform != TARGET_PLATFORM:
|
||||
raise HTTPException(status_code=404, detail="商品映射不存在")
|
||||
referenced = (
|
||||
db.query(PlatformFulfillmentTask.id)
|
||||
.filter(PlatformFulfillmentTask.commodity_mapping_id == row.id)
|
||||
.first()
|
||||
)
|
||||
if referenced:
|
||||
raise HTTPException(status_code=409, detail="映射已被任务引用,只能归档")
|
||||
db.delete(row)
|
||||
db.commit()
|
||||
|
||||
|
||||
def mapping_impact(db: Session, *, mapping_id: int) -> dict[str, Any]:
|
||||
row = db.get(PlatformCommodityMapping, int(mapping_id))
|
||||
if row is None or row.target_platform != TARGET_PLATFORM:
|
||||
raise HTTPException(status_code=404, detail="商品映射不存在")
|
||||
rows = (
|
||||
db.query(
|
||||
PlatformFulfillmentTask.execution_status,
|
||||
PlatformFulfillmentTask.sale_mode,
|
||||
func.count(PlatformFulfillmentTask.id),
|
||||
)
|
||||
.filter(
|
||||
PlatformFulfillmentTask.internal_sku_key == row.internal_sku_key,
|
||||
PlatformFulfillmentTask.account_id.is_(None),
|
||||
)
|
||||
.group_by(
|
||||
PlatformFulfillmentTask.execution_status,
|
||||
PlatformFulfillmentTask.sale_mode,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
"mappingId": row.id,
|
||||
"internalSkuKey": row.internal_sku_key,
|
||||
"affectedTasks": sum(int(count) for _status, _mode, count in rows),
|
||||
"groups": [
|
||||
{
|
||||
"executionStatus": status,
|
||||
"saleMode": mode,
|
||||
"count": int(count),
|
||||
}
|
||||
for status, mode, count in rows
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def upsert_mapping(
|
||||
db: Session,
|
||||
*,
|
||||
internal_sku_key: str,
|
||||
commodity_id: str,
|
||||
goods_name: str,
|
||||
required_points: int | None,
|
||||
enabled: bool,
|
||||
current: User,
|
||||
campaign_key: str = "douyu-current",
|
||||
campaign_name: str = "",
|
||||
sale_mode: str = "unknown",
|
||||
available_from: datetime | None = None,
|
||||
available_until: datetime | None = None,
|
||||
released_at: datetime | None = None,
|
||||
) -> dict[str, Any]:
|
||||
row = (
|
||||
db.query(PlatformCommodityMapping)
|
||||
.filter(
|
||||
PlatformCommodityMapping.target_platform == TARGET_PLATFORM,
|
||||
PlatformCommodityMapping.internal_sku_key == internal_sku_key.strip(),
|
||||
PlatformCommodityMapping.campaign_key == campaign_key.strip(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
values = {
|
||||
"internal_sku_key": internal_sku_key,
|
||||
"campaign_key": campaign_key,
|
||||
"campaign_name": campaign_name,
|
||||
"commodity_id": commodity_id,
|
||||
"goods_name": goods_name,
|
||||
"required_points": required_points,
|
||||
"sale_mode": sale_mode,
|
||||
"available_from": available_from,
|
||||
"available_until": available_until,
|
||||
"released_at": released_at,
|
||||
"enabled": enabled,
|
||||
"current": current,
|
||||
}
|
||||
if row is None:
|
||||
return create_mapping(db, **values)
|
||||
return update_mapping(db, mapping_id=row.id, **values)
|
||||
Reference in New Issue
Block a user