feat(shipping-notice): 新增库存快照管理与RPA批量导出功能

This commit is contained in:
hugo committed 2026-07-08 08:59:08 +08:00
1 parent fc694a8f43
commit d54f51ddc3
48 files changed
+4970 -543

No files matched your search

+5
View File
@@ -328,6 +328,11 @@ def rpa_inventory_ready():
"""RPA 回调入口:上报库存导出结果并回写任务状态。"""
return jsonify(shipping_tools.rpa_report_inventory(_payload()))
@shipping_notice_bp.route('/rpa/inventory-batch-ready', methods=['POST'])
def rpa_inventory_batch_ready():
"""RPA 批量库存导出回调:按 Warehouse 写入库存快照。"""
return jsonify(shipping_tools.rpa_report_inventory_batch(_payload()))
@shipping_notice_bp.route('/rpa/upload-complete', methods=['POST'])
def rpa_upload_complete():
"""RPA 回调入口:上报货代上传结果并回写任务状态。"""
+10 -1
View File
@@ -156,7 +156,7 @@ class Config:
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '360'
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '900'
)
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM = os.getenv('SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM', 'false').lower() == 'true'
SHIPPING_NOTICE_AUTO_MATCH_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_MATCH_ENABLED', 'true').lower() == 'true'
@@ -177,6 +177,15 @@ class Config:
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int(
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000'
)
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG = _backend_path(
'SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG', 'config', 'shipping_inventory_sources.json'
)
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS = int(
os.getenv('SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS') or '24'
)
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED = (
os.getenv('SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE = float(
os.getenv('SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE') or '0.8'
)
+21
View File
@@ -143,6 +143,13 @@ class ShippingInventoryFile(Base):
__table_args__ = (
Index('ix_shipping_inventory_files_batch_created', 'batch_id', 'created_at'),
Index('ix_shipping_inventory_files_user_created', 'user_id', 'created_at'),
Index(
'ix_shipping_inventory_files_source_snapshot',
'source_code',
'warehouse_id',
'snapshot_status',
'exported_at',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -158,6 +165,16 @@ class ShippingInventoryFile(Base):
inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
line_count: Mapped[int] = mapped_column(Integer, default=0)
share_mode: Mapped[str] = mapped_column(String(32), default='task_only')
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
snapshot_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
exported_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
rpa_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
schedule_run_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True)
source_query_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
@@ -184,6 +201,10 @@ class ShippingTaskInventoryLink(Base):
link_role: Mapped[str] = mapped_column(String(32), default='member')
access_mode: Mapped[str] = mapped_column(String(32), default='readonly')
is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), index=True)
link_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
matched_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
snapshot_age_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
audit_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
linked_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
@@ -276,6 +276,9 @@ def resolve_schedule_executor(task: ScheduleTask) -> ScheduleExecutor:
if dst == "faq_hot_aggregate":
from app.services.schedule.faq_hot_aggregate_job import run_faq_hot_aggregate_schedule
return run_faq_hot_aggregate_schedule
if dst == "shipping_inventory_rpa":
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
return run_shipping_inventory_rpa_schedule
if dst in ("database", "external_api"):
return _run_generic_check_job
return _run_common_executor
@@ -0,0 +1,104 @@
"""
backend/app/services/schedule/shipping_inventory_rpa_job.py
用途:排程触发货代库存 RPA 批量导出(各 Warehouse 一次登录多导出)。
依赖:inventory_sources、rpa.write_inventory_export_batch_trigger、ScheduleTask/ScheduleRun。
逻辑:data_source_type=shipping_inventory_rpa 时由 resolve_schedule_executor 调用。
"""
from __future__ import annotations
import json
from datetime import datetime
from typing import Any
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source, list_inventory_sources
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
def _parse_api_body_template(task: ScheduleTask) -> dict[str, Any] | None:
"""解析 ScheduleTaskConfig.api_body_template(Text JSON)。"""
cfg = getattr(task, "config", None)
raw = getattr(cfg, "api_body_template", None) if cfg else None
if isinstance(raw, dict):
return raw
if isinstance(raw, str) and raw.strip():
try:
parsed = json.loads(raw)
return parsed if isinstance(parsed, dict) else None
except json.JSONDecodeError:
return None
return None
def _filter_sources(task: ScheduleTask) -> list[dict[str, Any]]:
"""读取 enabled 库存源;api_body_template 可限定 source_code 子集。"""
enabled = list_inventory_sources()
body_template = _parse_api_body_template(task)
if body_template:
codes = body_template.get("source_codes") or body_template.get("source_code")
if isinstance(codes, str):
codes = [codes]
if isinstance(codes, list):
wanted = {str(code).strip().upper() for code in codes if str(code).strip()}
enabled = [item for item in enabled if str(item.get("source_code") or "").upper() in wanted]
return [source for source in enabled if build_rpa_inventory_source(source.get("source_code"))]
def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
写入批量库存 RPA trigger,由 worker 异步导出并在 callback 入库。
核心逻辑:不在排程内同步等待 RPA;ScheduleRun 记录 trigger 写入结果。
"""
sources = _filter_sources(task)
step_logs: list[dict[str, Any]] = [{
"step": "shipping_inventory_rpa",
"status": "started",
"detail": {"source_count": len(sources)},
}]
if not sources:
message = "no enabled inventory sources"
step_logs.append({"step": "shipping_inventory_rpa", "status": "skipped", "detail": {"message": message}})
return 0, 0, 0, 1, [], [message], step_logs
run_no = run.run_no or f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}"
trigger_path = write_inventory_export_batch_trigger(
run_no,
sources,
payload={
"trigger_type": "scheduled",
"schedule_run_id": run.id,
"schedule_task_id": task.id,
},
)
if not trigger_path:
message = "inventory RPA trigger dir not configured"
step_logs.append({"step": "shipping_inventory_rpa", "status": "failed", "detail": {"message": message}})
return len(sources), 0, 0, len(sources), [], [message], step_logs
run.api_request_json = {
"run_no": run_no,
"trigger_path": trigger_path,
"source_codes": [item.get("source_code") for item in sources],
}
db.session.commit()
step_logs.append({
"step": "shipping_inventory_rpa",
"status": "triggered",
"detail": {"trigger_path": trigger_path, "run_no": run_no},
})
details = [
{
"source_code": item.get("source_code"),
"warehouse_id": item.get("warehouse_id"),
"display_name": item.get("display_name"),
}
for item in sources
]
return len(sources), len(sources), 0, 0, details, [], step_logs
@@ -16,7 +16,11 @@ from app import db
from app.models import ShippingTask, ShippingTaskEvent
from app.services.shipping_notice.constants import CP_INVENTORY_SOURCE_REVIEW, CP_UPLOAD_REQ, PH_RPA_PENDING
from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file
from app.services.shipping_notice.inventory_file_store import save_task_inventory_file_from_local_path
from app.services.shipping_notice.inventory_snapshot_store import (
create_inventory_snapshot_from_rpa,
find_latest_ready_snapshot,
link_snapshot_to_task,
)
from app.services.shipping_notice.inventory_upload import save_task_inventory_local_file
from app.services.shipping_notice.inventory_source_rules import (
mark_inventory_source_review,
@@ -32,7 +36,7 @@ from app.services.shipping_notice.query_service import (
from app.services.shipping_notice.rpa import (
find_latest_inventory_file,
inventory_processed_dir,
write_inventory_export_trigger,
write_inventory_export_trigger_for_task,
)
from app.services.shipping_notice.rpa_attempts import (
inventory_rpa_attempts,
@@ -60,33 +64,29 @@ def latest_task_event(task: ShippingTask, event_type: str) -> ShippingTaskEvent
def _inventory_rpa_attempt_label(*, attempt_no: int, max_attempts: int, manual_retry_round: bool) -> str:
"""
生成库存 RPA 尝试轮次文案。
【AI 触发时机】:需要把当前 RPA 处于单次自动尝试、多次自动尝试或手动重试轮次解释给用户时调用。
生成库存 RPA 尝试状态文案。
【AI 触发时机】:需要向前台说明当前 RPA 库存获取已触发或仍在等待时调用。
核心逻辑:手动 retry_rpa 始终强调“手动第 N 次”;自动模式在 max_attempts=1 时不再输出“1/1”,
避免 Dify 误解为系统还会继续自动重试。
核心逻辑:前台不展示“第 N 次”这类内部排障指标,避免用户误解自动重试策略;
真正的 attempt 仍保留在 ShippingTaskEvent.detail 里供运维排查。
"""
if manual_retry_round:
return f"手动第 {attempt_no} 次尝试"
return "已手动重新触发库存获取"
if max_attempts <= 1:
return "当前配置为单次自动尝试"
return f"第 {attempt_no}/{max_attempts} 次尝试"
return "库存获取自动尝试中"
def _inventory_rpa_running_prefix(*, attempt_no: int, max_attempts: int) -> str:
"""生成库存 RPA 运行中的简短前缀,单次模式不暴露 1/1 计数。"""
if max_attempts <= 1:
return "库存获取进行中。"
return f"库存获取进行中(第 {attempt_no}/{max_attempts} 次)。"
"""生成库存 RPA 运行中的简短前缀,前台不暴露尝试次数。"""
return "库存获取进行中。"
def _inventory_rpa_triggered_prefix(*, attempt_no: int, max_attempts: int, manual_retry_round: bool) -> str:
"""生成库存 RPA 触发成功后的摘要文案,区分自动单次、自动多次与人工重试。"""
"""生成库存 RPA 触发成功后的摘要文案,前台不暴露尝试次数。"""
if manual_retry_round:
return f"已重新触发库存获取(第 {attempt_no} 次)。"
if max_attempts <= 1:
return "已触发库存获取。"
return f"已触发库存获取(第 {attempt_no}/{max_attempts} 次)。"
return "已重新触发库存获取。"
return "已触发库存获取。"
def _inventory_rpa_exhausted_message(attempts: int) -> str:
@@ -96,6 +96,97 @@ def _inventory_rpa_exhausted_message(attempts: int) -> str:
return f"已尝试 {attempts} 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。"
def _try_reuse_inventory_snapshot(
task: ShippingTask,
rpa_source: dict[str, Any],
*,
mode: str,
) -> dict[str, Any] | None:
"""
优先复用未过期库存快照,避免重复触发 RPA。
【AI 触发时机】:ensure_inventory_via_rpa 已确定库存源且 mode 非 retry_rpa 时调用。
核心逻辑:按 source_code + warehouse_id 查找 ready 快照;命中则 link 并进入映射/匹配。
retry_rpa 必须跳过缓存强制重新导出。
"""
if mode == "retry_rpa":
return None
from app.services.shipping_notice.inventory_mapping_workflow import (
awaiting_inventory_mapping_confirm,
inventory_loaded_response,
inventory_mapping_checkpoint_response,
)
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 ""),
)
if not snapshot:
return None
link = link_snapshot_to_task(
task,
snapshot,
reason="reuse_latest",
audit_payload={"mode": mode, "source_type": rpa_source.get("source_type")},
)
if not link:
return None
log_task_event(
task,
"inventory_snapshot_reused",
{
"inventory_file_no": snapshot.inventory_file_no,
"source_code": snapshot.source_code,
"warehouse_id": snapshot.warehouse_id,
"snapshot_age_seconds": link.snapshot_age_seconds,
},
)
db.session.flush()
cached_lines = [
row for row in (snapshot.inventory_lines_json or []) if isinstance(row, dict)
]
if cached_lines:
task.inventory_lines_json = cached_lines
if awaiting_inventory_mapping_confirm(task):
db.session.commit()
return inventory_mapping_checkpoint_response(task)
return inventory_loaded_response(
task,
cached_lines,
column_meta={"source": "snapshot_reuse"},
source="snapshot_reuse",
require_mapping_review=not snapshot.mapping_confirmed,
event_type="inventory_snapshot_reused",
)
path = Path(snapshot.storage_path)
if path.is_file():
lines, column_meta = ingest_inventory_file(path, move_to=None)
if lines:
snapshot.inventory_lines_json = lines
snapshot.line_count = len(lines)
return inventory_loaded_response(
task,
lines,
column_meta=column_meta,
source="snapshot_reuse",
require_mapping_review=True,
event_type="inventory_snapshot_reused",
)
db.session.commit()
return tool_response(
status="running",
task_id=task.task_no,
message="已关联最新库存快照,正在读取字段映射。",
data=serialize_task_for_tool(task),
)
def _save_last_inventory_rpa_runtime(task: ShippingTask, payload: dict[str, Any]) -> dict[str, Any]:
"""保存 worker 回调上报的实际执行模式,供前端显示本次真实来源。"""
raw_mode = str(payload.get("rpa_mode") or payload.get("mode") or "").strip().lower()
@@ -295,6 +386,11 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
stop_agent_turn=True,
)
# [STEP 0.5] 未过期库存快照优先复用;retry_rpa 强制跳过。
reused = _try_reuse_inventory_snapshot(task, rpa_source, mode=mode)
if reused is not None:
return reused
# [STEP 1] 先检查当前是否已有进行中的 RPA 导出。
# 若仍在超时窗口内,则返回 running 轮询信息;超时则补记失败事件,避免重复无脑触发。
timeout_seconds = rpa_inventory_timeout_seconds()
@@ -379,12 +475,12 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
# [STEP 3] 触发下一次 RPA 导出或给出人工兜底提示。
# 触发成功则推进到 pending;触发失败则明确要求用户改走手工上传。
attempt_no = attempts + 1
trigger = write_inventory_export_trigger(
trigger = write_inventory_export_trigger_for_task(
task.task_no,
{
rpa_source,
payload={
"mode": mode,
"attempt": attempt_no,
"rpa_inventory_source": rpa_source,
},
)
if trigger:
@@ -508,10 +604,24 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
processed = inventory_processed_dir()
managed_path = save_task_inventory_local_file(task.task_no, path)
inv_file = save_task_inventory_file_from_local_path(
task,
managed_path,
rpa_source = task_rpa_inventory_source(task) or {}
if not rpa_source.get("source_code") and payload.get("source_code"):
rpa_source = build_rpa_inventory_source(str(payload.get("source_code"))) or rpa_source
inv_file = create_inventory_snapshot_from_rpa(
source=rpa_source or {"source_code": payload.get("source_code"), "source_type": payload.get("source_type")},
local_path=managed_path,
source_file_name=path.name,
rpa_run_no=str(payload.get("run_no") or "").strip() or None,
trigger_type="on_demand",
success=True,
user_id=task.user_id,
batch_id=task.batch_id,
)
link_snapshot_to_task(
task,
inv_file,
reason="rpa_callback",
audit_payload={"rpa_runtime": runtime},
)
lines, column_meta = ingest_inventory_file(path, move_to=processed)
set_task_step_progress(
@@ -543,3 +653,108 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
require_mapping_review=True,
event_type="inventory_rpa_ready",
)
def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
"""
RPA 批量库存导出回调:为每个 Warehouse 创建库存快照,可选关联发货任务。
【AI 触发时机】:freight_rpa_worker 完成 inventory_export_batch 后 POST 本接口。
核心逻辑:遍历 results;定时任务只入库;带 task_no 的成功项关联对应任务。
"""
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
run_no = str(payload.get("run_no") or "").strip()
schedule_run_id = payload.get("schedule_run_id")
try:
schedule_run_id = int(schedule_run_id) if schedule_run_id is not None else None
except (TypeError, ValueError):
schedule_run_id = None
results = payload.get("results") or []
if not isinstance(results, list):
return tool_response(status="failed", message="results must be a list")
created: list[dict[str, Any]] = []
failed: list[dict[str, Any]] = []
for item in results:
if not isinstance(item, dict):
continue
source_code = str(item.get("source_code") or "").strip().upper()
warehouse_id = str(item.get("warehouse_id") or "").strip()
success = bool(item.get("success", False))
source = build_rpa_inventory_source(source_code) or {
"source_code": source_code,
"warehouse_id": warehouse_id,
"source_type": item.get("source_type"),
}
if success:
file_path = str(item.get("file_path") or "").strip()
path = Path(file_path) if file_path else None
if not path or not path.is_file():
failed.append({"source_code": source_code, "warehouse_id": warehouse_id, "error": "file_missing"})
continue
inv_file = create_inventory_snapshot_from_rpa(
source=source,
local_path=path,
source_file_name=path.name,
rpa_run_no=run_no or None,
schedule_run_id=schedule_run_id,
trigger_type=str(payload.get("trigger_type") or "scheduled"),
success=True,
)
created.append({
"inventory_file_no": inv_file.inventory_file_no,
"source_code": source_code,
"warehouse_id": warehouse_id,
})
task_no = str(item.get("task_no") or "").strip()
if task_no:
task = resolve_task_from_payload({"task_id": task_no, "task_no": task_no})
if task:
link_snapshot_to_task(
task,
inv_file,
reason="rpa_batch_callback",
audit_payload={"run_no": run_no},
)
lines, column_meta = ingest_inventory_file(path, move_to=inventory_processed_dir())
if lines and task.process_status not in {"uploaded", "completed", "closed", "rejected"}:
inventory_loaded_response(
task,
lines,
column_meta=column_meta,
source="rpa_batch_callback",
require_mapping_review=True,
event_type="inventory_rpa_ready",
)
else:
create_inventory_snapshot_from_rpa(
source=source,
local_path=item.get("file_path") or "",
rpa_run_no=run_no or None,
schedule_run_id=schedule_run_id,
trigger_type=str(payload.get("trigger_type") or "scheduled"),
success=False,
error_message=str(item.get("error_message") or "export failed")[:500],
)
failed.append({
"source_code": source_code,
"warehouse_id": warehouse_id,
"error": item.get("error_message"),
})
db.session.commit()
return tool_response(
status="ok" if created else "failed",
message=f"批量库存回调完成:成功 {len(created)},失败 {len(failed)}",
data={
"run_no": run_no,
"created": created,
"failed": failed,
"rpa_mode": payload.get("rpa_mode"),
},
)
@@ -0,0 +1,270 @@
"""
services/shipping_notice/inventory_snapshot_store.py
用途:库存快照查询、TTL 复用、RPA 入库与任务关联审计。
依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_file_store、Flask config。
逻辑:ensure_inventory 优先调用本模块查找未过期快照;RPA batch callback 创建快照记录。
"""
from __future__ import annotations
import shutil
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
from flask import current_app
from app import db
from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink
from app.services.shipping_notice.inventory_file_store import (
_can_relink_inventory,
generate_inventory_file_no,
inventory_file_upload_path,
replace_task_inventory_link,
)
from app.services.shipping_notice.inventory_snapshot import read_inventory_schema_preview
_SNAPSHOT_STATUS_READY = "ready"
_SNAPSHOT_STATUS_FAILED = "failed"
_SNAPSHOT_STATUS_EXPIRED = "expired"
def inventory_snapshot_ttl_hours() -> int:
"""库存快照 TTL(小时);默认 24。"""
raw = current_app.config.get("SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS", 24)
try:
return max(int(raw), 1)
except (TypeError, ValueError):
return 24
def snapshot_expires_at(exported_at: datetime | None = None) -> datetime:
"""根据导出时间计算快照过期时间。"""
base = exported_at or datetime.utcnow()
return base + timedelta(hours=inventory_snapshot_ttl_hours())
def is_snapshot_fresh(inv_file: ShippingInventoryFile, *, now: datetime | None = None) -> bool:
"""
判断库存快照是否仍处于 ready 且未过期。
【AI 触发时机】:ensure_inventory 决定是否复用已有快照前调用。
"""
if not inv_file or str(inv_file.snapshot_status or "").strip().lower() != _SNAPSHOT_STATUS_READY:
return False
if not Path(inv_file.storage_path).is_file():
return False
moment = now or datetime.utcnow()
expires_at = inv_file.expires_at
if expires_at and moment >= expires_at:
return False
return True
def find_latest_ready_snapshot(
source_code: str | None,
warehouse_id: str | None,
) -> ShippingInventoryFile | None:
"""
查找指定 source/warehouse 最新 ready 且未过期的库存快照。
核心逻辑:按 exported_at 倒序取第一条;过期快照不在此返回。
"""
code = str(source_code or "").strip().upper()
warehouse = str(warehouse_id or "").strip().upper()
if not code or not warehouse:
return None
rows = (
ShippingInventoryFile.query.filter_by(
source_code=code,
warehouse_id=warehouse,
snapshot_status=_SNAPSHOT_STATUS_READY,
)
.order_by(ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc())
.limit(5)
.all()
)
for row in rows:
if is_snapshot_fresh(row):
return row
return None
def list_available_snapshots(
*,
source_code: str | None = None,
warehouse_id: str | None = None,
limit: int = 20,
) -> list[ShippingInventoryFile]:
"""列出未过期 ready 快照,供工作台查询。"""
query = ShippingInventoryFile.query.filter_by(snapshot_status=_SNAPSHOT_STATUS_READY)
if source_code:
query = query.filter_by(source_code=str(source_code).strip().upper())
if warehouse_id:
query = query.filter_by(warehouse_id=str(warehouse_id).strip().upper())
rows = query.order_by(ShippingInventoryFile.exported_at.desc()).limit(max(limit, 1)).all()
return [row for row in rows if is_snapshot_fresh(row)]
def expire_snapshot(inv_file: ShippingInventoryFile, reason: str) -> None:
"""将快照标记为 expired。"""
inv_file.snapshot_status = _SNAPSHOT_STATUS_EXPIRED
inv_file.updated_at = datetime.utcnow()
def create_inventory_snapshot_from_rpa(
*,
source: dict[str, Any],
local_path: str | Path,
source_file_name: str | None = None,
rpa_run_no: str | None = None,
schedule_run_id: int | None = None,
trigger_type: str = "on_demand",
success: bool = True,
error_message: str | None = None,
user_id: int | None = None,
batch_id: int | None = None,
share_mode: str | None = None,
) -> ShippingInventoryFile:
"""
从 RPA 导出文件创建库存快照记录。
【AI 触发时机】:RPA 单条或 batch 回调成功/失败时调用;定时任务只入库不绑定发货任务。
Args:
source: rpa_inventory_source 配置副本。
local_path: RPA 落盘 Excel 路径。
trigger_type: scheduled / on_demand / manual_upload 等来源标识。
success: False 时写入 failed 快照,不复制文件到标准目录。
Returns:
ShippingInventoryFile: 已持久化的快照对象。
"""
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()
if success:
path = inventory_file_upload_path(inventory_file_no)
path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(local_path, path)
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
storage_path = str(path)
else:
path = Path(local_path) if local_path else None
preview = {"error": error_message or "RPA export failed"}
snapshot_status = _SNAPSHOT_STATUS_FAILED
storage_path = str(path) if path and path.is_file() else ""
inv_file = ShippingInventoryFile(
inventory_file_no=inventory_file_no,
batch_id=batch_id,
user_id=user_id,
source_file_name=str(source_file_name or (path.name if path else "")).strip() or None,
storage_path=storage_path or f"failed://{inventory_file_no}",
schema_preview_json=preview,
share_mode=share_mode or ("task_only" if trigger_type in {"on_demand", "manual_upload"} else "warehouse_pool"),
line_count=0,
warehouse_id=warehouse_id or None,
warehouse_code=warehouse_code or None,
source_code=source_code or None,
source_type=str(source.get("source_type") or "").strip() or None,
snapshot_status=snapshot_status,
exported_at=exported_at,
expires_at=snapshot_expires_at(exported_at) if success else None,
rpa_run_no=str(rpa_run_no or "").strip() or None,
schedule_run_id=schedule_run_id,
source_query_json={
"query": source.get("query"),
"navigation": source.get("navigation"),
"parameters": source.get("parameters"),
"trigger_type": trigger_type,
},
)
db.session.add(inv_file)
db.session.flush()
return inv_file
def link_snapshot_to_task(
task: ShippingTask,
inv_file: ShippingInventoryFile,
*,
reason: str,
audit_payload: dict[str, Any] | None = None,
) -> ShippingTaskInventoryLink | None:
"""
将 ready 库存快照关联到发货任务并写入审计字段。
【AI 触发时机】:ensure_inventory 复用快照或 RPA 回调带 task_no 时调用。
Returns:
ShippingTaskInventoryLink | None: 终态任务不允许 relink 时返回 None。
"""
if not _can_relink_inventory(task):
return None
if not is_snapshot_fresh(inv_file):
return None
age_seconds: int | None = None
if inv_file.exported_at:
age_seconds = max(int((datetime.utcnow() - inv_file.exported_at).total_seconds()), 0)
link = replace_task_inventory_link(task, inv_file, role="member")
link.link_reason = reason
link.matched_warehouse_id = inv_file.warehouse_id
link.snapshot_age_seconds = age_seconds
link.audit_payload_json = {
**(audit_payload or {}),
"source_code": inv_file.source_code,
"warehouse_id": inv_file.warehouse_id,
"exported_at": inv_file.exported_at.isoformat() if inv_file.exported_at else None,
"expires_at": inv_file.expires_at.isoformat() if inv_file.expires_at else None,
"inventory_file_no": inv_file.inventory_file_no,
"trigger_type": (inv_file.source_query_json or {}).get("trigger_type"),
}
task.inventory_snapshot_id = inv_file.id
db.session.add(
ShippingTaskEvent(
task_id=task.id,
event_type="inventory_snapshot_linked",
detail_json={
"inventory_file_no": inv_file.inventory_file_no,
"link_reason": reason,
"snapshot_age_seconds": age_seconds,
**(audit_payload or {}),
},
)
)
return link
def serialize_inventory_snapshot_link(task: ShippingTask) -> dict[str, Any] | None:
"""序列化任务当前 active 库存快照摘要,供工作台/Tool 展示。"""
if task.id is None:
return None
link = (
ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True)
.order_by(ShippingTaskInventoryLink.id.desc())
.first()
)
if not link or not link.inventory_file:
return None
inv_file = link.inventory_file
trigger_type = (inv_file.source_query_json or {}).get("trigger_type") if isinstance(inv_file.source_query_json, dict) else None
return {
"inventory_file_no": inv_file.inventory_file_no,
"source_code": inv_file.source_code,
"warehouse_id": inv_file.warehouse_id,
"warehouse_code": inv_file.warehouse_code,
"exported_at": inv_file.exported_at.isoformat() if inv_file.exported_at else None,
"expires_at": inv_file.expires_at.isoformat() if inv_file.expires_at else None,
"snapshot_status": inv_file.snapshot_status,
"is_fresh": is_snapshot_fresh(inv_file),
"link_reason": link.link_reason,
"snapshot_age_seconds": link.snapshot_age_seconds,
"trigger_type": trigger_type,
"rpa_run_no": inv_file.rpa_run_no,
}
@@ -3,7 +3,7 @@ services/shipping_notice/inventory_source_rules.py
用途:根据发货通知目的地/港口/仓库线索解析应使用的库存 RPA 源。
依赖:inventory_sources、ShippingTask step_payload_json/单头/订单行。
逻辑:Dify 只提供候选字段;本模块负责标准化、规则命中、唯一性判断和写入任务上下文。
逻辑:从 JSON 配置的 match_aliases 命中库存源;Dify 只提供候选字段,本模块负责标准化与唯一性判断。
"""
from __future__ import annotations
@@ -16,17 +16,6 @@ from app.models import ShippingTask
from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source, list_inventory_sources
ROUTE_RULES: tuple[dict[str, Any], ...] = (
{"source_code": "DSV360_AWSBI", "aliases": ("BISON", "AWSBI")},
{"source_code": "DSV360_AWSCV", "aliases": ("CINCINNATI", "CVG", "AWSCV")},
{"source_code": "DSV360_AWSDU", "aliases": ("DBS DUB", "DUB", "DUBLIN")},
{"source_code": "DSV360_AWSAMS", "aliases": ("MOERDIJK", "AMS", "AWSAMS")},
{"source_code": "DSV360_AWSSL", "aliases": ("USLCK", "SALT LAKE CITY", "SALTLAKECITY")},
{"source_code": "DSV360_AWSSG", "aliases": ("SINGAPORE HUB", "SINGAPORE", "SG")},
{"source_code": "CRANE_TZR2", "aliases": ("TZR2", "THAILAND")},
)
@dataclass(frozen=True)
class InventorySourceResolution:
"""库存源解析结果。"""
@@ -75,24 +64,42 @@ def extract_destination_candidates(task: ShippingTask) -> list[str]:
if not isinstance(line, dict):
continue
_extract_destination_object(candidates, line.get("destination"))
for key in ("destination_port", "destination_city", "destination_country", "warehouse_hint", "ship_to"):
for key in ("destination_port", "destination_city", "destination_country", "warehouse_hint", "ship_to", "raw_text"):
_append_candidate(candidates, line.get(key))
return candidates
def _matches_alias(candidate: str, alias: str) -> bool:
normalized_alias = normalize_destination(alias)
return candidate == normalized_alias or normalized_alias in candidate.split() or normalized_alias in candidate
if not normalized_alias:
return False
return (
candidate == normalized_alias
or normalized_alias in candidate.split()
or normalized_alias in candidate
)
def _candidate_summary(source: dict[str, Any]) -> dict[str, Any]:
"""人工确认候选项展示字段。"""
return {
"source_code": source.get("source_code"),
"display_name": source.get("display_name"),
"warehouse_id": source.get("warehouse_id"),
"site": source.get("site"),
"source_type": source.get("source_type"),
}
def resolve_inventory_source(task: ShippingTask) -> InventorySourceResolution:
"""根据任务目的地候选解析唯一库存源;无法唯一命中时返回人工确认所需候选。"""
"""根据任务目的地候选与 JSON match_aliases 解析唯一库存源。"""
candidates = extract_destination_candidates(task)
matched_codes: list[str] = []
for candidate in candidates:
for rule in ROUTE_RULES:
if any(_matches_alias(candidate, alias) for alias in rule.get("aliases") or []):
code = str(rule.get("source_code") or "").strip().upper()
for source in list_inventory_sources():
aliases = source.get("match_aliases") or []
if any(_matches_alias(candidate, alias) for alias in aliases):
code = str(source.get("source_code") or "").strip().upper()
if code and code not in matched_codes:
matched_codes.append(code)
@@ -102,12 +109,12 @@ def resolve_inventory_source(task: ShippingTask) -> InventorySourceResolution:
return InventorySourceResolution(
status="resolved",
source=source,
candidates=[source],
candidates=[_candidate_summary(source)],
destination_candidates=candidates,
)
if len(matched_codes) > 1:
matched_sources = [
source
_candidate_summary(source)
for code in matched_codes
for source in [build_rpa_inventory_source(code)]
if source
@@ -122,7 +129,7 @@ def resolve_inventory_source(task: ShippingTask) -> InventorySourceResolution:
return InventorySourceResolution(
status="unresolved",
source=None,
candidates=list_inventory_sources(),
candidates=[_candidate_summary(item) for item in list_inventory_sources()],
destination_candidates=candidates,
reason="no_route_rule_matched",
)
@@ -1,137 +1,217 @@
"""
services/shipping_notice/inventory_sources.py
用途:定义发货通知库存 RPA 源配置,并构造写入 trigger 的标准 rpa_inventory_source。
依赖:纯配置与校验逻辑;inventory_source_rules / inventory_rpa_workflow 调用本模块。
逻辑:第一版先用代码配置承载 DSV 360 与 Crane FootPrint 的库存入口,后续可迁移到数据库规则表。
用途:从 JSON 配置加载发货通知库存 RPA 源,并构造写入 trigger 的标准 rpa_inventory_source。
依赖:Flask current_app、pathlib/json;inventory_source_rules / inventory_rpa_workflow 调用本模块。
逻辑:新增 Warehouse 只改 backend/config/shipping_inventory_sources.json,不改 Python。
"""
from __future__ import annotations
import json
from copy import deepcopy
from pathlib import Path
from typing import Any
from flask import current_app
INVENTORY_SOURCES: dict[str, dict[str, Any]] = {
"DSV360_AWSBI": {
"source_code": "DSV360_AWSBI",
"source_type": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI",
"enabled": True,
"entry_url": "https://s360.dbschenker.com/",
"query": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv",
"owner_code": "CADU-0000000100",
},
},
"DSV360_AWSCV": {
"source_code": "DSV360_AWSCV",
"source_type": "dsv360",
"display_name": "DSV 360 / Cincinnati / AWSCV",
"enabled": True,
"entry_url": "https://s360.dbschenker.com/",
"query": {
"program_group": "Cincinnati",
"program_label": "AWSCV",
"report_group": "Inventory",
"report_name": "On Hand Inventory by Location",
"owner_code": "CACV-0000000100",
},
},
"DSV360_AWSDU": {
"source_code": "DSV360_AWSDU",
"source_type": "dsv360",
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
"enabled": True,
"entry_url": "https://s360.dbschenker.com/",
"query": {
"program_group": "Dublin",
"program_label": "AWSDU - Prod (JDA)",
"report_group": "Inventory",
"report_name": "On Hand Inventory by Location",
"owner_code": "CADU-0000000100",
},
},
"DSV360_AWSAMS": {
"source_code": "DSV360_AWSAMS",
"source_type": "dsv360",
"display_name": "DSV 360 / Moerdijk / AWSAMS",
"enabled": True,
"entry_url": "https://s360.dbschenker.com/",
"query": {
"program_group": "Moerdijk",
"program_label": "AWSAMS",
"report_group": "Inventory",
"report_name": "On Hand Inventory by Location",
"owner_code": "CADU-0000000100",
},
},
"DSV360_AWSSL": {
"source_code": "DSV360_AWSSL",
"source_type": "dsv360",
"display_name": "DSV 360 / Salt Lake City / AWSSL",
"enabled": True,
"entry_url": "https://s360.dbschenker.com/",
"query": {
"program_group": "Salt Lake City",
"program_label": "AWSSL",
"report_group": "Inventory",
"report_name": "On Hand Inventory by Location",
"owner_code": "CACV-0000000100",
},
},
"DSV360_AWSSG": {
"source_code": "DSV360_AWSSG",
"source_type": "dsv360",
"display_name": "DSV 360 / Singapore / AWSSG - Prod (JDA)",
"enabled": True,
"entry_url": "https://s360.dbschenker.com/",
"query": {
"program_group": "Singapore",
"program_label": "AWSSG - Prod (JDA)",
"report_group": "Inventory",
"report_name": "On Hand Inventory by Location",
"owner_code": "CACV-0000000100",
},
},
"CRANE_TZR2": {
"source_code": "CRANE_TZR2",
"source_type": "crane_footprint",
"display_name": "Crane FootPrint / Warehouse TZR2",
"enabled": True,
"entry_url": "https://wms-portal.craneww.com/#/on-hand-details-query",
"query": {
"owner_code": "0000000100",
"project_code": None,
"warehouse_code": "TZR2",
},
"export": {
"report_name": "On Hand Details Query",
"download_mode": "file_download",
},
},
_SITE_TO_SOURCE_TYPE = {
"dsv360": "dsv360",
"crane_footprint": "crane_footprint",
}
_VALID_PARAMETER_MODES = frozenset({"single", "multi_text", "multi_select"})
_CONFIG_CACHE: dict[str, Any] | None = None
class InventorySourceConfigError(ValueError):
"""库存源 JSON 配置校验失败。"""
def _config_path() -> Path:
"""解析库存源配置文件路径;优先 Flask config,其次默认 backend/config。"""
raw = str(current_app.config.get("SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG") or "").strip()
if raw:
path = Path(raw)
if not path.is_absolute():
from app.path_utils import resolve_backend_relative_path
path = Path(resolve_backend_relative_path(raw, path))
return path
from app.path_utils import resolve_backend_relative_path
default = Path(__file__).resolve().parents[3] / "config" / "shipping_inventory_sources.json"
return Path(resolve_backend_relative_path(None, default))
def _join_parameter_values(parameter: dict[str, Any]) -> str | None:
"""将 multi_text 参数值按 joiner 拼接为单字符串。"""
values = [str(item).strip() for item in (parameter.get("values") or []) if str(item).strip()]
if not values:
return None
joiner = str(parameter.get("joiner") or ",")
return joiner.join(values)
def _build_legacy_query(source: dict[str, Any]) -> dict[str, Any]:
"""
从 navigation + parameters 构造 worker 兼容的 query 字段。
核心逻辑:保留 DSV/Crane worker 现有读取口径,同时支持新版 parameters 驱动。
"""
navigation = dict(source.get("navigation") or {})
query: dict[str, Any] = {}
site = str(source.get("site") or "").strip().lower()
if site == "dsv360":
for key in ("program_group", "program_label", "report_group", "report_name"):
if navigation.get(key):
query[key] = navigation[key]
elif site == "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
for parameter in source.get("parameters") or []:
if not isinstance(parameter, dict):
continue
name = str(parameter.get("name") or "").strip()
mode = str(parameter.get("mode") or "single").strip().lower()
if mode == "multi_text":
joined = _join_parameter_values(parameter)
if not joined:
continue
if name.lower() == "owner":
query["owner_code"] = joined
elif name.lower() == "putawayzone":
query["putaway_zone"] = joined
elif name.lower() == "warehouse":
query["warehouse_code"] = joined
continue
values = [str(item).strip() for item in (parameter.get("values") or []) if str(item).strip()]
if not values:
continue
value = values[0]
if name.lower() == "owner":
query["owner_code"] = value
elif name.lower() == "putawayzone":
query["putaway_zone"] = value
elif name.lower() == "warehouse":
query["warehouse_code"] = value
elif name.lower() == "project":
query["project_code"] = value
return query
def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str, Any]:
"""校验并规范化单条库存源配置。"""
source_code = str(raw.get("source_code") or "").strip().upper()
if not source_code:
raise InventorySourceConfigError("source_code is required")
if source_code in seen_codes:
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")
parameters: list[dict[str, Any]] = []
for item in raw.get("parameters") or []:
if not isinstance(item, dict):
raise InventorySourceConfigError(f"{source_code}: parameters[] must be objects")
mode = str(item.get("mode") or "single").strip().lower()
if mode not in _VALID_PARAMETER_MODES:
raise InventorySourceConfigError(f"{source_code}: invalid parameter mode {mode}")
required = bool(item.get("required", False))
values = [str(v).strip() for v in (item.get("values") or []) if str(v).strip()]
if required and not values:
raise InventorySourceConfigError(f"{source_code}: required parameter {item.get('name')} has no values")
parameters.append({**item, "mode": mode, "values": values})
normalized = {
"source_code": source_code,
"source_type": _SITE_TO_SOURCE_TYPE[site],
"site": site,
"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": [
str(alias).strip()
for alias in (raw.get("match_aliases") or [])
if str(alias).strip()
],
}
if site == "crane_footprint" and raw.get("export"):
normalized["export"] = dict(raw.get("export") or {})
normalized["query"] = _build_legacy_query(normalized)
return normalized
def _load_config(*, force_reload: bool = False) -> dict[str, Any]:
"""加载并缓存 JSON 配置;force_reload 用于测试。"""
global _CONFIG_CACHE
if _CONFIG_CACHE is not None and not force_reload:
return _CONFIG_CACHE
path = _config_path()
if not path.is_file():
raise InventorySourceConfigError(f"inventory sources config not found: {path}")
payload = json.loads(path.read_text(encoding="utf-8"))
sources_raw = payload.get("sources")
if not isinstance(sources_raw, list):
raise InventorySourceConfigError("sources must be a list")
seen_codes: set[str] = set()
sources: dict[str, dict[str, Any]] = {}
for item in sources_raw:
if not isinstance(item, dict):
raise InventorySourceConfigError("each source must be an object")
normalized = _validate_source(item, seen_codes=seen_codes)
sources[normalized["source_code"]] = normalized
_CONFIG_CACHE = {
"version": int(payload.get("version") or 1),
"sources": sources,
"path": str(path),
}
return _CONFIG_CACHE
def reload_inventory_sources_config() -> dict[str, Any]:
"""强制重新加载库存源配置(管理/测试用)。"""
return _load_config(force_reload=True)
def get_inventory_source(source_code: str | None) -> dict[str, Any] | None:
"""按 source_code 返回启用的库存源配置副本。"""
code = str(source_code or "").strip().upper()
source = INVENTORY_SOURCES.get(code)
if not code:
return None
source = _load_config()["sources"].get(code)
if not source or not source.get("enabled", True):
return None
return deepcopy(source)
def list_inventory_sources() -> list[dict[str, Any]]:
"""返回所有启用库存源配置副本,供人工检查点展示候选项。"""
return [
deepcopy(source)
for source in INVENTORY_SOURCES.values()
if source.get("enabled", True)
]
def list_inventory_sources(*, enabled_only: bool = True) -> list[dict[str, Any]]:
"""返回库存源配置副本,供人工检查点展示候选项。"""
sources = _load_config()["sources"].values()
if enabled_only:
sources = [item for item in sources if item.get("enabled", True)]
return [deepcopy(item) for item in sources]
def build_rpa_inventory_source(
@@ -274,6 +274,9 @@ def _task_tool_payload(task: ShippingTask) -> dict[str, Any]:
}
raw_content = str(task.raw_content or "").strip()
lines = task.lines_json or []
from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link
payload["inventory_snapshot"] = serialize_inventory_snapshot_link(task)
# Dify 画布 LLM 字段抽取需要正文;已落库订单行后不再重复下发全文。
if raw_content and (not lines or str(task.process_status or "").strip().lower() == "created"):
limit = max_notice_chars()
@@ -283,6 +286,13 @@ def _task_tool_payload(task: ShippingTask) -> dict[str, Any]:
return payload
def _serialize_inventory_snapshot(task: ShippingTask) -> dict[str, Any] | None:
"""工作台任务摘要中的库存快照投影。"""
from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link
return serialize_inventory_snapshot_link(task)
def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str, Any]:
"""按投影类型序列化任务;TOOL 会剔除 Agent 不应复述的内部状态码。"""
from app.services.shipping_notice.rpa import rpa_runtime_mode
@@ -321,6 +331,7 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
"rpa_runtime": rpa_runtime_mode(step_payload.get("last_inventory_rpa_runtime") if isinstance(step_payload, dict) else None),
"rpa_inventory_source": step_payload.get("rpa_inventory_source") if isinstance(step_payload, dict) else None,
"inventory_source_resolution": step_payload.get("inventory_source_resolution") if isinstance(step_payload, dict) else None,
"inventory_snapshot": _serialize_inventory_snapshot(task),
"shortage": task.shortage_json,
"line_results": task.line_results_json or [],
"created_at": task.created_at.isoformat() if task.created_at else None,
@@ -96,6 +96,100 @@ def write_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None
return str(path)
def write_inventory_export_batch_trigger(
run_no: str,
sources: list[dict[str, Any]],
*,
payload: dict[str, Any] | None = None,
) -> str | None:
"""
写入批量库存导出 trigger(DSV/Crane 一次登录多 Warehouse)。
【AI 触发时机】:定时排程或后台批量预热库存快照时调用。
Args:
run_no: RPA 批次号,写入回调 audit。
sources: build_rpa_inventory_source 构造的源列表。
payload: 额外字段(trigger_type、schedule_run_id 等)。
Returns:
str | None: 触发文件绝对路径。
"""
trigger_dir = inventory_trigger_dir()
if not trigger_dir or not sources:
return None
trigger_dir.mkdir(parents=True, exist_ok=True)
inventory_sources = []
for source in sources:
if not isinstance(source, dict) or not source.get("source_code"):
continue
inventory_sources.append({
"source_code": source.get("source_code"),
"source_type": source.get("source_type"),
"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 [],
"query": source.get("query") or {},
})
if not inventory_sources:
return None
body = {
"action": "inventory_export_batch",
"run_no": run_no,
"trigger_type": "scheduled",
"requested_at": datetime.utcnow().isoformat(),
"inventory_sources": inventory_sources,
**(payload or {}),
}
safe_run = "".join(ch for ch in run_no if ch.isalnum() or ch in {"-", "_"}) or "batch"
path = trigger_dir / f"inventory_export_batch_{safe_run}.json"
path.write_text(json.dumps(body, ensure_ascii=False, indent=2), encoding="utf-8")
return str(path)
def inventory_rpa_batch_enabled() -> bool:
"""是否启用按需单票走 batch trigger 统一路径(Flask config 优先于环境变量)。"""
raw = current_app.config.get("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED")
if raw is None:
raw = os.getenv("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", "true")
return str(raw).strip().lower() in {"1", "true", "yes", "on"}
def write_inventory_export_trigger_for_task(
task_no: str,
rpa_source: dict[str, Any],
*,
payload: dict[str, Any] | None = None,
) -> str | None:
"""
写入按需库存 RPA trigger;batch 开启时包装为单源 batch trigger,与定时导出共用 worker 路径。
【AI 触发时机】:ensure_inventory_via_rpa 触发单票 RPA 导出时调用。
核心逻辑:batch 模式写 inventory_export_batch(含 task_no);否则写 legacy inventory_export。
"""
body = dict(payload or {})
if inventory_rpa_batch_enabled():
run_no = f"TASK-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S')}"
return write_inventory_export_batch_trigger(
run_no,
[rpa_source],
payload={
"trigger_type": "on_demand",
"task_no": task_no,
**body,
},
)
return write_inventory_export_trigger(
task_no,
{
"rpa_inventory_source": rpa_source,
**body,
},
)
def write_upload_trigger(task_no: str, export_file_path: str, payload: dict[str, Any] | None = None) -> tuple[str | None, str | None]:
"""
复制 Excel 至上传队列并写入 RPA 上传触发 JSON。
@@ -56,7 +56,7 @@ def auto_rpa_inventory_enabled() -> bool:
def rpa_inventory_timeout_seconds() -> int:
"""RPA 库存导出等待超时秒数。"""
return cfg_int("SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS", 360, min_value=5)
return cfg_int("SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS", 900, min_value=5)
def auto_mapping_allow_llm() -> bool:
@@ -31,6 +31,7 @@ get_inventory_schema_preview = inventory_workflow.get_inventory_schema_preview
apply_inventory_mapping = inventory_workflow.apply_inventory_mapping
upload_inventory_file = inventory_workflow.upload_inventory_file
rpa_report_inventory = inventory_rpa_workflow.rpa_report_inventory
rpa_report_inventory_batch = inventory_rpa_workflow.rpa_report_inventory_batch
confirm_inventory_source = inventory_rpa_workflow.confirm_inventory_source
# 履约阶段
@@ -85,6 +85,7 @@ _BLOCKED_CHECKPOINTS = {
CP_ALIGN_REVIEW,
RS_SHORTAGE_REVIEW,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_UPLOAD_REQ,
CP_UPLOAD_FAILED,
}
@@ -142,6 +143,7 @@ def build_shipping_workflow_steps(task: ShippingTask, checkpoint: str | None) ->
"""
current_index = _derive_current_step_index(task)
process_status = str(task.process_status or "").strip()
pending_reason = str(task.pending_human_reason or "").strip()
checkpoint_value = str(checkpoint or "").strip()
steps: list[dict[str, str]] = []
for index, step in enumerate(WORKFLOW_STEPS):
@@ -153,7 +155,11 @@ def build_shipping_workflow_steps(task: ShippingTask, checkpoint: str | None) ->
status = "current"
else:
status = "pending"
if index == current_index and checkpoint_value in _BLOCKED_CHECKPOINTS:
inventory_blocked = (
index == 2
and pending_reason in {PH_INV_UNAVAIL, PH_RPA_EXHAUSTED}
)
if index == current_index and (checkpoint_value in _BLOCKED_CHECKPOINTS or inventory_blocked):
status = "blocked"
steps.append({**step, "status": status})
return steps