feat(schedule): 增加库存源选项描述字段与站点ID支持

This commit is contained in:
hugo committed 2026-07-10 00:48:27 +08:00
1 parent f4e74f7b07
commit 8b1efbedb9
37 files changed
+8488 -4126

No files matched your search

+5 -1
View File
@@ -39,7 +39,11 @@ def _shipping_inventory_sources_options() -> list[dict[str, Any]]:
{
"label": source.get("display_name") or source.get("source_code"),
"value": source.get("source_code"),
"description": f"{source.get('site')} · {source.get('warehouse_id')}",
"description": (
f"{source.get('source_type')} · "
f"{source.get('site_id') or '-'} · "
f"{source.get('warehouse_id')}"
),
}
for source in list_inventory_sources()
]
@@ -28,6 +28,7 @@ FinalizeScheduleRunResult = dict[str, Any]
_INVENTORY_RPA_HEADER_ORDER = [
"source_code",
"site_id",
"warehouse_id",
"display_name",
"inventory_file_no",
@@ -36,6 +37,7 @@ _INVENTORY_RPA_HEADER_ORDER = [
]
_INVENTORY_RPA_HEADER_LABELS = {
"source_code": "库存源",
"site_id": "站点",
"warehouse_id": "仓库",
"display_name": "名称",
"inventory_file_no": "库存快照号",
@@ -139,6 +141,7 @@ def _build_finalize_details(
base = pending_by_key.get(key, {})
details.append({
"source_code": code or item.get("source_code"),
"site_id": item.get("site_id") or base.get("site_id"),
"warehouse_id": wh or base.get("warehouse_id"),
"display_name": base.get("display_name"),
"inventory_file_no": item.get("inventory_file_no"),
@@ -155,6 +158,7 @@ def _build_finalize_details(
base = pending_by_key.get(key, {})
details.append({
"source_code": code or item.get("source_code"),
"site_id": item.get("site_id") or base.get("site_id"),
"warehouse_id": wh or base.get("warehouse_id"),
"display_name": base.get("display_name"),
"inventory_file_no": "",
@@ -166,6 +170,7 @@ def _build_finalize_details(
continue
details.append({
"source_code": base.get("source_code"),
"site_id": base.get("site_id"),
"warehouse_id": base.get("warehouse_id"),
"display_name": base.get("display_name"),
"inventory_file_no": "",
@@ -52,9 +52,9 @@ def _normalize_filter_tokens(raw: Any) -> set[str]:
def _source_identity_tokens(source: dict[str, Any]) -> set[str]:
"""收集库存源可用于匹配的标识集合(source_code / warehouse_id / match_aliases)。"""
"""收集库存源可用于匹配的标识集合(source_code / site_id / warehouse_id / match_aliases)。"""
tokens: set[str] = set()
for key in ("source_code", "warehouse_id", "warehouse_code"):
for key in ("source_code", "site_id", "warehouse_id"):
value = str(source.get(key) or "").strip().upper()
if value:
tokens.add(value)
@@ -68,12 +68,14 @@ def _source_identity_tokens(source: dict[str, Any]) -> set[str]:
def _extract_wanted_tokens(body_template: dict[str, Any]) -> set[str]:
"""
从 api_body_template 提取筛选 token。
推荐键:source_codes;兼容:source_code / warehouse_ids / warehouse_id / match_aliases。
推荐键:source_codes;兼容:source_code / site_ids / site_id / warehouse_ids / warehouse_id / match_aliases。
"""
wanted: set[str] = set()
for key in (
"source_codes",
"source_code",
"site_ids",
"site_id",
"warehouse_ids",
"warehouse_id",
"match_aliases",
@@ -103,7 +105,7 @@ def _resolve_filter_payload(task: ScheduleTask) -> dict[str, Any] | None:
def _filter_sources(task: ScheduleTask) -> list[dict[str, Any]]:
"""
读取 enabled 库存源;job_params / api_body_template 可限定子集。
核心逻辑:无筛选则导出全部启用源;有筛选时按 source_code / warehouse_id / match_aliases 命中。
核心逻辑:无筛选则导出全部启用源;有筛选时按 source_code / site_id / warehouse_id / match_aliases 命中。
"""
enabled = list_inventory_sources()
body_template = _resolve_filter_payload(task)
@@ -164,6 +166,7 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) ->
details = [
{
"source_code": item.get("source_code"),
"site_id": item.get("site_id"),
"warehouse_id": item.get("warehouse_id"),
"display_name": item.get("display_name"),
}
+19 -2
View File
@@ -122,6 +122,24 @@ def _resolve_odm_id(task: ShippingTask) -> str:
return ""
def _shipment_warehouse_id(task: ShippingTask) -> str:
"""
解析发货 Excel Header 的 Warehouse ID。
核心逻辑:库存快照入库时按「配置 site_id 优先,否则库存 Excel 的 warehouse id」写入 inv_file.warehouse_id。
"""
try:
from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link
snapshot = serialize_inventory_snapshot_link(task)
except Exception:
snapshot = None
if isinstance(snapshot, dict):
value = str(snapshot.get("warehouse_id") or "").strip()
if value:
return value
return "AWSDU"
def _line_po_number(task: ShippingTask, line: dict[str, Any]) -> str:
for value in (line.get("po_number"), task.po_number):
text = str(value or "").strip()
@@ -158,8 +176,7 @@ def _fill_pvmi_template(task: ShippingTask, path: Path) -> None:
_clear_sheet_data_rows(detail_ws)
_clear_sheet_data_rows(header_ws, from_row=DATA_START_ROW)
if header_ws.cell(DATA_START_ROW, 1).value in (None, ""):
header_ws.cell(DATA_START_ROW, 1).value = "AWSDU"
header_ws.cell(DATA_START_ROW, 1).value = _shipment_warehouse_id(task)
if header_ws.cell(DATA_START_ROW, 2).value in (None, ""):
header_ws.cell(DATA_START_ROW, 2).value = "n"
if header_ws.cell(DATA_START_ROW, 3).value in (None, ""):
@@ -106,7 +106,7 @@ def _try_reuse_inventory_snapshot(
优先复用未过期库存快照,避免重复触发 RPA。
【AI 触发时机】:ensure_inventory_via_rpa 已确定库存源且 mode 非 retry_rpa 时调用。
核心逻辑:按 source_code + warehouse_id 查找 ready 快照;命中则 link 并进入映射/匹配。
核心逻辑:按 source_code + 发货 Excel warehouse id 查找 ready 快照;命中则 link 并进入映射/匹配。
retry_rpa 必须跳过缓存强制重新导出。
"""
if mode == "retry_rpa":
@@ -120,7 +120,7 @@ def _try_reuse_inventory_snapshot(
snapshot = find_latest_ready_snapshot(
str(rpa_source.get("source_code") or ""),
str(rpa_source.get("warehouse_id") or rpa_source.get("warehouse_code") or ""),
str(rpa_source.get("site_id") or ""),
)
if not snapshot:
return None
@@ -687,6 +687,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
success = bool(item.get("success", False))
source = build_rpa_inventory_source(source_code) or {
"source_code": source_code,
"site_id": item.get("site_id"),
"warehouse_id": warehouse_id,
"source_type": item.get("source_type"),
}
@@ -14,6 +14,7 @@ from pathlib import Path
from typing import Any
from flask import current_app
from openpyxl import load_workbook
from app import db
from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink
@@ -28,6 +29,13 @@ from app.services.shipping_notice.inventory_snapshot import read_inventory_schem
_SNAPSHOT_STATUS_READY = "ready"
_SNAPSHOT_STATUS_FAILED = "failed"
_SNAPSHOT_STATUS_EXPIRED = "expired"
_WAREHOUSE_ID_HEADER_ALIASES = {
"warehouseid",
"warehouse",
"warehousecode",
"warehousecodeid",
"whid",
}
def inventory_snapshot_ttl_hours() -> int:
@@ -112,6 +120,41 @@ def expire_snapshot(inv_file: ShippingInventoryFile, reason: str) -> None:
inv_file.updated_at = datetime.utcnow()
def _normalize_header_key(value: Any) -> str:
"""将 Excel 表头标准化为可比较 key。"""
return "".join(ch for ch in str(value or "").strip().lower() if ch.isalnum())
def _extract_warehouse_id_from_inventory_excel(path: Path) -> str:
"""
从库存 Excel 内容中提取 Warehouse ID。
核心逻辑:扫描前几行表头,命中 Warehouse ID/WH ID 等列后取其下方第一条非空值。
"""
if not path or not path.is_file():
return ""
try:
wb = load_workbook(filename=str(path), data_only=True, read_only=True)
except Exception:
return ""
try:
ws = wb.active
rows = list(ws.iter_rows(min_row=1, max_row=min(ws.max_row or 1, 40), values_only=True))
finally:
wb.close()
for row_idx, row in enumerate(rows):
for col_idx, cell in enumerate(row):
if _normalize_header_key(cell) not in _WAREHOUSE_ID_HEADER_ALIASES:
continue
for data_row in rows[row_idx + 1:]:
if col_idx >= len(data_row):
continue
value = str(data_row[col_idx] or "").strip().upper()
if value:
return value
return ""
def create_inventory_snapshot_from_rpa(
*,
source: dict[str, Any],
@@ -142,13 +185,19 @@ def create_inventory_snapshot_from_rpa(
exported_at = datetime.utcnow()
inventory_file_no = generate_inventory_file_no()
source_code = str(source.get("source_code") or "").strip().upper()
warehouse_id = str(source.get("warehouse_id") or source.get("warehouse_code") or "").strip()
warehouse_code = str(source.get("warehouse_code") or warehouse_id).strip()
configured_site_id = str(source.get("site_id") or "").strip().upper()
export_warehouse_id = str(source.get("warehouse_id") or "").strip().upper()
excel_warehouse_id = ""
warehouse_id = configured_site_id
warehouse_code = warehouse_id
if success:
path = inventory_file_upload_path(inventory_file_no)
path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(local_path, path)
excel_warehouse_id = _extract_warehouse_id_from_inventory_excel(path)
warehouse_id = configured_site_id or excel_warehouse_id
warehouse_code = warehouse_id
preview = read_inventory_schema_preview(path)
preview["upload_filename"] = str(source_file_name or Path(local_path).name).strip() or path.name
snapshot_status = _SNAPSHOT_STATUS_READY
@@ -181,6 +230,10 @@ def create_inventory_snapshot_from_rpa(
"query": source.get("query"),
"navigation": source.get("navigation"),
"parameters": source.get("parameters"),
"site_id": configured_site_id or None,
"export_warehouse_id": export_warehouse_id,
"excel_warehouse_id": excel_warehouse_id or None,
"warehouse_id_source": "site_id" if configured_site_id else ("inventory_excel" if excel_warehouse_id else None),
"trigger_type": trigger_type,
},
)
@@ -16,7 +16,7 @@ from typing import Any
import yaml
from flask import current_app
_SITE_TO_SOURCE_TYPE = {
_VALID_SOURCE_TYPES = {
"dsv360": "dsv360",
"crane_footprint": "crane_footprint",
}
@@ -84,20 +84,20 @@ def _build_legacy_query(source: dict[str, Any]) -> dict[str, Any]:
"""
navigation = dict(source.get("navigation") or {})
query: dict[str, Any] = {}
site = str(source.get("site") or "").strip().lower()
source_type = str(source.get("source_type") or "").strip().lower()
if site == "dsv360":
if source_type == "dsv360":
for key in ("program_group", "program_label", "report_group", "report_name"):
if navigation.get(key):
query[key] = navigation[key]
elif site == "crane_footprint":
elif source_type == "crane_footprint":
if navigation.get("report_name"):
query["report_name"] = navigation["report_name"]
query["project_code"] = navigation.get("project_code")
warehouse_code = str(source.get("warehouse_code") or source.get("warehouse_id") or "").strip()
if warehouse_code:
query["warehouse_code"] = warehouse_code
warehouse_id = str(source.get("warehouse_id") or "").strip()
if warehouse_id:
query["warehouse_code"] = warehouse_id
for parameter in source.get("parameters") or []:
if not isinstance(parameter, dict):
@@ -140,14 +140,14 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
raise InventorySourceConfigError(f"duplicate source_code: {source_code}")
seen_codes.add(source_code)
site = str(raw.get("site") or "").strip().lower()
if site not in _SITE_TO_SOURCE_TYPE:
raise InventorySourceConfigError(f"{source_code}: site must be dsv360 or crane_footprint")
warehouse_id = str(raw.get("warehouse_id") or "").strip()
if not warehouse_id:
raise InventorySourceConfigError(f"{source_code}: warehouse_id is required")
source_type = str(raw.get("source_type") or "").strip().lower()
if source_type not in _VALID_SOURCE_TYPES:
raise InventorySourceConfigError(f"{source_code}: source_type must be dsv360 or crane_footprint")
warehouse_id = str(raw.get("warehouse_id") or "").strip().upper()
site_id = str(raw.get("site_id") or "").strip().upper()
if source_type == "dsv360" and not site_id:
raise InventorySourceConfigError(f"{source_code}: site_id is required for dsv360")
parameters: list[dict[str, Any]] = []
for item in raw.get("parameters") or []:
if not isinstance(item, dict):
@@ -163,13 +163,12 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
normalized = {
"source_code": source_code,
"source_type": _SITE_TO_SOURCE_TYPE[site],
"site": site,
"source_type": _VALID_SOURCE_TYPES[source_type],
"site_id": site_id,
"display_name": str(raw.get("display_name") or source_code).strip(),
"enabled": bool(raw.get("enabled", True)),
"entry_url": str(raw.get("entry_url") or "").strip(),
"warehouse_id": warehouse_id,
"warehouse_code": str(raw.get("warehouse_code") or warehouse_id).strip(),
"navigation": dict(raw.get("navigation") or {}),
"parameters": parameters,
"match_aliases": [
@@ -178,7 +177,7 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
if str(alias).strip()
],
}
if site == "crane_footprint" and raw.get("export"):
if source_type == "crane_footprint" and raw.get("export"):
normalized["export"] = dict(raw.get("export") or {})
normalized["query"] = _build_legacy_query(normalized)
return normalized
+1 -1
View File
@@ -125,8 +125,8 @@ def write_inventory_export_batch_trigger(
inventory_sources.append({
"source_code": source.get("source_code"),
"source_type": source.get("source_type"),
"site_id": source.get("site_id"),
"warehouse_id": source.get("warehouse_id"),
"warehouse_code": source.get("warehouse_code"),
"entry_url": source.get("entry_url"),
"navigation": source.get("navigation") or {},
"parameters": source.get("parameters") or [],