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
@@ -0,0 +1,923 @@
{
"version": 1,
"sources": [
{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"warehouse_code": "BYAWSATL01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSATL01"
],
"required": true
}
],
"match_aliases": [
"BYAWSATL01",
"ATL01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSAVP01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSAVP01",
"warehouse_id": "BYAWSAVP01",
"warehouse_code": "BYAWSAVP01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSAVP01"
],
"required": true
}
],
"match_aliases": [
"BYAWSAVP01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSAZA01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSAZA01",
"warehouse_id": "BYAWSAZA01",
"warehouse_code": "BYAWSAZA01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSAZA01"
],
"required": true
}
],
"match_aliases": [
"BYAWSAZA01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSCMH01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSCMH01",
"warehouse_id": "BYAWSCMH01",
"warehouse_code": "BYAWSCMH01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSCMH01"
],
"required": true
}
],
"match_aliases": [
"BYAWSCMH01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSCMN01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSCMN01",
"warehouse_id": "BYAWSCMN01",
"warehouse_code": "BYAWSCMN01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSCMN01"
],
"required": true
}
],
"match_aliases": [
"BYAWSCMN01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSEZE01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSEZE01",
"warehouse_id": "BYAWSEZE01",
"warehouse_code": "BYAWSEZE01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSEZE01"
],
"required": true
}
],
"match_aliases": [
"BYAWSEZE01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSFRA01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSFRA01",
"warehouse_id": "BYAWSFRA01",
"warehouse_code": "BYAWSFRA01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSFRA01"
],
"required": true
}
],
"match_aliases": [
"BYAWSFRA01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSGRU01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSGRU01",
"warehouse_id": "BYAWSGRU01",
"warehouse_code": "BYAWSGRU01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSGRU01"
],
"required": true
}
],
"match_aliases": [
"BYAWSGRU01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSIAD01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSIAD01",
"warehouse_id": "BYAWSIAD01",
"warehouse_code": "BYAWSIAD01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSIAD01"
],
"required": true
}
],
"match_aliases": [
"BYAWSIAD01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSJAN01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSJAN01",
"warehouse_id": "BYAWSJAN01",
"warehouse_code": "BYAWSJAN01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSJAN01"
],
"required": true
}
],
"match_aliases": [
"BYAWSJAN01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSLTN01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSLTN01",
"warehouse_id": "BYAWSLTN01",
"warehouse_code": "BYAWSLTN01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSLTN01"
],
"required": true
}
],
"match_aliases": [
"BYAWSLTN01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSMEL01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSMEL01",
"warehouse_id": "BYAWSMEL01",
"warehouse_code": "BYAWSMEL01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSMEL01"
],
"required": true
}
],
"match_aliases": [
"BYAWSMEL01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSNRT01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSNRT01",
"warehouse_id": "BYAWSNRT01",
"warehouse_code": "BYAWSNRT01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSNRT01"
],
"required": true
}
],
"match_aliases": [
"BYAWSNRT01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSPHX01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSPHX01",
"warehouse_id": "BYAWSPHX01",
"warehouse_code": "BYAWSPHX01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSPHX01"
],
"required": true
}
],
"match_aliases": [
"BYAWSPHX01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSPNE01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSPNE01",
"warehouse_id": "BYAWSPNE01",
"warehouse_code": "BYAWSPNE01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSPNE01"
],
"required": true
}
],
"match_aliases": [
"BYAWSPNE01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSPRD01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSPRD01",
"warehouse_id": "BYAWSPRD01",
"warehouse_code": "BYAWSPRD01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSPRD01"
],
"required": true
}
],
"match_aliases": [
"BYAWSPRD01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSPSC01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSPSC01",
"warehouse_id": "BYAWSPSC01",
"warehouse_code": "BYAWSPSC01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSPSC01"
],
"required": true
}
],
"match_aliases": [
"BYAWSPSC01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSQRO01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSQRO01",
"warehouse_id": "BYAWSQRO01",
"warehouse_code": "BYAWSQRO01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSQRO01"
],
"required": true
}
],
"match_aliases": [
"BYAWSQRO01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSRIC01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSRIC01",
"warehouse_id": "BYAWSRIC01",
"warehouse_code": "BYAWSRIC01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSRIC01"
],
"required": true
}
],
"match_aliases": [
"BYAWSRIC01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSRNO01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSRNO01",
"warehouse_id": "BYAWSRNO01",
"warehouse_code": "BYAWSRNO01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSRNO01"
],
"required": true
}
],
"match_aliases": [
"BYAWSRNO01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSRUH01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSRUH01",
"warehouse_id": "BYAWSRUH01",
"warehouse_code": "BYAWSRUH01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSRUH01"
],
"required": true
}
],
"match_aliases": [
"BYAWSRUH01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSSBN01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSSBN01",
"warehouse_id": "BYAWSSBN01",
"warehouse_code": "BYAWSSBN01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSSBN01"
],
"required": true
}
],
"match_aliases": [
"BYAWSSBN01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSSCL01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSSCL01",
"warehouse_id": "BYAWSSCL01",
"warehouse_code": "BYAWSSCL01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSSCL01"
],
"required": true
}
],
"match_aliases": [
"BYAWSSCL01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSYYZ01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSYYZ01",
"warehouse_id": "BYAWSYYZ01",
"warehouse_code": "BYAWSYYZ01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSYYZ01"
],
"required": true
}
],
"match_aliases": [
"BYAWSYYZ01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSZAZ01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSZAZ01",
"warehouse_id": "BYAWSZAZ01",
"warehouse_code": "BYAWSZAZ01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSZAZ01"
],
"required": true
}
],
"match_aliases": [
"BYAWSZAZ01"
]
},
{
"source_code": "DSV360_AWSCV",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Cincinnati / AWSCV",
"warehouse_id": "AWSCV",
"warehouse_code": "AWSCV",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Cincinnati",
"program_label": "AWSCV",
"report_group": "Inventory",
"report_name": "On Hand Inventory by Location"
},
"parameters": [
{
"name": "Owner",
"selector_env": "FREIGHT_RPA_DSV_OWNER_SELECTOR",
"mode": "single",
"values": [
"CACV-0000000100"
],
"required": true
}
],
"match_aliases": [
"CINCINNATI",
"CVG",
"AWSCV"
]
},
{
"source_code": "DSV360_AWSDU",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
"warehouse_id": "AWSDU",
"warehouse_code": "AWSDU",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Dublin",
"program_label": "AWSDU - Prod (JDA)",
"report_group": "Inventory",
"report_name": "On Hand Inventory by Location"
},
"parameters": [
{
"name": "Owner",
"selector_env": "FREIGHT_RPA_DSV_OWNER_SELECTOR",
"mode": "single",
"values": [
"CADU-0000000100"
],
"required": true
}
],
"match_aliases": [
"DBS DUB",
"DUB",
"DUBLIN"
]
},
{
"source_code": "DSV360_AWSAMS",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Moerdijk / AWSAMS",
"warehouse_id": "AWSAMS",
"warehouse_code": "AWSAMS",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Moerdijk",
"program_label": "AWSAMS",
"report_group": "Inventory",
"report_name": "On Hand Inventory by Location"
},
"parameters": [
{
"name": "Owner",
"selector_env": "FREIGHT_RPA_DSV_OWNER_SELECTOR",
"mode": "single",
"values": [
"CADU-0000000100"
],
"required": true
}
],
"match_aliases": [
"MOERDIJK",
"AMS",
"AWSAMS"
]
},
{
"source_code": "DSV360_AWSSL",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Salt Lake City / AWSSL",
"warehouse_id": "AWSSL",
"warehouse_code": "AWSSL",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Salt Lake City",
"program_label": "AWSSL",
"report_group": "Inventory",
"report_name": "On Hand Inventory by Location"
},
"parameters": [
{
"name": "Owner",
"selector_env": "FREIGHT_RPA_DSV_OWNER_SELECTOR",
"mode": "single",
"values": [
"CACV-0000000100"
],
"required": true
}
],
"match_aliases": [
"USLCK",
"SALT LAKE CITY",
"SALTLAKECITY"
]
},
{
"source_code": "DSV360_AWSSG",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Singapore / AWSSG - Prod (JDA)",
"warehouse_id": "AWSSG",
"warehouse_code": "AWSSG",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Singapore",
"program_label": "AWSSG - Prod (JDA)",
"report_group": "Inventory",
"report_name": "On Hand Inventory by Location"
},
"parameters": [
{
"name": "Owner",
"selector_env": "FREIGHT_RPA_DSV_OWNER_SELECTOR",
"mode": "single",
"values": [
"CACV-0000000100"
],
"required": true
}
],
"match_aliases": [
"SINGAPORE HUB",
"SINGAPORE",
"SG"
]
},
{
"source_code": "CRANE_TZR2",
"enabled": true,
"site": "crane_footprint",
"display_name": "Crane FootPrint / Warehouse TZR2",
"warehouse_id": "TZR2",
"warehouse_code": "TZR2",
"entry_url": "https://wms-portal.craneww.com/#/on-hand-details-query",
"navigation": {
"report_name": "On Hand Details Query",
"download_mode": "file_download"
},
"parameters": [
{
"name": "Owner",
"selector_env": "FREIGHT_RPA_CRANE_OWNER_SELECTOR",
"mode": "single",
"values": [
"0000000100"
],
"required": true
},
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_CRANE_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"TZR2"
],
"required": true
}
],
"match_aliases": [
"TZR2",
"THAILAND"
]
}
]
}
@@ -0,0 +1,84 @@
"""Add shipping inventory snapshot source and audit fields.
Purpose:
Support warehouse-level inventory snapshots, TTL reuse, scheduled RPA runs,
and task-to-snapshot audit links.
Dependencies:
Alembic revision b3c4d5e6f7a8.
Flow:
RPA batch callback writes source_code/warehouse_id/expires_at on
shipping_inventory_files; task links record reuse reason and age.
Revision ID: a8b9c0d1e2f3
Revises: b3c4d5e6f7a8
Create Date: 2026-07-07 19:30:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = "a8b9c0d1e2f3"
down_revision = "b3c4d5e6f7a8"
branch_labels = None
depends_on = None
def upgrade():
"""Add inventory snapshot source metadata and link audit columns."""
with op.batch_alter_table("shipping_inventory_files", schema=None) as batch_op:
batch_op.add_column(sa.Column("warehouse_id", sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column("warehouse_code", sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column("source_code", sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column("source_type", sa.String(length=32), nullable=True))
batch_op.add_column(sa.Column("snapshot_status", sa.String(length=32), nullable=True))
batch_op.add_column(sa.Column("exported_at", sa.DateTime(), nullable=True))
batch_op.add_column(sa.Column("expires_at", sa.DateTime(), nullable=True))
batch_op.add_column(sa.Column("rpa_run_no", sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column("schedule_run_id", sa.Integer(), nullable=True))
batch_op.add_column(sa.Column("source_query_json", sa.JSON(), nullable=True))
batch_op.create_index("ix_shipping_inventory_files_warehouse_id", ["warehouse_id"], unique=False)
batch_op.create_index("ix_shipping_inventory_files_source_code", ["source_code"], unique=False)
batch_op.create_index("ix_shipping_inventory_files_snapshot_status", ["snapshot_status"], unique=False)
batch_op.create_index("ix_shipping_inventory_files_exported_at", ["exported_at"], unique=False)
batch_op.create_index("ix_shipping_inventory_files_expires_at", ["expires_at"], unique=False)
batch_op.create_index("ix_shipping_inventory_files_schedule_run_id", ["schedule_run_id"], unique=False)
batch_op.create_index(
"ix_shipping_inventory_files_source_snapshot",
["source_code", "warehouse_id", "snapshot_status", "exported_at"],
unique=False,
)
with op.batch_alter_table("shipping_task_inventory_links", schema=None) as batch_op:
batch_op.add_column(sa.Column("link_reason", sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column("matched_warehouse_id", sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column("snapshot_age_seconds", sa.Integer(), nullable=True))
batch_op.add_column(sa.Column("audit_payload_json", sa.JSON(), nullable=True))
def downgrade():
"""Remove inventory snapshot source metadata and link audit columns."""
with op.batch_alter_table("shipping_task_inventory_links", schema=None) as batch_op:
batch_op.drop_column("audit_payload_json")
batch_op.drop_column("snapshot_age_seconds")
batch_op.drop_column("matched_warehouse_id")
batch_op.drop_column("link_reason")
with op.batch_alter_table("shipping_inventory_files", schema=None) as batch_op:
batch_op.drop_index("ix_shipping_inventory_files_source_snapshot")
batch_op.drop_index("ix_shipping_inventory_files_schedule_run_id")
batch_op.drop_index("ix_shipping_inventory_files_expires_at")
batch_op.drop_index("ix_shipping_inventory_files_exported_at")
batch_op.drop_index("ix_shipping_inventory_files_snapshot_status")
batch_op.drop_index("ix_shipping_inventory_files_source_code")
batch_op.drop_index("ix_shipping_inventory_files_warehouse_id")
batch_op.drop_column("source_query_json")
batch_op.drop_column("schedule_run_id")
batch_op.drop_column("rpa_run_no")
batch_op.drop_column("expires_at")
batch_op.drop_column("exported_at")
batch_op.drop_column("snapshot_status")
batch_op.drop_column("source_type")
batch_op.drop_column("source_code")
batch_op.drop_column("warehouse_code")
batch_op.drop_column("warehouse_id")
+114
View File
@@ -0,0 +1,114 @@
"""scripts/rpa/dsv_report_parameters.py 单元测试。"""
from __future__ import annotations
import importlib.util
from pathlib import Path
def _load_module():
path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "dsv_report_parameters.py"
spec = importlib.util.spec_from_file_location("dsv_report_parameters_test", path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def test_fill_dsv_owner_filter_defaults_to_reportviewer_owner_input():
"""Owner 未配置 selector 时,应写入 ReportViewer Owner 文本框。"""
module = _load_module()
filled: dict[str, str] = {}
class _FakeText:
first = None
def __init__(self) -> None:
self.first = self
def is_visible(self, timeout: int | None = None) -> bool:
return False
class _FakeFrame:
def evaluate(self, script: str, payload: dict[str, str], timeout: int | None = None) -> bool:
assert "disabled = false" in script
filled[payload["selector"]] = payload["value"]
return True
class _FakePage:
frames = [_FakeFrame()]
def get_by_text(self, text: str, exact: bool = False) -> _FakeText:
return _FakeText()
module.fill_dsv_filter_if_needed(
_FakePage(),
"FREIGHT_RPA_DSV_OWNER_SELECTOR",
"Owner",
"CADU-0000000100",
env=lambda name, default="": default,
browser_timeout_ms=lambda: 3_000,
)
assert filled == {"#ReportViewerMain_ctl08_ctl03_txtValue": "CADU-0000000100"}
def test_fill_dsv_warehouse_select_uses_default_ddvalue():
"""Warehouse 未配置 selector 时,应对 ReportViewer select 执行 select_option。"""
module = _load_module()
selected: dict[str, str] = {}
class _FakeLocator:
first = None
def __init__(self) -> None:
self.first = self
def wait_for(self, *args, **kwargs) -> None:
return None
def evaluate(self, script: str, value: str | None = None):
if value is not None and "removeAttribute" in script:
selected["value"] = value
return True
if "realOptionCount" in script:
return {
"hasTarget": True,
"enabled": False,
"optionCount": 26,
"realOptionCount": 25,
}
if "aspNetDisabled" in script and "hasTarget" not in script:
return True
return False
def select_option(self, *, label: str, timeout: int) -> None:
selected["label"] = label
class _FakeReportRootLocator:
def count(self) -> int:
return 1
class _FakeFrame:
def locator(self, selector: str) -> _FakeLocator | _FakeReportRootLocator:
if selector == "#ReportViewerMain":
return _FakeReportRootLocator()
assert selector == "#ReportViewerMain_ctl08_ctl17_ddValue"
return _FakeLocator()
class _FakePage:
frames = [_FakeFrame()]
def get_by_text(self, text: str, exact: bool = False):
raise RuntimeError("not visible")
module.fill_dsv_filter_if_needed(
_FakePage(),
"FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"Warehouse",
"BYAWSATL01",
env=lambda name, default="": default,
browser_timeout_ms=lambda: 3_000,
)
assert selected.get("value") == "BYAWSATL01" or selected.get("label") == "BYAWSATL01"
+73 -10
View File
@@ -367,7 +367,7 @@ def test_maybe_auto_login_dsv_does_not_retry_username_when_method_page_ready(mon
monkeypatch.setattr(worker, "_click_dsv_continue", lambda current_page, locator=None: True)
monkeypatch.setattr(worker, "_fill_dsv_password_page_fields", lambda current_page, username, password: False)
monkeypatch.setattr(worker, "_wait_for_dsv_human_check_if_present", lambda current_page, timeout_ms=None: None)
monkeypatch.setattr(worker, "_wait_for_dsv_app_after_login", lambda current_page, timeout_ms=None: False)
monkeypatch.setattr(worker, "_wait_for_dsv_app_after_login", lambda current_page, timeout_ms=None, on_portal_shell_seen=None: False)
monkeypatch.setattr(worker, "_wait_for_dsv_login_method_page", lambda current_page, timeout_ms=None: True)
monkeypatch.setattr(
worker,
@@ -469,7 +469,7 @@ def test_maybe_auto_login_dsv_waits_before_retrying_username_page(monkeypatch):
monkeypatch.setattr(worker, "_click_dsv_continue", lambda current_page, locator=None: True)
monkeypatch.setattr(worker, "_fill_dsv_password_page_fields", lambda current_page, username, password: False)
monkeypatch.setattr(worker, "_wait_for_dsv_human_check_if_present", lambda current_page, timeout_ms=None: None)
monkeypatch.setattr(worker, "_wait_for_dsv_app_after_login", lambda current_page, timeout_ms=None: False)
monkeypatch.setattr(worker, "_wait_for_dsv_app_after_login", lambda current_page, timeout_ms=None, on_portal_shell_seen=None: False)
monkeypatch.setattr(worker, "_wait_for_dsv_login_method_page", lambda current_page, timeout_ms=None: False)
def fake_is_username_page(current_page) -> bool:
@@ -1148,8 +1148,10 @@ def test_wait_for_dsv_home_ready_skips_duplicate_upgrade_prompt_check(monkeypatc
def _fake_is_home_ready(page) -> bool:
return ready_state["value"]
def _fake_wait_for_app_after_login(page, timeout_ms=None) -> bool:
def _fake_wait_for_app_after_login(page, timeout_ms=None, on_portal_shell_seen=None) -> bool:
ready_state["value"] = True
if on_portal_shell_seen is not None:
on_portal_shell_seen()
return True
monkeypatch.setattr(worker, "_dismiss_dsv_password_upgrade_prompt", lambda page: dismiss_calls.__setitem__("value", dismiss_calls["value"] + 1))
@@ -1209,9 +1211,26 @@ def test_wait_for_dsv_app_after_login_accepts_attached_portal_shell(monkeypatch)
worker = _load_freight_rpa_worker()
class _FakeNavLocator:
first = None
def __init__(self) -> None:
self.first = self
def count(self) -> int:
return 1
def is_visible(self, timeout: int | None = None) -> bool:
return False
class _FakeEmptyLocator:
first = None
def __init__(self) -> None:
self.first = self
def count(self) -> int:
return 0
class _FakePage:
url = "https://s360.dbschenker.com/main/portal"
frames: list[object] = []
@@ -1219,14 +1238,14 @@ def test_wait_for_dsv_app_after_login_accepts_attached_portal_shell(monkeypatch)
def title(self) -> str:
return "360°"
def locator(self, selector: str) -> _FakeNavLocator:
assert selector == "#report-mega-legacy"
return _FakeNavLocator()
def locator(self, selector: str):
if selector.startswith("#report-mega-legacy") or "Reports" in selector:
return _FakeNavLocator()
return _FakeEmptyLocator()
def wait_for_load_state(self, state: str, timeout: int | None = None) -> None:
return None
monkeypatch.setattr(worker, "_wait_for_visible_selector", lambda *args, **kwargs: None)
monkeypatch.setattr(worker, "_debug_dsv_stage", lambda *args, **kwargs: None)
monkeypatch.setattr(worker, "_report_debug_event", lambda *args, **kwargs: None)
@@ -1238,20 +1257,64 @@ def test_is_dsv_home_ready_accepts_attached_portal_shell(monkeypatch):
worker = _load_freight_rpa_worker()
class _FakeNavLocator:
first = None
def __init__(self) -> None:
self.first = self
def count(self) -> int:
return 1
def is_visible(self, timeout: int | None = None) -> bool:
return False
class _FakeEmptyLocator:
first = None
def __init__(self) -> None:
self.first = self
def count(self) -> int:
return 0
class _FakePage:
url = "https://s360.dbschenker.com/main/portal"
frames: list[object] = []
def locator(self, selector: str):
if selector.startswith("#report-mega-legacy") or "Reports" in selector:
return _FakeNavLocator()
return _FakeEmptyLocator()
assert worker._is_dsv_home_ready(_FakePage()) is True
def test_is_dsv_home_ready_rejects_iframe_shell_without_report_nav(monkeypatch):
"""仅有 dashboard iframe 欢迎语、顶栏 Reports DOM 未挂载时,不应判定 home-ready。"""
worker = _load_freight_rpa_worker()
class _FakeNavLocator:
def count(self) -> int:
return 0
class _FakeBodyLocator:
def inner_text(self, timeout: int | None = None) -> str:
return "Welcome back! Recent Reports On Hand Inventory"
class _FakeFrame:
def locator(self, selector: str) -> _FakeBodyLocator:
assert selector == "body"
return _FakeBodyLocator()
class _FakePage:
url = "https://s360.dbschenker.com/main/portal"
frames = [_FakeFrame()]
def locator(self, selector: str) -> _FakeNavLocator:
assert selector == "#report-mega-legacy"
return _FakeNavLocator()
monkeypatch.setattr(worker, "_wait_for_visible_selector", lambda *args, **kwargs: None)
assert worker._is_dsv_home_ready(_FakePage()) is True
assert worker._is_dsv_home_ready(_FakePage()) is False
def test_wait_for_dsv_report_form_ready_accepts_report_shell_without_title(monkeypatch):
@@ -0,0 +1,252 @@
"""freight_rpa_worker 参数填充与单票/批量路径统一测试。"""
from __future__ import annotations
import importlib.util
from pathlib import Path
from unittest.mock import MagicMock
def _load_worker():
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "freight_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_param_test", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def test_fill_report_parameter_multi_select(monkeypatch):
"""multi_select 应对每个值尝试多选填充,而非只取第一个。"""
worker = _load_worker()
page = MagicMock()
calls: list[tuple[str, str, list[str]]] = []
def _fake_multi(page_arg, selector_env, label, values):
calls.append((selector_env, label, list(values)))
monkeypatch.setattr(worker, "_fill_dsv_multi_select", _fake_multi)
worker._fill_report_parameter(
page,
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "multi_select",
"values": ["WH1", "WH2"],
},
)
assert calls == [("FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR", "Warehouse", ["WH1", "WH2"])]
def test_download_dsv360_inventory_delegates_to_shared_export(monkeypatch):
"""单票 DSV 导出应走与批量相同的 session + export 函数。"""
worker = _load_worker()
page = MagicMock()
source = {
"entry_url": "https://s360.dbschenker.com/",
"source_code": "DSV360_AWSDU",
"parameters": [{"name": "Warehouse", "mode": "single", "values": ["AWSDU"], "selector_env": "X"}],
}
monkeypatch.setattr(worker, "_ensure_dsv_session", MagicMock())
export_mock = MagicMock(return_value="download")
monkeypatch.setattr(worker, "_export_dsv_inventory_source", export_mock)
result = worker._download_dsv360_inventory(page, {"task_no": "SN-1"}, source)
worker._ensure_dsv_session.assert_called_once_with(page, "https://s360.dbschenker.com/")
export_mock.assert_called_once_with(page, {"task_no": "SN-1"}, source)
assert result == "download"
def test_reset_dsv_export_entry_goes_home_without_forcing_login(monkeypatch):
"""批量 navigation 变化时应 goto entry 并检测 session。"""
worker = _load_worker()
page = MagicMock()
login = MagicMock()
home = MagicMock()
nav = MagicMock()
monkeypatch.setattr(worker, "_maybe_auto_login_dsv", login)
monkeypatch.setattr(worker, "_wait_for_dsv_home_ready", home)
monkeypatch.setattr(worker, "_wait_for_dsv_reports_nav_stable", nav)
worker._reset_dsv_export_entry(page, "https://s360.dbschenker.com/")
page.goto.assert_called_once()
login.assert_called_once_with(page)
home.assert_called_once()
nav.assert_called_once()
def test_dsv_sources_share_navigation_when_program_report_match():
"""同 program/report 导航的 AWSBI 子仓应判定为可复用参数页。"""
worker = _load_worker()
nav = {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv",
}
prev = {"navigation": nav, "query": dict(nav), "warehouse_id": "BYAWSATL01"}
curr = {"navigation": nav, "query": {**nav, "warehouse_code": "BYAWSCMH01"}, "warehouse_id": "BYAWSCMH01"}
assert worker._dsv_sources_share_navigation(prev, curr) is True
def test_prepare_dsv_batch_export_reuses_parameter_form_when_navigation_matches(monkeypatch):
"""同 navigation 的第二步应 reload 参数页而非 reset 首页。"""
worker = _load_worker()
page = MagicMock()
ensure = MagicMock()
reset = MagicMock()
reuse = MagicMock()
monkeypatch.setattr(worker, "_ensure_dsv_session", ensure)
monkeypatch.setattr(worker, "_reset_dsv_export_entry", reset)
monkeypatch.setattr(worker, "_return_to_dsv_report_parameters", reuse)
nav = {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv",
}
prev = {"navigation": nav, "query": dict(nav)}
curr = {"navigation": nav, "query": {**nav, "warehouse_code": "BYAWSCMH01"}}
assert worker._prepare_dsv_batch_export_step(page, "https://s360.dbschenker.com/", None, curr, index=0) is False
ensure.assert_called_once()
assert worker._prepare_dsv_batch_export_step(page, "https://s360.dbschenker.com/", prev, curr, index=1) is True
reuse.assert_called_once()
reset.assert_not_called()
def test_prepare_dsv_batch_export_resets_home_when_navigation_differs(monkeypatch):
"""program/report 变化时仍应回 portal 首页。"""
worker = _load_worker()
page = MagicMock()
reset = MagicMock()
reuse = MagicMock()
monkeypatch.setattr(worker, "_reset_dsv_export_entry", reset)
monkeypatch.setattr(worker, "_return_to_dsv_report_parameters", reuse)
prev = {
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv",
}
}
curr = {
"navigation": {
"program_group": "Cincinnati",
"program_label": "AWSCV",
"report_group": "Inventory",
"report_name": "On Hand Inventory by Location",
}
}
assert worker._prepare_dsv_batch_export_step(page, "https://s360.dbschenker.com/", prev, curr, index=1) is False
reset.assert_called_once()
reuse.assert_not_called()
def test_reset_dsv_export_entry_skips_login_when_session_active(monkeypatch):
"""同 entry_url 且 session 有效时 reset 不应再触发 auto_login。"""
worker = _load_worker()
page = MagicMock()
login = MagicMock()
home = MagicMock()
nav = MagicMock()
monkeypatch.setattr(worker, "_is_dsv_session_active", MagicMock(return_value=True))
monkeypatch.setattr(worker, "_is_dsv_home_ready", MagicMock(return_value=True))
monkeypatch.setattr(worker, "_maybe_auto_login_dsv", login)
monkeypatch.setattr(worker, "_wait_for_dsv_home_ready", home)
monkeypatch.setattr(worker, "_wait_for_dsv_reports_nav_stable", nav)
worker._reset_dsv_export_entry(page, "https://s360.dbschenker.com/")
page.goto.assert_not_called()
login.assert_not_called()
home.assert_called_once()
nav.assert_called_once()
def test_ensure_dsv_session_skips_login_when_session_active(monkeypatch):
"""batch 首条前若 session 已有效,ensure 不应 goto + login。"""
worker = _load_worker()
page = MagicMock()
login = MagicMock()
home = MagicMock()
nav = MagicMock()
monkeypatch.setattr(worker, "_is_dsv_session_active", MagicMock(return_value=True))
monkeypatch.setattr(worker, "_maybe_auto_login_dsv", login)
monkeypatch.setattr(worker, "_wait_for_dsv_home_ready", home)
monkeypatch.setattr(worker, "_wait_for_dsv_reports_nav_stable", nav)
worker._ensure_dsv_session(page, "https://s360.dbschenker.com/")
page.goto.assert_not_called()
login.assert_not_called()
home.assert_called_once()
nav.assert_called_once()
def test_prepare_dsv_batch_reuses_form_for_different_source_code_same_entry(monkeypatch):
"""source_code 不同但 navigation/entry_url 一致时,第二步应复用参数页且不 reset 登录。"""
worker = _load_worker()
page = MagicMock()
ensure = MagicMock()
reset = MagicMock()
reuse = MagicMock()
monkeypatch.setattr(worker, "_ensure_dsv_session", ensure)
monkeypatch.setattr(worker, "_reset_dsv_export_entry", reset)
monkeypatch.setattr(worker, "_return_to_dsv_report_parameters", reuse)
nav = {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv",
}
prev = {
"source_code": "DSV360_AWSBI_BYAWSATL01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": nav,
"query": {**nav, "warehouse_code": "BYAWSATL01"},
}
curr = {
"source_code": "DSV360_AWSBI_BYAWSCMH01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": nav,
"query": {**nav, "warehouse_code": "BYAWSCMH01"},
}
assert worker._prepare_dsv_batch_export_step(
page, "https://s360.dbschenker.com/", prev, curr, index=1
) is True
reuse.assert_called_once()
reset.assert_not_called()
ensure.assert_not_called()
def test_is_dsv_oauth_handshake_url_detects_pingfederate_page():
"""authorization.oauth2 应识别为 OAuth 握手中间页。"""
worker = _load_worker()
url = (
"https://auth.dbschenker.com/as/authorization.oauth2?"
"response_type=code&client_id=contract-logistics-360"
)
assert worker._is_dsv_oauth_handshake_url(url) is True
assert worker._is_dsv_auth_ping_url("https://auth.dbschenker.com/as/x/resume/as/authorization.ping") is True
assert worker._is_dsv_oauth_handshake_url("https://auth.dbschenker.com/as/ntdo0/resume/as/authorization.ping") is False
def test_goto_dsv_entry_url_tolerates_domcontentloaded_timeout_on_auth_redirect(monkeypatch):
"""goto 超时但已跳转到 auth 域时不应抛错。"""
worker = _load_worker()
page = MagicMock()
page.url = "https://auth.dbschenker.com/as/authorization.oauth2?response_type=code"
def _raise_timeout(*args, **kwargs):
raise TimeoutError("Page.goto: Timeout 60000ms exceeded.")
page.goto.side_effect = _raise_timeout
worker._goto_dsv_entry_url(page, "https://s360.dbschenker.com/")
page.goto.assert_called_once()
@@ -667,6 +667,11 @@ def test_auto_progress_inventory_trigger_failure_marks_step3(app, tmp_path):
assert task.pending_human_reason == "inv_unavail"
assert task.current_step == "step3_inventory_prepare"
assert task.step_payload_json["current_step_progress"]["status"] == "needs_human"
from app.services.shipping_notice.ui_state import build_task_ui_state
ui_state = build_task_ui_state(task)
inventory_step = next(step for step in ui_state["steps"] if step["code"] == "inventory_prepare")
assert inventory_step["status"] == "blocked"
def test_workspace_task_detail_is_read_only_for_timed_out_inventory_rpa(app, client, tmp_path):
@@ -771,7 +776,7 @@ def test_inventory_source_rules_cover_dsv360_programs(app):
from app.services.shipping_notice.inventory_source_rules import resolve_inventory_source
cases = [
("Bison", "DSV360_AWSBI"),
("BYAWSATL01", "DSV360_AWSBI_BYAWSATL01"),
("Cincinnati", "DSV360_AWSCV"),
("Moerdijk", "DSV360_AWSAMS"),
]
@@ -871,8 +876,8 @@ def test_inventory_source_review_chat_actions_do_not_list_all_sources(app):
"status": "unresolved",
"candidates": [
{
"source_code": "DSV360_AWSBI",
"display_name": "DSV 360 / Bison / AWSBI",
"source_code": "DSV360_AWSBI_BYAWSATL01",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSATL01",
},
{
"source_code": "DSV360_AWSDU",
@@ -27,7 +27,7 @@ def test_inventory_rpa_single_attempt_messages_hide_fraction():
assert _inventory_rpa_attempt_label(attempt_no=1, max_attempts=1, manual_retry_round=False) == "当前配置为单次自动尝试"
assert _inventory_rpa_running_prefix(attempt_no=1, max_attempts=1) == "库存获取进行中。"
assert _inventory_rpa_triggered_prefix(attempt_no=1, max_attempts=1, manual_retry_round=False) == "已触发库存获取。"
assert _inventory_rpa_attempt_label(attempt_no=1, max_attempts=1, manual_retry_round=True) == "手动第 1 次尝试"
assert _inventory_rpa_attempt_label(attempt_no=1, max_attempts=1, manual_retry_round=True) == "已手动重新触发库存获取"
assert _inventory_rpa_running_message(attempt_no=1, max_attempts=1) == "库存获取进行中。请稍后刷新状态;若长时间无结果,可改为上传库存 Excel。"
assert _inventory_rpa_triggered_message(
attempt_no=1,
@@ -42,6 +42,7 @@ def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path):
trigger.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
@@ -159,6 +160,7 @@ def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path):
trigger.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
with app.app_context():
task = ShippingTask(
@@ -196,4 +198,7 @@ def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path):
assert task.step_payload_json["current_step_progress"]["detail"] == "当前配置为单次自动尝试"
events = ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").all()
assert len(events) == 1
assert list(trigger.glob("inventory_export_SN-CONFIRM-SOURCE-RPA*.json"))
assert (
list(trigger.glob("inventory_export_SN-CONFIRM-SOURCE-RPA*.json"))
or list(trigger.glob("inventory_export_batch_TASK-SN-CONFIRM-SOURCE-RPA*.json"))
)
@@ -0,0 +1,41 @@
"""shipping_notice 库存 RPA 定时排程 executor 测试。"""
from app.models import ScheduleRun, ScheduleTask, User
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
def test_shipping_inventory_rpa_schedule_writes_batch_trigger(app, tmp_path):
"""排程 executor 应写入 inventory_export_batch trigger。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
user = User(username="schedule_inv_user", email="schedule_inv_user@example.com")
from app import db
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no="SCH-INV-001",
name="货代库存每日导出",
owner_user_id=user.id,
cron_expr="0 3 * * *",
data_source_type="shipping_inventory_rpa",
enabled=True,
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(
run_no="RUN20260707030000",
schedule_task_id=task.id,
status="running",
)
db.session.add(run)
db.session.commit()
total, success, failed, skipped, details, errors, logs = run_shipping_inventory_rpa_schedule(task, run)
assert total >= 1
assert success >= 1
assert list(trigger_dir.glob("inventory_export_batch_*.json"))
assert any(item.get("source_code") for item in details)
@@ -0,0 +1,97 @@
"""shipping_notice 库存快照 TTL 复用测试。"""
from datetime import datetime, timedelta
from pathlib import Path
from app import db
from app.models import ShippingInventoryFile, ShippingTask
from app.services.shipping_notice.inventory_snapshot_store import (
create_inventory_snapshot_from_rpa,
find_latest_ready_snapshot,
is_snapshot_fresh,
link_snapshot_to_task,
snapshot_expires_at,
)
from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source
def test_fresh_snapshot_is_reused(app, tmp_path):
"""未过期 ready 快照应被 find_latest_ready_snapshot 命中。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
app.config["SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS"] = 24
from openpyxl import Workbook
xlsx = tmp_path / "stock.xlsx"
wb = Workbook()
wb.active.append(["sku", "qty"])
wb.active.append(["A001", 10])
wb.save(xlsx)
wb.close()
source = build_rpa_inventory_source("DSV360_AWSDU")
assert source is not None
with app.app_context():
inv = create_inventory_snapshot_from_rpa(
source=source,
local_path=xlsx,
trigger_type="scheduled",
success=True,
)
db.session.commit()
found = find_latest_ready_snapshot("DSV360_AWSDU", "AWSDU")
assert found is not None
assert found.inventory_file_no == inv.inventory_file_no
assert is_snapshot_fresh(found)
def test_expired_snapshot_not_reused(app, tmp_path):
"""过期快照不应被 find_latest_ready_snapshot 返回。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
app.config["SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS"] = 1
from openpyxl import Workbook
xlsx = tmp_path / "stock.xlsx"
wb = Workbook()
wb.active.append(["sku", "qty"])
wb.save(xlsx)
wb.close()
source = build_rpa_inventory_source("DSV360_AWSDU")
with app.app_context():
inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, success=True)
inv.exported_at = datetime.utcnow() - timedelta(hours=2)
inv.expires_at = snapshot_expires_at(inv.exported_at)
db.session.commit()
assert not is_snapshot_fresh(inv)
assert find_latest_ready_snapshot("DSV360_AWSDU", "AWSDU") is None
def test_link_snapshot_writes_audit_fields(app, tmp_path):
"""任务与快照 link 应写入 link_reason 与 audit_payload。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
from openpyxl import Workbook
xlsx = tmp_path / "stock.xlsx"
wb = Workbook()
wb.active.append(["sku", "qty"])
wb.save(xlsx)
wb.close()
with app.app_context():
task = ShippingTask(task_no="SN-SNAPSHOT-LINK", source_type="manual", process_status="waiting_inventory")
db.session.add(task)
db.session.commit()
source = build_rpa_inventory_source("DSV360_AWSDU")
inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True)
link = link_snapshot_to_task(task, inv, reason="reuse_latest", audit_payload={"mode": "auto"})
db.session.commit()
assert link is not None
assert link.link_reason == "reuse_latest"
assert link.matched_warehouse_id == "AWSDU"
assert link.audit_payload_json["source_code"] == "DSV360_AWSDU"
@@ -0,0 +1,70 @@
"""shipping_notice inventory_sources JSON 配置加载与校验测试。"""
from pathlib import Path
import pytest
from app.services.shipping_notice.inventory_sources import (
InventorySourceConfigError,
build_rpa_inventory_source,
get_inventory_source,
list_inventory_sources,
reload_inventory_sources_config,
)
def test_inventory_sources_json_loads(app):
"""默认 JSON 配置应成功加载并包含 DSV360_AWSDU。"""
with app.app_context():
reload_inventory_sources_config()
source = get_inventory_source("DSV360_AWSDU")
assert source is not None
assert source["warehouse_id"] == "AWSDU"
assert source["source_type"] == "dsv360"
assert source["query"]["program_label"]
def test_build_rpa_inventory_source_keeps_legacy_query(app):
"""build_rpa_inventory_source 应返回 worker 兼容 query,AWSBI 子仓仅含 Warehouse 参数。"""
with app.app_context():
payload = build_rpa_inventory_source("DSV360_AWSBI_BYAWSATL01")
assert payload is not None
assert payload["warehouse_id"] == "BYAWSATL01"
assert payload["query"]["warehouse_code"] == "BYAWSATL01"
assert payload["query"]["program_label"] == "AWSBI"
assert "owner_code" not in payload["query"]
assert len(payload["parameters"]) == 1
assert payload["parameters"][0]["name"] == "Warehouse"
def test_duplicate_source_code_raises(app, tmp_path):
"""source_code 重复时加载应报错。"""
bad = tmp_path / "bad_sources.json"
bad.write_text(
"""
{
"version": 1,
"sources": [
{"source_code": "X1", "enabled": true, "site": "dsv360", "warehouse_id": "W1", "entry_url": "http://x", "navigation": {}, "parameters": []},
{"source_code": "X1", "enabled": true, "site": "dsv360", "warehouse_id": "W2", "entry_url": "http://x", "navigation": {}, "parameters": []}
]
}
""",
encoding="utf-8",
)
app.config["SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG"] = str(bad)
with app.app_context():
with pytest.raises(InventorySourceConfigError, match="duplicate"):
reload_inventory_sources_config()
def test_match_aliases_available_via_list(app):
"""list_inventory_sources 应包含 match_aliases 供规则匹配。"""
with app.app_context():
reload_inventory_sources_config()
codes = {item["source_code"] for item in list_inventory_sources()}
assert "DSV360_AWSDU" in codes
assert "DSV360_AWSBI_BYAWSATL01" in codes
assert "CRANE_TZR2" in codes
awsbi_count = sum(1 for item in list_inventory_sources() if str(item.get("source_code", "")).startswith("DSV360_AWSBI_"))
assert awsbi_count == 25
@@ -0,0 +1,45 @@
"""rpa.py 按需 trigger 包装测试。"""
from app.services.shipping_notice.rpa import write_inventory_export_trigger_for_task
def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path):
"""batch 开启时单票按需应写 inventory_export_batch trigger。"""
trigger_dir = tmp_path / "triggers"
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = True
source = {
"source_code": "DSV360_AWSDU",
"source_type": "dsv360",
"warehouse_id": "AWSDU",
"entry_url": "https://s360.dbschenker.com/",
"parameters": [],
"query": {},
}
with app.app_context():
path = write_inventory_export_trigger_for_task(
"SN-ON-DEMAND-1",
source,
payload={"mode": "auto", "attempt": 1},
)
assert path
trigger_files = list(trigger_dir.glob("inventory_export_batch_*.json"))
assert trigger_files
text = trigger_files[0].read_text(encoding="utf-8")
assert "inventory_export_batch" in text
assert "SN-ON-DEMAND-1" in text
assert "DSV360_AWSDU" in text
def test_on_demand_uses_legacy_trigger_when_batch_disabled(app, tmp_path):
"""batch 关闭时仍写 legacy inventory_export trigger。"""
trigger_dir = tmp_path / "triggers"
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
source = {"source_code": "DSV360_AWSDU", "source_type": "dsv360", "warehouse_id": "AWSDU", "query": {}}
with app.app_context():
path = write_inventory_export_trigger_for_task("SN-LEGACY-1", source)
assert path
assert list(trigger_dir.glob("inventory_export_SN-LEGACY-1.json"))