feat(shipping-notice): 新增库存确认来源接口及相关逻辑

This commit is contained in:
hugo committed 2026-07-13 21:53:45 +08:00
1 parent a31735b689
commit 0a9bd6415d
69 files changed
+8442 -775

No files matched your search

+21
View File
@@ -262,6 +262,16 @@ def tool_submit_decision():
"""
return jsonify(shipping_tools.submit_decision(_payload()))
@shipping_notice_bp.route('/tools/confirm_inventory_source', methods=['POST'])
def tool_confirm_inventory_source():
"""
确认库存查询来源(仅提交 source_code)。
【AI 触发时机】:用户在库存源人工检查点选择正式库存源后调用。
"""
return jsonify(shipping_tools.confirm_inventory_source(_payload()))
@shipping_notice_bp.route('/tools/generate_shipment_excel', methods=['POST'])
def tool_generate_shipment_excel():
"""
@@ -353,6 +363,17 @@ def rpa_inventory_batch_ready():
"""RPA 批量库存导出回调:按 Warehouse 写入库存快照。"""
return jsonify(shipping_tools.rpa_report_inventory_batch(_payload()))
@shipping_notice_bp.route('/tasks/<task_no>/repair-inventory-attachment', methods=['POST'])
def repair_task_inventory_attachment(task_no: str):
"""
从任务库存快照幂等重建正式附件(不重新消费 RPA callback)。
核心逻辑:供晋升失败或 marker 异常后的人工/后台补偿。
"""
payload = _payload()
payload.setdefault("task_no", task_no)
payload.setdefault("task_id", task_no)
return jsonify(shipping_tools.repair_task_inventory_attachment(payload))
@shipping_notice_bp.route('/rpa/upload-complete', methods=['POST'])
def rpa_upload_complete():
"""RPA 回调入口:上报货代上传结果并回写任务状态。"""
+5 -1
View File
@@ -362,7 +362,11 @@ def workspace_confirm_shipping_inventory_source(task_no: str):
if not source_code:
raise ValidationError('source_code is required')
from app.services.shipping_notice import tools as shipping_tools
return jsonify(shipping_tools.confirm_inventory_source({'task_id': task.task_no, 'source_code': source_code}))
return jsonify(shipping_tools.confirm_inventory_source({
'task_id': task.task_no,
'source_code': source_code,
'_trusted_user_id': user.id,
}))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/apply-inventory-mapping', methods=['POST'])
def workspace_apply_inventory_mapping(task_no: str):
+56
View File
@@ -3,6 +3,7 @@ backend/app/models/shipping.py
用途:货代发货通知批次、任务、事件、库存文件与库存映射模型。
依赖:models.base.Base。
逻辑:ShippingTask 独立字段承载目的地与库存源身份;step_payload_json 仅保留候选/证据等辅助信息。
"""
from __future__ import annotations
@@ -59,6 +60,11 @@ class ShippingTask(Base):
Index('ix_shipping_tasks_conversation', 'conversation_id'),
Index('ix_shipping_tasks_batch_step', 'batch_id', 'current_step'),
Index('ix_shipping_tasks_upload_status', 'upload_status'),
Index('ix_shipping_tasks_inventory_source_code', 'inventory_source_code'),
Index('ix_shipping_tasks_inventory_site_id', 'inventory_site_id'),
Index('ix_shipping_tasks_inventory_source_status', 'inventory_source_status'),
Index('ix_shipping_tasks_inventory_routing_fingerprint', 'inventory_routing_fingerprint'),
Index('ix_shipping_tasks_inventory_rpa_consumed_run_no', 'inventory_rpa_consumed_run_no'),
)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -76,6 +82,21 @@ class ShippingTask(Base):
customer_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
customer_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
ship_to: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
destination_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
destination_city: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
destination_country: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
warehouse_hint: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
inventory_source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
inventory_site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
inventory_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
inventory_source_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
inventory_source_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
inventory_source_confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
inventory_source_confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
inventory_source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
inventory_routing_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
inventory_rpa_consumed_run_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
po_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
required_date: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
lines_json: Mapped[Optional[list]] = mapped_column(JSON, default=list)
@@ -150,6 +171,28 @@ class ShippingInventoryFile(Base):
'snapshot_status',
'exported_at',
),
Index(
'ix_shipping_inventory_files_source_site_wh',
'source_code',
'site_id',
'warehouse_id',
),
Index(
'uq_shipping_inventory_files_rpa_identity_ready',
'rpa_run_no',
'source_code',
'site_id',
'warehouse_id',
unique=True,
postgresql_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND site_id IS NOT NULL AND warehouse_id IS NOT NULL"
),
sqlite_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND site_id IS NOT NULL AND warehouse_id IS NOT NULL"
),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -167,6 +210,9 @@ class ShippingInventoryFile(Base):
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)
site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
identity_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=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)
@@ -193,6 +239,12 @@ class ShippingTaskInventoryLink(Base):
__table_args__ = (
Index('ix_shipping_task_inventory_links_task_active', 'task_id', 'is_active'),
Index('ix_shipping_task_inventory_links_file_active', 'inventory_file_id', 'is_active'),
Index(
'ix_shipping_task_inventory_links_task_source',
'task_id',
'matched_source_code',
'matched_site_id',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -203,6 +255,10 @@ class ShippingTaskInventoryLink(Base):
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)
matched_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
matched_site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
identity_check_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
identity_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, 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)
@@ -80,7 +80,8 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun)
"""
构造排程企微 textcard 跳转 query 参数。
核心逻辑:指向管理端 /admin/schedules;有原始库存归档时附加 raw_zip=1 供深链展示下载入口。
核心逻辑:指向管理端 /admin/schedules;有原始库存归档时附加 raw_zip=1 与 download 意图,
由前端在登录后自动触发一次下载,失败时保留手动下载入口。
"""
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
@@ -91,6 +92,7 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun)
}
if inventory_raw_zip_available_from_summary(summary):
params['raw_zip'] = '1'
params['download'] = 'inventory_raw_zip'
return params
@@ -99,7 +101,7 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
组装排程完成企微 textcard 正文。
核心逻辑:与管理端统计口径一致,展示 total/success/skipped/failed 四列计数;
有原始库存归档时提示点击卡片进入 HXOPS(URL 仅放 jump_url,不写进正文)。
有原始库存归档时提示点击卡片进入 HXOPS 并在登录后自动下载(URL 仅放 jump_url,不写进正文)。
"""
status_label = _WECOM_STATUS_LABEL.get(run.status, run.status)
skipped_count = int(run.skipped_count or 0)
@@ -115,7 +117,7 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
if inventory_raw_zip_available_from_summary(summary):
description += '\n原始库存包:点击本通知进入 HXOPS 下载'
description += '\n原始库存包:点击本通知,登录 HXOPS 后自动下载'
return description
@@ -160,6 +162,19 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
run.run_no, exc,
)
raw_zip_media_id = None
raw_zip_file_name = None
try:
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
raw_zip_path, raw_zip_file_name = resolve_inventory_raw_zip_download(run)
raw_zip_media_id = upload_wecom_temp_media(raw_zip_path.read_bytes(), raw_zip_file_name)
except Exception as exc:
current_app.logger.info(
'[wecom-schedule] raw inventory zip media skipped for run %s: %s',
run.run_no, exc,
)
textcard_ok_count = 0
errors = []
@@ -199,6 +214,22 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
except Exception as exc:
errors.append(f'{u.real_name or u.username}: file exception={exc}')
if raw_zip_media_id:
try:
raw_zip_audit = _create_audit(
f'{_WECOM_EVENT_TYPE}_inventory_raw_zip', u,
title, f'[原始库存包] {raw_zip_file_name}', uuid.uuid4().hex,
)
raw_zip_data = send_wecom_file_message(u.wecom_userid, raw_zip_media_id)
if raw_zip_data.get('errcode') == 0:
raw_zip_audit.status = 'sent'
else:
raw_zip_audit.error_code = str(raw_zip_data.get('errcode'))
raw_zip_audit.error_message = str(raw_zip_data.get('errmsg', 'unknown'))[:255]
errors.append(f'{u.real_name or u.username}: raw zip errcode={raw_zip_data.get("errcode")}')
except Exception as exc:
errors.append(f'{u.real_name or u.username}: raw zip exception={exc}')
if textcard_ok_count > 0:
run.wecom_notified = True
run.wecom_notified_at = datetime.utcnow()
@@ -641,6 +672,22 @@ def start_scheduler(app):
recovered_awaiting,
)
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
recover_pending_rpa_callback_cleanup_jobs,
)
cleanup_count, cleanup_warnings = recover_pending_rpa_callback_cleanup_jobs()
if cleanup_count:
current_app.logger.info(
"[schedule-worker] processed %d RPA callback cleanup job(s) on startup",
cleanup_count,
)
if cleanup_warnings:
current_app.logger.warning(
"[schedule-worker] RPA callback cleanup warnings: %s",
"; ".join(cleanup_warnings[:5]),
)
from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
maybe_alert_rpa_worker_status(force=True)
@@ -264,6 +264,7 @@ class ShippingConfirmInventorySourceAction:
"task_id": task.task_no,
"source_code": source_code,
"event_source": "chat_turn",
"_trusted_user_id": ctx.user_id,
})
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
raise ValidationError(_tool_result_message(result if isinstance(result, dict) else {}) or "confirm_inventory_source failed")
@@ -12,8 +12,10 @@ from typing import Any
from app import db
from app.services.shipping_notice.constants import (
CP_INVENTORY_SOURCE_REVIEW,
CP_MAP_INFER,
CP_PARSE_OK,
PH_INVENTORY_SOURCE_UNRESOLVED,
PH_LOW_CONF,
PH_RPA_PENDING,
PH_SHORTAGE,
@@ -36,9 +38,17 @@ from app.services.shipping_notice.inventory_file_store import (
from app.services.shipping_notice.inventory_upload import (
has_uploaded_task_inventory,
read_task_inventory_schema_preview,
resolve_task_inventory_upload_path,
task_inventory_upload_path,
)
from app.services.shipping_notice.inventory_workflow import ensure_inventory
from app.services.shipping_notice.inventory_source_gate import (
is_inventory_source_stable,
adjudicate_and_apply_inventory_source,
ensure_inventory_source_review_state,
task_needs_parse_review,
transition_task_to_inventory_source_review,
)
from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, resolve_task_ui_state
@@ -160,6 +170,24 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
and not match_completed(task)
)
):
is_low_confidence_parse_confirm = task.pending_human_reason == PH_LOW_CONF
if (
not is_low_confidence_parse_confirm
and (
task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED
or not is_inventory_source_stable(task)
)
):
ui = resolve_task_ui_state(task)
return tool_response(
status="needs_human",
task=task,
message="库存源尚未确定,请先完成订单解析阶段的库存源确认。",
data=serialize_task_for_tool(task),
human_options=ui.human_options,
checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW,
stop_agent_turn=True,
)
apply_task_transition(task, TaskTransition.CONFIRM_PARSE)
task.match_status = None
task.shortage_json = None
@@ -172,6 +200,24 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
comment=comment,
)
db.session.commit()
if not is_inventory_source_stable(task):
adjudication = ensure_inventory_source_review_state(task)
db.session.commit()
return tool_response(
status="ok",
task=task,
message="解析内容已确认,请继续选择正式库存源。",
data={
**serialize_task_for_tool(task),
"inventory_source_candidates": adjudication.candidates,
"inventory_source_status": adjudication.status,
"inventory_source_reason": adjudication.reason,
"destination_candidates": adjudication.destination_candidates,
},
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
human_options=resolve_task_ui_state(task).human_options,
stop_agent_turn=True,
)
if (not task.inventory_lines_json) and (not has_uploaded_task_inventory(task.task_no)):
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
@@ -408,8 +454,8 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.CORRECT_MAPPING)
log_task_event(task, "inventory_mapping_correction_requested", {"comment": comment})
db.session.commit()
upload_path = task_inventory_upload_path(task.task_no)
if upload_path.is_file():
upload_path = resolve_task_inventory_upload_path(task.task_no)
if upload_path is not None:
try:
preview = read_task_inventory_schema_preview(task.task_no)
except OSError as exc:
@@ -444,12 +490,13 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.REPARSE_INVENTORY_DEMOTE)
else:
apply_task_transition(task, TaskTransition.REPARSE_INVENTORY)
upload_path = task_inventory_upload_path(task.task_no)
if upload_path.is_file():
try:
upload_path.unlink()
except OSError:
pass
for suffix in (".xlsx", ".csv"):
upload_path = task_inventory_upload_path(task.task_no, suffix=suffix)
if upload_path.is_file():
try:
upload_path.unlink()
except OSError:
pass
log_task_event(task, "inventory_reparse_requested", {"comment": comment})
db.session.commit()
return tool_response(
@@ -39,6 +39,7 @@ from app.services.shipping_notice.rpa_attempts import (
max_rpa_upload_attempts,
upload_rpa_attempts,
)
from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
from app.services.shipping_notice.tool_common import prepend_tool_message, set_task_step_progress
from app.services.shipping_notice.tool_response import tool_response
@@ -270,6 +271,16 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
)
if not is_inventory_source_stable(task):
return tool_response(
status="needs_human",
task=task,
message="库存源尚未确定,无法执行库存匹配。",
data=serialize_task_for_tool(task),
checkpoint="inventory_source_review",
stop_agent_turn=True,
)
# [STEP 3] 执行匹配并按结果分流。
# fulfillable 时继续走自动串联;shortage/异常时停在人审确认,避免误生成 Excel 或误上传。
def _on_match_progress(processed: int, total: int) -> None:
@@ -363,6 +374,15 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
if not is_inventory_source_stable(task):
return tool_response(
status="failed",
task=task,
message="库存源尚未确定,无法生成发货 Excel。",
data=serialize_task_for_tool(task),
forbidden_next_tools=["upload_to_freight"],
)
# [STEP 1] 若任务已有可下载的导出文件,则直接返回成功,保证重复点击“生成 Excel”幂等。
# 这里不重复生成文件,避免任务已进入 waiting_upload 后再次点击却被旧门禁误判为“未完成匹配”。
if task.export_file_path and not task_export_error_message(task):
@@ -440,6 +460,14 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
if not is_inventory_source_stable(task):
return tool_response(
status="failed",
task=task,
message="库存源尚未确定,无法上传货代系统。",
data=serialize_task_for_tool(task),
)
# [STEP 1] 先确保上传所需的 Excel 已经存在。
# 调用方可能直接请求 upload,此时需要自动补齐 generate_excel 前置步骤。
if not task.export_file_path:
+3 -3
View File
@@ -105,7 +105,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.inventory.mapping_header_mismatch": "列映射与 Excel 表头不匹配。(表头在第 {row} 行){errors} 请根据 schema_preview.headers 重新调用 apply_inventory_mapping。",
"workflow.inventory.parse_failed_detail": "解析库存失败: {error}",
"workflow.inventory.file_missing": "未收到 file 字段",
"workflow.inventory.file_type_unsupported": "仅支持 .xlsx / .xls / .csv 库存文件",
"workflow.inventory.file_type_unsupported": "仅支持 .xlsx / .csv 库存文件",
"workflow.inventory.uploading": "正在上传并解析库存文件",
"workflow.inventory.uploading_detail": "正在处理库存文件 {filename}",
"workflow.inventory.save_failed": "保存库存文件失败: {error}",
@@ -240,7 +240,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.inventory.mapping_header_mismatch": "The column mapping does not match the Excel headers. (The header row is row {row}) {errors} Please call apply_inventory_mapping again using schema_preview.headers.",
"workflow.inventory.parse_failed_detail": "Failed to parse inventory: {error}",
"workflow.inventory.file_missing": "The file field was not received.",
"workflow.inventory.file_type_unsupported": "Only .xlsx / .xls / .csv inventory files are supported.",
"workflow.inventory.file_type_unsupported": "Only .xlsx / .csv inventory files are supported.",
"workflow.inventory.uploading": "Uploading and parsing the inventory file.",
"workflow.inventory.uploading_detail": "Processing inventory file {filename}",
"workflow.inventory.save_failed": "Failed to save inventory file: {error}",
@@ -375,7 +375,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.inventory.mapping_header_mismatch": "การจับคู่คอลัมน์ไม่ตรงกับหัวตาราง Excel (หัวตารางอยู่ที่แถว {row}) {errors} โปรดเรียก apply_inventory_mapping ใหม่โดยอ้างอิง schema_preview.headers",
"workflow.inventory.parse_failed_detail": "解析库存失败: {error}",
"workflow.inventory.file_missing": "ไม่ได้รับฟิลด์ file",
"workflow.inventory.file_type_unsupported": "รองรับเฉพาะไฟล์สต็อก .xlsx / .xls / .csv",
"workflow.inventory.file_type_unsupported": "รองรับเฉพาะไฟล์สต็อก .xlsx / .csv",
"workflow.inventory.uploading": "กำลังอัปโหลดและ解析ไฟล์สต็อก",
"workflow.inventory.uploading_detail": "กำลังประมวลผลไฟล์สต็อก {filename}",
"workflow.inventory.save_failed": "บันทึกไฟล์สต็อกไม่สำเร็จ: {error}",
@@ -0,0 +1,296 @@
"""
services/shipping_notice/inventory_file_identity.py
用途:校验库存 Excel/CSV 文件内容与任务/快照预期库位是否一致。
依赖:openpyxl、csv、app.core.errors.AppError。
逻辑:RPA 回调、人工上传、快照入库前统一调用;流式扫描 Warehouse 列,避免大文件全量加载。
"""
from __future__ import annotations
import csv
from pathlib import Path
from typing import Any, Iterator
from openpyxl import load_workbook
from app.core.errors import AppError
_WAREHOUSE_ID_HEADER_ALIASES = {
"warehouseid",
"warehouse",
"warehousecode",
"warehousecodeid",
"whid",
}
_HEADER_SCAN_ROWS = 20
def _normalize_header_key(value: Any) -> str:
"""将 Excel 表头标准化为可比较 key。"""
return "".join(ch for ch in str(value or "").strip().lower() if ch.isalnum())
def _row_non_empty_count(row: tuple[Any, ...] | list[Any]) -> int:
"""统计行内非空单元格数量,用于跳过标题行。"""
return sum(1 for cell in row if str(cell or "").strip())
def _score_warehouse_header_row(row: tuple[Any, ...] | list[Any]) -> tuple[int, int] | None:
"""
为候选表头行打分并定位 Warehouse 列。
核心逻辑:要求行内至少 2 个非空单元格,避免报表标题行单独出现 Warehouse 被误判为表头。
"""
if _row_non_empty_count(row) < 2:
return None
best_col: int | None = None
for col_idx, cell in enumerate(row):
if _normalize_header_key(cell) in _WAREHOUSE_ID_HEADER_ALIASES:
best_col = col_idx
break
if best_col is None:
return None
score = _row_non_empty_count(row) * 10 + (5 if best_col == 0 else 0)
return score, best_col
def _find_warehouse_column(rows: list[tuple[Any, ...]]) -> tuple[int | None, int | None]:
"""在表头候选区定位得分最高的 Warehouse 列。"""
scan_limit = min(len(rows), _HEADER_SCAN_ROWS)
best_score = 0
best_row: int | None = None
best_col: int | None = None
for row_idx in range(scan_limit):
scored = _score_warehouse_header_row(rows[row_idx])
if scored is None:
continue
score, col_idx = scored
if score > best_score:
best_score = score
best_row = row_idx
best_col = col_idx
return best_row, best_col
def _load_xlsx_header_rows(path: Path, *, max_rows: int = _HEADER_SCAN_ROWS) -> list[tuple[Any, ...]]:
"""仅读取 xlsx 前若干行供表头定位(小内存)。"""
try:
wb = load_workbook(filename=str(path), data_only=True, read_only=True)
except Exception:
return []
try:
ws = wb.active
rows: list[tuple[Any, ...]] = []
for i, row in enumerate(ws.iter_rows(values_only=True)):
if i >= max_rows:
break
rows.append(tuple(row))
return rows
finally:
wb.close()
def _iter_xlsx_warehouse_values(path: Path, *, header_row_idx: int, col_idx: int) -> Iterator[str]:
"""流式遍历 xlsx Warehouse 列非空值。"""
wb = load_workbook(filename=str(path), data_only=True, read_only=True)
try:
ws = wb.active
for i, row in enumerate(ws.iter_rows(values_only=True)):
if i <= header_row_idx:
continue
if col_idx >= len(row):
continue
value = str(row[col_idx] or "").strip().upper()
if value:
yield value
finally:
wb.close()
def _detect_csv_dialect(sample: str) -> csv.Dialect:
"""探测 CSV 分隔符(逗号/分号/Tab 等),失败时回退 excel 方言。"""
try:
return csv.Sniffer().sniff(sample, delimiters=",;\t|")
except csv.Error:
return csv.excel
def _load_csv_header_rows(path: Path, *, max_rows: int = _HEADER_SCAN_ROWS) -> list[tuple[Any, ...]]:
"""仅读取 CSV 前若干行供表头定位。"""
for encoding in ("utf-8-sig", "utf-8", "gbk"):
try:
with path.open("r", encoding=encoding, newline="") as handle:
sample = handle.read(4096)
handle.seek(0)
dialect = _detect_csv_dialect(sample)
rows: list[tuple[Any, ...]] = []
for row in csv.reader(handle, dialect=dialect):
rows.append(tuple(row))
if len(rows) >= max_rows:
break
return rows
except UnicodeDecodeError:
continue
except OSError:
return []
return []
def _iter_csv_warehouse_values(path: Path, *, header_row_idx: int, col_idx: int) -> Iterator[str]:
"""流式遍历 CSV Warehouse 列非空值。"""
for encoding in ("utf-8-sig", "utf-8", "gbk"):
try:
with path.open("r", encoding=encoding, newline="") as handle:
sample = handle.read(4096)
handle.seek(0)
dialect = _detect_csv_dialect(sample)
for row_idx, row in enumerate(csv.reader(handle, dialect=dialect)):
if row_idx <= header_row_idx:
continue
if col_idx >= len(row):
continue
value = str(row[col_idx] or "").strip().upper()
if value:
yield value
return
except UnicodeDecodeError:
continue
except OSError:
return
def load_inventory_csv_rows(path: Path, *, max_rows: int | None = None) -> list[list[Any]]:
"""
读取库存 CSV 行。
核心逻辑:max_rows 为 None 时读取全文件;预览场景请显式传入较小上限。
身份校验请使用流式 extract_warehouse_ids_from_inventory_excel。
"""
limit = None if max_rows is None else max(1, int(max_rows))
for encoding in ("utf-8-sig", "utf-8", "gbk"):
try:
with path.open("r", encoding=encoding, newline="") as handle:
sample = handle.read(4096)
handle.seek(0)
dialect = _detect_csv_dialect(sample)
rows: list[list[Any]] = []
for row in csv.reader(handle, dialect=dialect):
rows.append(list(row))
if limit is not None and len(rows) >= limit:
break
return rows
except UnicodeDecodeError:
continue
except OSError:
return []
return []
def _collect_unique_warehouse_values(values: Iterator[str]) -> set[str]:
"""从 Warehouse 列迭代器收集去重集合。"""
warehouses: set[str] = set()
for value in values:
warehouses.add(value)
return warehouses
def extract_warehouse_ids_from_inventory_excel(path: Path) -> set[str]:
"""
从库存文件提取所有非空 Warehouse ID 值(去重)。
核心逻辑:前 20 行定位表头;数据区流式扫描目标列,避免全表加载。
"""
if not path or not path.is_file():
return set()
suffix = path.suffix.lower()
if suffix == ".csv":
header_rows = _load_csv_header_rows(path)
header_row_idx, col_idx = _find_warehouse_column(header_rows)
if header_row_idx is None or col_idx is None:
return set()
return _collect_unique_warehouse_values(
_iter_csv_warehouse_values(path, header_row_idx=header_row_idx, col_idx=col_idx)
)
if suffix == ".xlsx":
header_rows = _load_xlsx_header_rows(path)
header_row_idx, col_idx = _find_warehouse_column(header_rows)
if header_row_idx is None or col_idx is None:
return set()
return _collect_unique_warehouse_values(
_iter_xlsx_warehouse_values(path, header_row_idx=header_row_idx, col_idx=col_idx)
)
if suffix == ".xls":
return set()
return set()
def assert_inventory_excel_warehouse_identity(
path: Path,
*,
expected_warehouse_id: str,
operation: str = "inventory_import",
) -> str:
"""
强制校验 Excel 内 Warehouse ID 与预期库位一致且唯一。
核心逻辑:混合多库位或内容与预期不符时抛出 AppError,拒绝入库/绑定。
Args:
path: 库存 Excel 路径。
expected_warehouse_id: 任务或运行时 source 要求的库位。
operation: 审计用途的操作名。
Returns:
str: Excel 中唯一的 Warehouse ID(大写)。
Raises:
AppError: 缺列、多库位或与预期不一致。
"""
expected = str(expected_warehouse_id or "").strip().upper()
if not expected:
raise AppError(
code="SHIPPING.INVENTORY_IDENTITY_MISMATCH",
message="预期库位为空,无法校验库存文件内容",
http_status=409,
details={"operation": operation},
)
suffix = path.suffix.lower()
if suffix not in {".xlsx", ".csv"}:
raise AppError(
code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
message="库存源身份校验仅支持 .xlsx / .csv,请转换后重新上传",
http_status=409,
details={"operation": operation, "file_suffix": suffix},
)
found = extract_warehouse_ids_from_inventory_excel(path)
if not found:
raise AppError(
code="SHIPPING.INVENTORY_FILE_WAREHOUSE_MISSING",
message="库存文件缺少可识别的 Warehouse ID 列或数据,已拒绝入库",
http_status=409,
details={"operation": operation, "expected_warehouse_id": expected},
)
if len(found) > 1:
raise AppError(
code="SHIPPING.INVENTORY_FILE_WAREHOUSE_MIXED",
message="库存文件包含多个 Warehouse ID,已拒绝入库",
http_status=409,
details={
"operation": operation,
"expected_warehouse_id": expected,
"excel_warehouse_ids": sorted(found),
},
)
actual = next(iter(found))
if actual != expected:
raise AppError(
code="SHIPPING.INVENTORY_IDENTITY_MISMATCH",
message=f"库存文件 Warehouse ID={actual} 与任务预期库位 {expected} 不一致,已拒绝入库",
http_status=409,
details={
"operation": operation,
"expected_warehouse_id": expected,
"excel_warehouse_id": actual,
},
)
return actual
@@ -17,12 +17,18 @@ from typing import Any
from werkzeug.datastructures import FileStorage
from app import db
from app.core.errors import AppError
from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink
from app.services.shipping_notice.export import _storage_root
from app.services.shipping_notice.inventory_snapshot import (
parse_inventory_excel_with_meta,
read_inventory_schema_preview,
)
from app.services.shipping_notice.inventory_source_gate import (
is_inventory_source_stable,
task_inventory_identity,
)
from app.services.shipping_notice.inventory_sources import get_inventory_sources_config_version
from app.services.shipping_notice.query_service import list_sorted_batch_tasks
_TERMINAL_PROCESS_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
@@ -44,9 +50,79 @@ def generate_inventory_file_no() -> str:
return f"SIF-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
def inventory_file_upload_path(inventory_file_no: str) -> Path:
"""库存快照文件标准落盘路径(inventory_uploads/{inventory_file_no}/inventory.xlsx)。"""
return _storage_root() / "inventory_uploads" / _safe_ref(inventory_file_no) / "inventory.xlsx"
_ALLOWED_INVENTORY_UPLOAD_SUFFIXES = frozenset({".xlsx", ".csv"})
def resolve_inventory_upload_suffix(filename: str) -> str:
"""
解析人工上传库存文件的合法落盘后缀。
核心逻辑:仅允许 .xlsx / .csv;.xls 明确拒绝,避免按 xlsx 误读导致身份校验失败。
Raises:
AppError: 后缀缺失、不支持或为 .xls。
"""
name = str(filename or "").strip().lower()
if not name or "." not in name:
raise AppError(
code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
message="库存上传缺少可识别的文件后缀",
http_status=409,
)
if name.endswith(".xlsx"):
return ".xlsx"
if name.endswith(".csv"):
return ".csv"
if name.endswith(".xls"):
raise AppError(
code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
message="库存上传不支持 .xls,请转换为 .xlsx 或 .csv 后重新上传",
http_status=409,
)
raise AppError(
code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
message="库存上传仅支持 .xlsx / .csv",
http_status=409,
)
def inventory_file_upload_path(inventory_file_no: str, *, suffix: str = ".xlsx") -> Path:
"""库存快照文件标准落盘路径(inventory_uploads/{inventory_file_no}/inventory{suffix})。"""
normalized = str(suffix or ".xlsx").lower()
if normalized not in _ALLOWED_INVENTORY_UPLOAD_SUFFIXES:
normalized = ".xlsx"
return _storage_root() / "inventory_uploads" / _safe_ref(inventory_file_no) / f"inventory{normalized}"
def inventory_storage_suffix_for_path(path: str | Path) -> str:
"""根据已有文件路径推导库存快照落盘后缀,未知格式回退 .xlsx。"""
suffix = Path(path).suffix.lower()
return suffix if suffix in _ALLOWED_INVENTORY_UPLOAD_SUFFIXES else ".xlsx"
def delete_inventory_storage_path(storage_path: str | Path | None) -> None:
"""
删除库存快照托管文件及空目录。
核心逻辑:数据库回滚或唯一约束冲突时清理已复制文件,避免孤儿目录。
"""
import logging
if not storage_path or str(storage_path).startswith("failed://"):
return
path = Path(storage_path)
if path.is_file():
try:
path.unlink()
except OSError as exc:
logging.getLogger(__name__).warning("failed to delete inventory file %s: %s", path, exc)
parent = path.parent
if parent.is_dir():
try:
next(parent.iterdir())
except StopIteration:
try:
parent.rmdir()
except OSError:
pass
def active_inventory_file_for_task(task: ShippingTask) -> ShippingInventoryFile | None:
@@ -77,18 +153,74 @@ def has_uploaded_inventory_file(task: ShippingTask) -> bool:
return False
def _same_stable_inventory_identity(lhs: ShippingTask, rhs: ShippingTask) -> bool:
"""判断两票任务是否具备相同且稳定的库存源身份,供批次库存快照共用。"""
if not is_inventory_source_stable(lhs) or not is_inventory_source_stable(rhs):
return False
left = task_inventory_identity(lhs)
right = task_inventory_identity(rhs)
return (
left["inventory_source_code"] == right["inventory_source_code"]
and left["inventory_site_id"] == right["inventory_site_id"]
and left["inventory_warehouse_id"] == right["inventory_warehouse_id"]
)
def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> ShippingInventoryFile:
"""
保存库存 Excel 并创建批次级库存快照。
【AI 触发时机】:用户为一批发货需求上传库存快照时调用;有 batch 时默认 link 本批全部票。
核心逻辑:快照须携带任务正式库存源身份;批次 link 仅覆盖与上传票库存源一致的可重链任务。
"""
if not is_inventory_source_stable(task):
raise AppError(
code="SHIPPING.INVENTORY_SOURCE_GATE_BLOCKED",
message="库存源尚未稳定,拒绝保存库存上传文件",
http_status=409,
)
identity = task_inventory_identity(task)
source_code = identity["inventory_source_code"] or ""
site_id = identity["inventory_site_id"]
warehouse_id = identity["inventory_warehouse_id"]
from datetime import datetime
inventory_file_no = generate_inventory_file_no()
path = inventory_file_upload_path(inventory_file_no)
upload_suffix = resolve_inventory_upload_suffix(str(upload.filename or ""))
path = inventory_file_upload_path(inventory_file_no, suffix=upload_suffix)
path.parent.mkdir(parents=True, exist_ok=True)
upload.save(str(path))
preview = read_inventory_schema_preview(path)
preview["upload_filename"] = str(upload.filename or path.name)
try:
upload.save(str(path))
from app.services.shipping_notice.inventory_file_identity import (
assert_inventory_excel_warehouse_identity,
)
assert_inventory_excel_warehouse_identity(
path,
expected_warehouse_id=str(warehouse_id or ""),
operation="manual_upload",
)
preview = read_inventory_schema_preview(path)
preview["upload_filename"] = str(upload.filename or path.name)
except AppError:
if path.is_file():
try:
path.unlink()
except OSError:
import logging
logging.getLogger(__name__).warning(
"failed to delete rejected inventory upload file %s", path
)
raise
except Exception:
if path.is_file():
try:
path.unlink()
except OSError:
pass
raise
inv_file = ShippingInventoryFile(
inventory_file_no=inventory_file_no,
@@ -97,16 +229,59 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship
source_file_name=str(upload.filename or "").strip() or path.name,
storage_path=str(path),
schema_preview_json=preview,
share_mode="batch_all" if task.batch_id else "task_only",
share_mode="task_only",
line_count=0,
source_code=source_code,
source_type=str(task.inventory_source_type or "").strip() or None,
site_id=site_id,
warehouse_id=warehouse_id,
source_config_version=task.inventory_source_config_version or get_inventory_sources_config_version(),
identity_status="pending",
snapshot_status="ready",
exported_at=datetime.utcnow(),
)
db.session.add(inv_file)
db.session.flush()
candidates = list_sorted_batch_tasks(task.batch) if task.batch_id and task.batch else [task]
linked_tasks = [item for item in candidates if _can_relink_inventory(item)]
linked_tasks = [
item
for item in candidates
if _can_relink_inventory(item) and _same_stable_inventory_identity(task, item)
]
from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task
created_links: list[ShippingTaskInventoryLink] = []
for item in linked_tasks:
replace_task_inventory_link(item, inv_file, role="owner" if item.id == task.id else "member")
link = link_snapshot_to_task(
item,
inv_file,
reason="manual_upload",
role="owner" if item.id == task.id else "member",
audit_payload={"upload_filename": preview.get("upload_filename")},
)
if link is None:
for prior in created_links:
db.session.delete(prior)
db.session.delete(inv_file)
db.session.flush()
if path.is_file():
try:
path.unlink()
except OSError:
import logging
logging.getLogger(__name__).warning(
"failed to delete inventory upload after link failure %s", path
)
raise AppError(
code="SHIPPING.INVENTORY_IDENTITY_MISMATCH",
message=f"任务 {item.task_no} 与库存快照身份不一致,已拒绝批次绑定",
http_status=409,
)
created_links.append(link)
if len(linked_tasks) > 1:
inv_file.share_mode = "batch_same_identity"
return inv_file
@@ -139,7 +314,8 @@ def save_task_inventory_file_from_local_path(
raise FileNotFoundError(f"未找到库存源文件: {source}")
inventory_file_no = generate_inventory_file_no()
path = inventory_file_upload_path(inventory_file_no)
storage_suffix = inventory_storage_suffix_for_path(source)
path = inventory_file_upload_path(inventory_file_no, suffix=storage_suffix)
path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, path)
preview = read_inventory_schema_preview(path)
@@ -282,6 +282,7 @@ def inventory_loaded_response(
chain_payload: dict[str, Any] | None = None,
field_mapping: dict[str, str] | None = None,
mapping_source: str | None = None,
commit: bool = True,
) -> dict[str, Any]:
"""
库存载入后的统一响应编排:写 inventory_lines → 映射复核或 inventory_ready → 可选 auto-chain。
@@ -289,7 +290,14 @@ def inventory_loaded_response(
Args:
require_mapping_review: True 时进入 align_review;False 时直接 inventory_ready。
chain_payload: 传递给 auto-chain 的原始请求体。
commit: False 时仅 flush,供 batch 外层统一提交,避免中途 commit 破坏事务边界。
"""
def _persist_inventory_loaded() -> None:
if commit:
db.session.commit()
else:
db.session.flush()
# [STEP 1] 先把库存快照写回任务,并计算当前字段对齐视图。
# 后续无论走人工确认还是直接进入 inventory_ready,都需要统一复用这份 field_alignment。
inv_file = active_inventory_file_for_task(task)
@@ -351,8 +359,11 @@ def inventory_loaded_response(
"column_meta": column_meta,
},
)
db.session.commit()
chained = _try_auto_chain_after_inventory_loaded(task, payload=chain_payload)
_persist_inventory_loaded()
if commit:
chained = _try_auto_chain_after_inventory_loaded(task, payload=chain_payload)
else:
chained = None
if chained is not None:
return chained
lang = None
@@ -391,8 +402,8 @@ def inventory_loaded_response(
"linked_task_nos": [item.task_no for item in linked_tasks],
},
)
db.session.commit()
if inv_file:
_persist_inventory_loaded()
if commit and inv_file:
start_inventory_file_linked_tasks(inv_file)
return tool_response(
status="ok",
@@ -0,0 +1,300 @@
"""
services/shipping_notice/inventory_rpa_callback_cleanup.py
用途:RPA callback drop 区文件归档失败后的持久化重试队列、隔离与消费标记。
依赖:rpa.inventory_drop_dir / inventory_processed_dir、json、uuid、Flask current_app。
逻辑:commit 后尝试归档;失败则移入 .hxops_quarantine 并入队;scheduler/worker 启动时定期消费队列。
"""
from __future__ import annotations
import json
import logging
import shutil
import uuid
from datetime import datetime
from pathlib import Path
from typing import Any
from flask import current_app
from app.services.shipping_notice.rpa import inventory_drop_dir, inventory_processed_dir
_CALLBACK_CONSUMED_SUFFIX = ".hxops_consumed"
_CLEANUP_QUEUE_DIRNAME = ".cleanup_queue"
_CLEANUP_FAILED_DIRNAME = ".cleanup_failed"
_QUARANTINE_DIRNAME = ".hxops_quarantine"
_DEFAULT_MAX_CLEANUP_ATTEMPTS = 16
_LOGGER = logging.getLogger(__name__)
def callback_cleanup_queue_dir() -> Path | None:
"""drop 目录下 callback 归档重试队列路径。"""
drop = inventory_drop_dir()
if not drop:
return None
return drop / _CLEANUP_QUEUE_DIRNAME
def callback_cleanup_failed_dir() -> Path | None:
"""超过最大重试次数的 cleanup job 隔离目录。"""
drop = inventory_drop_dir()
if not drop:
return None
return drop / _CLEANUP_FAILED_DIRNAME
def callback_quarantine_dir() -> Path | None:
"""
Worker 不应扫描的 callback 隔离目录(drop 根目录外的子目录)。
归档失败时 HXOPS 将文件原子移入此处,避免重复上报。
"""
drop = inventory_drop_dir()
if not drop:
return None
return drop / _QUARANTINE_DIRNAME
def callback_cleanup_max_attempts() -> int:
"""cleanup job 最大重试次数(SHIPPING_NOTICE_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS)。"""
try:
return max(
1,
int(current_app.config.get("SHIPPING_NOTICE_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS") or _DEFAULT_MAX_CLEANUP_ATTEMPTS),
)
except (TypeError, ValueError):
return _DEFAULT_MAX_CLEANUP_ATTEMPTS
def is_callback_drop_file_consumed(callback_path: Path) -> bool:
"""判断 drop 文件是否已被 HXOPS 消费(sidecar 或已位于 quarantine)。"""
path = Path(callback_path)
if not path.name:
return False
quarantine = callback_quarantine_dir()
if quarantine and quarantine in path.parents:
return True
sidecar = Path(f"{path}{_CALLBACK_CONSUMED_SUFFIX}")
return sidecar.is_file()
def mark_callback_drop_file_consumed(
callback_path: Path,
*,
run_no: str | None = None,
task_no: str | None = None,
schedule_run_id: int | None = None,
inventory_file_no: str | None = None,
) -> None:
"""
标记 drop 区 callback 文件已被系统消费。
核心逻辑:写 sidecar JSON;配合 quarantine 供 Worker 跳过重复扫描(Worker 须忽略 .hxops_* 子目录)。
"""
if not callback_path.is_file():
return
sidecar = Path(f"{callback_path}{_CALLBACK_CONSUMED_SUFFIX}")
payload = {
"callback_path": str(callback_path),
"consumed_at": datetime.utcnow().isoformat(),
"run_no": str(run_no or "").strip() or None,
"task_no": str(task_no or "").strip() or None,
"schedule_run_id": schedule_run_id,
"inventory_file_no": str(inventory_file_no or "").strip() or None,
}
try:
sidecar.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
except OSError as exc:
_LOGGER.warning("failed to write callback consumed marker %s: %s", sidecar, exc)
def quarantine_callback_drop_file(callback_path: Path) -> Path | None:
"""
将归档失败的 callback 原子移入隔离目录,避免 Worker 扫描 drop 根目录时重复上报。
Returns:
隔离后的路径;不可用时返回 None。
"""
path = Path(callback_path)
if not path.is_file():
return None
quarantine = callback_quarantine_dir()
if quarantine is None:
return None
quarantine.mkdir(parents=True, exist_ok=True)
target = quarantine / path.name
if target.exists():
target = quarantine / (
f"{path.stem}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{path.suffix}"
)
shutil.move(str(path), str(target))
consumed = Path(f"{path}{_CALLBACK_CONSUMED_SUFFIX}")
if consumed.is_file():
try:
consumed.unlink()
except OSError:
pass
return target
def enqueue_callback_file_move(
callback_path: Path,
*,
processed_dir: Path,
run_no: str | None = None,
task_no: str | None = None,
schedule_run_id: int | None = None,
error: str | None = None,
) -> Path | None:
"""
将失败的 callback 归档操作写入持久化队列,供后续重试。
Returns:
队列 job 文件路径;队列不可用时返回 None。
"""
queue = callback_cleanup_queue_dir()
if queue is None:
return None
queue.mkdir(parents=True, exist_ok=True)
job_id = uuid.uuid4().hex
job_path = queue / f"move_{job_id}.json"
payload: dict[str, Any] = {
"job_id": job_id,
"callback_path": str(callback_path),
"processed_dir": str(processed_dir),
"run_no": str(run_no or "").strip() or None,
"task_no": str(task_no or "").strip() or None,
"schedule_run_id": schedule_run_id,
"last_error": str(error or "").strip() or None,
"enqueued_at": datetime.utcnow().isoformat(),
"attempts": 0,
}
tmp = job_path.with_suffix(".json.tmp")
try:
tmp.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
tmp.replace(job_path)
except OSError as exc:
_LOGGER.warning("failed to enqueue callback move job for %s: %s", callback_path, exc)
return None
return job_path
def move_callback_drop_file_to_processed(callback_path: Path, processed_dir: Path) -> None:
"""将 callback 文件移入 processed 目录(公开给 workflow 直接调用)。"""
_move_callback_file_to_processed(callback_path, processed_dir)
def _move_callback_file_to_processed(callback_path: Path, processed_dir: Path) -> None:
"""将 callback 文件移入 processed 目录。"""
if not callback_path.is_file():
return
processed_dir.mkdir(parents=True, exist_ok=True)
target = processed_dir / callback_path.name
if target.exists():
target = processed_dir / (
f"{callback_path.stem}_{datetime.utcnow().strftime('%H%M%S')}{callback_path.suffix}"
)
shutil.move(str(callback_path), str(target))
consumed = Path(f"{callback_path}{_CALLBACK_CONSUMED_SUFFIX}")
if consumed.is_file():
try:
consumed.unlink()
except OSError:
pass
def _archive_failed_cleanup_job(job_path: Path, payload: dict[str, Any]) -> None:
"""超过最大重试次数后将 job 移入 failed 目录。"""
failed_dir = callback_cleanup_failed_dir()
if failed_dir is None:
try:
job_path.unlink()
except OSError:
pass
return
failed_dir.mkdir(parents=True, exist_ok=True)
target = failed_dir / job_path.name
payload["archived_at"] = datetime.utcnow().isoformat()
try:
target.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
job_path.unlink()
except OSError as exc:
_LOGGER.warning("failed to archive cleanup job %s: %s", job_path, exc)
def flush_callback_cleanup_queue(*, max_jobs: int = 32) -> list[str]:
"""
重试持久化 callback 归档队列。
核心逻辑:源文件已不存在视为完成;超限 job 移入 failed;仍失败则累加 attempts。
"""
queue = callback_cleanup_queue_dir()
if queue is None or not queue.is_dir():
return []
warnings: list[str] = []
max_attempts = callback_cleanup_max_attempts()
jobs = sorted(queue.glob("move_*.json"))[: max(max_jobs, 1)]
for job_path in jobs:
try:
payload = json.loads(job_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError, TypeError, ValueError) as exc:
warnings.append(f"{job_path.name}:invalid_job:{str(exc)[:80]}")
try:
job_path.unlink()
except OSError:
pass
continue
callback_raw = str(payload.get("callback_path") or "").strip()
processed_raw = str(payload.get("processed_dir") or "").strip()
callback_path = Path(callback_raw) if callback_raw else None
processed_dir = Path(processed_raw) if processed_raw else inventory_processed_dir()
if callback_path is None or processed_dir is None:
try:
job_path.unlink()
except OSError:
pass
continue
if not callback_path.is_file():
try:
job_path.unlink()
except OSError:
pass
continue
if int(payload.get("attempts") or 0) >= max_attempts:
warnings.append(f"{callback_path}:max_attempts_exceeded")
_archive_failed_cleanup_job(job_path, payload)
continue
try:
_move_callback_file_to_processed(callback_path, processed_dir)
try:
job_path.unlink()
except OSError:
pass
except Exception as exc:
payload["attempts"] = int(payload.get("attempts") or 0) + 1
payload["last_error"] = str(exc)[:240]
payload["last_attempt_at"] = datetime.utcnow().isoformat()
warnings.append(f"{callback_path}:{str(exc)[:120]}")
if int(payload["attempts"]) >= max_attempts:
_archive_failed_cleanup_job(job_path, payload)
else:
try:
job_path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
except OSError:
pass
_LOGGER.warning(
"callback cleanup retry failed for %s (attempt=%s)",
callback_path,
payload["attempts"],
exc_info=exc,
)
return warnings
def recover_pending_rpa_callback_cleanup_jobs(*, max_jobs: int = 64) -> tuple[int, list[str]]:
"""
启动或调度恢复时消费 callback cleanup 队列。
Returns:
tuple: (成功消化或移除的 job 数, 告警列表)。
"""
queue = callback_cleanup_queue_dir()
before = len(list(queue.glob("move_*.json"))) if queue and queue.is_dir() else 0
warnings = flush_callback_cleanup_queue(max_jobs=max_jobs)
after = len(list(queue.glob("move_*.json"))) if queue and queue.is_dir() else 0
return max(0, before - after), warnings
File diff suppressed because it is too large. Load diff
@@ -248,7 +248,18 @@ def find_inventory_header_row_index(rows: list[list[Any]], *, max_scan: int = 40
def _load_excel_rows(path: Path, *, max_rows: int | None = None) -> tuple[list[list[Any]], int]:
"""Load worksheet rows; returns (rows, total_row_count_hint)."""
"""Load worksheet or CSV rows; returns (rows, total_row_count_hint)."""
suffix = path.suffix.lower()
if suffix == ".csv":
from app.services.shipping_notice.inventory_file_identity import load_inventory_csv_rows
rows = load_inventory_csv_rows(path, max_rows=max_rows)
try:
total = sum(1 for _ in path.open("r", encoding="utf-8", errors="ignore"))
except OSError:
total = len(rows)
return rows, int(total)
wb = load_workbook(filename=str(path), data_only=True, read_only=True)
try:
ws = wb.active
@@ -14,7 +14,6 @@ from pathlib import Path
from typing import Any
from flask import current_app
from openpyxl import load_workbook
from app import db
from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink
@@ -22,6 +21,7 @@ from app.services.shipping_notice.inventory_file_store import (
_can_relink_inventory,
generate_inventory_file_no,
inventory_file_upload_path,
inventory_storage_suffix_for_path,
replace_task_inventory_link,
)
from app.services.shipping_notice.inventory_snapshot import read_inventory_schema_preview
@@ -71,33 +71,156 @@ def is_snapshot_fresh(inv_file: ShippingInventoryFile, *, now: datetime | None =
def find_latest_ready_snapshot(
source_code: str | None,
warehouse_id: str | None,
site_id: str | None,
warehouse_id: str | None = None,
) -> ShippingInventoryFile | None:
"""
查找指定 source/warehouse 最新 ready 且未过期的库存快照。
核心逻辑:按 exported_at 倒序取第一条;过期快照不在此返回。
查找指定 source/site/warehouse 最新 ready 且未过期的库存快照。
核心逻辑:库存身份须与任务正式库存源一致;site_id 与 warehouse_id 分别匹配,禁止混用。
"""
code = str(source_code or "").strip().upper()
site = str(site_id or "").strip().upper()
warehouse = str(warehouse_id or "").strip().upper()
if not code or not warehouse:
if not code:
return None
if not site and 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()
query = ShippingInventoryFile.query.filter_by(
source_code=code,
snapshot_status=_SNAPSHOT_STATUS_READY,
)
if site:
query = query.filter_by(site_id=site)
if warehouse:
query = query.filter_by(warehouse_id=warehouse)
elif site:
query = query.filter(
(ShippingInventoryFile.warehouse_id.is_(None)) | (ShippingInventoryFile.warehouse_id == "")
)
rows = query.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 find_ready_rpa_inventory_snapshot(
*,
rpa_run_no: str,
source_code: str,
site_id: str,
warehouse_id: str,
) -> ShippingInventoryFile | None:
"""
按 RPA 轮次 + 四字段身份查找已入库 ready 快照。
核心逻辑:定时 finalize 重试或并发回调时复用同一快照,避免重复落盘。
"""
run_no = str(rpa_run_no or "").strip()
code = str(source_code or "").strip().upper()
site = str(site_id or "").strip().upper()
warehouse = str(warehouse_id or "").strip().upper()
if not run_no or not code or not site or not warehouse:
return None
return (
ShippingInventoryFile.query.filter_by(
rpa_run_no=run_no,
source_code=code,
site_id=site,
warehouse_id=warehouse,
snapshot_status=_SNAPSHOT_STATUS_READY,
)
.order_by(ShippingInventoryFile.id.desc())
.first()
)
def get_or_create_rpa_inventory_snapshot(
*,
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,
verify_warehouse_id: str | None = None,
) -> tuple[ShippingInventoryFile, bool]:
"""
幂等创建 RPA 库存快照:同 run_no + 身份已存在时直接复用。
核心逻辑:先查后建;并发插入冲突时回退到 savepoint 并复用已有记录。
Returns:
tuple[ShippingInventoryFile, bool]: (快照, 是否新建)。
"""
from sqlalchemy.exc import IntegrityError
run_no = str(rpa_run_no or "").strip()
code = str(source.get("source_code") or "").strip().upper()
site = str(source.get("site_id") or "").strip().upper()
warehouse = str(verify_warehouse_id or source.get("warehouse_id") or "").strip().upper()
if run_no and code and site and warehouse:
existing = find_ready_rpa_inventory_snapshot(
rpa_run_no=run_no,
source_code=code,
site_id=site,
warehouse_id=warehouse,
)
if existing:
return existing, False
savepoint = db.session.begin_nested()
orphan_storage_path: str | None = None
try:
inv_file = create_inventory_snapshot_from_rpa(
source=source,
local_path=local_path,
source_file_name=source_file_name,
rpa_run_no=rpa_run_no,
schedule_run_id=schedule_run_id,
trigger_type=trigger_type,
success=success,
error_message=error_message,
user_id=user_id,
batch_id=batch_id,
share_mode=share_mode,
verify_warehouse_id=verify_warehouse_id,
)
if inv_file.storage_path and not str(inv_file.storage_path).startswith("failed://"):
orphan_storage_path = str(inv_file.storage_path)
db.session.flush()
savepoint.commit()
return inv_file, True
except IntegrityError:
savepoint.rollback()
if orphan_storage_path:
from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
delete_inventory_storage_path(orphan_storage_path)
if run_no and code and site and warehouse:
existing = find_ready_rpa_inventory_snapshot(
rpa_run_no=run_no,
source_code=code,
site_id=site,
warehouse_id=warehouse,
)
if existing:
return existing, False
raise
except Exception:
savepoint.rollback()
if orphan_storage_path:
from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
delete_inventory_storage_path(orphan_storage_path)
raise
def list_available_snapshots(
*,
source_code: str | None = None,
@@ -126,33 +249,15 @@ def _normalize_header_key(value: Any) -> str:
def _extract_warehouse_id_from_inventory_excel(path: Path) -> str:
"""
从库存 Excel 内容中提取 Warehouse ID。
核心逻辑:扫描前几行表头,命中 Warehouse ID/WH ID 等列后取其下方第一条非空值。
"""
if not path or not path.is_file():
return ""
try:
wb = load_workbook(filename=str(path), data_only=True, read_only=True)
except Exception:
return ""
try:
ws = wb.active
rows = list(ws.iter_rows(min_row=1, max_row=min(ws.max_row or 1, 40), values_only=True))
finally:
wb.close()
"""从库存 Excel 提取首个 Warehouse ID(兼容旧调用)。"""
from app.services.shipping_notice.inventory_file_identity import extract_warehouse_ids_from_inventory_excel
for row_idx, row in enumerate(rows):
for col_idx, cell in enumerate(row):
if _normalize_header_key(cell) not in _WAREHOUSE_ID_HEADER_ALIASES:
continue
for data_row in rows[row_idx + 1:]:
if col_idx >= len(data_row):
continue
value = str(data_row[col_idx] or "").strip().upper()
if value:
return value
return ""
values = extract_warehouse_ids_from_inventory_excel(path)
if not values:
return ""
if len(values) > 1:
return ""
return next(iter(values))
def create_inventory_snapshot_from_rpa(
@@ -168,6 +273,7 @@ def create_inventory_snapshot_from_rpa(
user_id: int | None = None,
batch_id: int | None = None,
share_mode: str | None = None,
verify_warehouse_id: str | None = None,
) -> ShippingInventoryFile:
"""
从 RPA 导出文件创建库存快照记录。
@@ -187,19 +293,39 @@ def create_inventory_snapshot_from_rpa(
source_code = str(source.get("source_code") or "").strip().upper()
configured_site_id = str(source.get("site_id") or "").strip().upper()
export_warehouse_id = str(source.get("warehouse_id") or "").strip().upper()
runtime_identity_applied = bool(source.get("_runtime_identity_applied"))
excel_warehouse_id = ""
warehouse_id = configured_site_id
warehouse_code = warehouse_id
warehouse_id = export_warehouse_id
warehouse_code = warehouse_id or configured_site_id
excel_verified = False
if success:
path = inventory_file_upload_path(inventory_file_no)
path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(local_path, path)
excel_warehouse_id = _extract_warehouse_id_from_inventory_excel(path)
warehouse_id = configured_site_id or excel_warehouse_id
warehouse_code = warehouse_id
preview = read_inventory_schema_preview(path)
preview["upload_filename"] = str(source_file_name or Path(local_path).name).strip() or path.name
local = Path(local_path)
expected_wh = str(verify_warehouse_id or export_warehouse_id or "").strip().upper()
if expected_wh:
from app.services.shipping_notice.inventory_file_identity import (
assert_inventory_excel_warehouse_identity,
)
excel_warehouse_id = assert_inventory_excel_warehouse_identity(
local,
expected_warehouse_id=expected_wh,
operation="rpa_snapshot",
)
warehouse_id = expected_wh
warehouse_code = warehouse_id
excel_verified = True
path = inventory_file_upload_path(
inventory_file_no,
suffix=inventory_storage_suffix_for_path(local),
)
if not excel_verified and not warehouse_id:
excel_warehouse_id = _extract_warehouse_id_from_inventory_excel(local)
if excel_warehouse_id:
warehouse_id = excel_warehouse_id
warehouse_code = warehouse_id
preview = read_inventory_schema_preview(local)
preview["upload_filename"] = str(source_file_name or local.name).strip() or path.name
snapshot_status = _SNAPSHOT_STATUS_READY
storage_path = str(path)
else:
@@ -208,6 +334,8 @@ def create_inventory_snapshot_from_rpa(
snapshot_status = _SNAPSHOT_STATUS_FAILED
storage_path = str(path) if path and path.is_file() else ""
from app.services.shipping_notice.inventory_sources import get_inventory_sources_config_version
inv_file = ShippingInventoryFile(
inventory_file_no=inventory_file_no,
batch_id=batch_id,
@@ -219,6 +347,9 @@ def create_inventory_snapshot_from_rpa(
line_count=0,
warehouse_id=warehouse_id or None,
warehouse_code=warehouse_code or None,
site_id=configured_site_id or None,
source_config_version=get_inventory_sources_config_version(),
identity_status="pending" if success else "unknown",
source_code=source_code or None,
source_type=str(source.get("source_type") or "").strip() or None,
snapshot_status=snapshot_status,
@@ -233,12 +364,38 @@ def create_inventory_snapshot_from_rpa(
"site_id": configured_site_id or None,
"export_warehouse_id": export_warehouse_id,
"excel_warehouse_id": excel_warehouse_id or None,
"warehouse_id_source": "site_id" if configured_site_id else ("inventory_excel" if excel_warehouse_id else None),
"warehouse_id_source": (
"task_identity_excel_verified"
if excel_verified
else (
"runtime_identity"
if runtime_identity_applied
else (
"export_config"
if export_warehouse_id
else ("inventory_excel" if excel_warehouse_id else None)
)
)
),
"excel_warehouse_verified": excel_verified,
"trigger_type": trigger_type,
},
)
db.session.add(inv_file)
db.session.flush()
# [STEP] 先 flush 再落盘:唯一约束冲突时不会留下已复制的孤儿文件。
if success and storage_path and not str(storage_path).startswith("failed://"):
path = Path(storage_path)
path.parent.mkdir(parents=True, exist_ok=True)
try:
shutil.copy2(local_path, path)
except Exception:
if path.exists():
try:
path.unlink()
except OSError:
pass
raise
return inv_file
@@ -247,6 +404,7 @@ def link_snapshot_to_task(
inv_file: ShippingInventoryFile,
*,
reason: str,
role: str = "member",
audit_payload: dict[str, Any] | None = None,
) -> ShippingTaskInventoryLink | None:
"""
@@ -265,9 +423,25 @@ def link_snapshot_to_task(
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")
from app.services.shipping_notice.inventory_source_gate import inventory_identities_match
identity_ok = inventory_identities_match(
task,
source_code=inv_file.source_code,
site_id=inv_file.site_id,
warehouse_id=inv_file.warehouse_id,
)
inv_file.identity_status = "verified" if identity_ok else "mismatch"
if not identity_ok:
return None
link = replace_task_inventory_link(task, inv_file, role=role)
link.link_reason = reason
link.matched_warehouse_id = inv_file.warehouse_id
link.matched_source_code = inv_file.source_code
link.matched_site_id = inv_file.site_id
link.identity_check_status = "verified" if identity_ok else "mismatch"
link.identity_checked_at = datetime.utcnow()
link.snapshot_age_seconds = age_seconds
link.audit_payload_json = {
**(audit_payload or {}),
@@ -0,0 +1,402 @@
"""
services/shipping_notice/inventory_source_gate.py
用途:库存源稳定性门禁、独立字段写入与路由指纹管理。
依赖:inventory_source_rules、inventory_sources、models.ShippingTask、core.errors。
逻辑:订单解析与后续 RPA/库存/匹配/导出流程统一调用本模块,禁止散落判断。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app.core.errors import AppError
from app.models import ShippingTask
from app.services.shipping_notice.inventory_source_identity import identity_matches_config
from app.services.shipping_notice.inventory_source_rules import (
InventorySourceAdjudication,
adjudicate_inventory_source,
confirm_inventory_source_by_code,
compute_routing_fingerprint,
extract_routing_context,
)
from app.services.shipping_notice.inventory_sources import get_inventory_source, get_inventory_sources_config_version
STABLE_INVENTORY_SOURCE_STATUSES = frozenset({"resolved", "user_confirmed"})
INVENTORY_SOURCE_ERROR_CODES = {
"unresolved": "SHIPPING.INVENTORY_SOURCE_UNRESOLVED",
"ambiguous": "SHIPPING.INVENTORY_SOURCE_AMBIGUOUS",
"invalid": "SHIPPING.INVENTORY_SOURCE_INVALID",
"conflicted": "SHIPPING.INVENTORY_SOURCE_CONFLICTED",
"confirmation_required": "SHIPPING.INVENTORY_SOURCE_CONFIRMATION_REQUIRED",
"changed": "SHIPPING.INVENTORY_SOURCE_CHANGED",
"identity_mismatch": "SHIPPING.INVENTORY_IDENTITY_MISMATCH",
"gate_blocked": "SHIPPING.INVENTORY_SOURCE_GATE_BLOCKED",
}
def _inventory_source_config_current(task: ShippingTask) -> bool:
"""任务上记录的库存源配置版本须与当前 YAML 版本一致。"""
stored = str(task.inventory_source_config_version or "").strip()
current = get_inventory_sources_config_version()
if not stored:
return False
return stored == current
def is_inventory_source_stable(task: ShippingTask) -> bool:
"""
判断任务库存源是否稳定,可供后续库存/RPA/匹配流程使用。
核心逻辑:独立字段齐全、配置版本一致、与启用配置身份一致;status 须为 resolved 或 user_confirmed。
"""
status = str(task.inventory_source_status or "").strip()
if status not in STABLE_INVENTORY_SOURCE_STATUSES:
return False
if not _inventory_source_config_current(task):
return False
code = str(task.inventory_source_code or "").strip().upper()
if not code:
return False
source_type = str(task.inventory_source_type or "").strip()
if not source_type:
return False
source = get_inventory_source(code)
if not source:
return False
if source_type != str(source.get("source_type") or "").strip():
return False
site_id = str(task.inventory_site_id or "").strip().upper()
task_wh = str(task.inventory_warehouse_id or "").strip().upper()
if not site_id or not task_wh:
return False
if not identity_matches_config(
source,
site_id=site_id,
warehouse_id=task_wh,
context=extract_routing_context(task),
):
return False
fingerprint = str(task.inventory_routing_fingerprint or "").strip()
if not fingerprint:
return False
context = extract_routing_context(task)
if fingerprint != compute_routing_fingerprint(context):
return False
return True
def routing_fingerprint_changed(task: ShippingTask, context: dict[str, Any]) -> bool:
"""比较当前路由上下文与任务已存指纹,判断人工确认是否因重解析或配置变更失效。"""
previous = str(task.inventory_routing_fingerprint or "").strip()
if not previous:
return False
return previous != compute_routing_fingerprint(context)
def inventory_source_config_changed(task: ShippingTask) -> bool:
"""配置版本变化会使已确认库存源失效。"""
stored = str(task.inventory_source_config_version or "").strip()
if not stored:
return bool(str(task.inventory_source_status or "").strip())
return stored != get_inventory_sources_config_version()
def apply_destination_fields(task: ShippingTask, context: dict[str, Any]) -> None:
"""将标准化目的地线索写入任务独立字段。"""
task.destination_code = str(context.get("destination_code") or "").strip().upper() or None
task.destination_city = str(context.get("destination_city") or "").strip() or None
task.destination_country = str(context.get("destination_country") or "").strip().upper() or None
task.warehouse_hint = str(context.get("warehouse_hint") or "").strip() or None
def clear_inventory_source_confirmation(task: ShippingTask) -> None:
"""路由指纹或配置版本变化时清除旧人工确认信息及过期 RPA 参数。"""
task.inventory_source_confirmed_by = None
task.inventory_source_confirmed_at = None
if str(task.inventory_source_status or "").strip() == "user_confirmed":
task.inventory_source_status = "unresolved"
task.inventory_source_method = None
payload = dict(task.step_payload_json or {})
payload.pop("rpa_inventory_source", None)
task.step_payload_json = payload
def _adjudication_from_stable_task(task: ShippingTask) -> InventorySourceAdjudication:
"""从已稳定任务字段重建裁决结果,供跳过重复裁决时使用。"""
context = extract_routing_context(task)
return InventorySourceAdjudication(
status=str(task.inventory_source_status or "").strip(),
method=str(task.inventory_source_method or "").strip() or None,
source_code=str(task.inventory_source_code or "").strip().upper() or None,
source_type=str(task.inventory_source_type or "").strip() or None,
site_id=str(task.inventory_site_id or "").strip().upper() or None,
warehouse_id=str(task.inventory_warehouse_id or "").strip().upper() or None,
config_version=str(task.inventory_source_config_version or "").strip() or None,
routing_fingerprint=str(task.inventory_routing_fingerprint or "").strip()
or compute_routing_fingerprint(context),
destination_candidates=context.get("destination_candidates") or [],
)
def apply_inventory_source_adjudication(
task: ShippingTask,
adjudication: InventorySourceAdjudication,
*,
confirmed_by_user_id: int | None = None,
) -> None:
"""
将裁决结果写入任务独立字段,并同步候选/证据到 step_payload_json。
核心逻辑:正式身份以独立字段为准;JSON 仅承载展示与审计辅助信息。
"""
context = extract_routing_context(task)
fingerprint = adjudication.routing_fingerprint or compute_routing_fingerprint(context)
task.inventory_routing_fingerprint = fingerprint
apply_destination_fields(task, context)
task.inventory_source_status = adjudication.status
task.inventory_source_method = adjudication.method or None
task.inventory_source_config_version = adjudication.config_version or get_inventory_sources_config_version()
if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code:
task.inventory_source_code = adjudication.source_code
task.inventory_source_type = adjudication.source_type
task.inventory_site_id = adjudication.site_id
task.inventory_warehouse_id = adjudication.warehouse_id or None
if adjudication.status == "user_confirmed" and confirmed_by_user_id:
task.inventory_source_confirmed_by = confirmed_by_user_id
task.inventory_source_confirmed_at = datetime.utcnow()
elif adjudication.status not in STABLE_INVENTORY_SOURCE_STATUSES:
task.inventory_source_code = None
task.inventory_source_type = None
task.inventory_site_id = None
task.inventory_warehouse_id = None
payload = dict(task.step_payload_json or {})
payload.pop("rpa_inventory_source", None)
task.step_payload_json = payload
payload = dict(task.step_payload_json or {})
payload["inventory_source_resolution"] = {
"status": adjudication.status,
"method": adjudication.method,
"reason": adjudication.reason,
"destination_candidates": adjudication.destination_candidates,
"candidates": adjudication.candidates,
"evidence": adjudication.evidence,
"conflicts": adjudication.conflicts,
"config_version": adjudication.config_version,
"routing_fingerprint": fingerprint,
}
if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code:
from app.services.shipping_notice.inventory_sources import build_task_rpa_inventory_source
rpa_source = build_task_rpa_inventory_source(task)
if rpa_source:
payload["rpa_inventory_source"] = rpa_source
else:
payload.pop("rpa_inventory_source", None)
task.step_payload_json = payload
def adjudicate_and_apply_inventory_source(task: ShippingTask) -> InventorySourceAdjudication:
"""
对任务执行库存源裁决并写入独立字段。
【AI 触发时机】:订单解析完成后由 parse_notice 调用;重解析时同样调用以刷新裁决。
"""
context = extract_routing_context(task)
if inventory_source_config_changed(task) or routing_fingerprint_changed(task, context):
clear_inventory_source_confirmation(task)
if (
str(task.inventory_source_status or "").strip() == "user_confirmed"
and is_inventory_source_stable(task)
and not routing_fingerprint_changed(task, context)
and not inventory_source_config_changed(task)
):
return _adjudication_from_stable_task(task)
adjudication = adjudicate_inventory_source(task)
if (
str(task.inventory_source_status or "").strip() == "user_confirmed"
and adjudication.status == "resolved"
and adjudication.source_code
and str(adjudication.source_code).strip().upper() == str(task.inventory_source_code or "").strip().upper()
and is_inventory_source_stable(task)
):
adjudication = InventorySourceAdjudication(
status="user_confirmed",
method="user_confirmed",
source_code=adjudication.source_code,
source_type=adjudication.source_type,
site_id=adjudication.site_id,
warehouse_id=adjudication.warehouse_id,
config_version=adjudication.config_version,
routing_fingerprint=adjudication.routing_fingerprint,
candidates=adjudication.candidates,
destination_candidates=adjudication.destination_candidates,
evidence=adjudication.evidence,
reason=adjudication.reason,
)
apply_inventory_source_adjudication(task, adjudication)
return adjudication
def task_needs_parse_review(task: ShippingTask) -> bool:
"""
判断任务是否仍需完成低置信度解析人工确认。
核心逻辑:优先看 review/pending 标记;库存源先确认时依赖 step_payload 或 parse_confidence 兜底。
"""
from flask import current_app
from app.services.shipping_notice.constants import PH_LOW_CONF, RS_PARSE_REVIEW
if task.review_status == RS_PARSE_REVIEW or task.pending_human_reason == PH_LOW_CONF:
return True
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
if payload.get("pending_parse_review_after_source"):
return True
threshold = float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7)
try:
confidence = float(task.parse_confidence) if task.parse_confidence is not None else 1.0
except (TypeError, ValueError):
confidence = 1.0
lines = task.lines_json if isinstance(task.lines_json, list) else []
return confidence < threshold and bool(lines)
def transition_task_to_inventory_source_review(
task: ShippingTask,
adjudication: InventorySourceAdjudication,
*,
error_message: str | None = None,
mark_pending_parse_review: bool = False,
) -> None:
"""
将任务持久化到库存源人工复核检查点,并写入候选裁决信息。
核心逻辑:统一状态机转换 + current_step + step_payload 候选,供 UI 展示确认按钮。
"""
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW)
task.current_step = "step2_parse_confirm"
task.error_message = error_message or "无法根据发货通知唯一确定库存查询来源"
payload = dict(task.step_payload_json or {})
payload["inventory_source_resolution"] = {
"status": adjudication.status,
"method": adjudication.method,
"reason": adjudication.reason,
"destination_candidates": adjudication.destination_candidates,
"candidates": adjudication.candidates,
"evidence": adjudication.evidence,
"conflicts": adjudication.conflicts,
"config_version": adjudication.config_version,
"routing_fingerprint": adjudication.routing_fingerprint,
}
if mark_pending_parse_review:
payload["pending_parse_review_after_source"] = True
task.step_payload_json = payload
def ensure_inventory_source_review_state(task: ShippingTask) -> InventorySourceAdjudication:
"""
对已进入后续阶段但库存源不稳定的任务补做裁决并落库到 inventory_source_review。
【AI 触发时机】:auto_progress / ensure_inventory 等入口发现门禁未通过时调用。
"""
adjudication = adjudicate_and_apply_inventory_source(task)
if not is_inventory_source_stable(task):
transition_task_to_inventory_source_review(
task,
adjudication,
mark_pending_parse_review=task_needs_parse_review(task),
)
return adjudication
def confirm_task_inventory_source(
task: ShippingTask,
source_code: str,
*,
user_id: int | None = None,
) -> InventorySourceAdjudication:
"""
用户选择 source_code 后由后端重新校验并写入正式库存源。
核心逻辑:前端只提交 source_code;站点与库位始终从配置生成。
"""
adjudication = confirm_inventory_source_by_code(task, source_code)
apply_inventory_source_adjudication(task, adjudication, confirmed_by_user_id=user_id)
return adjudication
def assert_inventory_source_gate(
task: ShippingTask,
*,
operation: str = "continue",
) -> None:
"""
库存源硬门禁:未稳定时抛出统一业务异常,防止后续流程绕过。
Args:
task: 当前发货任务。
operation: 触发门禁的操作名,写入错误 details。
Raises:
AppError: 库存源未稳定或身份不一致。
"""
if inventory_source_config_changed(task):
raise AppError(
code=INVENTORY_SOURCE_ERROR_CODES["changed"],
message="库存源配置已更新,请重新确认库存查询来源",
http_status=409,
details={"operation": operation, "task_no": task.task_no},
)
if is_inventory_source_stable(task):
return
status = str(task.inventory_source_status or "unresolved").strip()
code = INVENTORY_SOURCE_ERROR_CODES.get(status, INVENTORY_SOURCE_ERROR_CODES["gate_blocked"])
raise AppError(
code=code,
message="库存源尚未确定,无法继续后续流程",
http_status=409,
details={
"operation": operation,
"inventory_source_status": status,
"task_no": task.task_no,
},
)
def task_inventory_identity(task: ShippingTask) -> dict[str, str | None]:
"""返回任务当前正式库存身份,供库存文件绑定与匹配校验。"""
return {
"inventory_source_code": str(task.inventory_source_code or "").strip().upper() or None,
"inventory_site_id": str(task.inventory_site_id or "").strip().upper() or None,
"inventory_warehouse_id": str(task.inventory_warehouse_id or "").strip().upper() or None,
}
def inventory_identities_match(
task: ShippingTask,
*,
source_code: str | None,
site_id: str | None,
warehouse_id: str | None,
) -> bool:
"""校验库存文件/链接身份与任务正式库存源是否完全一致。"""
identity = task_inventory_identity(task)
if not is_inventory_source_stable(task):
return False
expected_code = str(source_code or "").strip().upper()
if expected_code != identity["inventory_source_code"]:
return False
file_site = str(site_id or "").strip().upper()
file_wh = str(warehouse_id or "").strip().upper()
if not file_site or file_site != (identity["inventory_site_id"] or ""):
return False
if not file_wh or file_wh != (identity["inventory_warehouse_id"] or ""):
return False
return True
@@ -0,0 +1,156 @@
"""
services/shipping_notice/inventory_source_identity.py
用途:从库存源配置与订单路由上下文解析正式库存身份(source/site/warehouse)。
依赖:无业务模块反向依赖;normalize/match 工具在本文件内定义。
逻辑:裁决、门禁、RPA 与迁移回填统一调用本模块,禁止散落身份推导。
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Any
def normalize_destination(value: Any) -> str:
"""将 Dify/单据中的目的地线索标准化成可匹配 token。"""
text = str(value or "").strip().upper()
if not text:
return ""
return re.sub(r"[^A-Z0-9]+", " ", text).strip()
def _matches_alias(candidate: str, alias: str) -> bool:
"""别名按词元匹配,避免短 token 误命中更长编码。"""
return _alias_token_match(normalize_destination(candidate), alias)
@dataclass(frozen=True)
class ResolvedInventoryIdentity:
"""稳定库存源四元组中的站点/库位解析结果。"""
source_code: str
source_type: str
site_id: str
warehouse_id: str
@dataclass(frozen=True)
class InventoryIdentityResolution:
"""身份解析结果;失败时 reason 说明原因,ambiguous 时带 warehouse 候选。"""
ok: bool
identity: ResolvedInventoryIdentity | None = None
reason: str = ""
warehouse_candidates: tuple[str, ...] = ()
def _alias_token_match(candidate: str, alias: str) -> bool:
"""库位别名按词元精确匹配,禁止短别名误命中长编码。"""
alias_norm = normalize_destination(alias)
if not alias_norm:
return False
if candidate == alias_norm:
return True
return alias_norm in candidate.split()
def _resolve_crane_warehouse_id(source: dict[str, Any], context: dict[str, Any]) -> InventoryIdentityResolution:
"""Crane 库位由订单线索与 match_aliases 唯一命中决定。"""
aliases = [str(alias).strip() for alias in (source.get("match_aliases") or []) if str(alias).strip()]
if not aliases:
return InventoryIdentityResolution(ok=False, reason="crane_aliases_missing")
destination_candidates = list(context.get("destination_candidates") or [])
hint = normalize_destination(context.get("warehouse_hint"))
if hint:
destination_candidates.append(hint)
matched: list[str] = []
for candidate in destination_candidates:
candidate_norm = normalize_destination(candidate)
if not candidate_norm:
continue
for alias in aliases:
if _alias_token_match(candidate_norm, alias):
token = str(alias).strip().upper()
if token and token not in matched:
matched.append(token)
if len(matched) == 1:
site_id = str(source.get("site_id") or "CRANE").strip().upper()
return InventoryIdentityResolution(
ok=True,
identity=ResolvedInventoryIdentity(
source_code=str(source.get("source_code") or "").strip().upper(),
source_type=str(source.get("source_type") or "").strip(),
site_id=site_id,
warehouse_id=matched[0],
),
)
if len(matched) > 1:
return InventoryIdentityResolution(
ok=False,
reason="crane_warehouse_ambiguous",
warehouse_candidates=tuple(matched),
)
return InventoryIdentityResolution(ok=False, reason="crane_warehouse_unresolved")
def resolve_inventory_source_identity(
source: dict[str, Any],
context: dict[str, Any],
) -> InventoryIdentityResolution:
"""
解析库存源在订单上下文下的正式 site_id / warehouse_id。
核心逻辑:DSV 使用配置显式声明;Crane 通过别名唯一命中推导库位。
"""
source_code = str(source.get("source_code") or "").strip().upper()
source_type = str(source.get("source_type") or "").strip()
if not source_code or not source_type:
return InventoryIdentityResolution(ok=False, reason="source_incomplete")
if source_type == "crane_footprint":
return _resolve_crane_warehouse_id(source, context)
site_id = str(source.get("site_id") or "").strip().upper()
warehouse_id = str(source.get("warehouse_id") or "").strip().upper()
if not site_id or not warehouse_id:
return InventoryIdentityResolution(ok=False, reason="identity_incomplete")
return InventoryIdentityResolution(
ok=True,
identity=ResolvedInventoryIdentity(
source_code=source_code,
source_type=source_type,
site_id=site_id,
warehouse_id=warehouse_id,
),
)
def identity_matches_config(
source: dict[str, Any],
*,
site_id: str | None,
warehouse_id: str | None,
context: dict[str, Any] | None = None,
) -> bool:
"""校验任务身份与配置一致;Crane 额外要求库位与当前路由上下文唯一解析结果一致。"""
cfg_site = str(source.get("site_id") or "").strip().upper()
cfg_wh = str(source.get("warehouse_id") or "").strip().upper()
task_site = str(site_id or "").strip().upper()
task_wh = str(warehouse_id or "").strip().upper()
if not task_site or not task_wh:
return False
if cfg_site and task_site != cfg_site:
return False
source_type = str(source.get("source_type") or "").strip()
if source_type == "crane_footprint":
if context is None:
return False
resolution = resolve_inventory_source_identity(source, context)
if not resolution.ok or not resolution.identity:
return False
return resolution.identity.warehouse_id == task_wh
return bool(cfg_wh) and task_wh == cfg_wh
@@ -1,38 +1,89 @@
"""
services/shipping_notice/inventory_source_rules.py
用途:根据发货通知目的地/港口/仓库线索解析应使用的库存 RPA 源。
依赖:inventory_sources、ShippingTask step_payload_json/单头/订单行。
逻辑:从 JSON 配置的 match_aliases 命中库存源;Dify 只提供候选字段,本模块负责标准化与唯一性判断。
用途:根据发货通知路由线索对库存源做确定性裁决。
依赖:inventory_sources、ShippingTask 独立字段与 step_payload_json。
逻辑:Dify/LLM 只提供路由线索;本模块负责唯一性判断、冲突检测与人工确认复核。
"""
from __future__ import annotations
import re
from dataclasses import dataclass
import hashlib
import json
from dataclasses import dataclass, field
from typing import Any
from app.models import ShippingTask
from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source, list_inventory_sources
from app.services.shipping_notice.inventory_source_identity import (
normalize_destination,
resolve_inventory_source_identity,
)
from app.services.shipping_notice.inventory_sources import (
build_rpa_inventory_source,
get_inventory_source,
get_inventory_sources_config_version,
list_inventory_sources,
)
@dataclass(frozen=True)
class InventorySourceResolution:
"""库存源解析结果。"""
class InventorySourceAdjudication:
"""库存源裁决结构化结果。"""
status: str
source: dict[str, Any] | None
candidates: list[dict[str, Any]]
destination_candidates: list[str]
method: str | None = None
source_code: str | None = None
source_type: str | None = None
site_id: str | None = None
warehouse_id: str | None = None
config_version: str | None = None
routing_fingerprint: str | None = None
candidates: list[dict[str, Any]] = field(default_factory=list)
destination_candidates: list[str] = field(default_factory=list)
evidence: list[dict[str, Any]] = field(default_factory=list)
conflicts: list[str] = field(default_factory=list)
reason: str = ""
# Backward-compatible alias
InventorySourceResolution = InventorySourceAdjudication
def compute_routing_fingerprint(context: dict[str, Any]) -> str:
"""
根据标准化路由上下文与配置版本生成可比较指纹。
核心逻辑:相同输入与相同配置版本下指纹必须稳定,用于判断人工确认是否失效。
"""
normalized = {
"destination_code": str(context.get("destination_code") or "").strip().upper(),
"destination_city": str(context.get("destination_city") or "").strip().upper(),
"destination_country": str(context.get("destination_country") or "").strip().upper(),
"warehouse_hint": str(context.get("warehouse_hint") or "").strip().upper(),
"customer_code": str(context.get("customer_code") or "").strip().upper(),
"customer_name": str(context.get("customer_name") or "").strip().upper(),
"order_type": str(context.get("order_type") or "").strip().upper(),
"config_version": get_inventory_sources_config_version(),
"destination_candidates": sorted(
str(item).strip().upper()
for item in (context.get("destination_candidates") or [])
if str(item).strip()
),
}
digest = hashlib.sha256(json.dumps(normalized, sort_keys=True, ensure_ascii=False).encode("utf-8"))
return digest.hexdigest()[:32]
def normalize_destination(value: Any) -> str:
"""将 Dify/单据中的目的地线索标准化成可匹配 token。"""
text = str(value or "").strip().upper()
if not text:
return ""
return re.sub(r"[^A-Z0-9]+", " ", text).strip()
from app.services.shipping_notice.inventory_source_identity import normalize_destination as _normalize
return _normalize(value)
def _matches_alias(candidate: str, alias: str) -> bool:
from app.services.shipping_notice.inventory_source_identity import _matches_alias as _match
return _match(candidate, alias)
def _append_candidate(candidates: list[str], value: Any) -> None:
@@ -45,14 +96,14 @@ def _extract_destination_object(candidates: list[str], value: Any) -> None:
if not isinstance(value, dict):
_append_candidate(candidates, value)
return
for key in ("port_code", "city", "country", "warehouse_hint", "ship_to_location", "raw_text"):
for key in ("port_code", "city", "country", "warehouse_hint", "ship_to_location", "raw_text", "destination_code"):
_append_candidate(candidates, value.get(key))
def extract_destination_candidates(task: ShippingTask) -> list[str]:
"""
从任务解析结果提取目的地/港口/仓库候选。
【AI 触发时机】:需要根据发货通知判断库存 RPA 源时调用,Dify 输出与后端字段都作为候选证据。
【AI 触发时机】:订单解析后由裁决服务调用,Dify 输出与后端字段都作为候选证据。
"""
candidates: list[str] = []
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
@@ -60,6 +111,10 @@ def extract_destination_candidates(task: ShippingTask) -> list[str]:
_append_candidate(candidates, item)
_extract_destination_object(candidates, payload.get("destination"))
_append_candidate(candidates, task.ship_to)
_append_candidate(candidates, task.destination_code)
_append_candidate(candidates, task.destination_city)
_append_candidate(candidates, task.destination_country)
_append_candidate(candidates, task.warehouse_hint)
for line in task.lines_json or []:
if not isinstance(line, dict):
continue
@@ -69,104 +124,413 @@ def extract_destination_candidates(task: ShippingTask) -> list[str]:
return candidates
def _matches_alias(candidate: str, alias: str) -> bool:
normalized_alias = normalize_destination(alias)
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]:
"""人工确认候选项展示字段。"""
def extract_routing_context(task: ShippingTask) -> dict[str, Any]:
"""将任务解析结果标准化为库存路由上下文。"""
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
destination = payload.get("destination") if isinstance(payload.get("destination"), dict) else {}
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"),
"destination_code": task.destination_code or destination.get("port_code") or destination.get("destination_code"),
"destination_city": task.destination_city or destination.get("city"),
"destination_country": task.destination_country or destination.get("country"),
"warehouse_hint": task.warehouse_hint or destination.get("warehouse_hint"),
"customer_code": task.customer_code,
"customer_name": task.customer_name,
"order_type": payload.get("order_type"),
"destination_candidates": extract_destination_candidates(task),
}
def resolve_inventory_source(task: ShippingTask) -> InventorySourceResolution:
"""根据任务目的地候选与 JSON match_aliases 解析唯一库存源。"""
candidates = extract_destination_candidates(task)
matched_codes: list[str] = []
for candidate in candidates:
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)
def _candidate_summary(source: dict[str, Any], *, score: int = 0, matched_by: str | None = None) -> dict[str, Any]:
"""人工确认候选项展示字段;前端必须提交 source_code。"""
return {
"source_code": source.get("source_code"),
"display_name": source.get("display_name"),
"site_id": source.get("site_id"),
"warehouse_id": source.get("warehouse_id"),
"source_type": source.get("source_type"),
"match_score": score,
"matched_by": matched_by,
}
if len(matched_codes) == 1:
source = build_rpa_inventory_source(matched_codes[0])
if source:
return InventorySourceResolution(
status="resolved",
source=source,
candidates=[_candidate_summary(source)],
destination_candidates=candidates,
def _normalize_token_list(values: Any) -> list[str]:
if not isinstance(values, list):
return []
return [normalize_destination(item) for item in values if normalize_destination(item)]
def _all_enabled_source_candidates() -> list[dict[str, Any]]:
"""返回全部启用库存源候选项,供未命中时人工选择。"""
return [
_candidate_summary(source)
for source in list_inventory_sources()
if source.get("enabled", True) is not False
]
def _source_matches_destination(source: dict[str, Any], destination_candidates: list[str]) -> bool:
"""判断库存源别名是否与订单目的地线索有交集。"""
aliases = list(source.get("match_aliases") or [])
match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {}
aliases.extend(_normalize_token_list(match_cfg.get("aliases")))
if not aliases:
return False
return any(_matches_alias(candidate, alias) for candidate in destination_candidates for alias in aliases)
def _source_field_excluded(source: dict[str, Any], context: dict[str, Any]) -> bool:
"""显式 match 规则已声明但订单字段未命中时,排除该库存源。"""
match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {}
for field_name, cfg_key in (
("destination_code", "destination_codes"),
("customer_code", "customers"),
("order_type", "order_types"),
("warehouse_hint", "warehouse_hints"),
):
field_value = normalize_destination(context.get(field_name))
allowed = _normalize_token_list(match_cfg.get(cfg_key))
if allowed and field_value:
if not (
field_value in allowed
or any(field_value in item or item in field_value for item in allowed)
):
return True
return False
def _detect_rule_conflicts(
matches: list[tuple[int, dict[str, Any], list[dict[str, Any]]]],
context: dict[str, Any],
) -> list[str]:
"""多候选同分时,检测不同来源对同一订单字段给出互斥规则命中。"""
conflicts: list[str] = []
field_hits: dict[str, set[str]] = {}
for _, source, _ in matches:
match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {}
for field_name, cfg_key in (
("destination_code", "destination_codes"),
("customer_code", "customers"),
("order_type", "order_types"),
("warehouse_hint", "warehouse_hints"),
):
field_value = normalize_destination(context.get(field_name))
allowed = _normalize_token_list(match_cfg.get(cfg_key))
if not allowed or not field_value:
continue
hits = {
item
for item in allowed
if field_value in item or item in field_value or field_value == item
}
if hits:
field_hits.setdefault(field_name, set()).update(hits)
for field_name, hits in field_hits.items():
if len(hits) > 1:
conflicts.append(f"{field_name}_rule_conflict")
return conflicts
def _source_match_score(source: dict[str, Any], context: dict[str, Any], destination_candidates: list[str]) -> tuple[int, list[dict[str, Any]]]:
"""按配置 match 规则与 match_aliases 计算命中分数与证据。"""
score = 0
evidence: list[dict[str, Any]] = []
match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {}
for field_name, cfg_key in (
("destination_code", "destination_codes"),
("customer_code", "customers"),
("order_type", "order_types"),
("warehouse_hint", "warehouse_hints"),
):
field_value = normalize_destination(context.get(field_name))
allowed = _normalize_token_list(match_cfg.get(cfg_key))
if allowed and field_value:
if field_value in allowed or any(field_value in item or item in field_value for item in allowed):
score += 10
evidence.append({"field": field_name, "value": field_value, "rule": cfg_key})
aliases = list(source.get("match_aliases") or []) + _normalize_token_list(match_cfg.get("aliases"))
for candidate in destination_candidates:
for alias in aliases:
if _matches_alias(candidate, alias):
score += 5
evidence.append({"field": "destination_candidate", "value": candidate, "alias": alias})
break
priority = int(source.get("priority") or 0)
if score > 0 and priority:
score += min(priority // 10, 5)
return score, evidence
def _stable_from_source(
source: dict[str, Any],
*,
method: str,
evidence: list[dict[str, Any]],
context: dict[str, Any],
) -> InventorySourceAdjudication:
"""仅在四元组身份可完整解析时返回 resolved。"""
resolution = resolve_inventory_source_identity(source, context)
config_version = get_inventory_sources_config_version()
fingerprint = compute_routing_fingerprint(context)
destination_candidates = context.get("destination_candidates") or []
if not resolution.ok or not resolution.identity:
if resolution.reason == "crane_warehouse_ambiguous":
return InventorySourceAdjudication(
status="ambiguous",
method=method,
config_version=config_version,
routing_fingerprint=fingerprint,
candidates=[_candidate_summary(source, matched_by=method)],
destination_candidates=destination_candidates,
evidence=evidence,
reason=resolution.reason,
)
if len(matched_codes) > 1:
matched_sources = [
_candidate_summary(source)
for code in matched_codes
for source in [build_rpa_inventory_source(code)]
if source
]
return InventorySourceResolution(
status="ambiguous",
source=None,
candidates=matched_sources,
destination_candidates=candidates,
reason="matched_multiple_sources",
status = "invalid" if resolution.reason in {"source_incomplete", "crane_aliases_missing"} else "unresolved"
return InventorySourceAdjudication(
status=status,
method=method,
config_version=config_version,
routing_fingerprint=fingerprint,
candidates=[_candidate_summary(source, matched_by=method)],
destination_candidates=destination_candidates,
evidence=evidence,
conflicts=[resolution.reason] if resolution.reason else [],
reason=resolution.reason or "identity_incomplete",
)
return InventorySourceResolution(
status="unresolved",
source=None,
candidates=[_candidate_summary(item) for item in list_inventory_sources()],
destination_candidates=candidates,
reason="no_route_rule_matched",
identity = resolution.identity
return InventorySourceAdjudication(
status="resolved",
method=method,
source_code=identity.source_code,
source_type=identity.source_type,
site_id=identity.site_id,
warehouse_id=identity.warehouse_id,
config_version=config_version,
routing_fingerprint=fingerprint,
candidates=[_candidate_summary(source, score=100, matched_by=method)],
destination_candidates=destination_candidates,
evidence=evidence,
)
def adjudicate_inventory_source(task: ShippingTask) -> InventorySourceAdjudication:
"""
根据任务路由上下文与配置规则做确定性库存源裁决。
核心逻辑:相同输入与相同配置必须产生相同结果;区分未命中、多命中、冲突与配置无效。
"""
context = extract_routing_context(task)
destination_candidates = context.get("destination_candidates") or []
config_version = get_inventory_sources_config_version()
scored: list[tuple[int, dict[str, Any], list[dict[str, Any]]]] = []
for source in list_inventory_sources():
if _source_field_excluded(source, context):
continue
source_type = str(source.get("source_type") or "").strip()
if source_type == "dsv360" and (
not str(source.get("site_id") or "").strip()
or not str(source.get("warehouse_id") or "").strip()
):
continue
score, evidence = _source_match_score(source, context, destination_candidates)
if score > 0:
scored.append((score, source, evidence))
if not scored:
# Fallback: legacy match_aliases only
matched_codes: list[str] = []
alias_evidence: dict[str, list[dict[str, Any]]] = {}
for candidate in destination_candidates:
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)
alias_evidence.setdefault(code, []).append(
{"field": "destination_candidate", "value": candidate, "alias_only": True}
)
if len(matched_codes) == 1:
source = get_inventory_source(matched_codes[0])
if source:
return _stable_from_source(
source,
method="rule_exact",
evidence=alias_evidence.get(matched_codes[0], []),
context=context,
)
if len(matched_codes) > 1:
candidates = [
_candidate_summary(src, matched_by="rule_exact")
for code in matched_codes
for src in [get_inventory_source(code)]
if src
]
return InventorySourceAdjudication(
status="ambiguous",
config_version=config_version,
routing_fingerprint=compute_routing_fingerprint(context),
candidates=candidates,
destination_candidates=destination_candidates,
evidence=[item for ev in alias_evidence.values() for item in ev],
reason="matched_multiple_sources",
)
return InventorySourceAdjudication(
status="unresolved",
config_version=config_version,
routing_fingerprint=compute_routing_fingerprint(context),
candidates=_all_enabled_source_candidates(),
destination_candidates=destination_candidates,
reason="no_route_rule_matched",
)
scored.sort(key=lambda item: (-item[0], str(item[1].get("source_code") or "")))
top_score = scored[0][0]
top_matches = [item for item in scored if item[0] == top_score]
if len(top_matches) == 1:
_, source, evidence = top_matches[0]
method = "rule_combined" if len(evidence) > 1 else "rule_exact"
return _stable_from_source(source, method=method, evidence=evidence, context=context)
conflicts = _detect_rule_conflicts(top_matches, context)
if conflicts:
candidates = [_candidate_summary(item[1], score=item[0], matched_by="rule_combined") for item in top_matches]
return InventorySourceAdjudication(
status="conflicted",
config_version=config_version,
routing_fingerprint=compute_routing_fingerprint(context),
candidates=candidates,
destination_candidates=destination_candidates,
evidence=[ev for _, _, ev in top_matches for ev in ev],
conflicts=conflicts,
reason="matched_conflicting_rules",
)
candidates = [_candidate_summary(item[1], score=item[0], matched_by="rule_combined") for item in top_matches]
return InventorySourceAdjudication(
status="ambiguous",
config_version=config_version,
routing_fingerprint=compute_routing_fingerprint(context),
candidates=candidates,
destination_candidates=destination_candidates,
evidence=[ev for _, _, ev in top_matches for ev in ev],
reason="matched_multiple_sources",
)
def confirm_inventory_source_by_code(task: ShippingTask, source_code: str) -> InventorySourceAdjudication:
"""
用户只提交 source_code;站点与库位从配置生成。用户最终选择优先于自动裁决。
【AI 触发时机】:用户在 inventory_source_review 检查点选择正式库存源后调用。
"""
context = extract_routing_context(task)
destination_candidates = context.get("destination_candidates") or []
code = str(source_code or "").strip().upper()
source = get_inventory_source(code)
if not source or source.get("enabled", True) is False:
return InventorySourceAdjudication(
status="invalid",
config_version=get_inventory_sources_config_version(),
routing_fingerprint=compute_routing_fingerprint(context),
candidates=_all_enabled_source_candidates(),
destination_candidates=destination_candidates,
conflicts=["source_code_not_found"],
reason="source_code_not_found",
)
if str(source.get("source_type") or "").strip() == "dsv360" and (
not str(source.get("site_id") or "").strip() or not str(source.get("warehouse_id") or "").strip()
):
return InventorySourceAdjudication(
status="invalid",
config_version=get_inventory_sources_config_version(),
routing_fingerprint=compute_routing_fingerprint(context),
candidates=[_candidate_summary(source)],
destination_candidates=destination_candidates,
conflicts=["identity_incomplete_in_config"],
reason="identity_incomplete_in_config",
)
resolution = resolve_inventory_source_identity(source, context)
if not resolution.ok or not resolution.identity:
status = "ambiguous" if resolution.reason == "crane_warehouse_ambiguous" else "invalid"
return InventorySourceAdjudication(
status=status,
config_version=get_inventory_sources_config_version(),
routing_fingerprint=compute_routing_fingerprint(context),
candidates=[_candidate_summary(source)],
destination_candidates=destination_candidates,
conflicts=[resolution.reason] if resolution.reason else [],
reason=resolution.reason or "identity_incomplete",
)
identity = resolution.identity
return InventorySourceAdjudication(
status="user_confirmed",
method="user_confirmed",
source_code=identity.source_code,
source_type=identity.source_type,
site_id=identity.site_id,
warehouse_id=identity.warehouse_id,
config_version=get_inventory_sources_config_version(),
routing_fingerprint=compute_routing_fingerprint(context),
candidates=[_candidate_summary(source, matched_by="user_confirmed")],
destination_candidates=destination_candidates,
evidence=[{"field": "user_selection", "value": code}],
)
# Backward-compatible wrappers
def resolve_inventory_source(task: ShippingTask) -> InventorySourceAdjudication:
"""兼容旧调用点:委托 adjudicate_inventory_source。"""
return adjudicate_inventory_source(task)
def task_rpa_inventory_source(task: ShippingTask) -> dict[str, Any] | None:
"""读取任务当前已确认的 rpa_inventory_source。"""
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
source = payload.get("rpa_inventory_source")
return source if isinstance(source, dict) and source.get("source_code") else None
"""读取任务当前运行时 RPA source(静态配置 + 任务动态库位)。"""
from app.services.shipping_notice.inventory_sources import build_task_rpa_inventory_source
return build_task_rpa_inventory_source(task)
def save_task_rpa_inventory_source(
task: ShippingTask,
source: dict[str, Any],
*,
resolution: InventorySourceResolution | None = None,
resolution: InventorySourceAdjudication | None = None,
) -> None:
"""把已确认库存源写入 task.step_payload_json,供后续 RPA trigger 使用。"""
payload = dict(task.step_payload_json or {})
payload["rpa_inventory_source"] = source
"""把已确认库存源写入独立字段与 step_payload_json。"""
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
if resolution:
payload["inventory_source_resolution"] = {
"status": resolution.status,
"destination_candidates": resolution.destination_candidates,
"reason": resolution.reason,
}
task.step_payload_json = payload
apply_inventory_source_adjudication(task, resolution)
return
code = str(source.get("source_code") or "").strip().upper()
cfg = get_inventory_source(code)
if not cfg:
return
context = extract_routing_context(task)
resolution = resolve_inventory_source_identity(cfg, context)
if not resolution.ok or not resolution.identity:
return
identity = resolution.identity
adjudication = InventorySourceAdjudication(
status="user_confirmed",
method="user_confirmed",
source_code=identity.source_code,
source_type=identity.source_type,
site_id=identity.site_id,
warehouse_id=identity.warehouse_id,
config_version=get_inventory_sources_config_version(),
routing_fingerprint=compute_routing_fingerprint(context),
)
apply_inventory_source_adjudication(task, adjudication)
def mark_inventory_source_review(task: ShippingTask, resolution: InventorySourceResolution) -> None:
"""库存源无法唯一命中时,把候选项写入 task.step_payload_json 供前端/Agent 展示。"""
payload = dict(task.step_payload_json or {})
payload["inventory_source_resolution"] = {
"status": resolution.status,
"destination_candidates": resolution.destination_candidates,
"reason": resolution.reason,
"candidates": resolution.candidates,
}
task.step_payload_json = payload
def mark_inventory_source_review(task: ShippingTask, resolution: InventorySourceAdjudication) -> None:
"""库存源无法唯一命中时写入候选项;委托 apply_inventory_source_adjudication。"""
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
apply_inventory_source_adjudication(task, resolution)
@@ -22,6 +22,49 @@ _VALID_SOURCE_TYPES = {
}
_VALID_PARAMETER_MODES = frozenset({"single", "multi_text", "multi_select"})
_CONFIG_CACHE: dict[str, Any] | None = None
_CONFIG_PATH: str | None = None
_CONFIG_RAW_DIGEST: str | None = None
def _canonical_source_for_digest(source: dict[str, Any]) -> dict[str, Any]:
"""提取参与版本哈希的语义字段,忽略注释/空白等文件层噪声。"""
match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {}
return {
"source_code": source.get("source_code"),
"source_type": source.get("source_type"),
"site_id": source.get("site_id"),
"warehouse_id": source.get("warehouse_id"),
"warehouse_resolution": source.get("warehouse_resolution"),
"enabled": source.get("enabled", True),
"priority": source.get("priority", 0),
"entry_url": source.get("entry_url"),
"display_name": source.get("display_name"),
"match_aliases": sorted(source.get("match_aliases") or []),
"allowed_warehouse_ids": sorted(source.get("allowed_warehouse_ids") or []),
"match": {
key: sorted(value) if isinstance(value, list) else value
for key, value in sorted(match_cfg.items())
},
"navigation": source.get("navigation"),
"parameters": source.get("parameters"),
"export": source.get("export"),
}
def _normalized_config_digest(sources: dict[str, dict[str, Any]]) -> str:
"""基于规范化结构计算配置内容哈希。"""
import hashlib
canonical = [_canonical_source_for_digest(sources[code]) for code in sorted(sources)]
payload = json.dumps(canonical, sort_keys=True, ensure_ascii=False)
return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]
def _config_content_version(payload: dict[str, Any], sources: dict[str, dict[str, Any]]) -> str:
"""配置版本 = 声明版本 + 规范化结构哈希。"""
digest = _normalized_config_digest(sources)
declared = str(payload.get("version") or "1").strip()
return f"{declared}-{digest}"
class InventorySourceConfigError(ValueError):
@@ -131,6 +174,11 @@ def _build_legacy_query(source: dict[str, Any]) -> dict[str, Any]:
return query
def effective_warehouse_id(source: dict[str, Any]) -> str:
"""返回配置中显式声明的 warehouse_id;禁止用 site_id 回填。"""
return str(source.get("warehouse_id") or "").strip().upper()
def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str, Any]:
"""校验并规范化单条库存源配置。"""
source_code = str(raw.get("source_code") or "").strip().upper()
@@ -146,8 +194,31 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
warehouse_id = str(raw.get("warehouse_id") or "").strip().upper()
site_id = str(raw.get("site_id") or "").strip().upper()
if source_type == "dsv360" and not site_id:
raise InventorySourceConfigError(f"{source_code}: site_id is required for dsv360")
if source_type == "dsv360":
if not site_id:
raise InventorySourceConfigError(f"{source_code}: site_id is required for dsv360")
if not warehouse_id:
raise InventorySourceConfigError(f"{source_code}: warehouse_id is required for dsv360")
elif source_type == "crane_footprint":
if not site_id:
raise InventorySourceConfigError(f"{source_code}: site_id is required for crane_footprint")
aliases = [str(alias).strip() for alias in (raw.get("match_aliases") or []) if str(alias).strip()]
if not aliases:
raise InventorySourceConfigError(f"{source_code}: match_aliases is required for crane_footprint")
allowed_warehouse_ids = [
str(item).strip()
for item in (raw.get("allowed_warehouse_ids") or [])
if str(item).strip()
]
if not allowed_warehouse_ids:
raise InventorySourceConfigError(
f"{source_code}: allowed_warehouse_ids is required for crane_footprint"
)
warehouse_resolution = str(raw.get("warehouse_resolution") or "alias_match").strip().lower()
if warehouse_resolution != "alias_match":
raise InventorySourceConfigError(
f"{source_code}: warehouse_resolution must be alias_match for crane_footprint"
)
parameters: list[dict[str, Any]] = []
for item in raw.get("parameters") or []:
if not isinstance(item, dict):
@@ -167,6 +238,7 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
"site_id": site_id,
"display_name": str(raw.get("display_name") or source_code).strip(),
"enabled": bool(raw.get("enabled", True)),
"priority": int(raw.get("priority") or 0),
"entry_url": str(raw.get("entry_url") or "").strip(),
"warehouse_id": warehouse_id,
"navigation": dict(raw.get("navigation") or {}),
@@ -177,6 +249,18 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
if str(alias).strip()
],
}
if source_type == "crane_footprint":
normalized["warehouse_resolution"] = str(raw.get("warehouse_resolution") or "alias_match").strip().lower()
normalized["allowed_warehouse_ids"] = allowed_warehouse_ids
match_cfg = raw.get("match")
if isinstance(match_cfg, dict) and match_cfg:
normalized["match"] = {
"destination_codes": [str(v).strip() for v in (match_cfg.get("destination_codes") or []) if str(v).strip()],
"customers": [str(v).strip() for v in (match_cfg.get("customers") or []) if str(v).strip()],
"order_types": [str(v).strip() for v in (match_cfg.get("order_types") or []) if str(v).strip()],
"warehouse_hints": [str(v).strip() for v in (match_cfg.get("warehouse_hints") or []) if str(v).strip()],
"aliases": [str(v).strip() for v in (match_cfg.get("aliases") or []) if str(v).strip()],
}
if source_type == "crane_footprint" and raw.get("export"):
normalized["export"] = dict(raw.get("export") or {})
normalized["query"] = _build_legacy_query(normalized)
@@ -184,15 +268,24 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
def _load_config(*, force_reload: bool = False) -> dict[str, Any]:
"""加载并缓存 YAML/JSON 配置;force_reload 用于测试。"""
global _CONFIG_CACHE
if _CONFIG_CACHE is not None and not force_reload:
return _CONFIG_CACHE
"""加载并缓存 YAML/JSON 配置;路径或文件内容变化时刷新(不依赖 mtime 单独命中)。"""
import hashlib
global _CONFIG_CACHE, _CONFIG_PATH, _CONFIG_RAW_DIGEST
path = _config_path()
if not path.is_file():
raise InventorySourceConfigError(f"inventory sources config not found: {path}")
path_str = str(path.resolve())
raw_digest = hashlib.sha256(path.read_bytes()).hexdigest()[:16]
if (
_CONFIG_CACHE is not None
and not force_reload
and _CONFIG_PATH == path_str
and _CONFIG_RAW_DIGEST == raw_digest
):
return _CONFIG_CACHE
payload = _parse_config_payload(path)
sources_raw = payload.get("sources")
if not isinstance(sources_raw, list):
@@ -207,13 +300,21 @@ def _load_config(*, force_reload: bool = False) -> dict[str, Any]:
sources[normalized["source_code"]] = normalized
_CONFIG_CACHE = {
"version": int(payload.get("version") or 1),
"version": _config_content_version(payload, sources),
"sources": sources,
"path": str(path),
"path": path_str,
"raw_digest": raw_digest,
}
_CONFIG_PATH = path_str
_CONFIG_RAW_DIGEST = raw_digest
return _CONFIG_CACHE
def get_inventory_sources_config_version() -> str:
"""返回当前加载的库存源配置版本字符串。"""
return str(_load_config().get("version") or "1")
def reload_inventory_sources_config() -> dict[str, Any]:
"""强制重新加载库存源配置(管理/测试用)。"""
return _load_config(force_reload=True)
@@ -230,6 +331,44 @@ def get_inventory_source(source_code: str | None) -> dict[str, Any] | None:
return deepcopy(source)
def source_uses_dynamic_warehouse_id(source: dict[str, Any] | None) -> bool:
"""判断库存源是否采用运行时动态库位(如 CRANE alias_match)。"""
if not source:
return False
if str(source.get("warehouse_id") or "").strip():
return False
resolution = str(source.get("warehouse_resolution") or "").strip().lower()
return resolution in {"alias_match", "dynamic", "runtime"}
def configured_warehouse_aliases(source: dict[str, Any] | None) -> set[str]:
"""返回配置中的路由匹配别名集合(大写),供订单目的地裁决使用。"""
if not source:
return set()
return {
str(alias).strip().upper()
for alias in (source.get("match_aliases") or [])
if str(alias).strip()
}
def configured_allowed_warehouse_ids(source: dict[str, Any] | None) -> set[str]:
"""
返回 Worker 回调允许落库的库位 ID 集合(大写)。
核心逻辑:优先读 allowed_warehouse_ids;静态源回退 warehouse_id;与 match_aliases 解耦。
"""
if not source:
return set()
allowed = source.get("allowed_warehouse_ids")
if allowed:
return {str(item).strip().upper() for item in allowed if str(item).strip()}
# fallback for static DSV 等源
warehouse_id = str(source.get("warehouse_id") or "").strip().upper()
if warehouse_id:
return {warehouse_id}
return set()
def list_inventory_sources(*, enabled_only: bool = True) -> list[dict[str, Any]]:
"""返回库存源配置副本,供人工检查点展示候选项。"""
sources = _load_config()["sources"].values()
@@ -242,6 +381,8 @@ def build_rpa_inventory_source(
source_code: str | None,
*,
query_override: dict[str, Any] | None = None,
site_id: str | None = None,
warehouse_id: str | None = None,
) -> dict[str, Any] | None:
"""
构造 RPA trigger 使用的 rpa_inventory_source。
@@ -256,4 +397,59 @@ def build_rpa_inventory_source(
if value is not None and str(value).strip():
query[key] = value
source["query"] = query
return source
return merge_runtime_inventory_identity(source, site_id=site_id, warehouse_id=warehouse_id)
def merge_runtime_inventory_identity(
source: dict[str, Any],
*,
site_id: str | None = None,
warehouse_id: str | None = None,
) -> dict[str, Any]:
"""
将任务已解析的 site/warehouse 合并进 RPA source,并同步 query.warehouse_code。
核心逻辑:Crane 动态库位、DSV 子仓均通过本函数进入 trigger/回调/快照复用。
"""
merged = deepcopy(source)
site = str(site_id or merged.get("site_id") or "").strip().upper()
warehouse = str(warehouse_id or merged.get("warehouse_id") or "").strip().upper()
if site:
merged["site_id"] = site
if warehouse:
merged["warehouse_id"] = warehouse
merged["_runtime_identity_applied"] = True
query = dict(merged.get("query") or {})
query["warehouse_code"] = warehouse
merged["query"] = query
source_type = str(merged.get("source_type") or "").strip()
if source_type == "crane_footprint":
navigation = dict(merged.get("navigation") or {})
navigation["project_code"] = warehouse
merged["navigation"] = navigation
query["project_code"] = warehouse
merged["query"] = query
return merged
def build_task_rpa_inventory_source(task: "ShippingTask") -> dict[str, Any] | None:
"""
基于任务正式库存身份构造运行时 RPA source(配置 + 动态库位)。
【AI 触发时机】:ensure_inventory_via_rpa、RPA 回调、快照复用统一调用。
"""
from app.models import ShippingTask
if not isinstance(task, ShippingTask):
return None
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
code = str(task.inventory_source_code or "").strip().upper()
site_id = str(task.inventory_site_id or "").strip().upper() or None
warehouse_id = str(task.inventory_warehouse_id or "").strip().upper() or None
if not code:
legacy = payload.get("rpa_inventory_source")
if isinstance(legacy, dict) and legacy.get("source_code"):
return merge_runtime_inventory_identity(legacy, site_id=site_id, warehouse_id=warehouse_id)
return None
base = get_inventory_source(code)
if not base:
return None
return merge_runtime_inventory_identity(base, site_id=site_id, warehouse_id=warehouse_id)
@@ -3,25 +3,199 @@ services/shipping_notice/inventory_upload.py
用途:管理任务级库存附件上传、落盘、schema preview 读取与文本长度限制。
依赖:inventory_snapshot、export._storage_root、Werkzeug FileStorage、Flask current_app 配置。
逻辑:由 inventory_workflow、task_workflow 与工作台上传入口调用本文件,把库存文件保存到任务目录并读取预览信息。
逻辑:由 inventory_workflow、task_workflow 与工作台上传入口调用本文件,把库存文件保存到任务目录并读取预览信息;
正式附件使用版本化文件名 + .current_inventory 原子指针,避免多格式并存或崩溃后误读旧文件。
"""
from __future__ import annotations
import hashlib
import re
import shutil
from datetime import datetime
from pathlib import Path
from typing import Any
from flask import current_app
from werkzeug.datastructures import FileStorage
from app.models import ShippingInventoryFile, ShippingTask
from app.services.shipping_notice.export import _storage_root
from app.services.shipping_notice.inventory_file_store import inventory_storage_suffix_for_path
from app.services.shipping_notice.inventory_snapshot import (
parse_inventory_excel_with_meta,
read_inventory_schema_preview,
)
_TASK_INVENTORY_SUFFIXES = (".xlsx", ".csv")
_TASK_INVENTORY_MARKER = ".current_inventory"
_TASK_INVENTORY_VERSION_PREFIX = "inventory_"
def _inventory_file_sha256(path: Path) -> str:
"""计算库存附件 SHA256,用于幂等安装判断。"""
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _task_inventory_attachment_marker_path(task_no: str) -> Path:
"""任务当前正式库存附件指针文件路径。"""
return _task_inventory_upload_dir(task_no) / _TASK_INVENTORY_MARKER
def _atomic_write_task_inventory_marker(task_no: str, attachment_filename: str) -> None:
"""通过临时文件 + os.replace 原子切换 .current_inventory 指针。"""
import os
marker = _task_inventory_attachment_marker_path(task_no)
tmp = marker.with_name(f"{marker.name}.tmp")
marker.parent.mkdir(parents=True, exist_ok=True)
tmp.write_text(attachment_filename, encoding="utf-8")
os.replace(tmp, marker)
def _read_task_inventory_attachment_marker(task_no: str) -> Path | None:
"""读取指针文件并校验对应附件仍存在。"""
marker = _task_inventory_attachment_marker_path(task_no)
if not marker.is_file():
return None
name = marker.read_text(encoding="utf-8").strip()
if not name:
return None
path = _task_inventory_upload_dir(task_no) / name
if path.is_file() and _is_task_inventory_attachment_name(path.name):
return path
return None
def _is_task_inventory_attachment_name(name: str) -> bool:
"""判断文件名是否为合法任务库存附件。"""
lowered = str(name or "").lower()
if not lowered.startswith("inventory"):
return False
return any(lowered.endswith(suffix) for suffix in _TASK_INVENTORY_SUFFIXES)
def _versioned_task_inventory_path(task_no: str, suffix: str) -> Path:
"""生成不可变版本化任务库存附件路径。"""
token = datetime.utcnow().strftime("%Y%m%d%H%M%S%f")
normalized = suffix if suffix in _TASK_INVENTORY_SUFFIXES else ".xlsx"
return _task_inventory_upload_dir(task_no) / f"{_TASK_INVENTORY_VERSION_PREFIX}{token}{normalized}"
def _list_task_inventory_attachment_candidates(task_no: str) -> list[Path]:
"""列出任务目录下全部库存附件候选文件。"""
base = _task_inventory_upload_dir(task_no)
if not base.is_dir():
return []
return [
path
for path in base.iterdir()
if path.is_file() and _is_task_inventory_attachment_name(path.name)
]
def _cleanup_superseded_task_inventory_files(task_no: str, *, keep_name: str) -> list[str]:
"""
指针切换后清理旧版附件(best effort)。
Returns:
未能删除的文件名列表。
"""
warnings: list[str] = []
for path in _list_task_inventory_attachment_candidates(task_no):
if path.name == keep_name:
continue
try:
path.unlink()
except OSError as exc:
warnings.append(f"{path.name}:{str(exc)[:80]}")
return warnings
def install_task_inventory_attachment_from_file(
task_no: str,
source_path: str | Path,
*,
source_file_name: str | None = None,
) -> Path:
"""
将源库存文件安装为任务正式附件(版本化文件名 + 原子 marker 切换)。
【AI 触发时机】:RPA 回调晋升失败补偿、人工修复任务附件时调用;不依赖重新消费 callback。
核心逻辑:复制到 inventory_{timestamp}{suffix} → 原子切换 .current_inventory → 清理旧附件。
若当前正式附件与源文件内容一致则幂等返回现有路径。
Args:
task_no: 发货任务号。
source_path: 源库存文件(通常为 inv_file.storage_path 或 staging)。
source_file_name: 可选展示名,仅用于日志语义。
Returns:
安装后的正式附件路径。
Raises:
FileNotFoundError: 源文件不存在。
OSError: 复制或 marker 切换失败。
"""
source = Path(source_path)
if not source.is_file():
raise FileNotFoundError(f"未找到库存源文件: {source}")
current = resolve_task_inventory_upload_path(task_no)
if current is not None and _inventory_file_sha256(current) == _inventory_file_sha256(source):
return current
suffix = inventory_storage_suffix_for_path(source)
versioned = _versioned_task_inventory_path(task_no, suffix)
versioned.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, versioned)
try:
_atomic_write_task_inventory_marker(task_no, versioned.name)
_cleanup_superseded_task_inventory_files(task_no, keep_name=versioned.name)
except Exception:
if versioned.is_file():
try:
versioned.unlink()
except OSError:
pass
raise
if source_file_name:
_ = source_file_name
return versioned
def rebuild_task_inventory_attachment_from_snapshot(
task: ShippingTask | str,
inv_file: ShippingInventoryFile,
) -> Path:
"""
从已提交库存快照 storage_path 幂等重建任务正式附件。
【AI 触发时机】:RPA 回调 DB 已提交但任务附件晋升失败,或运维人工补偿时调用。
Args:
task: 任务对象或 task_no。
inv_file: 已链接的库存快照。
Returns:
重建后的任务正式附件路径。
"""
task_no = task.task_no if isinstance(task, ShippingTask) else str(task or "").strip()
if not task_no:
raise ValueError("task_no is required")
storage_path = Path(str(inv_file.storage_path or ""))
if not storage_path.is_file() or str(inv_file.storage_path or "").startswith("failed://"):
raise FileNotFoundError(
f"库存快照托管文件不存在: {inv_file.inventory_file_no}",
)
return install_task_inventory_attachment_from_file(
task_no,
storage_path,
source_file_name=str(inv_file.source_file_name or storage_path.name),
)
def inventory_text_max_chars() -> int:
"""库存粘贴文本最大字符数(SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS,默认 80000)。"""
@@ -31,18 +205,72 @@ def inventory_text_max_chars() -> int:
return 80000
def task_inventory_upload_path(task_no: str) -> Path:
"""任务级库存 Excel 标准落盘路径(inventory_uploads/{task_no}/inventory.xlsx)。"""
safe = re.sub(r"[^\w\-]+", "_", str(task_no or "").strip()) or "unknown"
return _storage_root() / "inventory_uploads" / safe / "inventory.xlsx"
def _task_inventory_upload_dir(task_no: str) -> Path:
"""任务级库存附件目录(inventory_uploads/{task_no})。"""
safe = _sanitize_task_no(task_no)
return _storage_root() / "inventory_uploads" / safe
def task_inventory_upload_path(task_no: str, *, suffix: str | None = None) -> Path:
"""
任务级库存附件标准落盘路径(默认 inventory.xlsx)。
suffix 仅允许 .xlsx / .csv,用于 RPA 回调保留源文件格式。
"""
normalized = (suffix or ".xlsx").lower()
if normalized not in _TASK_INVENTORY_SUFFIXES:
normalized = ".xlsx"
return _task_inventory_upload_dir(task_no) / f"inventory{normalized}"
def _recover_and_repair_task_inventory_marker(task_no: str) -> Path | None:
"""
marker 缺失或损坏时扫描附件目录并修复 .current_inventory。
核心逻辑:仅在此路径下根据 mtime 选择候选;修复后返回已提交附件。
"""
candidates = _list_task_inventory_attachment_candidates(task_no)
if not candidates:
return None
versioned = [
path
for path in candidates
if path.name.startswith(_TASK_INVENTORY_VERSION_PREFIX)
]
if versioned:
chosen = max(versioned, key=lambda item: item.stat().st_mtime)
elif len(candidates) == 1:
chosen = candidates[0]
else:
chosen = max(candidates, key=lambda item: item.stat().st_mtime)
_atomic_write_task_inventory_marker(task_no, chosen.name)
return chosen
def resolve_task_inventory_upload_path(task_no: str) -> Path | None:
"""
返回任务当前已提交的正式库存附件路径。
核心逻辑:marker 有效且目标文件存在时必须无条件相信 marker;
仅 marker 缺失或损坏时才执行恢复扫描并同步修复 marker。
"""
marked = _read_task_inventory_attachment_marker(task_no)
if marked is not None:
return marked
return _recover_and_repair_task_inventory_marker(task_no)
def save_task_inventory_upload(task_no: str, upload: FileStorage) -> Path:
"""保存 werkzeug FileStorage 库存上传并返回落盘路径。"""
path = task_inventory_upload_path(task_no)
path.parent.mkdir(parents=True, exist_ok=True)
upload.save(str(path))
return path
suffix = ".xlsx"
filename = str(getattr(upload, "filename", "") or "").lower()
if filename.endswith(".csv"):
suffix = ".csv"
staging_dir = _task_inventory_upload_dir(task_no) / ".staging"
staging_dir.mkdir(parents=True, exist_ok=True)
staging = staging_dir / f"manual_upload_{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}{suffix}"
upload.save(str(staging))
try:
return install_task_inventory_attachment_from_file(task_no, staging)
finally:
delete_staged_task_inventory_file(staging)
def save_task_inventory_local_file(task_no: str, source_path: str | Path) -> Path:
@@ -66,16 +294,111 @@ def save_task_inventory_local_file(task_no: str, source_path: str | Path) -> Pat
source = Path(source_path)
if not source.is_file():
raise FileNotFoundError(f"未找到库存源文件: {source}")
path = task_inventory_upload_path(task_no)
path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, path)
return path
return install_task_inventory_attachment_from_file(
task_no,
source,
source_file_name=source.name,
)
def _sanitize_task_no(task_no: str) -> str:
"""将任务号规范为库存上传目录名。"""
return re.sub(r"[^\w\-]+", "_", str(task_no or "").strip()) or "unknown"
def stage_task_inventory_callback_file(
task_no: str,
source_path: str | Path,
*,
run_no: str | None = None,
) -> Path:
"""
将 RPA 回调文件复制到本轮唯一 staging 路径,避免在校验前覆盖任务正式附件。
核心逻辑:落盘至 inventory_uploads/{task_no}/.staging/rpa_callback_{token}.xlsx。
Args:
task_no: 发货任务号。
source_path: Worker 回调提供的本地库存文件。
run_no: 可选轮次号,用于生成稳定且唯一的 staging 文件名。
Returns:
Path: staging 文件路径。
Raises:
FileNotFoundError: 源文件不存在。
"""
source = Path(source_path)
if not source.is_file():
raise FileNotFoundError(f"未找到库存源文件: {source}")
token = re.sub(
r"[^\w\-]+",
"_",
str(run_no or "").strip() or datetime.utcnow().strftime("%Y%m%d%H%M%S%f"),
)
suffix = source.suffix.lower() if source.suffix else ".xlsx"
staging_dir = _storage_root() / "inventory_uploads" / _sanitize_task_no(task_no) / ".staging"
staging_dir.mkdir(parents=True, exist_ok=True)
staging_path = staging_dir / f"rpa_callback_{token}{suffix}"
shutil.copy2(source, staging_path)
return staging_path
def promote_staged_task_inventory_file(task_no: str, staging_path: str | Path) -> Path:
"""
校验与数据库提交成功后,将 staging 安装为任务正式库存附件。
核心逻辑:版本化落盘 + 原子 marker 切换 + 异步清理旧附件;旧附件删除失败返回 warning 列表。
"""
import os
staging = Path(staging_path)
if not staging.is_file():
raise FileNotFoundError(f"未找到 staging 库存文件: {staging}")
suffix = staging.suffix.lower() if staging.suffix else ".xlsx"
if suffix not in _TASK_INVENTORY_SUFFIXES:
suffix = ".xlsx"
versioned = _versioned_task_inventory_path(task_no, suffix)
versioned.parent.mkdir(parents=True, exist_ok=True)
os.replace(staging, versioned)
try:
_atomic_write_task_inventory_marker(task_no, versioned.name)
cleanup_warnings = _cleanup_superseded_task_inventory_files(task_no, keep_name=versioned.name)
if cleanup_warnings:
raise OSError(f"legacy_attachment_cleanup_failed:{';'.join(cleanup_warnings)[:200]}")
except Exception:
if versioned.is_file():
try:
versioned.unlink()
except OSError:
pass
raise
try:
staging.parent.rmdir()
except OSError:
pass
return versioned
def delete_staged_task_inventory_file(staging_path: str | Path | None) -> None:
"""删除本轮 staging 库存文件(失败回滚用,不触碰任务正式附件)。"""
if not staging_path:
return
path = Path(staging_path)
if not path.is_file():
return
try:
path.unlink()
except OSError:
return
try:
path.parent.rmdir()
except OSError:
pass
def read_task_inventory_schema_preview(task_no: str) -> dict[str, Any]:
"""读取已上传库存文件的表头与样本行 preview(供映射表单/LLM 用)。"""
path = task_inventory_upload_path(task_no)
if not path.is_file():
path = resolve_task_inventory_upload_path(task_no)
if path is None:
raise FileNotFoundError(f"未找到任务 {task_no} 的库存上传文件")
preview = read_inventory_schema_preview(path)
preview["upload_filename"] = path.name
@@ -97,8 +420,8 @@ def parse_uploaded_task_inventory(
Returns:
tuple: (inventory_lines, column_meta, 文件路径)。
"""
path = task_inventory_upload_path(task_no)
if not path.is_file():
path = resolve_task_inventory_upload_path(task_no)
if path is None:
raise FileNotFoundError(f"未找到任务 {task_no} 的库存上传文件")
lines, column_meta = parse_inventory_excel_with_meta(
path,
@@ -112,5 +435,5 @@ def parse_uploaded_task_inventory(
def has_uploaded_task_inventory(task_no: str) -> bool:
"""任务是否已有落盘的库存 Excel 文件。"""
return task_inventory_upload_path(task_no).is_file()
"""任务是否已有落盘的库存附件(.xlsx 或 .csv)。"""
return resolve_task_inventory_upload_path(task_no) is not None
@@ -12,9 +12,11 @@ import json
from typing import Any
from app import db
from app.core.errors import AppError
from app.models import ShippingTask
from app.services.shipping_notice.constants import (
AUTO_MAP,
CP_INVENTORY_SOURCE_REVIEW,
CP_MAP_INFER,
CP_UPLOAD_REQ,
SUGGEST_OK,
@@ -57,6 +59,8 @@ from app.services.shipping_notice.query_service import (
serialize_task_for_tool,
)
from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable
from app.services.shipping_notice.state_machine import resolve_task_ui_state
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
from app.services.shipping_notice.tool_common import log_task_event, set_task_step_progress
from app.services.shipping_notice.tool_response import tool_response
@@ -117,6 +121,29 @@ def _extract_partial_inventory_field_mapping(raw: Any) -> dict[str, str]:
return result
def _inventory_source_gate_response(task: ShippingTask, *, operation: str, lang: str) -> dict[str, Any] | None:
"""
库存相关 Tool 入口统一门禁;未稳定时返回 needs_human 响应。
核心逻辑:仅捕获预期 AppError,其它异常继续向上抛出。
"""
if is_inventory_source_stable(task):
return None
try:
assert_inventory_source_gate(task, operation=operation)
except AppError:
ui = resolve_task_ui_state(task)
return tool_response(
status="needs_human",
task=task,
message="库存源尚未确定,请先完成订单解析阶段的库存源确认。",
data=serialize_task_for_tool(task),
human_options=ui.human_options,
checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW,
stop_agent_turn=True,
)
return None
def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]:
"""Parse inventory from uploaded file, chat text, or structured JSON."""
lang = resolve_lang(payload)
@@ -124,6 +151,10 @@ def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
gate_resp = _inventory_source_gate_response(task, operation="parse_inventory", lang=lang)
if gate_resp is not None:
return gate_resp
# [STEP 1] 先归一化库存输入来源与映射提示。
# 同一个入口要兼容已上传文件、聊天粘贴文本、结构化 JSON 和 LLM 传入的 map_json 扩展字段。
use_uploaded = str(payload.get("use_uploaded_file") or "").strip().lower() in {
@@ -237,6 +268,10 @@ def get_inventory_schema_preview(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
gate_resp = _inventory_source_gate_response(task, operation="get_inventory_schema_preview", lang=lang)
if gate_resp is not None:
return gate_resp
if not has_uploaded_inventory_file(task) and not has_uploaded_task_inventory(task.task_no):
return tool_response(
status="needs_human",
@@ -279,6 +314,10 @@ def apply_inventory_mapping(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
gate_resp = _inventory_source_gate_response(task, operation="apply_inventory_mapping", lang=lang)
if gate_resp is not None:
return gate_resp
# [STEP 1] 先校验上传文件与 schema preview 是否存在。
# 映射应用必须基于真实上传文件的表头,不能只凭 LLM 文本猜测继续执行。
if not has_uploaded_inventory_file(task) and not has_uploaded_task_inventory(task.task_no):
@@ -415,6 +454,9 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang="zh"))
lang = resolve_lang({"lang": None})
gate_resp = _inventory_source_gate_response(task, operation="upload_inventory_file", lang=lang)
if gate_resp is not None:
return gate_resp
if str(task.process_status or "").strip().lower() in _TERMINAL_PROCESS_STATUSES:
return tool_response(
status="failed",
@@ -432,7 +474,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
)
filename = str(upload.filename or "").strip()
if not filename.lower().endswith((".xlsx", ".xls", ".csv")):
if not filename.lower().endswith((".xlsx", ".csv")):
return tool_response(
status="failed",
task_id=task.task_no,
@@ -452,7 +494,18 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
db.session.flush()
inv_file = save_batch_inventory_upload(task, upload)
preview = read_linked_inventory_schema_preview(task)
except AppError as exc:
db.session.rollback()
return tool_response(
status="failed",
task=task,
task_id=task.task_no,
message=str(exc.message or "库存上传被拒绝"),
data=serialize_task_for_tool(task),
stop_agent_turn=True,
)
except OSError as exc:
db.session.rollback()
return tool_response(
status="failed",
task_id=task.task_no,
@@ -537,6 +590,20 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
if not is_inventory_source_stable(task):
try:
assert_inventory_source_gate(task, operation="ensure_inventory")
except AppError:
pass
return tool_response(
status="needs_human",
task=task,
message="库存源尚未确定,请先完成订单解析阶段的库存源确认。",
data=serialize_task_for_tool(task),
checkpoint="inventory_source_review",
stop_agent_turn=True,
)
# [STEP 1] 优先接受当前请求直接携带的库存明细。
# 这条路径用于小表/结构化库存输入,能直接跳过上传与 RPA 等外围链路。
mode = str(payload.get("mode") or "auto").strip().lower()
@@ -183,6 +183,24 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
},
required=["task_id", MAP_JSON],
),
"/tools/confirm_inventory_source": _post_op(
"confirm_inventory_source",
"在库存源人工检查点确认正式库存查询来源(仅提交 source_code)",
{
"task_id": task_id,
"source_code": _str_prop(
"启用配置中的库存源编码,如 DSV360_AWSDU、CRANE;"
"站点 site_id 与库位 warehouse_id 由后端根据配置与订单路由解析,禁止前端直传"
),
},
required=["task_id", "source_code"],
description=(
"库存源门禁:稳定身份须同时具备 source_code、source_type、site_id、warehouse_id,"
"且 routing_fingerprint 与当前配置版本一致。"
"Tool API 使用集成密钥鉴权,确认人审计由宿主会话内部链路写入,不接受外部 user_id。"
"若返回 needs_human,说明身份未完整解析或需先完成解析确认。"
),
),
"/tools/submit_decision": _post_op(
"submit_decision",
"人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由后台任务统一续跑。",
@@ -218,11 +236,19 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
),
"/tools/get_task_status": _post_op(
"get_task_status",
"查询任务当前状态与 human_options。task_id 与 conversation_id 至少传一个",
"查询任务当前状态与 human_options;响应含 inventory_source_* 独立字段与候选结构",
{
"task_id": task_id,
"conversation_id": _str_prop("Dify 会话 ID"),
},
description=(
"返回 inventory_source_code、inventory_source_type、inventory_site_id、"
"inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|"
"user_confirmed|invalid|conflicted)、inventory_source_method、"
"inventory_source_config_version、inventory_routing_fingerprint、"
"inventory_source_confirmed_by、inventory_source_confirmed_at,"
"以及 step_payload.inventory_source_resolution.candidates。"
),
),
"/tools/get_batch_status": _post_op(
"get_batch_status",
@@ -14,7 +14,17 @@ from flask import current_app
from app.services.shipping_notice import fulfillment_workflow
from app import db
from app.services.shipping_notice.constants import CP_UPLOAD_REQ, PH_LOW_CONF, RS_PARSE_REVIEW
from app.services.shipping_notice.constants import (
CP_INVENTORY_SOURCE_REVIEW,
CP_UPLOAD_REQ,
PH_INVENTORY_SOURCE_UNRESOLVED,
PH_LOW_CONF,
RS_PARSE_REVIEW,
)
from app.services.shipping_notice.inventory_source_gate import (
is_inventory_source_stable,
ensure_inventory_source_review_state,
)
from app.services.shipping_notice.inventory_mapping_workflow import (
awaiting_inventory_mapping_confirm,
inventory_mapping_checkpoint_response,
@@ -84,6 +94,27 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
stop_agent_turn=True,
)
if task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED or not is_inventory_source_stable(task):
adjudication = ensure_inventory_source_review_state(task)
db.session.commit()
if not is_inventory_source_stable(task):
ui = resolve_task_ui_state(task)
return tool_response(
status="needs_human",
task=task,
message="库存源尚未确定,请先完成订单解析阶段的库存源确认。",
data={
**serialize_task_for_tool(task),
"inventory_source_candidates": adjudication.candidates,
"inventory_source_status": adjudication.status,
"inventory_source_reason": adjudication.reason,
"destination_candidates": adjudication.destination_candidates,
},
human_options=ui.human_options,
checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW,
stop_agent_turn=True,
)
# [STEP 2] 保证库存已经就绪。
# 若库存还没导入,则根据配置决定触发 RPA 拉取,或明确提示人工上传 Excel。
if not task.inventory_lines_json:
@@ -331,6 +331,20 @@ 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,
"destination_code": task.destination_code,
"destination_city": task.destination_city,
"destination_country": task.destination_country,
"warehouse_hint": task.warehouse_hint,
"inventory_source_code": task.inventory_source_code,
"inventory_source_type": task.inventory_source_type,
"inventory_site_id": task.inventory_site_id,
"inventory_warehouse_id": task.inventory_warehouse_id,
"inventory_source_status": task.inventory_source_status,
"inventory_source_method": task.inventory_source_method,
"inventory_source_config_version": task.inventory_source_config_version,
"inventory_routing_fingerprint": task.inventory_routing_fingerprint,
"inventory_source_confirmed_at": task.inventory_source_confirmed_at.isoformat() if task.inventory_source_confirmed_at else None,
"inventory_source_confirmed_by": task.inventory_source_confirmed_by,
"inventory_snapshot": _serialize_inventory_snapshot(task),
"shortage": task.shortage_json,
"line_results": task.line_results_json or [],
@@ -110,14 +110,27 @@ def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None:
def recover_stale_shipping_notice_jobs() -> tuple[int, str]:
"""兼容旧调用:回收通用 jobs 表里超时的发货任务。"""
"""兼容旧调用:回收通用 jobs 表里超时的发货任务,并顺带消费 RPA callback cleanup 队列。"""
from app.jobs.queue import recover_stale_jobs
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
recover_pending_rpa_callback_cleanup_jobs,
)
timeout_sec = float(current_app.config.get('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', 300))
count = recover_stale_jobs(domain=SHIPPING_NOTICE_JOB_DOMAIN, timeout_seconds=timeout_sec)
cleanup_count, cleanup_warnings = recover_pending_rpa_callback_cleanup_jobs()
if cleanup_warnings:
logger.warning('rpa callback cleanup warnings: %s', '; '.join(cleanup_warnings[:5]))
if count:
logger.warning('recovered %s stale shipping_notice job(s)', count)
return count, f'recovered_{count}' if count else 'no_stale_jobs'
if cleanup_count:
logger.info('processed %s rpa callback cleanup job(s)', cleanup_count)
parts = []
if count:
parts.append(f'recovered_{count}')
if cleanup_count:
parts.append(f'callback_cleanup_{cleanup_count}')
return count, '_'.join(parts) if parts else 'no_stale_jobs'
def claim_next_shipping_notice_job() -> Job | None:
+2 -1
View File
@@ -91,6 +91,7 @@ def write_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None
body = {
"action": "inventory_export",
"task_no": task_no,
"run_no": f"LEGACY-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}",
"requested_at": datetime.utcnow().isoformat(),
**(payload or {}),
}
@@ -177,7 +178,7 @@ def write_inventory_export_trigger_for_task(
"""
body = dict(payload or {})
if inventory_rpa_batch_enabled():
run_no = f"TASK-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S')}"
run_no = f"TASK-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}"
return write_inventory_export_batch_trigger(
run_no,
[rpa_source],
@@ -512,7 +512,7 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
pending_human_reason=PH_INV_UNAVAIL,
),
TaskTransition.INVENTORY_SOURCE_REVIEW: _TransitionSpec(
process_status="waiting_inventory",
process_status="pending_review",
review_status=None,
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
),
@@ -17,12 +17,18 @@ from flask import current_app
from app import db
from app.models import ShippingBatch, ShippingTask
from app.services.shipping_notice.constants import (
CP_INVENTORY_SOURCE_REVIEW,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_PARSE_OK,
CP_RSV_REQ,
CP_TASK_EXISTS,
PH_INVENTORY_SOURCE_UNRESOLVED,
RS_PARSE_REVIEW,
)
from app.services.shipping_notice.inventory_source_gate import (
adjudicate_and_apply_inventory_source,
is_inventory_source_stable,
)
from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.decision_workflow import submit_decision
from app.services.shipping_notice.extract import extract_notice_fields
@@ -66,11 +72,23 @@ def _capture_destination_context(task: ShippingTask, parsed: dict[str, Any], lin
if isinstance(destination, dict):
payload["destination"] = destination
candidates.append(destination)
task.destination_code = str(destination.get("port_code") or destination.get("destination_code") or "").strip().upper() or None
task.destination_city = str(destination.get("city") or "").strip() or None
task.destination_country = str(destination.get("country") or "").strip().upper() or None
task.warehouse_hint = str(destination.get("warehouse_hint") or "").strip() or None
elif destination:
candidates.append(destination)
for key in ("destination_port", "destination_city", "destination_country", "warehouse_hint", "ship_to_location"):
if parsed.get(key):
candidates.append(parsed.get(key))
if parsed.get("destination_port") and not task.destination_code:
task.destination_code = str(parsed.get("destination_port") or "").strip().upper() or None
if parsed.get("destination_city") and not task.destination_city:
task.destination_city = str(parsed.get("destination_city") or "").strip() or None
if parsed.get("destination_country") and not task.destination_country:
task.destination_country = str(parsed.get("destination_country") or "").strip().upper() or None
if parsed.get("warehouse_hint") and not task.warehouse_hint:
task.warehouse_hint = str(parsed.get("warehouse_hint") or "").strip() or None
if task.ship_to:
candidates.append(task.ship_to)
for line in lines:
@@ -565,23 +583,78 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"],
)
# [STEP 4] 低置信度停待人审;否则标记 parsed 并准备后续库存链路。
if confidence < float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7):
if not _has_parse_review_content(task, lines):
apply_task_transition(task, TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED)
log_task_event(task, "notice_text_extraction_failed", {"confidence": confidence, "warnings": warnings})
db.session.commit()
message = (
"未能从发货通知中解析到可审核内容,请重新上传清晰版 PDF/文本,"
"或复制粘贴通知正文后重新解析。"
)
return tool_response(
status="needs_human",
task=task,
message=message,
data={**serialize_task_for_tool(task), "warnings": warnings},
checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED,
)
# [STEP 4] 无可审核内容时优先返回 notice_text_extraction_failed,不进入库存源裁决。
if not _has_parse_review_content(task, lines):
apply_task_transition(task, TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED)
log_task_event(task, "notice_text_extraction_failed", {"confidence": confidence, "warnings": warnings})
db.session.commit()
message = (
"未能从发货通知中解析到可审核内容,请重新上传清晰版 PDF/文本,"
"或复制粘贴通知正文后重新解析。"
)
return tool_response(
status="needs_human",
task=task,
message=message,
data={**serialize_task_for_tool(task), "warnings": warnings},
checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED,
)
# [STEP 5] 库存源硬门禁:订单解析阶段必须先完成库存源裁决(先于低置信度人工确认)。
low_confidence = confidence < float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7)
adjudication = adjudicate_and_apply_inventory_source(task)
if not is_inventory_source_stable(task):
from app.services.shipping_notice.inventory_source_gate import transition_task_to_inventory_source_review
transition_task_to_inventory_source_review(
task,
adjudication,
error_message="无法根据发货通知唯一确定库存查询来源",
mark_pending_parse_review=low_confidence,
)
set_task_step_progress(
task,
step_key="step2_parse_confirm",
step_title="确认解析",
status="needs_human",
message="库存源待确认",
progress_percent=100,
detail="请确认本票应使用哪个库存源后继续。",
extra={"warnings": warnings, "inventory_source_status": adjudication.status},
)
log_task_event(
task,
"inventory_source_review_required",
{
"status": adjudication.status,
"reason": adjudication.reason,
"destination_candidates": adjudication.destination_candidates,
"candidate_source_codes": [item.get("source_code") for item in adjudication.candidates],
},
)
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=(
"订单字段已解析,但库存源尚未唯一确定。"
"请选择正式库存源后继续;站点与库位将由系统根据配置自动填充。"
),
data={
**serialize_task_for_tool(task),
"warnings": warnings,
"inventory_source_candidates": adjudication.candidates,
"inventory_source_status": adjudication.status,
"inventory_source_reason": adjudication.reason,
"destination_candidates": adjudication.destination_candidates,
},
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
stop_agent_turn=True,
forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"],
)
# [STEP 6] 低置信度停待人审;库存源已稳定后才进入解析内容复核。
if low_confidence:
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
log_task_event(task, "parse_needs_review", {"confidence": confidence, "warnings": warnings})
_upsert_parse_review_chat_message(task)
@@ -32,6 +32,7 @@ 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
repair_task_inventory_attachment = inventory_rpa_workflow.repair_task_inventory_attachment
confirm_inventory_source = inventory_rpa_workflow.confirm_inventory_source
# 履约阶段
@@ -29,6 +29,7 @@ from app.services.shipping_notice.constants import (
CP_UPLOAD_REQ,
CP_WAITING_UPLOAD,
PH_INV_UNAVAIL,
PH_INVENTORY_SOURCE_UNRESOLVED,
PH_MAP_INFER,
PH_RPA_EXHAUSTED,
PH_RPA_PENDING,
@@ -82,6 +83,7 @@ _TERMINAL_PROCESS_STATUSES = {"uploaded", "closed"}
_BLOCKED_CHECKPOINTS = {
CP_PARSE_REVIEW,
CP_RSV_REQ,
CP_INVENTORY_SOURCE_REVIEW,
CP_ALIGN_REVIEW,
RS_SHORTAGE_REVIEW,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
@@ -129,7 +131,7 @@ def _derive_current_step_index(task: ShippingTask) -> int:
if process_status in {"parsed", "pending_review"} or review_status in {
RS_PARSE_REVIEW,
PH_RSV_REQ,
} or pending_reason in {"low_confidence", PH_RSV_REQ}:
} or pending_reason in {"low_confidence", PH_RSV_REQ, PH_INVENTORY_SOURCE_UNRESOLVED}:
return 1
return 0
@@ -159,7 +161,11 @@ def build_shipping_workflow_steps(task: ShippingTask, checkpoint: str | None) ->
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):
parse_blocked = index == 1 and (
checkpoint_value in {CP_PARSE_REVIEW, CP_RSV_REQ, CP_INVENTORY_SOURCE_REVIEW, CP_NOTICE_TEXT_EXTRACTION_FAILED}
or pending_reason in {"low_confidence", PH_RSV_REQ, PH_INVENTORY_SOURCE_UNRESOLVED}
)
if index == current_index and (checkpoint_value in _BLOCKED_CHECKPOINTS or inventory_blocked or parse_blocked):
status = "blocked"
steps.append({**step, "status": status})
return steps
@@ -181,7 +187,7 @@ def _build_task_summary(task: ShippingTask, checkpoint: str | None) -> dict[str,
CP_RSV_REQ: "发货通知缺少后续匹配必需字段,请补充或重新上传。",
CP_UPLOAD_REQ: "当前需要提供库存数据或重试库存获取。",
CP_INVENTORY_PENDING: "发货通知已就绪,等待库存数据。",
CP_INVENTORY_SOURCE_REVIEW: "库存查询来源不明确,需要先确认。",
CP_INVENTORY_SOURCE_REVIEW: "库存源尚未确定,请先选择正式库存源。",
CP_MAP_INFER: "库存列映射需要确认或重新选择。",
CP_ALIGN_REVIEW: "库存字段对齐需要人工确认。",
RS_SHORTAGE_REVIEW: "库存存在缺口,当前不能继续上传货代。",