feat(platform): 增加履约分类映射管理并锁定迁移
This commit is contained in:
@@ -0,0 +1,104 @@
|
||||
"""直播账号履约工作台的销售模式、开放状态和工作队列派生。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
SALE_MODES = {"presale", "direct", "manual", "unknown"}
|
||||
AVAILABILITY_WAITING_RELEASE = "waiting_release"
|
||||
AVAILABILITY_AVAILABLE = "available"
|
||||
AVAILABILITY_SOLD_OUT = "sold_out"
|
||||
AVAILABILITY_ENDED = "ended"
|
||||
AVAILABILITY_UNKNOWN = "unknown"
|
||||
|
||||
QUEUE_PENDING_MAPPING = "pending_mapping"
|
||||
QUEUE_PRESALE_WAITING = "presale_waiting"
|
||||
QUEUE_READY = "ready_for_fulfillment"
|
||||
QUEUE_NEEDS_ACTION = "needs_action"
|
||||
QUEUE_COMPLETED = "completed"
|
||||
QUEUE_CANCELLED = "cancelled"
|
||||
|
||||
QUEUE_BUCKETS = {
|
||||
QUEUE_PENDING_MAPPING,
|
||||
QUEUE_PRESALE_WAITING,
|
||||
QUEUE_READY,
|
||||
QUEUE_NEEDS_ACTION,
|
||||
QUEUE_COMPLETED,
|
||||
QUEUE_CANCELLED,
|
||||
}
|
||||
|
||||
|
||||
def normalize_sale_mode(value: Any) -> str:
|
||||
mode = str(value or "").strip().lower()
|
||||
return mode if mode in SALE_MODES else "unknown"
|
||||
|
||||
|
||||
def availability_state(
|
||||
*,
|
||||
sale_mode: str,
|
||||
available_from: datetime | None,
|
||||
available_until: datetime | None,
|
||||
goods_status: str = "",
|
||||
now: datetime | None = None,
|
||||
) -> str:
|
||||
"""按报价窗口和最近商品状态派生,不回写销售模式。"""
|
||||
moment = now or datetime.now(UTC)
|
||||
if available_from is not None and moment < _aware(available_from):
|
||||
return AVAILABILITY_WAITING_RELEASE
|
||||
if available_until is not None and moment > _aware(available_until):
|
||||
return AVAILABILITY_ENDED
|
||||
status = str(goods_status or "").strip().lower()
|
||||
if status in {"sold_out", "out_of_stock"}:
|
||||
return AVAILABILITY_SOLD_OUT
|
||||
if sale_mode == "presale":
|
||||
return (
|
||||
AVAILABILITY_AVAILABLE
|
||||
if available_from is not None
|
||||
else AVAILABILITY_WAITING_RELEASE
|
||||
)
|
||||
if sale_mode in {"direct", "manual"}:
|
||||
return AVAILABILITY_AVAILABLE
|
||||
if available_from is not None or available_until is not None:
|
||||
return AVAILABILITY_AVAILABLE
|
||||
return AVAILABILITY_UNKNOWN
|
||||
|
||||
|
||||
def manual_reason(issue_code: str, exchange_status: str) -> str:
|
||||
issue = str(issue_code or "").strip()
|
||||
exchange = str(exchange_status or "").strip()
|
||||
if issue == "points_short" or exchange == "points_short":
|
||||
return "points_short"
|
||||
if issue == "elite_not_opened" or exchange == "not_opened":
|
||||
return "elite_not_opened"
|
||||
if issue == "commodity_limit_reached" or exchange == "limited":
|
||||
return "limit_reached"
|
||||
if issue in {"binding_failed", "account_role_cooldown", "customer_role_cooldown"}:
|
||||
return "binding_failed"
|
||||
if issue in {"lease_expired", "manual_required"}:
|
||||
return "account_cooldown"
|
||||
return "other_manual"
|
||||
|
||||
|
||||
def queue_bucket(
|
||||
*,
|
||||
execution_status: str,
|
||||
sale_mode: str,
|
||||
availability: str,
|
||||
) -> str:
|
||||
status = str(execution_status or "")
|
||||
if status == "cancelled":
|
||||
return QUEUE_CANCELLED
|
||||
if status == "completed":
|
||||
return QUEUE_COMPLETED
|
||||
if status == "pending_mapping":
|
||||
return QUEUE_PENDING_MAPPING
|
||||
if sale_mode == "presale" and availability == AVAILABILITY_WAITING_RELEASE:
|
||||
return QUEUE_PRESALE_WAITING
|
||||
if status == "manual_required":
|
||||
return QUEUE_NEEDS_ACTION
|
||||
return QUEUE_READY
|
||||
|
||||
|
||||
def _aware(value: datetime) -> datetime:
|
||||
return value if value.tzinfo is not None else value.replace(tzinfo=UTC)
|
||||
@@ -11,7 +11,7 @@ from typing import Any
|
||||
|
||||
from fastapi import HTTPException
|
||||
from loguru import logger
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy import func, or_
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -57,6 +57,7 @@ from ..external_order_source import (
|
||||
lookup_pending_manual_fulfillment,
|
||||
)
|
||||
from ..file_service import build_file_url
|
||||
from . import classification
|
||||
from .account_selector import (
|
||||
AccountCandidate,
|
||||
capability_candidate_accounts,
|
||||
@@ -120,7 +121,9 @@ def _mapping_for_sku(
|
||||
PlatformCommodityMapping.target_platform == TARGET_PLATFORM,
|
||||
PlatformCommodityMapping.internal_sku_key == internal_sku_key,
|
||||
PlatformCommodityMapping.enabled.is_(True),
|
||||
PlatformCommodityMapping.archived_at.is_(None),
|
||||
)
|
||||
.order_by(PlatformCommodityMapping.updated_at.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
@@ -396,14 +399,17 @@ def _mapping_map(db: Session) -> dict[str, PlatformCommodityMapping]:
|
||||
.filter(
|
||||
PlatformCommodityMapping.target_platform == TARGET_PLATFORM,
|
||||
PlatformCommodityMapping.enabled.is_(True),
|
||||
PlatformCommodityMapping.archived_at.is_(None),
|
||||
)
|
||||
.order_by(PlatformCommodityMapping.updated_at.desc())
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
str(row.internal_sku_key or "").strip(): row
|
||||
for row in rows
|
||||
if str(row.internal_sku_key or "").strip()
|
||||
}
|
||||
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(
|
||||
@@ -812,13 +818,33 @@ def _apply_mapping(
|
||||
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:
|
||||
@@ -995,6 +1021,8 @@ def list_tasks(
|
||||
db: Session,
|
||||
*,
|
||||
status: str = "",
|
||||
queue_bucket: str = "",
|
||||
sale_mode: str = "",
|
||||
keyword: str = "",
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
@@ -1007,6 +1035,51 @@ def list_tasks(
|
||||
PlatformFulfillmentTask.commodity_id != "",
|
||||
)
|
||||
)
|
||||
mode_filter = classification.normalize_sale_mode(sale_mode)
|
||||
if sale_mode and mode_filter != "unknown":
|
||||
query = query.filter(PlatformFulfillmentTask.sale_mode == mode_filter)
|
||||
elif sale_mode == "unknown":
|
||||
query = query.filter(PlatformFulfillmentTask.sale_mode == "unknown")
|
||||
if queue_bucket:
|
||||
now = datetime.now(UTC)
|
||||
if queue_bucket == classification.QUEUE_CANCELLED:
|
||||
query = query.filter(PlatformFulfillmentTask.execution_status == "cancelled")
|
||||
elif queue_bucket == classification.QUEUE_COMPLETED:
|
||||
query = query.filter(PlatformFulfillmentTask.execution_status == "completed")
|
||||
elif queue_bucket == classification.QUEUE_PENDING_MAPPING:
|
||||
query = query.filter(
|
||||
PlatformFulfillmentTask.execution_status == "pending_mapping"
|
||||
)
|
||||
elif queue_bucket == classification.QUEUE_NEEDS_ACTION:
|
||||
query = query.filter(
|
||||
PlatformFulfillmentTask.execution_status == "manual_required"
|
||||
)
|
||||
elif queue_bucket == classification.QUEUE_PRESALE_WAITING:
|
||||
query = query.filter(
|
||||
PlatformFulfillmentTask.execution_status.notin_(
|
||||
["completed", "cancelled", "pending_mapping", "manual_required"]
|
||||
),
|
||||
PlatformFulfillmentTask.sale_mode == "presale",
|
||||
or_(
|
||||
PlatformFulfillmentTask.offer_available_from.is_(None),
|
||||
PlatformFulfillmentTask.offer_available_from > now,
|
||||
),
|
||||
)
|
||||
elif queue_bucket == classification.QUEUE_READY:
|
||||
query = query.filter(
|
||||
PlatformFulfillmentTask.execution_status.notin_(
|
||||
["completed", "cancelled", "pending_mapping", "manual_required"]
|
||||
),
|
||||
or_(
|
||||
PlatformFulfillmentTask.sale_mode != "presale",
|
||||
PlatformFulfillmentTask.offer_available_from.is_(None),
|
||||
PlatformFulfillmentTask.offer_available_from <= now,
|
||||
),
|
||||
)
|
||||
else:
|
||||
query = query.filter(
|
||||
PlatformFulfillmentTask.execution_status.notin_(["completed", "cancelled"])
|
||||
)
|
||||
if status:
|
||||
if status == "unfinished":
|
||||
query = query.filter(
|
||||
@@ -1096,6 +1169,22 @@ def _task_out(
|
||||
)
|
||||
# 外层只消费共享绑定规则,不再自己比较角色名或 bindAct。
|
||||
pending_role = pending_binding_role_from_result(bind_result)
|
||||
sale_mode = classification.normalize_sale_mode(task.sale_mode)
|
||||
availability = classification.availability_state(
|
||||
sale_mode=sale_mode,
|
||||
available_from=task.offer_available_from,
|
||||
available_until=task.offer_available_until,
|
||||
)
|
||||
queue_bucket = classification.queue_bucket(
|
||||
execution_status=task.execution_status,
|
||||
sale_mode=sale_mode,
|
||||
availability=availability,
|
||||
)
|
||||
manual_reason = (
|
||||
classification.manual_reason(task.issue_code, task.exchange_status)
|
||||
if task.execution_status == "manual_required"
|
||||
else ""
|
||||
)
|
||||
return {
|
||||
"id": task.id,
|
||||
"sourceSystem": task.source_system,
|
||||
@@ -1116,6 +1205,15 @@ def _task_out(
|
||||
"commodityMappingId": task.commodity_mapping_id,
|
||||
"commodityId": task.commodity_id,
|
||||
"requiredPoints": task.required_points,
|
||||
"saleMode": sale_mode,
|
||||
"campaignKey": task.campaign_key,
|
||||
"campaignName": task.campaign_name,
|
||||
"offerAvailableFrom": task.offer_available_from,
|
||||
"offerAvailableUntil": task.offer_available_until,
|
||||
"availabilityState": availability,
|
||||
"queueBucket": queue_bucket,
|
||||
"manualReason": manual_reason,
|
||||
"classificationSource": task.classification_source,
|
||||
"bindingStatus": task.binding_status,
|
||||
"executionStatus": task.execution_status,
|
||||
"exchangeStatus": task.exchange_status,
|
||||
@@ -1476,8 +1574,75 @@ async def customer_confirm_binding(db: Session, *, task_id: int) -> dict[str, An
|
||||
return customer_binding_out(db, task_id)
|
||||
|
||||
|
||||
def list_mappings(db: Session, *, keyword: str = "") -> list[dict[str, Any]]:
|
||||
query = db.query(PlatformCommodityMapping)
|
||||
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}%"
|
||||
@@ -1486,84 +1651,69 @@ def list_mappings(db: Session, *, keyword: str = "") -> list[dict[str, Any]]:
|
||||
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.updated_at.desc()).limit(300).all()
|
||||
return [
|
||||
{
|
||||
"id": row.id,
|
||||
"targetPlatform": row.target_platform,
|
||||
"internalSkuKey": row.internal_sku_key,
|
||||
"commodityId": row.commodity_id,
|
||||
"goodsName": row.goods_name,
|
||||
"requiredPoints": row.required_points,
|
||||
"scope": row.scope,
|
||||
"enabled": row.enabled,
|
||||
"updatedAt": row.updated_at,
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
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 upsert_mapping(
|
||||
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,
|
||||
*,
|
||||
internal_sku_key: str,
|
||||
commodity_id: str,
|
||||
goods_name: str,
|
||||
required_points: int | None,
|
||||
enabled: bool,
|
||||
current: User,
|
||||
) -> dict[str, Any]:
|
||||
sku_key = internal_sku_key.strip()
|
||||
commodity = commodity_id.strip()
|
||||
if not sku_key or not commodity:
|
||||
raise HTTPException(status_code=400, detail="内部 SKU 和斗鱼商品 ID 不能为空")
|
||||
goods = (
|
||||
db.query(DouyuGoodsSnapshot)
|
||||
.filter(DouyuGoodsSnapshot.commodity_id == commodity)
|
||||
.order_by(DouyuGoodsSnapshot.id.desc())
|
||||
.first()
|
||||
)
|
||||
row = (
|
||||
row: PlatformCommodityMapping,
|
||||
) -> None:
|
||||
others = (
|
||||
db.query(PlatformCommodityMapping)
|
||||
.filter(
|
||||
PlatformCommodityMapping.target_platform == TARGET_PLATFORM,
|
||||
PlatformCommodityMapping.internal_sku_key == sku_key,
|
||||
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),
|
||||
)
|
||||
.first()
|
||||
.all()
|
||||
)
|
||||
if row is None:
|
||||
row = PlatformCommodityMapping(
|
||||
target_platform=TARGET_PLATFORM,
|
||||
internal_sku_key=sku_key,
|
||||
created_by=current.id,
|
||||
created_at=_now(),
|
||||
)
|
||||
db.add(row)
|
||||
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.scope = SCOPE_ELITE
|
||||
row.enabled = bool(enabled)
|
||||
row.updated_at = _now()
|
||||
db.flush()
|
||||
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 == sku_key,
|
||||
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))
|
||||
pending = pending.all()
|
||||
task_ids: list[int] = []
|
||||
for task in pending:
|
||||
for task in pending.all():
|
||||
_apply_mapping(task, row if row.enabled else None)
|
||||
task.updated_at = _now()
|
||||
task.next_allocate_at = (
|
||||
@@ -1577,18 +1727,321 @@ def upsert_mapping(
|
||||
"mapping_updated",
|
||||
actor_type="user",
|
||||
actor_id=current.id,
|
||||
detail={"commodityId": row.commodity_id, "enabled": row.enabled},
|
||||
detail={
|
||||
"mappingId": row.id,
|
||||
"commodityId": row.commodity_id,
|
||||
"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))
|
||||
db.commit()
|
||||
if task_ids:
|
||||
from .auto_allocator import wake_auto_allocator
|
||||
|
||||
wake_auto_allocator(task_ids)
|
||||
return next(
|
||||
item for item in list_mappings(db, keyword=sku_key) if item["id"] == row.id
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]:
|
||||
@@ -2816,13 +3269,17 @@ def release_task_to_manual(
|
||||
|
||||
__all__ = [
|
||||
"allocate_task",
|
||||
"archive_mapping",
|
||||
"cancel_task",
|
||||
"complete_manual_exchange",
|
||||
"confirm_binding",
|
||||
"create_mapping",
|
||||
"customer_refresh_bindings",
|
||||
"delete_mapping",
|
||||
"get_task_detail",
|
||||
"list_mappings",
|
||||
"list_tasks",
|
||||
"mapping_impact",
|
||||
"mark_manual_required",
|
||||
"reconcile_binding_state_outbox",
|
||||
"record_douyu_operation_result",
|
||||
@@ -2833,11 +3290,14 @@ __all__ = [
|
||||
"release_task_to_manual",
|
||||
"reset_task_binding",
|
||||
"restore_cancelled_task",
|
||||
"restore_mapping",
|
||||
"set_mapping_enabled",
|
||||
"start_binding",
|
||||
"sync_order_item_ids",
|
||||
"sync_order_snapshot",
|
||||
"sync_pending_tasks",
|
||||
"sync_pending_tasks_if_due",
|
||||
"sync_task_from_binding_runner",
|
||||
"update_mapping",
|
||||
"upsert_mapping",
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user