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

+6 -3
View File
@@ -68,6 +68,9 @@ SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.json
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
# 字段对齐确认(生产建议 true;测试可设 false)
@@ -77,7 +80,7 @@ SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=6
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
@@ -106,8 +109,8 @@ SHIPPING_NOTICE_CHAT_DIFY_APP_ID=
SHIPPING_NOTICE_CHAT_DIFY_API_KEY=
SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
# 本地 Mock RPA(scripts/rpa/freight_rpa_worker.py,可选)
# FREIGHT_RPA_MOCK=true
# 本地 RPA(scripts/rpa/freight_rpa_worker.py)
FREIGHT_RPA_MOCK=false
# FREIGHT_RPA_POLL_SECONDS=3
# FREIGHT_RPA_SAMPLE_INVENTORY=
+4 -1
View File
@@ -72,6 +72,9 @@ SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.json
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
# 字段对齐确认(生产建议 true;测试可设 false)
@@ -81,7 +84,7 @@ SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=6
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
+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"))
+43 -3
View File
@@ -95,8 +95,8 @@ FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
# 发货后台任务执行模式:worker / sync / manual
# SHIPPING_NOTICE_TASK_EXECUTION_MODE=worker
# RPA 库存导出等待超时(秒,默认 360;DSV 实际链路建议至少 360)
# SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=360
# RPA 库存导出等待超时(秒,默认 900;DSV 实际链路建议至少 900)
# SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
# 发货 worker 轮询间隔(秒)
# SHIPPING_NOTICE_WORKER_POLL_SECONDS=2
@@ -2724,6 +2724,46 @@ API 层
| `backend/tests/test_shipping_notice_query_service.py` | 读模型投影与批次汇总单测 |
| `backend/tests/test_shipping_notice_batches.py` | 批次建单 / focus 切换测试 |
| `backend/tests/test_shipping_notice_inventory_rpa_workflow.py` | RPA 库存触发与回调单测 |
| `backend/tests/test_shipping_notice_inventory_sources_config.py` | 库存源 JSON 配置加载与校验单测 |
| `backend/tests/test_shipping_notice_inventory_snapshot_reuse.py` | 库存快照 TTL 复用与 link 审计单测 |
| `backend/tests/test_shipping_notice_inventory_schedule.py` | 定时批量库存 RPA 排程 executor 单测 |
| `backend/tests/test_shipping_notice_match_summary.py` | 匹配摘要相关测试 |
| `scripts/rpa/freight_rpa_worker.py` | 开发态 RPA worker |
| `scripts/rpa/freight_rpa_worker.py` | 开发态 RPA worker(支持单条/批量 inventory_export) |
| `backend/config/shipping_inventory_sources.json` | 库存 RPA 源配置(新增 Warehouse 只改此 JSON) |
| `seed_shipping_notice_agents.py` | Agent 注册脚本 |
---
## 5. 库存 RPA 独立化与快照复用(2026-07)
### 5.1 配置文件
- 路径:`backend/config/shipping_inventory_sources.json`(环境变量 `SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG`)
- **新增 Warehouse 只改 JSON**,不改 Python;字段含 `source_code`、`site`(`dsv360` / `crane_footprint`)、`warehouse_id`、`navigation`、`parameters`、`match_aliases`
- 环境变量:
- `SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS`(默认 24)
- `SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED`(默认 true)
### 5.2 快照复用规则
1. `ensure_inventory(mode=auto)` 在解析库存源后,优先 `find_latest_ready_snapshot(source_code, warehouse_id)`
2. 未过期快照 → `link_snapshot_to_task(reason=reuse_latest)` → 映射/匹配
3. 过期或缺失 → 触发 RPA(单 task trigger 或定时 batch trigger)
4. `retry_rpa` **强制跳过**快照缓存
5. 人工上传仍可覆盖;终态任务不可 relink
### 5.3 批量 RPA(一次登录多 Warehouse)
- Trigger action:`inventory_export_batch`;按 `source_type` 分组,DSV/Crane 各登录一次
- **每个 source 导出前**:DSV 调用 `_reset_dsv_export_entry`(goto entry + session 检测,不重复登录);Crane 调用 `_reset_crane_export_entry`
- **按需单票**:`write_inventory_export_trigger_for_task`;batch 开启时包装为单源 batch trigger(与定时共用 worker 路径)
- **单票 legacy 路径**:`_download_dsv360_inventory` / `_download_crane_inventory` 已委托 `_export_*_inventory_source`,与批量共用 `parameters` 填充
- **multi_select**:worker `_fill_dsv_multi_select` 支持多选控件(非仅取第一个值)
- Worker:`scripts/rpa/freight_rpa_worker.py` → `_handle_inventory_batch_trigger`
- 回调:`POST /api/shipping-notice/rpa/inventory-batch-ready`
- 定时排程:`data_source_type=shipping_inventory_rpa`,建议 cron `0 3 * * *`(Asia/Shanghai)
### 5.4 审计字段
- `shipping_inventory_files`:`warehouse_id`、`source_code`、`exported_at`、`expires_at`、`rpa_run_no`、`schedule_run_id`
- `shipping_task_inventory_links`:`link_reason`、`matched_warehouse_id`、`snapshot_age_seconds`、`audit_payload_json`
+4
View File
@@ -56,6 +56,10 @@
| --- | --- | --- |
| 发货通知技术手册 | 已文档化 | 见 [docs/features/shipping-notice/technical.md](features/shipping-notice/technical.md) |
| 发货通知业务说明 | 已文档化 | 见 [docs/features/shipping-notice/business.md](features/shipping-notice/business.md) |
| 库存 RPA 源 JSON 配置 | 已实现 | `backend/config/shipping_inventory_sources.json`,新增 Warehouse 只改 JSON |
| 库存快照 TTL 复用 | 已实现 | `inventory_snapshot_store`,按需任务优先复用未过期快照 |
| 库存 RPA 批量导出(DSV/Crane 一次登录) | 已实现 | `inventory_export_batch` trigger + worker + `/rpa/inventory-batch-ready` |
| 库存每日定时导出排程 | 已实现 | `data_source_type=shipping_inventory_rpa`,cron 建议 `0 3 * * *` |
| 产品原型 | 已文档化 | 见 [docs/prototype/shipping_notice_agent_prototype.md](prototype/shipping_notice_agent_prototype.md) |
### Agent 应用管理(platform)
@@ -108,9 +108,9 @@ const rpaRuntimeBadgeClass = (task: ShippingTaskSummary | ShippingTaskDetail) =>
*/
const resolveWorkspaceAssistButtonClass = (kind: 'focus' | 'shortage') => {
if (kind === 'shortage') {
return 'inline-flex min-h-[38px] items-center justify-center gap-1.5 rounded-xl border border-amber-200 bg-amber-50/90 px-3 py-2 text-xs font-semibold text-amber-700 transition-all hover:border-amber-300 hover:bg-amber-100 disabled:cursor-not-allowed disabled:opacity-60';
return 'inline-flex min-h-[32px] items-center justify-center gap-1.5 rounded-lg border border-amber-200 bg-amber-50/90 px-2.5 py-1.5 text-xs font-semibold text-amber-700 transition-all hover:border-amber-300 hover:bg-amber-100 disabled:cursor-not-allowed disabled:opacity-60';
}
return 'inline-flex min-h-[38px] items-center justify-center gap-1.5 rounded-xl border border-slate-200 bg-slate-50/90 px-3 py-2 text-xs font-semibold text-slate-700 transition-all hover:border-brand-200 hover:bg-white hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-60';
return 'inline-flex min-h-[32px] items-center justify-center gap-1.5 rounded-lg border border-slate-200 bg-slate-50/90 px-2.5 py-1.5 text-xs font-semibold text-slate-700 transition-all hover:border-brand-200 hover:bg-white hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-60';
};
/**
@@ -123,12 +123,12 @@ const resolveWorkspaceAssistButtonClass = (kind: 'focus' | 'shortage') => {
const resolveWorkspaceTaskActionClass = (action: ShippingChatAction, total: number) => {
const spanClass = action.variant === 'primary' || total === 1 ? 'col-span-2' : 'col-span-1';
if (action.variant === 'primary') {
return `${spanClass} inline-flex min-h-[42px] items-center justify-center rounded-xl bg-gradient-to-r from-brand-600 to-sky-500 px-4 py-2.5 text-sm font-semibold text-white shadow-[0_10px_24px_rgba(14,116,144,0.24)] transition-all hover:-translate-y-[1px] hover:from-brand-700 hover:to-sky-600 disabled:cursor-not-allowed disabled:opacity-60`;
return `${spanClass} inline-flex min-h-[36px] items-center justify-center rounded-lg bg-gradient-to-r from-brand-600 to-sky-500 px-3 py-1.5 text-sm font-semibold text-white shadow-sm transition-all hover:-translate-y-[1px] hover:from-brand-700 hover:to-sky-600 disabled:cursor-not-allowed disabled:opacity-60`;
}
if (action.variant === 'danger') {
return `${spanClass} inline-flex min-h-[42px] items-center justify-center rounded-xl border border-rose-200 bg-rose-50 px-4 py-2.5 text-sm font-semibold text-rose-700 transition-all hover:border-rose-300 hover:bg-rose-100 disabled:cursor-not-allowed disabled:opacity-60`;
return `${spanClass} inline-flex min-h-[36px] items-center justify-center rounded-lg border border-rose-200 bg-rose-50 px-3 py-1.5 text-sm font-semibold text-rose-700 transition-all hover:border-rose-300 hover:bg-rose-100 disabled:cursor-not-allowed disabled:opacity-60`;
}
return `${spanClass} inline-flex min-h-[42px] items-center justify-center rounded-xl border border-slate-200 bg-white px-4 py-2.5 text-sm font-semibold text-slate-700 shadow-sm transition-all hover:border-brand-200 hover:bg-brand-50 hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-60`;
return `${spanClass} inline-flex min-h-[36px] items-center justify-center rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-sm font-semibold text-slate-700 shadow-sm transition-all hover:border-brand-200 hover:bg-brand-50 hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-60`;
};
// #region debug-point A:workspace-action
@@ -569,7 +569,7 @@ const handleSwitchBatch = (batchNo: string) => {
{{ resolveSuggestedAction(task) }}
</div>
<div class="grid grid-cols-2 gap-2">
<div class="grid grid-cols-2 gap-1.5">
<button
v-if="hasShortageLines(task)"
type="button"
@@ -590,11 +590,11 @@ const handleSwitchBatch = (batchNo: string) => {
</button>
</div>
<div v-if="resolveWorkspaceActionButtons(task).length" class="mt-2 rounded-2xl border border-slate-200/80 bg-slate-50/70 p-2.5">
<div class="mb-2 px-1 text-[11px] font-semibold uppercase tracking-[0.08em] text-slate-500">
<div v-if="resolveWorkspaceActionButtons(task).length" class="mt-2 rounded-xl border border-slate-200/80 bg-slate-50/70 p-2">
<div class="mb-1.5 px-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-slate-500">
{{ t('chat.shippingNoticeActionsHint') }}
</div>
<div class="grid grid-cols-2 gap-2">
<div class="grid grid-cols-2 gap-1.5">
<button
v-for="action in resolveWorkspaceActionButtons(task)"
:key="`${task.task_no}-workspace-action-${action.id}-${action.source_code || ''}`"
@@ -0,0 +1,32 @@
/**
* features/chat/shipping/shippingStepper.spec.ts
* 用途:验证发货通知七步 Stepper 的本地兜底状态映射。
* 依赖:shippingStepper 纯函数、vitest。
* 逻辑:后端 UI State 缺失时,前端仍需把关键人工介入态渲染为 blocked。
*/
import { describe, expect, it } from 'vitest';
import { buildShippingWorkflowSteps } from './shippingStepper';
describe('shippingStepper', () => {
it('marks inventory step as blocked when RPA inventory is exhausted', () => {
// 关键断言:库存 RPA 获取失败是业务阻断态,不能在步骤条里继续显示为普通 current。
const steps = buildShippingWorkflowSteps({
process_status: 'waiting_inventory',
pending_human_reason: 'rpa_exhausted',
current_step: 'step3_inventory_prepare',
});
expect(steps[2]?.status).toBe('blocked');
});
it('marks inventory step as blocked when inventory source is unavailable', () => {
// 关键断言:库存触发失败需要用户上传库存或重试,同样应在第 3 步显示异常。
const steps = buildShippingWorkflowSteps({
process_status: 'waiting_inventory',
pending_human_reason: 'inv_unavail',
current_step: 'step3_inventory_prepare',
});
expect(steps[2]?.status).toBe('blocked');
});
});
@@ -160,6 +160,7 @@ export function buildShippingWorkflowSteps(
if (
(index === 1 && (reviewStatus === 'parse_review' || pendingReason === 'low_confidence' || pendingReason === 'rsv_required'))
|| (index === 2 && (pendingReason === 'inv_unavail' || pendingReason === 'rpa_exhausted'))
|| (index === 3 && (reviewStatus === 'align_review' || pendingReason === 'align_review'))
|| (index === 4 && (reviewStatus === 'shortage_review' || pendingReason === 'shortage_review' || pendingReason === 'shortage'))
|| (index === 6 && processStatus === 'upload_failed')
@@ -84,12 +84,11 @@ describe('shippingText', () => {
it('hides manual retry count in user-facing runtime copy', () => {
// 关键断言:前台状态文案不暴露“第几次重试”,只保留当前状态本身。
const result = sanitizeShippingConversationText(
'已手动重新触发 RPA 库存导出(手动第 2 次)。\n任务编号:SN-002',
'已重新触发库存获取(第 2 次)。\n任务编号:SN-002',
true,
);
expect(result).toContain('已重新触发库存获取。');
expect(result).not.toContain('手动第 2 次');
expect(result).not.toContain('第 2 次');
});
@@ -45,6 +45,14 @@ export function sanitizeShippingRuntimeStatusText(text: string): string {
/已手动重新触发\s*RPA\s*库存导出\s*[((]\s*(?:手动第\s*\d+\s*次(?:尝试)?|第\s*\d+(?:\s*\/\s*\d+)?\s*次(?:尝试)?)\s*[))]\s*[。.]?/gi,
'已重新触发库存获取。',
)
.replace(
/已重新触发库存获取\s*[((]\s*第\s*\d+(?:\s*\/\s*\d+)?\s*次(?:尝试)?\s*[))]\s*[。.]?/gi,
'已重新触发库存获取。',
)
.replace(
/已触发库存获取\s*[((]\s*第\s*\d+(?:\s*\/\s*\d+)?\s*次(?:尝试)?\s*[))]\s*[。.]?/gi,
'已触发库存获取。',
)
.replace(
/已触发\s*RPA\s*库存导出\s*[((]\s*第\s*\d+(?:\s*\/\s*\d+)?\s*次(?:尝试)?\s*[))]\s*[。.]?/gi,
'已触发库存获取。',
@@ -4,6 +4,21 @@
* 依赖:无(纯类型模块)。
* 逻辑:shipping.api.ts 与 Chat/工作台组件统一引用本文件 DTO 类型。
*/
export interface ShippingInventorySnapshot {
inventory_file_no?: string | null;
source_code?: string | null;
warehouse_id?: string | null;
warehouse_code?: string | null;
exported_at?: string | null;
expires_at?: string | null;
snapshot_status?: string | null;
is_fresh?: boolean;
link_reason?: string | null;
snapshot_age_seconds?: number | null;
trigger_type?: string | null;
rpa_run_no?: string | null;
}
export interface ShippingTaskSummary {
id: number;
task_no: string;
@@ -34,6 +49,7 @@ export interface ShippingTaskSummary {
rpa_runtime?: ShippingRpaRuntime | null;
rpa_inventory_source?: Record<string, unknown> | null;
inventory_source_resolution?: Record<string, unknown> | null;
inventory_snapshot?: ShippingInventorySnapshot | null;
created_at?: string | null;
updated_at?: string | null;
ui_state?: ShippingTaskUiState;
@@ -131,6 +131,16 @@ const detailErrorMessage = computed(() =>
sanitizeShippingRuntimeStatusText(String(detail.value?.error_message || '').trim()),
);
const inventorySnapshotLabel = (triggerType?: string | null) => {
const key = String(triggerType || 'on_demand');
const map: Record<string, string> = {
scheduled: t('workspace.shippingNotice.inventorySnapshot.sourceScheduled'),
on_demand: t('workspace.shippingNotice.inventorySnapshot.sourceOnDemand'),
manual_upload: t('workspace.shippingNotice.inventorySnapshot.sourceManual'),
};
return map[key] || map.on_demand;
};
const loadCases = async () => {
loading.value = true;
try {
@@ -378,6 +388,39 @@ onMounted(async () => {
<div><dt class="text-muted">{{ $t('workspace.shippingNotice.fields.freightRef') }}</dt><dd>{{ detail.freight_ref_no || '—' }}</dd></div>
</dl>
<div
v-if="detail.inventory_snapshot"
class="rounded-2xl border border-default/80 bg-surface px-4 py-3 text-sm"
>
<h3 class="mb-2 text-sm font-semibold text-secondary">
{{ $t('workspace.shippingNotice.inventorySnapshot.title') }}
</h3>
<dl class="grid gap-2 sm:grid-cols-2">
<div>
<dt class="text-xs text-muted">{{ $t('workspace.shippingNotice.inventorySnapshot.warehouseId') }}</dt>
<dd class="font-mono">{{ detail.inventory_snapshot.warehouse_id || '—' }}</dd>
</div>
<div>
<dt class="text-xs text-muted">{{ $t('workspace.shippingNotice.inventorySnapshot.source') }}</dt>
<dd>{{ inventorySnapshotLabel(detail.inventory_snapshot.trigger_type) }}</dd>
</div>
<div>
<dt class="text-xs text-muted">{{ $t('workspace.shippingNotice.inventorySnapshot.exportedAt') }}</dt>
<dd>{{ detail.inventory_snapshot.exported_at || '—' }}</dd>
</div>
<div>
<dt class="text-xs text-muted">{{ $t('workspace.shippingNotice.inventorySnapshot.fileNo') }}</dt>
<dd class="font-mono text-xs">{{ detail.inventory_snapshot.inventory_file_no || '—' }}</dd>
</div>
</dl>
<div
v-if="detail.inventory_snapshot.is_fresh === false"
class="mt-2 text-xs text-amber-700"
>
{{ $t('workspace.shippingNotice.inventorySnapshot.expired') }}
</div>
</div>
<div v-if="detailErrorMessage" class="rounded-xl border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-700">
{{ detailErrorMessage }}
</div>
+11
View File
@@ -180,6 +180,17 @@
"shipTo": "Ship to",
"freightRef": "Freight ref no."
},
"inventorySnapshot": {
"title": "Inventory snapshot",
"warehouseId": "Warehouse ID",
"source": "Inventory source",
"sourceScheduled": "Scheduled export",
"sourceOnDemand": "On-demand RPA",
"sourceManual": "Manual upload",
"exportedAt": "Exported at",
"fileNo": "Snapshot ID",
"expired": "Snapshot expired; system will re-trigger RPA or wait for manual upload"
},
"status": {
"all": "All",
"created": "Created",
+11
View File
@@ -110,6 +110,17 @@
"shipTo": "ที่อยู่จัดส่ง",
"freightRef": "เลขอ้างอิงขนส่ง"
},
"inventorySnapshot": {
"title": "สแนปช็อตสต็อก",
"warehouseId": "Warehouse ID",
"source": "แหล่งสต็อก",
"sourceScheduled": "ส่งออกตามกำหนด",
"sourceOnDemand": "RPA ตามต้องการ",
"sourceManual": "อัปโหลดด้วยตนเอง",
"exportedAt": "เวลาส่งออก",
"fileNo": "รหัสสแนปช็อต",
"expired": "สแนปช็อตหมดอายุ ระบบจะเรียก RPA ใหม่หรือรอการอัปโหลดด้วยตนเอง"
},
"status": {
"all": "ทั้งหมด",
"created": "สร้างแล้ว",
+11
View File
@@ -181,6 +181,17 @@
"shipTo": "收货地址",
"freightRef": "货代单号"
},
"inventorySnapshot": {
"title": "库存快照",
"warehouseId": "Warehouse ID",
"source": "库存来源",
"sourceScheduled": "定时导出",
"sourceOnDemand": "按需 RPA",
"sourceManual": "手动上传",
"exportedAt": "导出时间",
"fileNo": "快照编号",
"expired": "快照已过期,系统将重新触发 RPA 或等待人工上传"
},
"status": {
"all": "全部",
"created": "已创建",
+11
View File
@@ -180,6 +180,17 @@
"shipTo": "收貨地址",
"freightRef": "貨代單號"
},
"inventorySnapshot": {
"title": "庫存快照",
"warehouseId": "Warehouse ID",
"source": "庫存來源",
"sourceScheduled": "定時匯出",
"sourceOnDemand": "按需 RPA",
"sourceManual": "手動上傳",
"exportedAt": "匯出時間",
"fileNo": "快照編號",
"expired": "快照已過期,系統將重新觸發 RPA 或等待人工上傳"
},
"status": {
"all": "全部",
"created": "已建立",
+1
View File
@@ -15,6 +15,7 @@ export default defineConfig({
},
server: {
port: 8881, // 前端开发端口,实际上我们会用 Nginx 反代,但本地开发先改这个方便
strictPort: true, // 端口被占用时直接失败,由 start_local.ps1 先释放旧进程
allowedHosts: ['hx.benl.cn'],
proxy: {
'/api': {
+18 -1
View File
@@ -6,7 +6,7 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA
| 环境变量 | 用途 |
|---------|------|
| `FREIGHT_RPA_INVENTORY_TRIGGER_DIR` | hxops 写入 `inventory_export_{task_no}.json`,RPA 读取后导库存 |
| `FREIGHT_RPA_INVENTORY_TRIGGER_DIR` | hxops 写入 `inventory_export_{task_no}.json` 或 `inventory_export_batch_{run_no}.json`,RPA 读取后导库存 |
| `FREIGHT_INVENTORY_DROP_DIR` | RPA 落盘库存 Excel(`.xlsx`),hxops / worker 回调 ingest |
| `FREIGHT_RPA_UPLOAD_TRIGGER_DIR` | hxops 写入 `upload_{task_no}.json` |
| `FREIGHT_UPLOAD_QUEUE_DIR` | hxops 复制待上传发货 Excel |
@@ -77,6 +77,23 @@ python scripts/rpa/freight_rpa_worker.py
| `dsv360` | 打开 DSV 360,进入 Reports / Program / Inventory 报表并下载 |
| `crane_footprint` | 打开 Crane FootPrint On Hand Details Query,选择 Owner/Project/Warehouse 后下载 |
### 批量库存导出(`inventory_export_batch`)
定时排程或后台预热会写入 `inventory_export_batch_{run_no}.json`,字段示例:
```json
{
"action": "inventory_export_batch",
"run_no": "RUN20260707030000",
"trigger_type": "scheduled",
"inventory_sources": [{ "source_code": "DSV360_AWSDU", "source_type": "dsv360", "warehouse_id": "AWSDU" }]
}
```
Worker 按 `source_type` 分组:**DSV 一次登录**循环各 Warehouse,**Crane 一次登录**循环各 Warehouse;完成后回调 `POST /api/shipping-notice/rpa/inventory-batch-ready`。
库存源定义见 `backend/config/shipping_inventory_sources.json`(新增 Warehouse 只改 JSON)。
页面控件如果默认可见文本无法稳定点击,可通过环境变量覆盖 selector:
| 环境变量 | 用途 |
+226
View File
@@ -0,0 +1,226 @@
"""
scripts/rpa/dsv_export_batch_smoke.py
用途:本地验证 DSV 360 同一浏览器 session 内连续导出 3 份库存 Excel。
依赖:Playwright(msedge)、FREIGHT_RPA_DSV_USERNAME/PASSWORD、shipping_inventory_sources.json、freight_rpa_worker。
逻辑:复用 worker 批量导出循环(一次登录 + reset 入口),不依赖 HXOPS callback。
场景:
warehouse — 同一 source_code / 同一 3lv 报表,仅 Warehouse 参数变化
source_code — 三个不同 source_code(JSON 中独立配置项)
用法:
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_batch_smoke.py warehouse
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_batch_smoke.py source_code
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_batch_smoke.py all
"""
from __future__ import annotations
import importlib.util
import json
import os
import shutil
import sys
import tempfile
import time
import traceback
from copy import deepcopy
from datetime import datetime
from pathlib import Path
from typing import Any
def _repo_root() -> Path:
return Path(__file__).resolve().parents[2]
def _load_worker():
module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_batch_smoke", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _load_export_smoke_helpers():
module_path = _repo_root() / "scripts" / "rpa" / "dsv_export_smoke.py"
spec = importlib.util.spec_from_file_location("dsv_export_smoke_batch", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _with_warehouse(source: dict[str, Any], warehouse: str, *, keep_source_code: bool) -> dict[str, Any]:
"""
克隆 source 并替换 Warehouse 参数与 query。
keep_source_code=True 时用于「同 source、仅 Warehouse 变化」场景。
"""
cloned = deepcopy(source)
wh = str(warehouse).strip()
if not keep_source_code:
cloned["source_code"] = f"DSV360_AWSBI_{wh}"
cloned["warehouse_id"] = wh
cloned["warehouse_code"] = wh
query = dict(cloned.get("query") or {})
query["warehouse_code"] = wh
cloned["query"] = query
parameters = []
for item in cloned.get("parameters") or []:
if not isinstance(item, dict):
continue
param = dict(item)
if str(param.get("name") or "").lower() == "warehouse":
param["values"] = [wh]
parameters.append(param)
cloned["parameters"] = parameters
return cloned
def _build_warehouse_scenario_sources() -> list[dict[str, Any]]:
"""场景 1:同一 source_code,3lv 报表不变,仅 Warehouse 下拉值变化。"""
helper = _load_export_smoke_helpers()
base = helper._build_source_from_config("DSV360_AWSBI_BYAWSCMH01")
warehouses = ["BYAWSATL01", "BYAWSCMH01", "BYAWSAVP01"]
return [_with_warehouse(base, wh, keep_source_code=True) for wh in warehouses]
def _build_source_code_scenario_sources() -> list[dict[str, Any]]:
"""场景 2:三个独立 source_code。"""
helper = _load_export_smoke_helpers()
codes = [
"DSV360_AWSBI_BYAWSATL01",
"DSV360_AWSBI_BYAWSCMH01",
"DSV360_AWSBI_BYAWSAVP01",
]
return [helper._build_source_from_config(code) for code in codes]
def _run_batch_exports(worker: Any, scenario: str, sources: list[dict[str, Any]], drop_dir: Path) -> list[dict[str, Any]]:
"""
在同一 DSV session 内连续导出多份库存。
核心逻辑:与 _handle_inventory_batch_trigger 浏览器分支一致,但不 POST callback。
"""
run_no = f"BATCH-SMOKE-{scenario.upper()}-{datetime.now().strftime('%Y%m%d%H%M%S')}"
trigger = {"run_no": run_no, "task_no": run_no}
entry_url = str((sources[0] or {}).get("entry_url") or "https://s360.dbschenker.com/").strip()
results: list[dict[str, Any]] = []
started = time.monotonic()
playwright = context = runtime_profile_dir = None
try:
playwright, context, page, runtime_profile_dir = worker._open_browser(drop_dir)
export_fn = worker._export_dsv_inventory_source
previous_source: dict[str, Any] | None = None
for index, source in enumerate(sources):
code = str(source.get("source_code") or "")
wh = str(source.get("warehouse_id") or source.get("warehouse_code") or "")
print(
f"[batch-smoke] scenario={scenario} step={index + 1}/{len(sources)} "
f"source_code={code} warehouse={wh}"
)
try:
skip_navigation = worker._prepare_dsv_batch_export_step(
page,
entry_url,
previous_source,
source,
index=index,
)
download = export_fn(page, trigger, source, skip_navigation=skip_navigation)
out_file = worker._save_batch_download(download, drop_dir, run_no, source)
size_kb = out_file.stat().st_size / 1024
results.append(
{
"source_code": code,
"warehouse_id": wh,
"success": True,
"file_path": str(out_file),
"size_kb": round(size_kb, 1),
}
)
print(f"[batch-smoke] OK {code}/{wh} -> {out_file.name} ({size_kb:.1f} KB)")
except Exception as exc:
results.append(
{
"source_code": code,
"warehouse_id": wh,
"success": False,
"error_message": str(exc),
}
)
print(f"[batch-smoke] FAIL {code}/{wh}: {exc}", file=sys.stderr)
traceback.print_exc()
previous_source = source
finally:
if context is not None:
context.close()
if playwright is not None:
playwright.stop()
if runtime_profile_dir is not None:
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
elapsed_s = int(time.monotonic() - started)
ok = sum(1 for item in results if item.get("success"))
print(
f"[batch-smoke] scenario={scenario} done success={ok}/{len(results)} "
f"elapsed={elapsed_s}s drop_dir={drop_dir}"
)
return results
def _run_scenario(worker: Any, scenario: str) -> int:
if scenario == "warehouse":
sources = _build_warehouse_scenario_sources()
elif scenario == "source_code":
sources = _build_source_code_scenario_sources()
else:
raise ValueError(f"unknown scenario: {scenario}")
drop_dir = Path(tempfile.mkdtemp(prefix=f"dsv_batch_{scenario}_"))
print(f"[batch-smoke] scenario={scenario} exports={len(sources)} drop_dir={drop_dir}")
for index, source in enumerate(sources, start=1):
print(
f"[batch-smoke] plan[{index}] source_code={source.get('source_code')} "
f"warehouse={source.get('warehouse_id')} "
f"query={json.dumps(source.get('query') or {}, ensure_ascii=False)}"
)
results = _run_batch_exports(worker, scenario, sources, drop_dir)
if not results or not all(item.get("success") for item in results):
return 2
return 0
def main() -> int:
scenario_arg = (sys.argv[1] if len(sys.argv) > 1 else "all").strip().lower()
os.environ.setdefault("FREIGHT_RPA_HEADLESS", "false")
os.environ.setdefault("FREIGHT_RPA_MOCK", "false")
os.environ.setdefault("FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR", "true")
os.environ.setdefault(
"FREIGHT_RPA_BROWSER_PROFILE_DIR",
"backend/data/shipping_notice/freight_rpa/browser_profile",
)
if not os.environ.get("FREIGHT_RPA_BROWSER_CHANNEL") and not os.environ.get("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH"):
os.environ.setdefault("FREIGHT_RPA_BROWSER_CHANNEL", "msedge")
worker = _load_worker()
if not worker._env("FREIGHT_RPA_DSV_USERNAME") or not worker._env("FREIGHT_RPA_DSV_PASSWORD"):
print("[batch-smoke] 缺少 FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD")
return 1
scenarios = ["warehouse", "source_code"] if scenario_arg == "all" else [scenario_arg]
exit_code = 0
for scenario in scenarios:
if scenario not in {"warehouse", "source_code"}:
print(f"[batch-smoke] 未知场景: {scenario}(可用 warehouse / source_code / all)")
return 1
print(f"\n[batch-smoke] ===== 开始场景: {scenario} =====")
code = _run_scenario(worker, scenario)
exit_code = max(exit_code, code)
return exit_code
if __name__ == "__main__":
sys.exit(main())
+148
View File
@@ -0,0 +1,148 @@
"""
scripts/rpa/dsv_export_smoke.py
用途:本地手动验证指定 DSV 360 库存源(默认 BYAWSATL01)的浏览器导出全流程。
依赖:Playwright(msedge)、FREIGHT_RPA_DSV_USERNAME/PASSWORD、backend/config/shipping_inventory_sources.json。
逻辑:加载 rpa_inventory_source → _download_inventory_with_browser → 输出 Excel 路径。
用法(仓库根目录):
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_smoke.py
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_smoke.py DSV360_AWSBI_BYAWSATL01
"""
from __future__ import annotations
import importlib.util
import json
import os
import sys
import tempfile
import traceback
from datetime import datetime
from pathlib import Path
def _repo_root() -> Path:
return Path(__file__).resolve().parents[2]
def _load_worker():
module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_export_smoke", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _build_source_from_config(source_code: str) -> dict:
"""
从 JSON 配置构造 worker 兼容的 rpa_inventory_source(不依赖 Flask 上下文)。
核心逻辑:复用与 inventory_sources._build_legacy_query 相同的 query 口径。
"""
config_path = _repo_root() / "backend" / "config" / "shipping_inventory_sources.json"
payload = json.loads(config_path.read_text(encoding="utf-8"))
raw = next(
(item for item in (payload.get("sources") or []) if str(item.get("source_code") or "").upper() == source_code.upper()),
None,
)
if not raw:
raise RuntimeError(f"source_code not found in config: {source_code}")
navigation = dict(raw.get("navigation") or {})
parameters = [dict(item) for item in (raw.get("parameters") or []) if isinstance(item, dict)]
site = str(raw.get("site") or "dsv360").strip().lower()
warehouse_id = str(raw.get("warehouse_id") or raw.get("warehouse_code") or "").strip()
query: dict[str, object] = {}
if site == "dsv360":
for key in ("program_group", "program_label", "report_group", "report_name"):
if navigation.get(key):
query[key] = navigation[key]
if warehouse_id:
query["warehouse_code"] = warehouse_id
for parameter in parameters:
name = str(parameter.get("name") or "").strip()
mode = str(parameter.get("mode") or "single").strip().lower()
values = [str(v).strip() for v in (parameter.get("values") or []) if str(v).strip()]
if not values:
continue
if mode == "multi_text":
joined = str(parameter.get("joiner") or ",").join(values)
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
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
return {
"source_code": str(raw.get("source_code") or source_code).upper(),
"source_type": "dsv360" if site == "dsv360" else site,
"display_name": str(raw.get("display_name") or source_code),
"enabled": bool(raw.get("enabled", True)),
"entry_url": str(raw.get("entry_url") or "https://s360.dbschenker.com/"),
"warehouse_id": warehouse_id,
"warehouse_code": str(raw.get("warehouse_code") or warehouse_id),
"navigation": navigation,
"parameters": parameters,
"query": query,
}
def main() -> int:
source_code = (sys.argv[1] if len(sys.argv) > 1 else "DSV360_AWSBI_BYAWSATL01").strip().upper()
os.environ.setdefault("FREIGHT_RPA_HEADLESS", "false")
os.environ.setdefault("FREIGHT_RPA_MOCK", "false")
os.environ.setdefault("FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR", "true")
os.environ.setdefault(
"FREIGHT_RPA_BROWSER_PROFILE_DIR",
"backend/data/shipping_notice/freight_rpa/browser_profile",
)
if not os.environ.get("FREIGHT_RPA_BROWSER_CHANNEL") and not os.environ.get("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH"):
os.environ.setdefault("FREIGHT_RPA_BROWSER_CHANNEL", "msedge")
worker = _load_worker()
if not worker._env("FREIGHT_RPA_DSV_USERNAME") or not worker._env("FREIGHT_RPA_DSV_PASSWORD"):
print("[export-smoke] 缺少 FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD")
return 1
source = _build_source_from_config(source_code)
task_no = f"SIF-SMOKE-{datetime.now().strftime('%Y%m%d%H%M%S')}"
trigger = {
"action": "inventory_export",
"task_no": task_no,
"requested_at": datetime.utcnow().isoformat(),
"mode": "smoke",
"attempt": 1,
"rpa_inventory_source": source,
}
drop_dir = Path(tempfile.mkdtemp(prefix=f"dsv_export_{source_code.lower()}_"))
print(f"[export-smoke] source={source_code} warehouse={source.get('warehouse_id')}")
print(f"[export-smoke] query={json.dumps(source.get('query') or {}, ensure_ascii=False)}")
print(f"[export-smoke] drop_dir={drop_dir}")
print("[export-smoke] 正在打开浏览器执行登录 + 报表导出(预计 3~8 分钟)…")
try:
out_file = worker._download_inventory_with_browser(trigger, drop_dir)
size_kb = out_file.stat().st_size / 1024
print(f"[export-smoke] SUCCESS — {out_file} ({size_kb:.1f} KB)")
return 0
except Exception as exc:
print(f"[export-smoke] FAILED — {exc}")
traceback.print_exc()
print("[export-smoke] FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR=true,浏览器保持打开以便排查。")
return 2
if __name__ == "__main__":
sys.exit(main())
+100
View File
@@ -0,0 +1,100 @@
"""
scripts/rpa/dsv_login_smoke.py
用途:本地手动验证 DSV 360 自动登录(含密码方式第二步、首页 ready)。
依赖:Playwright、FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD。
逻辑:打开可见浏览器 → _ensure_dsv_session → 保持窗口供人工观察,按 Enter 关闭。
用法(仓库根目录):
$env:FREIGHT_RPA_HEADLESS = "false"
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_login_smoke.py
"""
from __future__ import annotations
import importlib.util
import os
import shutil
import sys
import tempfile
import traceback
from pathlib import Path
def _load_worker():
repo_root = Path(__file__).resolve().parents[2]
module_path = repo_root / "scripts" / "rpa" / "freight_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_smoke", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def main() -> int:
os.environ.setdefault("FREIGHT_RPA_HEADLESS", "false")
os.environ.setdefault("FREIGHT_RPA_MOCK", "false")
os.environ.setdefault(
"FREIGHT_RPA_BROWSER_PROFILE_DIR",
"backend/data/shipping_notice/freight_rpa/browser_profile",
)
# Playwright 自带 Chromium 未安装时,回退到本机 Edge(Windows 开发机常见情况)。
if not os.environ.get("FREIGHT_RPA_BROWSER_CHANNEL") and not os.environ.get("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH"):
os.environ.setdefault("FREIGHT_RPA_BROWSER_CHANNEL", "msedge")
worker = _load_worker()
username = worker._env("FREIGHT_RPA_DSV_USERNAME")
password = worker._env("FREIGHT_RPA_DSV_PASSWORD")
if not username or not password:
print("[smoke] 缺少 FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD,请先配置环境变量。")
return 1
drop_dir = Path(tempfile.mkdtemp(prefix="dsv_smoke_drop_"))
playwright = context = runtime_profile_dir = None
entry_url = "https://s360.dbschenker.com/"
print(f"[smoke] headless={worker._env('FREIGHT_RPA_HEADLESS', 'false')}")
print(f"[smoke] user={username[:3]}*** entry={entry_url}")
print("[smoke] 正在打开浏览器并执行 DSV 自动登录…")
try:
playwright, context, page, runtime_profile_dir = worker._open_browser(drop_dir)
worker._ensure_dsv_session(page, entry_url)
print(f"[smoke] SUCCESS — DSV session ready, url={page.url}")
print("[smoke] 请在浏览器中确认 Reports 导航可见。按 Enter 关闭浏览器…")
try:
input()
except EOFError:
import time
print("[smoke] 非交互终端,保持浏览器 300 秒后自动关闭。")
time.sleep(300)
return 0
except Exception as exc:
print(f"[smoke] FAILED — {exc}")
traceback.print_exc()
print("[smoke] 浏览器将保持打开 120 秒以便排查,按 Enter 提前关闭…")
try:
input()
except EOFError:
import time
time.sleep(120)
return 2
finally:
if context is not None:
try:
context.close()
except Exception:
pass
if playwright is not None:
try:
playwright.stop()
except Exception:
pass
if runtime_profile_dir is not None:
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
shutil.rmtree(drop_dir, ignore_errors=True)
if __name__ == "__main__":
sys.exit(main())
+407
View File
@@ -0,0 +1,407 @@
"""
scripts/rpa/dsv_report_parameters.py
用途:填充 DSV 360 SSRS ReportViewer 报表参数(Owner / PutawayZone / Warehouse)。
依赖:Playwright Page/Frame;由 freight_rpa_worker._fill_dsv_filter_if_needed 委托调用。
逻辑:识别 multi-value checkbox 与 ValidValue select,在 report iframe 内操作并等待控件启用。
"""
from __future__ import annotations
import json
import sys
import time
from typing import Any, Callable
# BYAWSATL01 等 3lv 报表在 SSRS 中的默认控件 ID(与页面源码一致)。
_DSV_REPORT_PARAM_DEFAULTS: dict[str, dict[str, str]] = {
"Owner": {
"control": "multi_value",
"text": "#ReportViewerMain_ctl08_ctl03_txtValue",
"toggle": "#ReportViewerMain_ctl08_ctl03_ctl01",
"dropdown": "#ReportViewerMain_ctl08_ctl03_divDropDown",
},
"PutawayZone": {
"control": "multi_value",
"text": "#ReportViewerMain_ctl08_ctl07_txtValue",
"toggle": "#ReportViewerMain_ctl08_ctl07_ctl01",
"dropdown": "#ReportViewerMain_ctl08_ctl07_divDropDown",
},
"Warehouse": {
"control": "select",
"selector": "#ReportViewerMain_ctl08_ctl17_ddValue",
},
}
def _iter_dsv_report_roots(page: Any) -> list[Any]:
"""返回包含 ReportViewerMain 的 frame;找不到时回退到全部 roots。"""
matched: list[Any] = []
for frame in getattr(page, "frames", []):
try:
if frame.locator("#ReportViewerMain").count() > 0:
matched.append(frame)
except Exception:
continue
if matched:
return matched
return [page, *list(getattr(page, "frames", []))]
def _find_locator(page: Any, selector: str) -> tuple[Any | None, Any | None]:
"""在 report roots 中查找 selector 对应的 locator。"""
for root in _iter_dsv_report_roots(page):
try:
locator = root.locator(selector).first
locator.wait_for(state="attached", timeout=1_000)
return root, locator
except Exception:
continue
return None, None
def _warehouse_select_state(locator: Any, value: str) -> dict[str, Any]:
"""探测 Warehouse select 是否已有目标 option、是否已解除 disabled。"""
try:
result = locator.evaluate(
"""
(select, target) => {
const normalize = (text) => (text || '').replace(/\\s+/g, ' ').trim().toLowerCase();
const wanted = normalize(target);
const options = Array.from(select.options || []);
const hasTarget = options.some((item) => normalize(item.textContent) === wanted);
const realOptions = options.filter((item) => {
const label = normalize(item.textContent);
return label && label !== '<select a value>' && !label.includes('select a value');
}).length;
return {
hasTarget,
enabled: !select.disabled && !select.classList.contains('aspNetDisabled'),
optionCount: options.length,
realOptionCount: realOptions,
};
}
""",
value,
)
if isinstance(result, dict):
return result
except Exception:
pass
return {"hasTarget": False, "enabled": False, "optionCount": 0, "realOptionCount": 0}
def _apply_select_value_via_script(locator: Any, value: str) -> bool:
"""通过脚本写入 select 值;SSRS 常在 option 已加载但仍保持 aspNetDisabled。"""
try:
return bool(
locator.evaluate(
"""
(select, target) => {
const normalize = (text) => (text || '').replace(/\\s+/g, ' ').trim();
const wanted = normalize(target).toLowerCase();
const option = Array.from(select.options).find(
(item) => normalize(item.textContent).toLowerCase() === wanted
);
if (!option) return false;
select.disabled = false;
select.classList.remove('aspNetDisabled');
select.removeAttribute('disabled');
select.value = option.value;
select.dispatchEvent(new Event('input', { bubbles: true }));
select.dispatchEvent(new Event('change', { bubbles: true }));
return true;
}
""",
value,
)
)
except Exception:
return False
def _wait_for_warehouse_select_ready(locator: Any, value: str, *, timeout_ms: int) -> tuple[bool, int, dict[str, Any]]:
"""
等待 Warehouse 下拉出现目标 option。
核心逻辑:SSRS 报表参数页会先渲染 Owner/PutawayZone 默认值,Warehouse 的 option 列表
由 ReportViewer 异步拉取;此期间 select 长期保持 aspNetDisabled,肉眼像“卡住不能选”。
"""
started_at = time.monotonic()
deadline = started_at + (timeout_ms / 1000)
last_log_at = 0.0
last_state: dict[str, Any] = {}
while time.monotonic() < deadline:
last_state = _warehouse_select_state(locator, value)
if last_state.get("hasTarget"):
elapsed_ms = int((time.monotonic() - started_at) * 1000)
return True, elapsed_ms, last_state
now = time.monotonic()
if now - last_log_at >= 2.0:
print(
"[dsv-filter] waiting warehouse options "
f"target={value!r} optionCount={last_state.get('optionCount')} "
f"realOptionCount={last_state.get('realOptionCount')} enabled={last_state.get('enabled')}"
)
last_log_at = now
time.sleep(0.2)
elapsed_ms = int((time.monotonic() - started_at) * 1000)
return False, elapsed_ms, last_state
def _wait_until_enabled(locator: Any, *, timeout_ms: int = 15_000) -> bool:
"""等待 SSRS 控件从 aspNetDisabled 变为可操作。"""
deadline = time.monotonic() + (timeout_ms / 1000)
while time.monotonic() < deadline:
try:
disabled = locator.evaluate(
"(node) => Boolean(node.disabled || node.classList.contains('aspNetDisabled'))"
)
if not disabled:
return True
except Exception:
pass
time.sleep(0.25)
return False
def _fill_input_via_script(root: Any, selector: str, value: str) -> bool:
"""
通过脚本解除 disabled 并写入文本框(Owner/PutawayZone 兜底)。
核心逻辑:ReportViewer 初始常把参数控件设为 aspNetDisabled,需先启用再赋值。
"""
try:
return bool(
root.evaluate(
"""
({ selector, value }) => {
const node = document.querySelector(selector);
if (!node) return false;
node.disabled = false;
node.removeAttribute('disabled');
node.classList.remove('aspNetDisabled');
node.readOnly = false;
node.removeAttribute('readonly');
node.value = value;
node.dispatchEvent(new Event('input', { bubbles: true }));
node.dispatchEvent(new Event('change', { bubbles: true }));
return true;
}
""",
{"selector": selector, "value": value},
)
)
except Exception:
return False
def _fill_multi_value_parameter(page: Any, label: str, values: list[str], *, timeout_ms: int) -> bool:
"""
填充 SSRS MultiValueParameterInputControl(Owner / PutawayZone)。
核心逻辑:展开 dropdown → 按 label 勾选/取消 checkbox → 关闭 dropdown。
"""
config = _DSV_REPORT_PARAM_DEFAULTS.get(label, {})
if config.get("control") != "multi_value":
return False
cleaned = [str(item).strip() for item in values if str(item).strip()]
if not cleaned:
return False
_, text_locator = _find_locator(page, config["text"])
if text_locator is not None:
try:
current = str(text_locator.input_value(timeout=2_000) or "").strip()
if current and all(item in current for item in cleaned):
print(f"[dsv-filter] {label} already set text={current!r}")
return True
except Exception:
pass
root, toggle = _find_locator(page, config["toggle"])
if root is not None and toggle is not None:
try:
toggle.click(timeout=timeout_ms, force=True)
time.sleep(0.4)
except Exception:
pass
root, _ = _find_locator(page, config["dropdown"])
if root is None:
return False
desired = {item.casefold() for item in cleaned}
try:
adjusted = root.evaluate(
"""
({ dropdownSelector, desiredValues, restrictToDesired }) => {
const dropdown = document.querySelector(dropdownSelector);
if (!dropdown) return false;
const normalize = (text) => (text || '').replace(/\\s+/g, ' ').trim();
const labels = Array.from(dropdown.querySelectorAll('label'));
let changed = false;
for (const labelNode of labels) {
const text = normalize(labelNode.textContent);
if (!text || text === '(Select All)') continue;
let checkbox = null;
const htmlFor = labelNode.getAttribute('for');
if (htmlFor) {
checkbox = document.getElementById(htmlFor);
}
if (!checkbox) {
checkbox = labelNode.previousElementSibling;
}
if (!checkbox || checkbox.type !== 'checkbox') continue;
const shouldCheck = desiredValues.includes(text.toLowerCase());
if (restrictToDesired) {
if (checkbox.checked !== shouldCheck) {
checkbox.click();
changed = true;
}
} else if (shouldCheck && !checkbox.checked) {
checkbox.click();
changed = true;
}
}
return changed || labels.length > 0;
}
""",
{
"dropdownSelector": config["dropdown"],
"desiredValues": list(desired),
"restrictToDesired": label == "PutawayZone",
},
)
if adjusted:
print(f"[dsv-filter] {label} multi_value checkboxes={cleaned!r}")
if toggle is not None:
try:
toggle.click(timeout=2_000, force=True)
except Exception:
pass
return True
except Exception as exc:
print(f"[dsv-filter] {label} multi_value checkbox failed: {exc}", file=sys.stderr)
joined = ", ".join(cleaned)
for root in _iter_dsv_report_roots(page):
if _fill_input_via_script(root, config["text"], joined):
print(f"[dsv-filter] {label} multi_value script text={joined!r}")
return True
return False
def _fill_select_parameter(page: Any, label: str, value: str, selector: str, *, timeout_ms: int) -> bool:
"""
填充 SSRS ValidValueParameterInputControl(Warehouse 等原生 select)。
核心逻辑:目标 option 出现在 DOM 后即用脚本赋值,不必等 Playwright 可见的 enabled 状态。
"""
_, locator = _find_locator(page, selector)
if locator is None:
return False
wait_cap_ms = min(timeout_ms, 45_000) if label == "Warehouse" else timeout_ms
ready, waited_ms, state = _wait_for_warehouse_select_ready(locator, value, timeout_ms=wait_cap_ms)
if ready and _apply_select_value_via_script(locator, value):
mode = "script-after-options" if not state.get("enabled") else "script-after-enabled"
print(
f"[dsv-filter] {label} select {mode} value={value!r} "
f"waitedMs={waited_ms} selector={selector!r}"
)
return True
if waited_ms >= 500:
print(
f"[dsv-filter] {label} warehouse options not ready after {waited_ms}ms; "
f"fallback enabled-wait state={state!r}"
)
enable_started = time.monotonic()
_wait_until_enabled(locator, timeout_ms=min(wait_cap_ms, 15_000))
enable_wait_ms = int((time.monotonic() - enable_started) * 1000)
if enable_wait_ms >= 500:
print(f"[dsv-filter] {label} enabled-waitMs={enable_wait_ms}")
try:
locator.select_option(label=value, timeout=min(timeout_ms, 10_000))
print(f"[dsv-filter] {label} select_option label={value!r} selector={selector!r}")
return True
except Exception:
pass
if _apply_select_value_via_script(locator, value):
print(f"[dsv-filter] {label} select script fallback value={value!r} selector={selector!r}")
return True
return False
def fill_dsv_filter_if_needed(
page: Any,
selector_env: str,
label: str,
value: str | None,
*,
env: Callable[[str, str], str],
browser_timeout_ms: Callable[[], int],
debug_stage: Callable[..., None] | None = None,
) -> None:
"""
按 ReportViewer 控件类型填充 DSV 报表参数。
核心逻辑:优先使用 JSON/页面默认 selector;Warehouse 走 select_option,Owner/PutawayZone 走 checkbox。
"""
text = str(value or "").strip()
if not text:
return
def _debug(stage: str, target: str) -> None:
if debug_stage is not None:
debug_stage(page, stage, target_text=target)
try:
if page.get_by_text(text, exact=False).first.is_visible(timeout=1_500):
print(f"[dsv-filter] {label} already visible text={text!r}")
_debug(f"filter-skip-{label.lower()}", text)
return
except Exception:
pass
timeout_ms = browser_timeout_ms()
defaults = _DSV_REPORT_PARAM_DEFAULTS.get(label, {})
custom_selector = str(env(selector_env) or "").strip()
selector = custom_selector or defaults.get("selector") or defaults.get("text")
if not selector and not defaults:
print(f"[dsv] skip {label} filter; no selector configured")
_debug(f"filter-no-selector-{label.lower()}", text)
return
values = [part.strip() for part in text.split(",") if part.strip()] if label == "PutawayZone" else [text]
if defaults.get("control") == "multi_value" or label in {"Owner", "PutawayZone"}:
if _fill_multi_value_parameter(page, label, values, timeout_ms=timeout_ms):
_debug(f"filter-filled-{label.lower()}", text)
return
select_selector = custom_selector or defaults.get("selector", "")
if defaults.get("control") == "select" or label == "Warehouse" or select_selector.endswith("ddValue"):
if _fill_select_parameter(page, label, text, select_selector, timeout_ms=timeout_ms):
_debug(f"filter-filled-{label.lower()}", text)
return
print(f"[dsv-filter] filling {label} text={text!r} selector={selector!r}")
for root in _iter_dsv_report_roots(page):
if _fill_input_via_script(root, selector, text):
_debug(f"filter-filled-{label.lower()}", text)
return
# 最后回退:Playwright fill(适用于普通文本参数)
_, locator = _find_locator(page, selector)
if locator is not None:
_wait_until_enabled(locator, timeout_ms=timeout_ms)
try:
locator.fill(text, timeout=timeout_ms)
_debug(f"filter-filled-{label.lower()}", text)
return
except Exception as exc:
print(f"[dsv-filter] {label} fill fallback failed: {exc}", file=sys.stderr)
print(f"[dsv] failed to fill {label} filter text={text!r}", file=sys.stderr)
_debug(f"filter-failed-{label.lower()}", text)
File diff suppressed because it is too large. Load diff
+230 -13
View File
@@ -1,13 +1,130 @@
<#
scripts/start_local.ps1
用途:本地一键启动 HXOPS 前后端与后台 worker。
依赖:backend venv、frontend npm、.env.shared / .env.dev(worker 与 RPA 读取)。
逻辑:先停止本仓库遗留的 backend/worker/frontend 进程并释放 5052/8881 端口,再分别在新 PowerShell 窗口启动各服务。
#>
param(
[ValidateSet("sqlite", "postgres")]
[string]$DbMode = "sqlite",
[string]$DatabaseUrl = "",
[switch]$SkipInstall,
[switch]$SkipWorker
[switch]$SkipWorker,
[switch]$SkipRpaWorker
)
$ErrorActionPreference = "Stop"
$script:LocalFrontendPort = 8881
$script:LocalBackendPort = 5052
function Stop-ProcessSafe {
param(
[int]$ProcessId,
[string]$Label
)
if ($ProcessId -le 0) {
return
}
$proc = Get-Process -Id $ProcessId -ErrorAction SilentlyContinue
if (-not $proc) {
return
}
Write-Host "[$Label] stopping PID $ProcessId ($($proc.ProcessName))" -ForegroundColor Yellow
Stop-Process -Id $ProcessId -Force -ErrorAction SilentlyContinue
}
function Stop-PortListeners {
param(
[int]$Port,
[string]$Label
)
$pids = @(
Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue |
Select-Object -ExpandProperty OwningProcess -Unique
)
foreach ($processId in $pids) {
Stop-ProcessSafe -ProcessId $processId -Label $Label
}
}
function Stop-StaleHxopsPythonProcesses {
param(
[string]$RepoRoot,
[string]$BackendPath
)
$patterns = @(
[regex]::Escape((Join-Path $BackendPath "run.py")),
[regex]::Escape((Join-Path $BackendPath "worker_kb.py")),
[regex]::Escape((Join-Path $BackendPath "workers\worker_shipping_notice.py")),
[regex]::Escape((Join-Path $RepoRoot "scripts\rpa\freight_rpa_worker.py"))
)
Get-CimInstance Win32_Process -Filter "Name='python.exe'" -ErrorAction SilentlyContinue | ForEach-Object {
$cmd = $_.CommandLine
if ([string]::IsNullOrWhiteSpace($cmd)) {
return
}
foreach ($pattern in $patterns) {
if ($cmd -match $pattern) {
Stop-ProcessSafe -ProcessId $_.ProcessId -Label "hxops-python"
return
}
}
}
}
function Stop-StaleHxopsFrontendProcesses {
param([string]$FrontendPath)
$frontendPattern = [regex]::Escape($FrontendPath)
Get-CimInstance Win32_Process -Filter "Name='node.exe'" -ErrorAction SilentlyContinue | ForEach-Object {
$cmd = $_.CommandLine
if ([string]::IsNullOrWhiteSpace($cmd)) {
return
}
if ($cmd -match $frontendPattern -and $cmd -match 'vite') {
Stop-ProcessSafe -ProcessId $_.ProcessId -Label "hxops-frontend"
}
}
}
function Stop-LocalHxopsStack {
param(
[string]$RepoRoot,
[string]$BackendPath,
[string]$FrontendPath
)
Write-Host "[cleanup] stopping stale hxops local processes..." -ForegroundColor Yellow
Stop-StaleHxopsPythonProcesses -RepoRoot $RepoRoot -BackendPath $BackendPath
Stop-StaleHxopsFrontendProcesses -FrontendPath $FrontendPath
Stop-PortListeners -Port $script:LocalBackendPort -Label "backend-port"
Stop-PortListeners -Port $script:LocalFrontendPort -Label "frontend-port"
# Vite 端口被占用时可能漂移到 8882+,一并清理本机 node 监听
for ($port = $script:LocalFrontendPort + 1; $port -le ($script:LocalFrontendPort + 10); $port++) {
$pids = @(
Get-NetTCPConnection -LocalPort $port -State Listen -ErrorAction SilentlyContinue |
Where-Object { (Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName -eq 'node' } |
Select-Object -ExpandProperty OwningProcess -Unique
)
foreach ($processId in $pids) {
Stop-ProcessSafe -ProcessId $processId -Label "stale-vite-$port"
}
}
Start-Sleep -Milliseconds 800
}
function Test-CommandExists {
param([string]$Name)
return $null -ne (Get-Command $Name -ErrorAction SilentlyContinue)
@@ -133,6 +250,62 @@ function Start-BackendWindow {
Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null
}
function Get-DatabaseUrlExport {
param(
[string]$Mode,
[string]$DbUrl
)
if ($Mode -eq "postgres" -and -not [string]::IsNullOrWhiteSpace($DbUrl)) {
$escaped = $DbUrl.Replace("'", "''")
return "`$env:DATABASE_URL='$escaped'; "
}
return ""
}
function Get-DotEnvExportPrefix {
param([string[]]$Paths)
$exports = @()
foreach ($path in $Paths) {
if (-not (Test-Path $path)) {
continue
}
foreach ($line in Get-Content $path) {
if ($line -match '^\s*#' -or $line -match '^\s*$') {
continue
}
if ($line -match '^\s*([^=]+)=(.*)$') {
$name = $matches[1].Trim()
$value = $matches[2].Trim()
if ($value.Length -ge 2 -and (
($value.StartsWith('"') -and $value.EndsWith('"')) -or
($value.StartsWith("'") -and $value.EndsWith("'"))
)) {
$value = $value.Substring(1, $value.Length - 2)
}
$escaped = $value.Replace("'", "''")
$exports += "`$env:$name='$escaped';"
}
}
}
return ($exports -join ' ')
}
function Start-WorkerWindow {
param(
[string]$Title,
[string]$WorkingDirectory,
[string]$Command,
[string]$EnvPrefix = ""
)
$cmd = "$EnvPrefix Set-Location '$WorkingDirectory'; Write-Host '[$Title] started' -ForegroundColor Cyan; $Command"
Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null
}
function Start-KbWorkerWindow {
param(
[string]$BackendPath,
@@ -140,14 +313,42 @@ function Start-KbWorkerWindow {
[string]$DbUrl
)
$dbExport = ""
if ($Mode -eq "postgres" -and -not [string]::IsNullOrWhiteSpace($DbUrl)) {
$escaped = $DbUrl.Replace("'", "''")
$dbExport = "`$env:DATABASE_URL='$escaped'; "
}
Start-WorkerWindow `
-Title "kb-worker" `
-WorkingDirectory $BackendPath `
-EnvPrefix (Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl) `
-Command ".\venv\Scripts\python.exe .\worker_kb.py"
}
$cmd = "$dbExport Set-Location '$BackendPath'; .\venv\Scripts\python.exe .\worker_kb.py"
Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null
function Start-ShippingWorkerWindow {
param(
[string]$BackendPath,
[string]$Mode,
[string]$DbUrl
)
Start-WorkerWindow `
-Title "shipping-worker" `
-WorkingDirectory $BackendPath `
-EnvPrefix (Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl) `
-Command ".\venv\Scripts\python.exe .\workers\worker_shipping_notice.py"
}
function Start-FreightRpaWorkerWindow {
param(
[string]$RepoRoot,
[string]$BackendPath,
[string[]]$EnvFiles
)
$envPrefix = Get-DotEnvExportPrefix -Paths $EnvFiles
$envPrefix += " `$env:HXOPS_API_BASE='http://127.0.0.1:5052'; `$env:FREIGHT_RPA_MOCK='true';"
Start-WorkerWindow `
-Title "freight-rpa-worker" `
-WorkingDirectory $RepoRoot `
-EnvPrefix $envPrefix `
-Command "& '$BackendPath\venv\Scripts\python.exe' .\scripts\rpa\freight_rpa_worker.py"
}
function Start-FrontendWindow {
@@ -169,21 +370,37 @@ $doInstall = -not $SkipInstall.IsPresent
Write-Host "== HXOPS local startup ==" -ForegroundColor Green
Write-Host "mode: $DbMode" -ForegroundColor Green
Stop-LocalHxopsStack -RepoRoot $repoRoot -BackendPath $backendDir -FrontendPath $frontendDir
Ensure-Backend -BackendPath $backendDir -PyCmd $pythonCmd -Mode $DbMode -DbUrl $DatabaseUrl -DoInstall $doInstall
Ensure-Frontend -FrontendPath $frontendDir -DoInstall $doInstall
$envFiles = @(
(Join-Path $repoRoot ".env.shared"),
(Join-Path $repoRoot ".env.dev"),
(Join-Path $repoRoot ".env.local")
)
$windowCount = 2
Start-BackendWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl
if (-not $SkipWorker.IsPresent) {
Start-KbWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl
Start-ShippingWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl
$windowCount += 2
if (-not $SkipRpaWorker.IsPresent) {
Start-FreightRpaWorkerWindow -RepoRoot $repoRoot -BackendPath $backendDir -EnvFiles $envFiles
$windowCount += 1
}
}
Start-FrontendWindow -FrontendPath $frontendDir
$windowCount += 1
Write-Host ""
if ($SkipWorker.IsPresent) {
Write-Host "Started in two new PowerShell windows." -ForegroundColor Green
}
else {
Write-Host "Started in three new PowerShell windows." -ForegroundColor Green
Write-Host "Started in $windowCount new PowerShell windows." -ForegroundColor Green
if (-not $SkipWorker.IsPresent) {
Write-Host "Workers: kb-worker, shipping-worker$(if (-not $SkipRpaWorker.IsPresent) { ', freight-rpa-worker (mock)' })" -ForegroundColor Green
Write-Host "Schedule worker runs inside backend process (SCHEDULE_WORKER_ENABLED)." -ForegroundColor DarkGray
}
Write-Host "Frontend URL: http://127.0.0.1:8881" -ForegroundColor Green
Write-Host "Backend URL: http://127.0.0.1:5052" -ForegroundColor Green
Write-Host "Default local admin (sqlite/init scripts): admin / Hxit@54321" -ForegroundColor Green