feat(shipping-notice): 新增临时库存管理功能,支持创建会话、获取分析结果及字段映射建议

This commit is contained in:
hugo committed 2026-07-18 11:41:02 +08:00
1 parent 46eb63f5bb
commit e9bdd81f1a
320 files changed
+28361 -10487

No files matched your search

@@ -675,7 +675,8 @@ def create_shipping_batch_from_candidates(
target = (
db.session.query(ShippingTask)
.filter_by(task_no=target_no, user_id=int(user_id))
.with_for_update()
# Lock only ShippingTask. Its eager nullable ShippingCase join cannot be locked by PostgreSQL.
.with_for_update(of=ShippingTask)
.first()
)
if target is None:
@@ -157,7 +157,24 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
if (
process_status == "waiting_inventory"
and not getattr(task, "inventory_lines_json", None)
and pending_reason in {"", PH_RPA_PENDING}
and pending_reason == PH_RPA_PENDING
):
# A pending task already has an explicit RPA attempt. Poll its timeout
# state through the RPA workflow; normal auto-progress must not start RPA.
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
result = ensure_inventory_via_rpa(task, mode="auto")
if current_app:
current_app.logger.info(
"[shipping-orchestrator] rpa-inventory-recheck task_no=%s status=%s message=%s",
task.task_no,
result.get("status"),
str(result.get("message") or "")[:300],
)
elif (
process_status == "waiting_inventory"
and not getattr(task, "inventory_lines_json", None)
and pending_reason == ""
):
payload["mode"] = "auto"
result = auto_progress(payload)
@@ -370,7 +387,10 @@ def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]:
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
if process_status == "waiting_inventory" and pending_reason == PH_RPA_PENDING:
result = auto_progress({"task_id": task.task_no, "mode": "auto"})
# This is a poll of an existing request, never an implicit new RPA run.
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
result = ensure_inventory_via_rpa(task, mode="auto")
status = str(result.get("status") or "").strip().lower()
if status in {"ok", "running", "needs_human"}:
started += 1
@@ -3,7 +3,7 @@ services/shipping_notice/business_case_service.py
用途:为新建货代任务创建或继承业务单聚合。
依赖:db、ShippingCase、ShippingTask、uuid/datetime。
逻辑:普通任务和强制新建任务创建新业务单;修订任务继承父任务业务单,必要时为历史父任务补建。
逻辑:普通任务和强制新建任务创建新业务单;修订任务继承父任务业务单。
"""
from __future__ import annotations
@@ -50,8 +50,8 @@ def resolve_shipping_case_for_new_task(
"""
为即将创建的任务解析业务单归属。
核心逻辑:revision 继承父任务业务单;历史父任务未关联时在同一事务补建;
normal/force_create 均创建独立业务单,保证强制新建重新占用未来流水。
核心逻辑:revision 必须继承父任务业务单;normal/force_create 均创建独立业务单,
保证强制新建重新占用未来流水。
Args:
supersedes_task_id: 修订目标任务主键,仅 revision 使用。
@@ -78,11 +78,11 @@ def resolve_shipping_case_for_new_task(
code='SHIPPING_NOTICE.REVISION_TARGET_INVALID',
details={'supersedes_task_id': supersedes_task_id},
)
if parent.shipping_case is not None:
return parent.shipping_case
case = create_shipping_case(created_by_id=parent.user_id or created_by_id)
parent.shipping_case = case
db.session.flush()
return case
if parent.shipping_case is None:
raise ConflictError(
'修订目标任务缺少业务单关联',
code='SHIPPING_NOTICE.REVISION_CASE_MISSING',
details={'supersedes_task_id': supersedes_task_id},
)
return parent.shipping_case
@@ -1,27 +1,24 @@
"""
backend/app/services/shipping_notice/chat_action_extended_handlers.py
用途:货代 Chat Turn 扩展 Action Handler(上传/映射/切票/缺口查询)。
用途:货代 Chat Turn 扩展 Action Handler(通知重传/切票/缺口查询)。
依赖:shipping_tools、task_workflow、tool_common、shipping_turn_helpers、action_registry。
逻辑:turn_runtime 路由至本模块;与 chat_action_handlers 分工,避免单文件过大。
"""
from __future__ import annotations
import io
from typing import Any, Iterator
from werkzeug.datastructures import FileStorage
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.services.chat.action_registry import register_action_handler
from app.services.chat.action_schema import TurnEvent
from app.services.chat.turn_context import TurnContext
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK, MAP_JSON
from app.services.shipping_notice.query_service import (
get_batch_for_user,
get_task_by_ref,
get_task_for_user,
serialize_task_detail,
)
@@ -61,16 +58,11 @@ def _require_task(ctx: TurnContext):
return task
def _filestorage_from_staged(staged: dict[str, Any]) -> FileStorage:
data = staged.get("data")
if not isinstance(data, (bytes, bytearray)):
raise ValidationError("upload file data is missing")
filename = str(staged.get("filename") or "upload").strip() or "upload"
content_type = str(staged.get("content_type") or "").strip() or None
return FileStorage(stream=io.BytesIO(bytes(data)), filename=filename, content_type=content_type)
def _first_staged_upload(ctx: TurnContext):
"""将当前 Chat Turn 暂存附件转换为通知替换流程可读取的文件对象。"""
from io import BytesIO
from werkzeug.datastructures import FileStorage
def _first_staged_upload(ctx: TurnContext) -> FileStorage:
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
staged_files = payload.get("_staged_files")
if not isinstance(staged_files, list) or not staged_files:
@@ -78,18 +70,14 @@ def _first_staged_upload(ctx: TurnContext) -> FileStorage:
first = staged_files[0]
if not isinstance(first, dict):
raise ValidationError("invalid staged upload")
return _filestorage_from_staged(first)
def _format_inventory_upload_message(result: dict[str, Any], task_no: str) -> str:
base = tool_result_message(result) or "库存文件已上传。"
lines = [base, f"任务编号:{task_no}"]
checkpoint = str(result.get("checkpoint") or "").strip()
if checkpoint == "map_infer":
lines.append("下一步:请确认或调整列映射。")
elif checkpoint == "align_review":
lines.append("下一步:请核对字段对齐结果。")
return "\n".join(lines)
data = first.get("data")
if not isinstance(data, (bytes, bytearray)):
raise ValidationError("upload file data is missing")
return FileStorage(
stream=BytesIO(bytes(data)),
filename=str(first.get("filename") or "upload").strip() or "upload",
content_type=str(first.get("content_type") or "").strip() or None,
)
def _format_replace_notice_message(result: dict[str, Any], task_no: str) -> str:
@@ -105,45 +93,6 @@ def _format_replace_notice_message(result: dict[str, Any], task_no: str) -> str:
return "\n".join(line for line in lines if line)
def _format_mapping_applied_message(result: dict[str, Any], task_no: str, mapping: dict[str, str]) -> str:
mapping_text = ",".join(f"{key}={value}" for key, value in mapping.items())
hint = tool_result_message(result)
lines = [
f"映射已应用:{mapping_text}" if mapping_text else "映射已应用并解析库存。",
f"任务编号:{task_no}",
hint,
]
return "\n".join(line for line in lines if line)
class ShippingUploadInventoryAction:
action_type = "shipping.upload_inventory"
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
task = _require_task(ctx)
upload = _first_staged_upload(ctx)
yield TurnEvent(event="step.started", data={"step_id": "upload_inventory", "label": "上传库存文件..."})
result = shipping_tools.upload_inventory_file(task.task_no, upload)
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 "upload_inventory failed")
from app.services.shipping_notice.query_service import get_task_by_ref
refreshed = get_task_by_ref(task.task_no) or task
yield shipping_task_ui_state_event(refreshed)
data = result.get("data") if isinstance(result.get("data"), dict) else {}
message_payload: dict[str, Any] = {
"task_no": task.task_no,
"tool_result": result,
"checkpoint": result.get("checkpoint"),
}
preview = data.get("schema_preview")
if isinstance(preview, dict):
message_payload["schema_preview"] = preview
content = _format_inventory_upload_message(result, task.task_no)
yield from stream_text_events(content, message_type="text", payload=message_payload)
yield TurnEvent(event="step.completed", data={"step_id": "upload_inventory"})
class ShippingReplaceNoticeAction:
action_type = "shipping.replace_notice"
@@ -190,34 +139,37 @@ class ShippingReplaceNoticeAction:
yield TurnEvent(event="step.completed", data={"step_id": "replace_notice"})
class ShippingApplyInventoryMappingAction:
action_type = "shipping.apply_inventory_mapping"
class ShippingUploadInventoryAction:
"""为已有发货任务上传正式库存文件,并使用库存站点发布方案解析。"""
action_type = "shipping.upload_inventory"
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
task = _require_task(ctx)
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
mapping_raw = payload.get(MAP_JSON) or payload.get("map_json") or payload.get("mapping")
if not isinstance(mapping_raw, dict) or not mapping_raw:
raise ValidationError(f"{MAP_JSON} is required")
mapping = {str(k): str(v) for k, v in mapping_raw.items() if str(v or "").strip()}
if not mapping.get("part_number") or not mapping.get("available_qty"):
raise ValidationError("part_number and available_qty mapping are required")
yield TurnEvent(event="step.started", data={"step_id": "apply_inventory_mapping", "label": "应用列映射..."})
result = shipping_tools.apply_inventory_mapping({
"task_id": task.task_no,
MAP_JSON: mapping,
AUTO_CHAIN_FALLBACK: True,
"event_source": "chat_turn",
})
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 "apply_inventory_mapping failed")
from app.services.shipping_notice.query_service import get_task_by_ref
"""
保存当前 Turn 的库存附件并返回确定性解析结果。
核心逻辑:先按当前用户反查任务,再将 multipart 暂存附件交给既有库存工作流;
本 Handler 不调用 Dify、不创建临时库存会话,也不允许任务级猜列或字段映射确认。
"""
task = _require_task(ctx)
upload = _first_staged_upload(ctx)
yield TurnEvent(event="step.started", data={"step_id": "upload_inventory", "label": "上传库存文件..."})
result = shipping_tools.upload_inventory_file(task.task_no, upload)
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 "upload_inventory failed")
refreshed = get_task_by_ref(task.task_no) or task
yield shipping_task_ui_state_event(refreshed)
content = _format_mapping_applied_message(result, task.task_no, mapping)
yield from stream_text_events(content, payload={"task_no": task.task_no, "mapping": mapping, "tool_result": result})
yield TurnEvent(event="step.completed", data={"step_id": "apply_inventory_mapping"})
data = result.get("data") if isinstance(result.get("data"), dict) else {}
content = "\n".join(filter(None, [tool_result_message(result), f"任务编号:{task.task_no}"]))
yield from stream_text_events(
content,
payload={
"task_no": task.task_no,
"inventory_file_no": data.get("inventory_file_no"),
"tool_result": result,
},
)
yield TurnEvent(event="step.completed", data={"step_id": "upload_inventory"})
class ShippingSwitchBatchFocusAction:
@@ -274,9 +226,8 @@ class ShippingQueryShortageDetailsAction:
_HANDLERS = (
ShippingUploadInventoryAction(),
ShippingReplaceNoticeAction(),
ShippingApplyInventoryMappingAction(),
ShippingUploadInventoryAction(),
ShippingSwitchBatchFocusAction(),
ShippingQueryShortageDetailsAction(),
)
@@ -51,35 +51,8 @@ def _require_task(ctx: TurnContext):
def _format_decision_message(decision: str, result: dict[str, Any], task_no: str) -> str:
"""对齐前端 shippingDecisionFormat.ts 的助手摘要格式。"""
lines = [_tool_result_message(result) or "操作已完成。"]
data = result.get("data") if isinstance(result.get("data"), dict) else {}
if decision == "correct_inventory_mapping":
preview = data.get("schema_preview") if isinstance(data.get("schema_preview"), dict) else {}
headers = [str(item) for item in (preview.get("headers") or []) if item]
suggested = preview.get("suggested_mapping") if isinstance(preview.get("suggested_mapping"), dict) else {}
header_row_index = preview.get("header_row_index")
if header_row_index:
lines.extend(["", f"表头在第 {header_row_index} 行:{' | '.join(headers)}"])
elif headers:
lines.extend(["", f"当前表头:{' | '.join(headers)}"])
mapping_lines = [
f"- part_number → {suggested['part_number']}" if suggested.get("part_number") else None,
f"- aws_part_number → {suggested['aws_part_number']}" if suggested.get("aws_part_number") else None,
f"- reservation_id → {suggested['reservation_id']}" if suggested.get("reservation_id") else None,
f"- available_qty → {suggested['available_qty']}" if suggested.get("available_qty") else None,
]
mapping_lines = [line for line in mapping_lines if line]
if mapping_lines:
lines.extend(["", "建议列映射:", *mapping_lines])
lines.extend([
"",
"如需调整,请说明要改的列(例如:available_qty 改用 Qty Available)。",
"也可点击「选择库存文件」重新上传。",
])
elif decision == "confirm_inventory_mapping":
if str(result.get("checkpoint") or "").strip() == "map_ok":
lines.extend(["", "下一步:匹配库存与发货需求。"])
elif decision == "reparse_inventory":
lines.extend(["", "请重新上传或粘贴库存 Excel。"])
if decision == "reparse_inventory":
lines.extend(["", "请点击「选择库存文件」重新上传。"])
lines.extend(["", f"任务编号:{task_no}"])
return "\n".join(lines)
@@ -8,23 +8,11 @@ services/shipping_notice/constants.py
from __future__ import annotations
from typing import Any
# HTTP JSON request/response fields
MAP_JSON = "map_json"
SUGGEST_OK = "suggest_ok"
AUTO_MAP = "auto_map"
# Workspace / Hxops chat fallback only — Dify 正式路径不直接调用主推进 Tool;人工确认后由后端 worker 续跑
AUTO_CHAIN_FALLBACK = "auto_chain_fallback"
# Legacy request field names (read-only compat)
MAP_JSON_LEGACY = "column_mapping_json"
# Checkpoints (tool_response.checkpoint; canonical ids — register buttons in state_machine.py)
CP_ALIGN_REVIEW = "align_review"
CP_MAP_INFER = "map_infer"
CP_UPLOAD_REQ = "upload_req"
CP_MAP_OK = "map_ok"
CP_PARSE_OK = "parse_ok"
CP_PARSE_REVIEW = "parse_review"
CP_CUSTOMER_REVIEW = "customer_review"
@@ -45,7 +33,6 @@ CP_UPLOADED = "uploaded"
CP_COMPLETED = "completed"
# review_status
RS_ALIGN_REVIEW = "align_review"
RS_PARSE_REVIEW = "parse_review"
RS_SHORTAGE_REVIEW = "shortage_review"
RS_RSV_REQ = "rsv_req"
@@ -53,8 +40,6 @@ RS_REJECTED = "rejected"
RS_CONFIRMED = "confirmed"
# pending_human_reason (internal; shortened)
PH_ALIGN_REVIEW = CP_ALIGN_REVIEW
PH_MAP_INFER = CP_MAP_INFER
PH_LOW_CONF = "low_confidence"
PH_RSV_REQ = CP_RSV_REQ
PH_SHORTAGE = "shortage"
@@ -65,13 +50,3 @@ PH_INVENTORY_SOURCE_UNRESOLVED = "inventory_source_unresolved"
PH_NOTICE_TEXT_EXTRACTION_FAILED = CP_NOTICE_TEXT_EXTRACTION_FAILED
PH_UPLOAD_RPA_FAILED = "upload_rpa_failed"
PH_UPLOAD_RPA_PENDING = "upload_rpa_pending"
def payload_map_json(payload: dict[str, Any]) -> Any:
"""从请求体读取列映射 JSON,兼容 map_json 与 legacy column_mapping_json 字段名。"""
raw = payload.get(MAP_JSON)
if raw is None:
raw = payload.get(MAP_JSON_LEGACY)
if raw is None:
raw = payload.get("field_mapping")
return raw
@@ -3,7 +3,7 @@ backend/app/services/shipping_notice/context_adapter.py
用途:发货通知 Agent 的 Context Adapter,构建 agent_runtime_context Dify inputs。
依赖:shipping_notice.dify_inputs.build_dify_chat_inputs、agent_runtime_context.registry。
逻辑:agent_code=shipping_notice 时由 build_chat_dify_inputs 分发至本模块;adapter_hints.shipping_notice 透传 task/batch。
逻辑:agent_code=shipping_notice 时由 build_chat_dify_inputs 分发至本模块;adapter_hints.shipping_notice 透传任务锚点或临时库存资产锚点。
"""
from __future__ import annotations
@@ -28,7 +28,7 @@ def build_shipping_notice_context_adapter(
"""
构建发货通知 Dify Start inputs。
核心逻辑:从 adapter_hints.shipping_notice 读取 task/batch 或待抽取 Intake 集合,委托 dify_inputs 组装 runtime_context。
核心逻辑:从 adapter_hints.shipping_notice 读取 task/batch、待抽取 Intake 集合或临时库存资产,委托 dify_inputs 组装 runtime_context。
Args:
agent: 当前对话 Agent(保留签名一致性;发货上下文主要依赖 session_id)。
@@ -52,4 +52,6 @@ def build_shipping_notice_context_adapter(
locale=locale,
intake_nos=shipping_hints.get('intake_nos'),
capability=shipping_hints.get('capability'),
temporary_inventory_asset_no=shipping_hints.get('temporary_inventory_asset_no'),
temporary_inventory_session_no=shipping_hints.get('temporary_inventory_session_no'),
)
@@ -0,0 +1,82 @@
"""
services/shipping_notice/credential_crypto.py
用途:加密和解密库存 RPA Profile 的登录凭据。
依赖:Flask current_app、cryptography.fernet;调用方仅保存密文,不将凭据写入日志或 API 响应。
逻辑:管理服务写入 Profile 前调用 encrypt_credential;RPA 配置读取服务在受控内存中调用 decrypt_credential。
"""
from __future__ import annotations
from cryptography.fernet import Fernet, InvalidToken
from flask import current_app
from app.core.errors import ServiceUnavailableError, ValidationError
def _fernet() -> Fernet:
"""
构造当前环境的凭据加密器。
核心逻辑:主密钥只从运行环境读取,缺失或格式无效时拒绝继续,避免写入无法恢复的密文。
Returns:
Fernet: 可执行对称加密的实例。
Raises:
ServiceUnavailableError: 未配置或配置了无效的主密钥。
"""
key = str(current_app.config.get('SHIPPING_NOTICE_RPA_CREDENTIAL_KEY') or '').strip()
if not key:
raise ServiceUnavailableError(
'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY is not configured',
code='SHIPPING.RPA_CREDENTIAL_KEY_MISSING',
)
try:
return Fernet(key.encode('ascii'))
except (ValueError, UnicodeEncodeError) as exc:
raise ServiceUnavailableError(
'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY is invalid',
code='SHIPPING.RPA_CREDENTIAL_KEY_INVALID',
) from exc
def encrypt_credential(value: str) -> str:
"""
加密单个 RPA 凭据字段以便持久化。
Args:
value: 非空明文凭据;调用方不得记录此值。
Returns:
str: 可安全保存到数据库的 Fernet 密文。
Raises:
ValidationError: 传入空凭据。
"""
plaintext = str(value or '')
if not plaintext:
raise ValidationError('RPA credential must not be empty', code='SHIPPING.RPA_CREDENTIAL_EMPTY')
return _fernet().encrypt(plaintext.encode('utf-8')).decode('ascii')
def decrypt_credential(ciphertext: str) -> str:
"""
在受控运行时解密 RPA 凭据。
Args:
ciphertext: 数据库中保存的 Fernet 密文。
Returns:
str: 仅供 RPA 执行内存使用的明文。
Raises:
ValidationError: 密文为空、已损坏或使用了错误主密钥。
"""
value = str(ciphertext or '').strip()
if not value:
raise ValidationError('RPA credential ciphertext is missing', code='SHIPPING.RPA_CREDENTIAL_MISSING')
try:
return _fernet().decrypt(value.encode('ascii')).decode('utf-8')
except (InvalidToken, UnicodeDecodeError) as exc:
raise ValidationError('RPA credential ciphertext is invalid', code='SHIPPING.RPA_CREDENTIAL_INVALID') from exc
@@ -25,7 +25,7 @@ from app.models import (
)
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
from app.services.shipping_notice.customer_normalization import is_public_email_domain
from app.services.shipping_notice.tool_common import cfg_bool
from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int
from app.services.shipping_notice.business_case_service import generate_shipping_case_no
from app.services.shipping_notice.business_numbering_service import assign_business_number
@@ -35,7 +35,6 @@ CUSTOMER_AUDIT_EVENT_TYPES = (
"customer_auto_resolution_evaluated",
"customer_auto_confirmed",
"customer_correction_applied",
"customer_historical_backfilled",
)
@@ -44,6 +43,48 @@ def auto_customer_resolution_enabled() -> bool:
return cfg_bool("SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED", False)
def _auto_confirmation_quality_gate() -> dict[str, Any]:
"""
评估自动确认质量门禁,只以当前强规则会唯一命中的已人工标注样本为分母。
人工标签覆盖的是解析不稳定的真实来件;未达到样本量或准确率时,宁可保留人工复核,
不允许生成不可逆的客户绑定和业务编号。
"""
min_samples = cfg_int('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES', 20, min_value=0)
min_accuracy = cfg_float('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY', 0.98, min_value=0.0, max_value=1.0)
labeled = (
db.session.query(ShippingCustomerShadowResolution)
.filter(ShippingCustomerShadowResolution.manual_customer_id.isnot(None))
.all()
)
eligible_samples = 0
correct_samples = 0
for shadow in labeled:
decision = _resolve_auto_customer_from_evidence(shadow.evidence_json or [])
if decision['status'] != 'unique_strong_match':
continue
eligible_samples += 1
if int(decision['customer_id']) == int(shadow.manual_customer_id):
correct_samples += 1
accuracy = (correct_samples / eligible_samples) if eligible_samples else None
if eligible_samples < min_samples:
status = 'insufficient_labeled_samples'
# min_samples=0 是显式受控放行配置;无样本时不存在可计算的准确率,不应误判为失败。
elif min_samples > 0 and (accuracy is None or accuracy < min_accuracy):
status = 'insufficient_accuracy'
else:
status = 'eligible'
return {
'status': status,
'is_eligible': status == 'eligible',
'labeled_sample_count': eligible_samples,
'correct_sample_count': correct_samples,
'accuracy': accuracy,
'min_labeled_samples': min_samples,
'min_accuracy': min_accuracy,
}
def _eligible_identifier(identifier: ShippingCustomerIdentifier) -> bool:
"""判断识别证据是否达到自动确认门槛。"""
if identifier.status != "approved" or not identifier.auto_match_allowed:
@@ -55,33 +96,10 @@ def _eligible_identifier(identifier: ShippingCustomerIdentifier) -> bool:
return True
def resolve_auto_customer_from_shadow(task: ShippingTask) -> dict[str, Any]:
"""
使用任务来源 Candidate 的影子证据执行受控自动裁决。
Args:
task: 已创建但客户仍 pending 的任务。
Returns:
status、规则版本、唯一 customer_id 与命中证据;歧义/关闭时 customer_id 为空。
"""
if not auto_customer_resolution_enabled():
return {"status": "disabled", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
if task.source_candidate_id is None:
return {"status": "no_candidate", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
shadow = db.session.query(ShippingCustomerShadowResolution).filter_by(
candidate_id=int(task.source_candidate_id),
).first()
if shadow is None:
candidate = db.session.get(ShippingNoticeCandidate, int(task.source_candidate_id))
if candidate is not None:
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
shadow = refresh_candidate_shadow_resolution(candidate)
if shadow is None:
return {"status": "no_shadow", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
def _resolve_auto_customer_from_evidence(evidence_rows: list[object]) -> dict[str, Any]:
"""以候选的规范化证据求唯一强规则客户,不读取总开关或质量门禁。"""
matched: dict[int, list[dict[str, Any]]] = {}
for evidence in shadow.evidence_json or []:
for evidence in evidence_rows:
if not isinstance(evidence, dict):
continue
kind = str(evidence.get("type") or "").strip()
@@ -120,6 +138,43 @@ def resolve_auto_customer_from_shadow(task: ShippingTask) -> dict[str, Any]:
}
def resolve_auto_customer_from_shadow(task: ShippingTask) -> dict[str, Any]:
"""
使用任务来源 Candidate 的影子证据执行受控自动裁决。
Args:
task: 已创建但客户仍 pending 的任务。
Returns:
status、规则版本、唯一 customer_id 与命中证据;歧义/关闭时 customer_id 为空。
"""
if not auto_customer_resolution_enabled():
return {"status": "disabled", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
quality_gate = _auto_confirmation_quality_gate()
if not quality_gate['is_eligible']:
return {
'status': quality_gate['status'],
'rule_version': AUTO_RESOLUTION_VERSION,
'customer_id': None,
'evidence': [],
'quality_gate': quality_gate,
}
if task.source_candidate_id is None:
return {"status": "no_candidate", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
shadow = db.session.query(ShippingCustomerShadowResolution).filter_by(
candidate_id=int(task.source_candidate_id),
).first()
if shadow is None:
candidate = db.session.get(ShippingNoticeCandidate, int(task.source_candidate_id))
if candidate is not None:
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
shadow = refresh_candidate_shadow_resolution(candidate)
if shadow is None:
return {"status": "no_shadow", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
return {**_resolve_auto_customer_from_evidence(shadow.evidence_json or []), 'quality_gate': quality_gate}
def try_auto_confirm_task_customer(task: ShippingTask) -> dict[str, Any]:
"""
尝试自动确认并生成业务编号;未达门槛时保持 customer_review。
@@ -157,52 +212,6 @@ def try_auto_confirm_task_customer(task: ShippingTask) -> dict[str, Any]:
return {**decision, "status": "auto_confirmed", "business_no": updated.shipping_case.business_no}
def backfill_historical_task_customer(
task: ShippingTask,
*,
customer_id: int,
actor_id: int | None,
) -> dict[str, Any]:
"""
为历史无业务单任务回填标准客户,但默认不生成历史业务编号。
Args:
task: shipping_case_id 为空且 task_no 为历史技术号的任务。
customer_id: 管理员确认的标准客户 ID。
actor_id: 管理员审计 ID。
Returns:
回填后的 task_no、customer_id、business_no(None)。
"""
customer = db.session.get(ShippingCustomer, int(customer_id))
if customer is None or customer.status != "active":
raise ValueError("active customer is required")
if task.shipping_case_id is not None:
raise ValueError("historical backfill only supports tasks without a shipping case")
case = ShippingCase(
case_no=generate_shipping_case_no(),
customer_id=customer.id,
customer_name_snapshot=customer.standard_name,
customer_short_code_snapshot=customer.short_code,
numbering_status="historical_unnumbered",
status="open",
created_by_id=actor_id,
)
db.session.add(case)
db.session.flush()
task.shipping_case_id = case.id
task.customer_resolution_status = "confirmed"
task.customer_resolution_method = "historical_backfill"
task.customer_confirmed_by = actor_id
task.customer_confirmed_at = datetime.utcnow()
db.session.add(ShippingTaskEvent(
task_id=task.id,
event_type="customer_historical_backfilled",
detail_json={"customer_id": customer.id, "business_no": None},
))
db.session.commit()
return {"task_no": task.task_no, "customer_id": customer.id, "business_no": None}
def correct_numbered_task_customer(
task: ShippingTask,
*,
@@ -264,6 +273,8 @@ def correct_numbered_task_customer(
customer = db.session.get(ShippingCustomer, int(customer_id))
if customer is None:
raise NotFoundError("Customer not found", code="SHIPPING.CUSTOMER_NOT_FOUND")
if customer.status == "merged":
raise ConflictError("Merged customer cannot be used", code="SHIPPING.CUSTOMER_MERGED_LOCKED")
if customer.status != "active":
raise ValidationError("Inactive customer cannot be used", code="SHIPPING.CUSTOMER_INACTIVE")
if original_case.customer_id == customer.id:
@@ -339,7 +350,6 @@ def correct_numbered_task_customer(
# 客户变化会使库存路由、匹配和导出失效;只重置当前版本,旧版本状态通过事件保留审计语义。
latest.inventory_source_code = None
latest.inventory_connector_type = None
latest.inventory_site_id = None
latest.inventory_warehouse_id = None
latest.inventory_source_status = None
latest.inventory_source_method = None
@@ -383,7 +393,7 @@ def correct_numbered_task_customer(
def get_auto_resolution_metrics() -> dict[str, Any]:
"""汇总自动裁决、纠错和回填事件,供管理员监控、查询与降级判断。"""
"""汇总自动裁决和纠错事件,供管理员监控、查询与降级判断。"""
evaluated = db.session.query(ShippingTaskEvent.task_id).filter_by(
event_type="customer_auto_resolution_evaluated",
).distinct().count()
@@ -393,9 +403,6 @@ def get_auto_resolution_metrics() -> dict[str, Any]:
corrected = db.session.query(ShippingTaskEvent.task_id).filter_by(
event_type="customer_correction_applied",
).distinct().count()
backfilled = db.session.query(ShippingTaskEvent.task_id).filter_by(
event_type="customer_historical_backfilled",
).distinct().count()
recent_events = (
db.session.query(ShippingTaskEvent, ShippingTask.task_no)
.join(ShippingTask, ShippingTask.id == ShippingTaskEvent.task_id)
@@ -407,10 +414,10 @@ def get_auto_resolution_metrics() -> dict[str, Any]:
return {
"enabled": auto_customer_resolution_enabled(),
"rule_version": AUTO_RESOLUTION_VERSION,
'quality_gate': _auto_confirmation_quality_gate(),
"evaluated_count": evaluated,
"auto_confirmed_count": confirmed,
"corrected_task_count": corrected,
"historical_backfilled_count": backfilled,
"auto_confirmation_rate": (confirmed / evaluated) if evaluated else None,
"recent_events": [
{
@@ -24,9 +24,9 @@ CUSTOMER_GATE_ERROR_CODE = 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
def customer_identity_is_confirmed(task: ShippingTask) -> bool:
"""判断任务是否通过客户 Gate;无业务单历史任务兼容放行。"""
"""判断任务是否已关联业务单并通过标准客户确认。"""
if task.shipping_case_id is None:
return True
return False
case = task.shipping_case or db.session.get(ShippingCase, int(task.shipping_case_id))
if case is None or case.customer_id is None:
return False
@@ -36,10 +36,10 @@ def customer_identity_is_confirmed(task: ShippingTask) -> bool:
def assert_customer_identity_gate(task: ShippingTask, *, operation: str = 'continue') -> None:
"""
标准客户硬门禁;新业务单未确认时阻断库存、RPA、匹配、Excel 与上传。
标准客户硬门禁;业务单缺失或客户未确认时阻断库存、RPA、匹配、Excel 与上传。
Args:
task: 当前发货任务;历史无业务单任务兼容放行。
task: 当前发货任务。
operation: 触发门禁的操作名,写入错误详情。
Raises:
AppError: 客户尚未确认、客户已停用或业务单关联无效。
@@ -101,8 +101,8 @@ def confirm_task_customer(
"""
if task.shipping_case_id is None:
raise ConflictError(
'Legacy tasks without a shipping case cannot confirm customer in this workflow',
code='SHIPPING.CUSTOMER_CONFIRMATION_LEGACY_UNSUPPORTED',
'Shipping task is missing its required shipping case',
code='SHIPPING.CUSTOMER_CASE_REQUIRED',
)
case = (
db.session.query(ShippingCase)
@@ -115,6 +115,8 @@ def confirm_task_customer(
customer = db.session.get(ShippingCustomer, int(customer_id))
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if customer.status == 'merged':
raise ConflictError('Merged customer cannot be confirmed', code='SHIPPING.CUSTOMER_MERGED_LOCKED')
if customer.status != 'active':
raise ValidationError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE')
if case.business_no and case.customer_id not in {None, customer.id}:
@@ -17,10 +17,11 @@ from typing import Any
from sqlalchemy import func
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingCustomer,
ShippingCustomerIdentifier,
ShippingCustomerShadowMatch,
ShippingCustomerShadowResolution,
ShippingNoticeCandidate,
ShippingNoticeIntake,
@@ -135,6 +136,24 @@ def refresh_candidate_shadow_resolution(candidate: ShippingNoticeCandidate) -> S
row.candidate_matches_json = matches
row.top_customer_id = int(matches[0]['customer_id']) if status == 'unique_candidate' else None
row.top_score = top_score
# 规范化候选关联用于客户生命周期约束;JSON 继续保留完整证据供展示与审计。
# 先落库删除旧快照,避免 SQLite/PostgreSQL 在同次 flush 中先插入后删除而触发唯一约束。
db.session.query(ShippingCustomerShadowMatch).filter_by(resolution_id=row.id).delete(
synchronize_session=False,
)
db.session.flush()
db.session.expire(row, ['matches'])
row.matches = [
ShippingCustomerShadowMatch(
customer_id=int(item['customer_id']),
match_rank=index,
score=float(item['score']),
standard_name_snapshot=str(item['standard_name']),
short_code_snapshot=str(item['short_code']),
reasons_json=list(item.get('reasons') or []),
)
for index, item in enumerate(matches, start=1)
]
row.updated_at = datetime.utcnow()
db.session.flush()
return row
@@ -168,6 +187,9 @@ def refresh_candidate_shadow_resolution_safely(candidate: ShippingNoticeCandidat
row.candidate_matches_json = []
row.top_customer_id = None
row.top_score = None
db.session.query(ShippingCustomerShadowMatch).filter_by(resolution_id=row.id).delete(
synchronize_session=False,
)
row.updated_at = datetime.utcnow()
db.session.flush()
except Exception:
@@ -186,6 +208,8 @@ def label_shadow_resolution(resolution_id: int, *, customer_id: int, actor_id: i
raise NotFoundError('Shadow resolution not found', code='SHIPPING.CUSTOMER_SHADOW_NOT_FOUND')
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if customer.status == 'merged':
raise ConflictError('Merged customer cannot be used as a new label', code='SHIPPING.CUSTOMER_MERGED_LOCKED')
row.manual_customer_id = customer.id
row.labeled_by_id = actor_id
row.labeled_at = datetime.utcnow()
@@ -1,8 +1,8 @@
"""
services/shipping_notice/decision_workflow.py
用途:承接发货通知任务的人工作业决策流转,包括确认、驳回、重匹配、重解析和映射修正。
依赖:state_machine、tool_response、query_service、inventory_mapping_workflow、inventory_upload、fulfillment_workflow、task_line_store。
用途:承接发货通知任务的人工作业决策流转,包括确认、驳回、重匹配和重解析。
依赖:state_machine、tool_response、query_service、库存源 Gate、fulfillment_workflow、task_line_store。
逻辑:由 task_workflow 对外转调本文件;本文件在当前任务上下文内执行决策分支,并在必要时回调后端 orchestrator。
"""
@@ -11,9 +11,9 @@ from __future__ import annotations
from typing import Any
from app import db
from app.models import ShippingTaskInventoryLink
from app.services.shipping_notice.constants import (
CP_INVENTORY_SOURCE_REVIEW,
CP_MAP_INFER,
CP_PARSE_OK,
PH_INVENTORY_SOURCE_UNRESOLVED,
PH_LOW_CONF,
@@ -23,32 +23,12 @@ from app.services.shipping_notice.constants import (
RS_SHORTAGE_REVIEW,
)
from app.services.shipping_notice.fulfillment_workflow import match_completed, match_inventory
from app.services.shipping_notice.inventory_mapping import mapping_is_complete
from app.services.shipping_notice.task_line_store import clear_task_order_lines
from app.services.shipping_notice.inventory_mapping_store import upsert_inventory_mapping
from app.services.shipping_notice.inventory_mapping_workflow import (
awaiting_inventory_mapping_confirm,
inventory_mapping_checkpoint_response,
latest_inventory_column_meta,
)
from app.services.shipping_notice.inventory_file_store import (
active_inventory_file_for_task,
linked_task_nos_for_inventory_file,
start_inventory_file_linked_tasks,
)
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
@@ -91,12 +71,26 @@ def _reset_inventory_state_for_forced_rpa(task) -> None:
task.error_message = None
def _prepare_task_for_inventory_reupload(task) -> None:
"""
解除任务当前库存快照并清理派生结果,等待用户重新选择正式库存文件。
【AI 触发时机】:用户明确选择“重新上传库存”时由 submit_decision 内部调用。
历史库存快照与 link 保留审计,但当前 active link 会停用,且不会进入字段推断链路。
"""
if task.id is not None:
for link in ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).all():
link.is_active = False
_reset_inventory_state_for_forced_rpa(task)
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
"""
提交人工决策,驱动任务在确认、重解析、重匹配、关闭等分支间流转。
【AI 触发时机】:当用户明确说“确认”“驳回”“重跑库存”“更正映射”“关闭任务”等决策类指令时调用。
【AI 触发时机】:当用户明确说“确认”“驳回”“重跑库存”“重新上传库存”“关闭任务”等决策类指令时调用。
核心逻辑:先解析 decision,再按状态机规则分发到解析确认、映射确认、重匹配或重解析等分支;rematch 会同步调用 match_inventory 完成重算。
核心逻辑:先解析 decision,再按状态机规则分发到解析确认、库存重置、重匹配或重解析等分支;rematch 会同步调用 match_inventory 完成重算。
Args:
payload: 必须包含任务定位信息与 decision,可选 comment、lang 等上下文。
@@ -115,6 +109,37 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
lang = resolve_lang(payload)
event_source = str(payload.get("event_source") or "").strip() or "decision_workflow"
# Published parsing profiles are the only production mapping contract.
# Reject legacy task-level mapping decisions instead of reopening a manual
# mapping path that could override the source's configured profile.
if decision in {"confirm_inventory_mapping", "correct_inventory_mapping"}:
return tool_response(
status="failed",
task_id=task.task_no,
message="库存字段映射已由库存站点的已发布解析方案管理;请在库存映射中调整方案后重新获取库存。",
data=serialize_task_for_tool(task),
)
if decision == "reparse_inventory":
_prepare_task_for_inventory_reupload(task)
log_task_action_event(
task,
"inventory_reupload_requested",
action="reparse_inventory",
source=event_source,
comment=comment,
)
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message="当前库存已解除关联,请重新选择库存文件。系统将按库存站点已发布的解析方案校验并解析。",
data=serialize_task_for_tool(task),
checkpoint="upload_req",
human_options=["upload_inventory_file", "retry_rpa"],
stop_agent_turn=True,
)
# [STEP 1] 先处理终止型决策。
# reject / close 会直接结束当前任务,不再继续进入库存或出货链路。
if decision == "reject":
@@ -240,7 +265,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
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)):
if not task.inventory_lines_json:
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
status="running" if orchestrator_started else "ok",
@@ -289,10 +314,6 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
data=serialize_task_for_tool(task),
)
if awaiting_inventory_mapping_confirm(task):
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
return inventory_mapping_checkpoint_response(task, lang=lang or None)
if task.inventory_lines_json or task.process_status == "inventory_ready":
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
@@ -310,7 +331,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
)
# [STEP 3] 处理重算型决策。
# retry_rpa / rematch / confirm_inventory_mapping / correct_inventory_mapping / reparse_inventory
# retry_rpa / rematch 都是在当前任务基础上回退或重放局部链路,
# 都是在当前任务基础上回退或重放局部链路,而不是重新 create_task。
if decision == "retry_rpa":
_reset_inventory_state_for_forced_rpa(task)
@@ -350,186 +371,6 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
)
return match_result
if decision == "confirm_inventory_mapping":
if not awaiting_inventory_mapping_confirm(task):
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.decision.mapping_not_needed", lang=lang),
data=serialize_task_for_tool(task),
)
meta = latest_inventory_column_meta(task) or {}
inv_mapping = meta.get("mapping") if isinstance(meta.get("mapping"), dict) else {}
res_source = None
if isinstance(inv_mapping.get("reservation_id"), dict):
res_source = inv_mapping["reservation_id"].get("source_column")
if not str(res_source or "").strip():
apply_task_transition(task, TaskTransition.ALIGN_REVIEW_HOLD)
db.session.commit()
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
warning = t("workflow.decision.mapping_missing_reservation_warning", lang=lang)
ui = resolve_task_ui_state(task)
return tool_response(
status="needs_human",
task=task,
message=warning,
data=serialize_task_for_tool(task),
checkpoint=ui.checkpoint,
human_options=ui.human_options,
next_required_action=t("workflow.decision.mapping_correction_next", lang=lang),
forbidden_next_tools=["match_inventory"],
stop_agent_turn=True,
)
headers = meta.get("headers") if isinstance(meta.get("headers"), list) else []
field_mapping = meta.get("field_mapping") if isinstance(meta.get("field_mapping"), dict) else None
if headers and field_mapping and mapping_is_complete(field_mapping):
upsert_inventory_mapping(
task.customer_code,
preview={
"headers": headers,
"header_row_index": meta.get("header_row_index") or 1,
},
field_mapping={str(k): str(v).strip() for k, v in field_mapping.items() if str(v or "").strip()},
)
apply_task_transition(task, TaskTransition.MAPPING_CONFIRMED)
inv_file = active_inventory_file_for_task(task)
linked_task_nos = [task.task_no]
if inv_file:
inv_file.mapping_confirmed = True
log_task_event(
task,
"inventory_mapping_confirmed",
{
**{
"comment": comment,
"confirmed_by_task_no": task.task_no,
"inventory_file_no": inv_file.inventory_file_no,
},
**{
"action": "confirm_inventory_mapping",
"source": event_source,
"target_type": "task",
"target_id": task.task_no,
"batch_no": task.batch.batch_no if task.batch else "",
"conversation_id": task.conversation_id or "",
},
},
)
for link in inv_file.links or []:
linked_task = link.task
if not link.is_active or not linked_task:
continue
linked_task_nos.append(linked_task.task_no)
if awaiting_inventory_mapping_confirm(linked_task):
apply_task_transition(linked_task, TaskTransition.MAPPING_CONFIRMED)
log_task_event(
linked_task,
"inventory_mapping_confirmed",
{
**{
"comment": comment,
"confirmed_by_task_no": task.task_no,
"inventory_file_no": inv_file.inventory_file_no,
},
**{
"action": "confirm_inventory_mapping",
"source": event_source,
"target_type": "task",
"target_id": linked_task.task_no,
"batch_no": linked_task.batch.batch_no if linked_task.batch else "",
"conversation_id": linked_task.conversation_id or "",
},
},
)
else:
log_task_action_event(
task,
"inventory_mapping_confirmed",
action="confirm_inventory_mapping",
source=event_source,
comment=comment,
)
db.session.commit()
orchestrator_started = (
start_inventory_file_linked_tasks(inv_file)
if inv_file
else start_task_orchestrator(task.task_no)
)
if inv_file:
linked_task_nos = linked_task_nos_for_inventory_file(inv_file)
return tool_response(
status="running" if orchestrator_started else "ok",
task=task,
message=t("workflow.decision.mapping_confirmed_running", lang=lang),
data={**serialize_task_for_tool(task), "linked_task_nos": linked_task_nos},
)
if decision == "correct_inventory_mapping":
if not awaiting_inventory_mapping_confirm(task):
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.decision.mapping_correction_invalid_state", lang=lang),
data=serialize_task_for_tool(task),
)
task.inventory_lines_json = None
apply_task_transition(task, TaskTransition.CORRECT_MAPPING)
log_task_event(task, "inventory_mapping_correction_requested", {"comment": comment})
db.session.commit()
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:
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.decision.read_inventory_preview_failed", lang=lang).format(error=exc),
data=serialize_task_for_tool(task),
)
else:
meta = latest_inventory_column_meta(task) or {}
preview = {
"headers": meta.get("headers") or [],
"sample_rows": [],
"suggested_mapping": meta.get("field_mapping") or {},
"note": t("workflow.decision.mapping_preview_note", lang=lang),
}
return tool_response(
status="needs_human",
task=task,
message=t("workflow.decision.mapping_correction_needed", lang=lang),
data={**serialize_task_for_tool(task), "schema_preview": preview},
checkpoint=CP_MAP_INFER,
next_required_action=t("workflow.decision.mapping_correction_next", lang=lang),
forbidden_next_tools=["match_inventory"],
stop_agent_turn=True,
)
if decision == "reparse_inventory":
task.inventory_lines_json = None
if task.process_status == "inventory_ready":
apply_task_transition(task, TaskTransition.REPARSE_INVENTORY_DEMOTE)
else:
apply_task_transition(task, TaskTransition.REPARSE_INVENTORY)
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(
status="ok",
task_id=task.task_no,
message=t("workflow.decision.inventory_cleared", lang=lang),
data=serialize_task_for_tool(task),
next_required_action=t("workflow.decision.mapping_correction_next", lang=lang),
forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"],
)
# [STEP 4] 最后处理整单重新解析。
# 整单重解析必须回到 created 并交给后台 Dify 编排,避免启发式兜底直接覆盖 AI 解析。
if decision == "reparse":
@@ -10,9 +10,10 @@ services/shipping_notice/dify_inputs.py
from __future__ import annotations
from datetime import datetime
from typing import Any
from app.models import ShippingBatch, ShippingTask
from app.models import ShippingBatch, ShippingTask, ShippingTemporaryInventorySession
from app.services.agent_runtime_context.builder import serialize_for_dify
from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPUT
from app.services.shipping_notice.runtime_context import build_shipping_runtime_context
@@ -38,6 +39,35 @@ def _task_by_task_no(task_id: str) -> ShippingTask | None:
return ShippingTask.query.filter_by(task_no=normalized).first()
def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | None:
"""
恢复当前聊天中仍待用户处理的临时库存会话锚点。
Args:
conversation_id: HXOPS 本地聊天会话 ID。
Returns:
最新未过期待处理会话号;没有符合条件的会话时返回 None。
"""
normalized = str(conversation_id or '').strip()
if not normalized:
return None
item = ShippingTemporaryInventorySession.query.filter(
ShippingTemporaryInventorySession.conversation_id == normalized,
ShippingTemporaryInventorySession.status.in_([
'created',
'awaiting_profile_confirmation',
'awaiting_mapping_suggestion',
'awaiting_mapping_confirmation',
]),
ShippingTemporaryInventorySession.expires_at > datetime.utcnow(),
).order_by(
ShippingTemporaryInventorySession.updated_at.desc(),
ShippingTemporaryInventorySession.id.desc(),
).first()
return str(item.session_no or '').strip().upper() or None if item else None
def _focus_task_row(focus_task: str, explicit_task_row: ShippingTask | None) -> ShippingTask | None:
"""
解析当前显式焦点任务行。
@@ -70,6 +100,8 @@ def build_dify_chat_inputs(
locale: str | None = None,
intake_nos: list[str] | None = None,
capability: str | None = None,
temporary_inventory_asset_no: str | None = None,
temporary_inventory_session_no: str | None = None,
) -> dict[str, Any]:
"""
构建发货通知 Dify Chatflow inputs。
@@ -83,6 +115,15 @@ def build_dify_chat_inputs(
explicit_task = str(task_id or "").strip().upper()
explicit_batch = str(batch_no or "").strip().upper()
explicit_temporary_session = str(temporary_inventory_session_no or '').strip().upper()
resolved_temporary_session = (
explicit_temporary_session
or (
_latest_pending_temporary_inventory_session(conv_id)
if trigger_source != 'backend_orchestrator'
else None
)
)
batch = _latest_batch_for_conversation(conv_id)
explicit_task_row = _task_by_task_no(explicit_task)
@@ -113,10 +154,12 @@ def build_dify_chat_inputs(
run_purpose=(
"parse_notice"
if trigger_source == "backend_orchestrator"
else ("order_extraction" if intake_nos else "chat_turn")
else ("temporary_inventory" if temporary_inventory_asset_no else ("order_extraction" if intake_nos else "chat_turn"))
),
intake_nos=intake_nos,
capability=capability,
capability=capability or ("temporary_inventory" if temporary_inventory_asset_no else None),
temporary_inventory_asset_no=temporary_inventory_asset_no,
temporary_inventory_session_no=resolved_temporary_session,
)
if not runtime_context:
return {}
@@ -320,6 +320,11 @@ def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]:
summary = cand.structured_result_json.get('business_summary')
structured = cand.structured_result_json if isinstance(cand.structured_result_json, dict) else {}
extraction = structured.get('extraction') if isinstance(structured.get('extraction'), dict) else {}
customer_matches = (
extraction.get('customer_matches')
if isinstance(extraction.get('customer_matches'), list)
else []
)
adjudication = (
extraction.get('field_adjudication')
if isinstance(extraction.get('field_adjudication'), dict)
@@ -354,6 +359,7 @@ def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]:
'observation_history': list(adjudication.get('observation_history') or []),
'conflicts': list(adjudication.get('conflicts') or []),
} if adjudication else None,
'customer_matches': list(customer_matches),
'duplicate': {
'status': status,
'blocking': blocking,
@@ -0,0 +1,358 @@
"""
services/shipping_notice/excel_template.py
用途:管理发货 Excel 模板草稿、映射定义、发布版本与受管模板文件。
依赖:openpyxl、ShippingExcelTemplate、订单字段目录、Flask 配置与统一业务异常。
逻辑:上传 xlsx 创建草稿;草稿可改定义;发布时验证工作表、字段引用和映射目标并计算不可变校验和。
"""
from __future__ import annotations
import hashlib
import json
import re
import uuid
from datetime import datetime
from io import BytesIO
from typing import Any
from flask import current_app
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter
from werkzeug.datastructures import FileStorage
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingExcelTemplate,
ShippingExportArtifact,
ShippingInventoryField,
ShippingInventorySource,
ShippingOrderField,
)
from app.services.file_assets.storage import file_asset_storage
ALLOWED_SOURCE_KINDS = {'order_field', 'inventory_field', 'system_fact', 'constant'}
ALLOWED_ROW_MODES = {'header', 'line'}
ALLOWED_FORMATTERS = {'text', 'upper', 'lower', 'date_mmddyyyy', 'integer', 'decimal'}
ALLOWED_SYSTEM_FACTS = {'task_no', 'business_no', 'warehouse_id', 'inventory_source_code', 'export_date'}
def _storage_key(template_code: str, version: int) -> str:
"""构造长期私有模板对象键,与临时上传资产生命周期隔离。"""
return f'shipping-excel-templates/{template_code}/v{version}/{uuid.uuid4().hex}.xlsx'
def _checksum_json(value: Any) -> str:
payload = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), default=str)
return hashlib.sha256(payload.encode('utf-8')).hexdigest()
def _payload(item: ShippingExcelTemplate) -> dict[str, Any]:
"""序列化模板元数据,绝不向管理端暴露服务器存储路径。"""
return {
'id': item.id, 'template_code': item.template_code, 'display_name': item.display_name,
'version': item.version, 'status': item.status, 'original_filename': item.original_filename,
'file_checksum': item.file_checksum, 'definition': item.definition_json or {},
'definition_checksum': item.definition_checksum,
'created_at': item.created_at.isoformat() if item.created_at else None,
'published_at': item.published_at.isoformat() if item.published_at else None,
}
def list_templates() -> list[dict[str, Any]]:
"""按编码和版本列出模板,供库存源绑定及草稿编辑。"""
rows = ShippingExcelTemplate.query.order_by(
ShippingExcelTemplate.template_code, ShippingExcelTemplate.version.desc(),
).all()
return [_payload(item) for item in rows]
def _next_version(template_code: str) -> int:
latest = ShippingExcelTemplate.query.filter_by(template_code=template_code).order_by(
ShippingExcelTemplate.version.desc(),
).first()
return int(latest.version) + 1 if latest else 1
def create_draft(upload: FileStorage | None, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""
上传模板文件并创建新草稿版本。
Args:
upload: 必须为非空 xlsx 文件;宏工作簿和 CSV 不接受。
data: template_code、display_name 与 JSON definition。
actor_id: 当前管理员 ID。
"""
code = str(data.get('template_code') or '').strip().upper()
name = str(data.get('display_name') or '').strip()
filename = str(getattr(upload, 'filename', '') or '').strip()
if not code or not name or upload is None or not filename.lower().endswith('.xlsx'):
raise ValidationError('template_code, display_name and xlsx file are required', code='SHIPPING.EXCEL_TEMPLATE_INVALID')
if not re.fullmatch(r'[A-Z0-9_-]{2,64}', code):
raise ValidationError('template_code format is invalid', code='SHIPPING.EXCEL_TEMPLATE_INVALID')
if ShippingExcelTemplate.query.filter_by(template_code=code, status='draft').count():
raise ConflictError('A draft already exists for this template code', code='SHIPPING.EXCEL_TEMPLATE_DRAFT_EXISTS')
raw = upload.read()
if not raw:
raise ValidationError('Template file is empty', code='SHIPPING.EXCEL_TEMPLATE_INVALID')
max_mb = max(int(current_app.config.get('SHIPPING_EXCEL_TEMPLATE_MAX_SIZE_MB') or 20), 1)
if len(raw) > max_mb * 1024 * 1024:
raise ValidationError('Template file exceeds size limit', code='SHIPPING.EXCEL_TEMPLATE_INVALID')
try:
workbook = load_workbook(BytesIO(raw), read_only=True)
workbook.close()
except Exception as exc:
raise ValidationError('Template file is not a valid xlsx workbook', code='SHIPPING.EXCEL_TEMPLATE_INVALID') from exc
definition = data.get('definition') if isinstance(data.get('definition'), dict) else {}
version = _next_version(code)
storage_key = _storage_key(code, version)
file_asset_storage.upload_bytes(
storage_key=storage_key, data=raw,
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
)
item = ShippingExcelTemplate(
template_code=code, display_name=name, version=version, status='draft',
storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key,
original_filename=filename[:255],
file_checksum=hashlib.sha256(raw).hexdigest(), definition_json=definition,
created_by=actor_id,
)
try:
db.session.add(item)
db.session.commit()
except Exception:
db.session.rollback()
try:
file_asset_storage.delete_object(storage_key)
except Exception:
pass
raise
return _payload(item)
def update_draft(template_id: int, data: dict[str, Any]) -> dict[str, Any]:
"""更新草稿显示名称和映射定义;发布版本禁止原地修改。"""
item = db.session.get(ShippingExcelTemplate, template_id)
if item is None:
raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND')
if item.status != 'draft':
raise ConflictError('Published template is immutable', code='SHIPPING.EXCEL_TEMPLATE_IMMUTABLE')
name = str(data.get('display_name') or '').strip()
definition = data.get('definition')
if not name or not isinstance(definition, dict):
raise ValidationError('display_name and definition are required', code='SHIPPING.EXCEL_TEMPLATE_INVALID')
item.display_name = name
item.definition_json = definition
db.session.commit()
return _payload(item)
def _workbook_layout(raw: bytes, definition: dict[str, Any]) -> dict[str, list[dict[str, Any]]]:
"""读取受管模板的工作表和首行栏位,供编辑器重新加载已保存文件的结构。"""
workbook = load_workbook(BytesIO(raw), read_only=True, data_only=False)
try:
header_rows: dict[str, int] = {}
for mapping in definition.get('mappings', []):
if not isinstance(mapping, dict):
continue
sheet_name = str(mapping.get('sheet') or '')
start_row = int(mapping.get('start_row') or 1)
candidate_row = max(start_row - 1, 1)
header_rows[sheet_name] = min(header_rows.get(sheet_name, candidate_row), candidate_row)
layout: dict[str, list[dict[str, Any]]] = {}
for sheet_name in workbook.sheetnames:
sheet = workbook[sheet_name]
if sheet.max_column is None:
sheet.calculate_dimension(force=True)
header_row = header_rows.get(sheet_name, 1)
max_column = int(sheet.max_column or 0)
columns: list[dict[str, Any]] = []
for column_index in range(1, max_column + 1):
value = sheet.cell(header_row, column_index).value
column = get_column_letter(column_index)
columns.append({'index': column_index, 'label': f'{column} - {value}' if value else column})
layout[sheet_name] = columns
return layout
finally:
workbook.close()
def get_layout(template_id: int) -> dict[str, Any]:
"""返回已保存模板的工作表和目标列信息,不要求用户重新上传文件。"""
item = db.session.get(ShippingExcelTemplate, template_id)
if item is None:
raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND')
raw = file_asset_storage.get_bytes(item.storage_key)
if hashlib.sha256(raw).hexdigest() != item.file_checksum:
raise ValidationError('Template asset is missing or changed', code='SHIPPING.EXCEL_TEMPLATE_ASSET_INVALID')
return {'template_id': item.id, 'sheets': _workbook_layout(raw, item.definition_json or {})}
def create_draft_from_existing(template_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""复制已保存模板文件和映射定义,创建可编辑的新草稿版本。"""
source = db.session.get(ShippingExcelTemplate, template_id)
if source is None:
raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND')
if source.status not in {'draft', 'published', 'retired'}:
raise ConflictError('Template status cannot create a new version', code='SHIPPING.EXCEL_TEMPLATE_VERSION_INVALID')
if ShippingExcelTemplate.query.filter_by(template_code=source.template_code, status='draft').count():
raise ConflictError('A draft already exists for this template code', code='SHIPPING.EXCEL_TEMPLATE_DRAFT_EXISTS')
raw = file_asset_storage.get_bytes(source.storage_key)
if hashlib.sha256(raw).hexdigest() != source.file_checksum:
raise ValidationError('Template asset is missing or changed', code='SHIPPING.EXCEL_TEMPLATE_ASSET_INVALID')
version = _next_version(source.template_code)
storage_key = _storage_key(source.template_code, version)
file_asset_storage.upload_bytes(
storage_key=storage_key, data=raw,
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
)
item = ShippingExcelTemplate(
template_code=source.template_code, display_name=source.display_name, version=version, status='draft',
storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key,
original_filename=source.original_filename, file_checksum=hashlib.sha256(raw).hexdigest(),
definition_json=json.loads(json.dumps(source.definition_json or {}, ensure_ascii=False)), created_by=actor_id,
)
try:
db.session.add(item)
db.session.commit()
except Exception:
db.session.rollback()
try:
file_asset_storage.delete_object(storage_key)
except Exception:
pass
raise
return _payload(item)
def _validate_definition(item: ShippingExcelTemplate) -> dict[str, Any]:
"""验证模板定义、实际工作表和稳定字段引用,返回规范化定义。"""
definition = item.definition_json if isinstance(item.definition_json, dict) else {}
mappings = definition.get('mappings')
filename_pattern = str(definition.get('filename_pattern') or '').strip()
if not isinstance(mappings, list) or not mappings or not filename_pattern:
raise ValidationError('Template mappings and filename_pattern are required', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID')
try:
rendered_name = filename_pattern.format(
task_no='TASK', business_no='BUSINESS', source_code='SOURCE', ts='20260101000000', date='20260101',
customer_short_code='CUSTOMER', business_date='260602', sequence='01',
)
except (KeyError, ValueError) as exc:
raise ValidationError('Template filename_pattern is invalid', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID') from exc
if not rendered_name.strip():
raise ValidationError('Template filename_pattern is empty', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID')
raw = file_asset_storage.get_bytes(item.storage_key)
if hashlib.sha256(raw).hexdigest() != item.file_checksum:
raise ValidationError('Template asset is missing or changed', code='SHIPPING.EXCEL_TEMPLATE_ASSET_INVALID')
wb = load_workbook(BytesIO(raw), read_only=True)
sheet_names = set(wb.sheetnames)
wb.close()
published_field_ids: set[str] = set()
if any(isinstance(mapping, dict) and mapping.get('source_kind') == 'order_field' for mapping in mappings):
from app.services.shipping_notice.order_schema import service as order_schema_service
published_field_ids = {
str(field.get('field_id') or '')
for field in order_schema_service.get_published_contract().get('fields', [])
}
normalized: list[dict[str, Any]] = []
seen_targets: set[tuple[str, str, int]] = set()
for index, raw in enumerate(mappings):
if not isinstance(raw, dict):
raise ValidationError('Template mapping must be an object', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID')
sheet = str(raw.get('sheet') or '').strip()
row_mode = str(raw.get('row_mode') or '').strip().lower()
source_kind = str(raw.get('source_kind') or '').strip().lower()
source_key = str(raw.get('source_key') or '').strip()
formatter = str(raw.get('formatter') or 'text').strip().lower()
try:
start_row = int(raw.get('start_row'))
target_column = int(raw.get('target_column'))
except (TypeError, ValueError) as exc:
raise ValidationError('Template target row and column must be integers', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID') from exc
if sheet not in sheet_names or row_mode not in ALLOWED_ROW_MODES or source_kind not in ALLOWED_SOURCE_KINDS:
raise ValidationError('Template mapping metadata is invalid', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID', details={'index': index})
if start_row < 1 or target_column < 1 or formatter not in ALLOWED_FORMATTERS:
raise ValidationError('Template mapping target or formatter is invalid', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID')
if source_kind == 'order_field':
field = db.session.get(ShippingOrderField, source_key)
allowed_scopes = {'header'} if row_mode == 'header' else {'header', 'line'}
if field is None or field.status != 'active' or field.scope not in allowed_scopes or field.id not in published_field_ids:
raise ValidationError('Order field is invalid for mapping scope', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID')
elif source_kind == 'inventory_field':
try:
inventory_field_id = int(source_key)
except (TypeError, ValueError) as exc:
raise ValidationError('Inventory field is invalid', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID') from exc
inventory_field = db.session.get(ShippingInventoryField, inventory_field_id)
if inventory_field is None or inventory_field.status != 'active':
raise ValidationError('Inventory field is unavailable', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID')
source_key = str(inventory_field.id)
elif source_kind == 'system_fact' and source_key not in ALLOWED_SYSTEM_FACTS:
raise ValidationError('System fact is not allowed', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID')
elif source_kind != 'constant' and not source_key:
raise ValidationError('source_key is required', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID')
target = (sheet, row_mode, target_column)
if target in seen_targets:
raise ValidationError('Duplicate template target column', code='SHIPPING.EXCEL_TEMPLATE_TARGET_DUPLICATE')
seen_targets.add(target)
normalized.append({
'sheet': sheet, 'row_mode': row_mode, 'start_row': start_row,
'target_column': target_column, 'source_kind': source_kind,
'source_key': source_key, 'formatter': formatter,
})
return {'filename_pattern': filename_pattern, 'mappings': normalized}
def publish(template_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""验证并发布模板版本;发布后文件和定义均不可变。"""
item = db.session.get(ShippingExcelTemplate, template_id)
if item is None:
raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND')
if item.status != 'draft':
raise ConflictError('Only draft template can be published', code='SHIPPING.EXCEL_TEMPLATE_PUBLISH_INVALID')
definition = _validate_definition(item)
item.definition_json = definition
item.definition_checksum = _checksum_json(definition)
item.status = 'published'
item.published_by = actor_id
item.published_at = datetime.utcnow()
db.session.commit()
return _payload(item)
def retire(template_id: int) -> dict[str, Any]:
"""退役不再供新库存源绑定的模板;现有产物引用保持不变。"""
item = db.session.get(ShippingExcelTemplate, template_id)
if item is None:
raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND')
if item.status != 'published':
raise ConflictError('Only published template can be retired', code='SHIPPING.EXCEL_TEMPLATE_RETIRE_INVALID')
if ShippingInventorySource.query.filter_by(excel_template_id=item.id).count():
raise ConflictError('Rebind inventory sources first', code='SHIPPING.EXCEL_TEMPLATE_RETIRE_BLOCKED')
item.status = 'retired'
db.session.commit()
return _payload(item)
def delete_draft(template_id: int) -> None:
"""删除未发布草稿及其受管文件;已有 Artifact 的模板永远不可删除。"""
item = db.session.get(ShippingExcelTemplate, template_id)
if item is None:
raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND')
if item.status != 'draft' or ShippingExportArtifact.query.filter_by(template_id=item.id).count():
raise ConflictError('Only unused draft can be deleted', code='SHIPPING.EXCEL_TEMPLATE_DELETE_BLOCKED')
storage_key = item.storage_key
raw = file_asset_storage.get_bytes(storage_key)
file_asset_storage.delete_object(storage_key)
try:
db.session.delete(item)
db.session.commit()
except Exception:
db.session.rollback()
file_asset_storage.upload_bytes(
storage_key=storage_key, data=raw,
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
)
raise
+332 -260
View File
@@ -1,311 +1,383 @@
"""
services/shipping_notice/export.py
用途:生成发货通知对应的货代出货 Excel,并管理模板与导出文件存储路径。
依赖:openpyxl、app.models.ShippingTask、path_utils、task_line_store、Flask current_app 配置。
逻辑:由 fulfillment_workflow.generate_excel 调用本文件;订单行经 read_task_order_lines 读取。
用途:按库存源绑定的已发布模板版本生成发货 Excel,并记录不可变导出产物。
依赖:ShippingExcelTemplate/ShippingExportArtifact、动态订单 FieldValue、库存快照与 openpyxl。
逻辑:锁定 Source、模板、订单 Schema/Extraction、库存解析 Profile 和库存快照,按白名单映射写入模板。
"""
from __future__ import annotations
from datetime import datetime
import hashlib
import json
import uuid
from datetime import date, datetime
from decimal import Decimal
from pathlib import Path
from shutil import copy2
from typing import Any
from zoneinfo import ZoneInfo
from flask import current_app
from openpyxl import Workbook, load_workbook
from openpyxl import load_workbook
from sqlalchemy import update
from app.models import ShippingTask
from app.path_utils import backend_dir, resolve_backend_relative_path
from app.services.shipping_notice.task_line_store import read_task_order_lines
DEFAULT_HEADERS = [
"客户名称",
"客户代码",
"收货地址",
"要求交期",
"料号",
"发货数量",
"单位",
"备注",
]
HEADER_SHEET = "PVMI Pull Request Header"
DETAIL_SHEET = "PVMI Pull Request Detail"
DATA_START_ROW = 4
from app import db
from app.models import (
ShippingExcelTemplate,
ShippingExportArtifact,
ShippingInventoryField,
ShippingInventorySource,
ShippingOrderExtraction,
ShippingOrderFieldValue,
ShippingTask,
)
from app.path_utils import resolve_backend_relative_path
from app.services.file_assets.storage import file_asset_storage
def _storage_root() -> Path:
"""发货通知文件存储根目录(exports/notice_uploads/inventory_uploads 的父路径)。"""
root = str(current_app.config.get("SHIPPING_NOTICE_STORAGE_ROOT") or "").strip()
if root:
return Path(resolve_backend_relative_path(root))
return Path(current_app.instance_path) / "shipping_notice"
def _default_template_path() -> Path | None:
configured = str(current_app.config.get("FREIGHT_SHIPMENT_TEMPLATE_PATH") or "").strip()
"""返回发货通知文件根目录。"""
configured = str(current_app.config.get('SHIPPING_NOTICE_STORAGE_ROOT') or '').strip()
if configured:
path = Path(resolve_backend_relative_path(configured))
if path.is_file():
return path
bundled = backend_dir() / "templates" / "freight_shipment_upload.xlsx"
return bundled if bundled.is_file() else None
return Path(resolve_backend_relative_path(configured))
return Path(current_app.instance_path) / 'shipping_notice'
def _is_pvmi_workbook(wb) -> bool:
return HEADER_SHEET in wb.sheetnames and DETAIL_SHEET in wb.sheetnames
def _format_delivery_date(value: Any) -> str:
text = str(value or "").strip()
if not text:
return ""
for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%d/%m/%Y", "%m/%d/%Y", "%Y%m%d"):
try:
parsed = datetime.strptime(text[:10], fmt)
return parsed.strftime("%m/%d/%Y")
except ValueError:
continue
if len(text) >= 10 and text[4] == "-" and text[7] == "-":
try:
parsed = datetime.strptime(text[:10], "%Y-%m-%d")
return parsed.strftime("%m/%d/%Y")
except ValueError:
pass
return text
def _delivery_date_for_task(task: ShippingTask) -> str:
if task.required_date:
formatted = _format_delivery_date(task.required_date)
if formatted:
return formatted
for line in read_task_order_lines(task):
formatted = _format_delivery_date(line.get("required_date"))
if formatted:
return formatted
return ""
def _resolve_odm_id(task: ShippingTask) -> str:
"""
按订单内部料号与 Reservation 定位当前库存投影中的 ODM ID。
核心逻辑:订单与库存统一按 part_number + reservation_id 配对。
Args:
task: 已关联库存快照的发货任务。
Returns:
首个匹配库存行的 ODM ID;未命中时回退库存中的首个非空值。
"""
notice_lines = read_task_order_lines(task)
inventory_lines = [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
if not inventory_lines:
return ""
inv_by_key: dict[tuple[str, str], dict[str, Any]] = {}
for row in inventory_lines:
key = (
str(row.get("part_number") or "").strip(),
str(row.get("reservation_id") or "").strip(),
)
inv_by_key[key] = row
for line in notice_lines:
key = (
str(line.get("part_number") or "").strip(),
str(line.get("reservation_id") or "").strip(),
)
matched = inv_by_key.get(key)
if matched:
odm_id = str(matched.get("odm_id") or "").strip()
if odm_id:
return odm_id
for row in inventory_lines:
odm_id = str(row.get("odm_id") or "").strip()
if odm_id:
return odm_id
return ""
def _shipment_warehouse_id(task: ShippingTask) -> str:
"""
解析发货 Excel Header 的 Warehouse ID。
核心逻辑:库存快照入库时按「配置 site_id 优先,否则库存 Excel 的 warehouse id」写入 inv_file.warehouse_id。
"""
try:
from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link
snapshot = serialize_inventory_snapshot_link(task)
except Exception:
snapshot = None
if isinstance(snapshot, dict):
value = str(snapshot.get("warehouse_id") or "").strip()
if value:
def _typed_value(item: ShippingOrderFieldValue) -> Any:
"""从类型化投影读取唯一业务值,禁止回退旧任务固定列。"""
for value in (
item.value_text, item.value_decimal, item.value_integer,
item.value_date, item.value_boolean, item.value_json,
):
if value is not None:
return value
return "AWSDU"
return None
def _line_po_number(task: ShippingTask, line: dict[str, Any]) -> str:
for value in (line.get("po_number"), task.po_number):
text = str(value or "").strip()
if text:
return text
return ""
def _order_values(extraction: ShippingOrderExtraction) -> tuple[dict[str, Any], list[dict[str, Any]]]:
"""将稳定 field_id 投影为 Header 字典及按订单行 position 排序的字典列表。"""
header: dict[str, Any] = {}
line_positions = {line.id: line.position for line in extraction.lines}
lines: dict[int, dict[str, Any]] = {position: {} for position in line_positions.values()}
for item in extraction.values:
value = _typed_value(item)
if item.line_id is None:
header[item.field_id] = value
elif item.line_id in line_positions:
lines[line_positions[item.line_id]][item.field_id] = value
return header, [lines[position] for position in sorted(lines)]
def _line_currency(task: ShippingTask, line: dict[str, Any]) -> str:
for value in (line.get("currency"), getattr(task, "currency", None)):
text = str(value or "").strip().upper()
if text:
return text
return ""
def order_field_id_values(task: ShippingTask) -> tuple[dict[str, Any], list[dict[str, Any]]]:
"""读取任务当前已接受订单解析,并按稳定字段 ID 返回 Header 与明细值。"""
extraction = (
db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
if task.current_order_extraction_id is not None else None
)
if extraction is None or extraction.status != 'accepted':
raise ValueError('任务没有可用于库存匹配的订单解析版本')
return _order_values(extraction)
def _line_part_number(line: dict[str, Any]) -> str:
"""返回货代明细使用的内部料号。"""
return str(line.get("part_number") or "").strip()
def _system_fact(task: ShippingTask, key: str) -> Any:
"""读取受控任务事实,模板不能通过任意属性路径访问 ORM。"""
values = {
'task_no': task.task_no,
'business_no': task.shipping_case.business_no if task.shipping_case else None,
'warehouse_id': task.inventory_warehouse_id,
'inventory_source_code': task.inventory_source_code,
'export_date': datetime.now(ZoneInfo('Asia/Shanghai')).date(),
}
return values.get(key)
def _clear_sheet_data_rows(ws, *, from_row: int = DATA_START_ROW) -> None:
if ws.max_row < from_row:
return
for row_idx in range(from_row, ws.max_row + 1):
for col_idx in range(1, ws.max_column + 1):
ws.cell(row_idx, col_idx).value = None
def _format_value(value: Any, formatter: str) -> Any:
"""应用发布契约允许的确定性格式化器。"""
if value is None:
return ''
if formatter == 'upper':
return str(value).upper()
if formatter == 'lower':
return str(value).lower()
if formatter == 'date_mmddyyyy':
if isinstance(value, (date, datetime)):
return value.strftime('%m/%d/%Y')
text = str(value).strip()
for pattern in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d', '%m/%d/%Y'):
try:
return datetime.strptime(text[:10], pattern).strftime('%m/%d/%Y')
except ValueError:
continue
return text
if formatter == 'integer':
return int(Decimal(str(value)))
if formatter == 'decimal':
return float(Decimal(str(value)))
return str(value) if isinstance(value, (Decimal, date, datetime)) else value
def _fill_pvmi_template(task: ShippingTask, path: Path) -> None:
"""将业务号作为货代主引用写入 PVMI 模板,技术任务号仍用于系统追踪和文件名。"""
wb = load_workbook(filename=str(path))
header_ws = wb[HEADER_SHEET]
detail_ws = wb[DETAIL_SHEET]
_clear_sheet_data_rows(detail_ws)
_clear_sheet_data_rows(header_ws, from_row=DATA_START_ROW)
header_ws.cell(DATA_START_ROW, 1).value = _shipment_warehouse_id(task)
if header_ws.cell(DATA_START_ROW, 2).value in (None, ""):
header_ws.cell(DATA_START_ROW, 2).value = "n"
if header_ws.cell(DATA_START_ROW, 3).value in (None, ""):
header_ws.cell(DATA_START_ROW, 3).value = "WEL"
if header_ws.cell(DATA_START_ROW, 4).value in (None, ""):
header_ws.cell(DATA_START_ROW, 4).value = "normal"
header_ws.cell(DATA_START_ROW, 5).value = _delivery_date_for_task(task)
header_ws.cell(DATA_START_ROW, 6).value = _resolve_odm_id(task)
business_ref = task.shipping_case.business_no if task.shipping_case and task.shipping_case.business_no else task.task_no
header_ws.cell(DATA_START_ROW, 7).value = business_ref
notice_lines = read_task_order_lines(task)
if not notice_lines:
notice_lines = [{}]
for index, line in enumerate(notice_lines, start=1):
row_idx = DATA_START_ROW + index - 1
line_no = str(line.get("line_no") or index).strip()
qty = line.get("qty")
amount = line.get("amount")
detail_ws.cell(row_idx, 1).value = business_ref
detail_ws.cell(row_idx, 2).value = line_no
detail_ws.cell(row_idx, 4).value = _line_part_number(line)
detail_ws.cell(row_idx, 5).value = qty if qty is not None else ""
detail_ws.cell(row_idx, 7).value = _line_po_number(task, line)
detail_ws.cell(row_idx, 10).value = amount if amount is not None else ""
detail_ws.cell(row_idx, 11).value = _line_currency(task, line)
wb.save(path)
def _mapping_value(
mapping: dict[str, Any], *, task: ShippingTask, order_values: dict[str, Any], inventory_values: dict[str, Any],
header_values: dict[str, Any] | None = None,
) -> Any:
"""按映射来源类型读取值;未知来源已在模板发布时被拒绝。"""
kind = mapping['source_kind']
key = mapping['source_key']
if kind == 'order_field':
value = order_values.get(key)
if value is None and mapping.get('row_mode') == 'line' and header_values is not None:
value = header_values.get(key)
elif kind == 'inventory_field':
value = inventory_values.get(str(key))
elif kind == 'system_fact':
value = _system_fact(task, key)
else:
value = key
return _format_value(value, mapping['formatter'])
def _row_values(task: ShippingTask, line: dict | None) -> list:
line = line or {}
return [
task.customer_name or "",
task.customer_code or "",
task.ship_to or "",
task.required_date or "",
line.get("part_number") or "",
line.get("qty") or "",
line.get("uom") or "EA",
line.get("remark") or "",
]
def _match_text(value: Any) -> str:
"""规范化订单与库存匹配键;仅做确定性文本比较,不进行模糊推断。"""
if value is None:
return ''
if isinstance(value, Decimal):
return format(value.normalize(), 'f')
return str(value).strip().casefold()
def _fill_legacy_template(task: ShippingTask, path: Path) -> None:
"""填充 legacy 模板;技术任务号继续保留在导出文件名与系统记录中。"""
wb = load_workbook(filename=str(path))
ws = wb.active
lines = read_task_order_lines(task) or [None]
if ws.max_row == 1 and not any(ws.cell(1, c).value for c in range(1, 9)):
ws.append(DEFAULT_HEADERS)
for line in lines:
ws.append(_row_values(task, line))
wb.save(path)
def _inventory_fields_by_mode(mappings: list[dict[str, Any]], row_mode: str) -> set[str]:
"""返回模板直接引用的库存字段 ID,用于多命中一致性验证。"""
raw_ids = {
str(item['source_key']) for item in mappings
if item.get('row_mode') == row_mode and item.get('source_kind') == 'inventory_field'
}
ids = {int(item) for item in raw_ids if item.isdigit()}
if len(ids) != len(raw_ids):
raise ValueError('发货模板引用的库存字段无效')
rows = ShippingInventoryField.query.filter(
ShippingInventoryField.id.in_(ids), ShippingInventoryField.status == 'active',
).all() if ids else []
if len(rows) != len(ids):
raise ValueError('发货模板引用的库存字段已不存在')
return {str(item.id) for item in rows}
def _fill_blank_workbook(task: ShippingTask, path: Path) -> None:
"""生成无模板工作簿;技术任务号继续保留在导出文件名与系统记录中。"""
wb = Workbook()
ws = wb.active
ws.title = "Shipment"
ws.append(DEFAULT_HEADERS)
lines = read_task_order_lines(task) or [None]
for line in lines:
ws.append(_row_values(task, line))
wb.save(path)
def _collapse_inventory_matches(rows: list[dict[str, Any]], required_fields: set[str]) -> dict[str, Any]:
"""多库存行仅在模板所需字段值一致时合并,避免任意选择第一行。"""
if not rows:
return {}
resolved = dict(rows[0])
for field in required_fields:
values = {_match_text(row.get(field)) for row in rows if _match_text(row.get(field))}
if len(values) > 1:
raise ValueError(f'订单行匹配到多个库存记录,字段 {field} 的值不一致')
if values:
resolved[field] = next(row.get(field) for row in rows if _match_text(row.get(field)))
return resolved
def _sanitize_filename(name: str) -> str:
cleaned = "".join(ch for ch in (name or "") if ch.isalnum() or ch in {"-", "_", "."})
return cleaned or "shipment.xlsx"
def _match_inventory_lines(
order_lines: list[dict[str, Any]], inventory_lines: list[dict[str, Any]],
match_keys: list[dict[str, str]], required_fields: set[str],
) -> list[dict[str, Any]]:
"""按 published 解析 Profile 的稳定字段匹配键解析每条订单行对应库存投影。"""
if not order_lines:
return []
if not match_keys:
raise ValueError('库存解析模板缺少订单与库存匹配键')
from app.models import ShippingInventoryField
ids = {
int(item.get('inventory_field_id'))
for item in match_keys
if isinstance(item, dict) and str(item.get('inventory_field_id') or '').isdigit()
}
catalog = {
str(item.id): str(item.id)
for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(ids)).all()
}
normalized_keys: list[dict[str, str]] = []
for item in match_keys:
if not isinstance(item, dict):
raise ValueError('库存解析模板匹配键无效')
field_id = str(item.get('inventory_field_id') or '').strip()
inventory_field = catalog.get(field_id)
if not inventory_field:
raise ValueError('库存解析模板引用的库存字段已不可用')
normalized_keys.append({
'order_field_id': str(item.get('order_field_id') or ''),
'inventory_field': inventory_field,
})
result: list[dict[str, Any]] = []
for position, order_line in enumerate(order_lines, start=1):
expected = [
(_match_text(order_line.get(item['order_field_id'])), item['inventory_field'])
for item in normalized_keys
]
if any(not value for value, _field in expected):
raise ValueError(f'第 {position} 条订单行缺少库存匹配键值')
matched = [
row for row in inventory_lines
if all(_match_text(row.get(inventory_field)) == value for value, inventory_field in expected)
]
if not matched:
raise ValueError(f'第 {position} 条订单行没有匹配的库存记录')
result.append(_collapse_inventory_matches(matched, required_fields))
return result
def _export_filename(task: ShippingTask, ts: str) -> str:
pattern = str(current_app.config.get("SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN") or "").strip()
if not pattern:
pattern = "shipment_{task_no}_{ts}.xlsx"
def _header_inventory_values(
matched_lines: list[dict[str, Any]], required_fields: set[str],
) -> dict[str, Any]:
"""Header 库存字段必须在所有订单行匹配结果中一致,否则不能生成单一 Header。"""
return _collapse_inventory_matches(matched_lines, required_fields)
def _safe_filename(name: str) -> str:
"""清理配置化文件名,防止路径穿越并强制 xlsx 扩展名。"""
cleaned = ''.join(ch for ch in name if ch.isalnum() or ch in {'-', '_', '.'}).strip('.')
cleaned = cleaned or 'shipment.xlsx'
return cleaned if cleaned.lower().endswith('.xlsx') else f'{cleaned}.xlsx'
def _filename(task: ShippingTask, template: ShippingExcelTemplate) -> str:
"""按发布规则生成下载名,业务单变量始终取已锁定的客户与编号快照。"""
pattern = str((template.definition_json or {}).get('filename_pattern') or '')
now = datetime.utcnow().strftime('%Y%m%d%H%M%S')
shipping_case = task.shipping_case
values = {
'task_no': task.task_no,
'business_no': shipping_case.business_no if shipping_case and shipping_case.business_no else task.task_no,
'source_code': task.inventory_source_code or '',
'ts': now,
'date': now[:8],
'customer_short_code': (shipping_case.customer_short_code_snapshot or '') if shipping_case else '',
'business_date': shipping_case.business_date.strftime('%y%m%d') if shipping_case and shipping_case.business_date else '',
'sequence': f'{int(shipping_case.sequence_value):02d}' if shipping_case and shipping_case.sequence_value else '',
}
try:
name = pattern.format(task_no=task.task_no, ts=ts, date=ts[:8])
except Exception:
name = f"shipment_{task.task_no}_{ts}.xlsx"
if not str(name).lower().endswith(".xlsx"):
name = f"{name}.xlsx"
return _sanitize_filename(str(name))
return _safe_filename(pattern.format(**values))
except (KeyError, ValueError) as exc:
raise ValueError('发货 Excel 文件名规则无效') from exc
def generate_shipment_excel(task: ShippingTask) -> tuple[str, str]:
def _input_checksum(
task: ShippingTask, source: ShippingInventorySource, template: ShippingExcelTemplate,
extraction: ShippingOrderExtraction, header: dict[str, Any], lines: list[dict[str, Any]],
) -> str:
"""计算完整生成输入指纹,供审计和重复生成差异判断。"""
payload = {
'task_id': task.id, 'source_id': source.id, 'template_id': template.id,
'template_checksum': template.file_checksum, 'definition_checksum': template.definition_checksum,
'schema_version_id': extraction.schema_version_id, 'extraction_id': extraction.id,
'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': task.inventory_snapshot_id,
'order_header': header, 'order_lines': lines, 'inventory_lines': task.inventory_lines_json or [],
}
raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'), default=str)
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
def generate_shipment_excel(task: ShippingTask) -> tuple[str, str, ShippingExportArtifact]:
"""
基于任务数据生成货代发货 Excel 并写入 exports 目录。
【AI 触发时机】:由 generate_excel Tool 调用;Agent 禁止直接操作文件系统。
核心逻辑:复制 PVMI/legacy 模板 → 填充 Header/Detail 或 legacy 行 → 返回 (绝对路径, 文件名)。
按库存源发布模板生成 Excel,并在当前事务新增不可变 Artifact。
【AI 触发时机】:仅由 generate_excel Tool 在库存匹配完成后调用;Agent 禁止传模板或字段映射。
Returns:
tuple[str, str]: (export_file_path, export_file_name)。
(绝对文件路径, 下载文件名, 待随任务事务提交的 Artifact)。
Raises:
ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。
"""
root = _storage_root() / "exports"
root.mkdir(parents=True, exist_ok=True)
source_code = str(task.inventory_source_code or '').strip().upper()
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
raise ValueError('库存源不存在或已停用,不能生成发货 Excel')
# Fixed Sources receive this value from configuration; dynamic Sources receive it
# only after Reservation ID + Part Number resolves a unique inventory Warehouse.
if not str(task.inventory_warehouse_id or '').strip():
raise ValueError('缺少已解析的 Warehouse ID,不能生成发货 Excel')
template = source.excel_template
if template is None or template.status != 'published':
raise ValueError('库存源未绑定已发布的发货 Excel 模板')
if source.parsing_profile is None or source.parsing_profile.status != 'published':
raise ValueError('库存源未绑定已发布的库存解析模板')
extraction = (
db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
if task.current_order_extraction_id is not None else None
)
if extraction is None or extraction.status != 'accepted':
raise ValueError('任务没有可用于导出的订单解析版本')
header_values, line_values = _order_values(extraction)
inventory_lines = [item for item in (task.inventory_lines_json or []) if isinstance(item, dict)]
definition = template.definition_json or {}
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
if not mappings:
raise ValueError('发货 Excel 模板没有已发布的字段映射')
profile_definition = source.parsing_profile.definition_json if isinstance(source.parsing_profile.definition_json, dict) else {}
match_keys = profile_definition.get('match_keys') if isinstance(profile_definition.get('match_keys'), list) else []
line_inventory_fields = _inventory_fields_by_mode(mappings, 'line')
header_inventory_fields = _inventory_fields_by_mode(mappings, 'header')
matched_inventory_lines = _match_inventory_lines(
line_values, inventory_lines, match_keys, line_inventory_fields | header_inventory_fields,
) if (line_inventory_fields or header_inventory_fields) else [{} for _item in line_values]
header_inventory = _header_inventory_values(matched_inventory_lines, header_inventory_fields)
ts = datetime.utcnow().strftime("%Y%m%d%H%M%S")
filename = _export_filename(task, ts)
path = root / filename
template = _default_template_path()
if template:
copy2(template, path)
wb = load_workbook(filename=str(path), read_only=True)
filename = _filename(task, template)
artifact_no = f'EXP-{datetime.utcnow():%Y%m%d}-{uuid.uuid4().hex[:10].upper()}'
directory = _storage_root() / 'exports' / f'{datetime.utcnow():%Y}' / f'{datetime.utcnow():%m}' / task.task_no
directory.mkdir(parents=True, exist_ok=True)
path = directory / f'{artifact_no}_{filename}'
template_bytes = file_asset_storage.get_bytes(template.storage_key)
if hashlib.sha256(template_bytes).hexdigest() != template.file_checksum:
raise ValueError('发货 Excel 模板文件缺失或校验失败')
try:
path.write_bytes(template_bytes)
wb = load_workbook(path)
try:
is_pvmi = _is_pvmi_workbook(wb)
for mapping in mappings:
ws = wb[mapping['sheet']]
start_row = int(mapping['start_row'])
column = int(mapping['target_column'])
if mapping['row_mode'] == 'header':
ws.cell(start_row, column).value = _mapping_value(
mapping, task=task, order_values=header_values, inventory_values=header_inventory,
)
continue
row_count = max(len(line_values), 1)
for row_index in range(start_row, max(ws.max_row, start_row + row_count - 1) + 1):
ws.cell(row_index, column).value = None
for index in range(row_count):
order_line = line_values[index] if index < len(line_values) else {}
inventory_line = matched_inventory_lines[index] if index < len(matched_inventory_lines) else {}
ws.cell(start_row + index, column).value = _mapping_value(
mapping, task=task, order_values=order_line, inventory_values=inventory_line,
header_values=header_values,
)
wb.save(path)
finally:
wb.close()
if is_pvmi:
_fill_pvmi_template(task, path)
else:
_fill_legacy_template(task, path)
else:
_fill_blank_workbook(task, path)
return str(path), filename
content = path.read_bytes()
db.session.execute(
update(ShippingExportArtifact)
.where(
ShippingExportArtifact.task_id == task.id,
ShippingExportArtifact.status == 'ready',
)
.values(status='superseded')
)
artifact = ShippingExportArtifact(
artifact_no=artifact_no, task_id=task.id, batch_id=task.batch_id, template_id=template.id,
order_schema_version_id=extraction.schema_version_id, order_extraction_id=extraction.id,
inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=task.inventory_snapshot_id,
input_checksum=_input_checksum(task, source, template, extraction, header_values, line_values),
file_path=str(path), file_name=filename, file_checksum=hashlib.sha256(content).hexdigest(),
file_size=len(content), status='ready',
)
db.session.add(artifact)
db.session.flush()
return str(path), filename, artifact
except Exception:
if path.is_file():
path.unlink()
raise
@@ -0,0 +1,129 @@
"""
services/shipping_notice/export_archive.py
用途:为一个批次或显式任务集合生成受权限控制的发货 Excel ZIP 下载包。
依赖:ShippingExportArtifact、query_service 用户归属查询、zipfile 与统一业务异常。
逻辑:只选每票最新 ready Artifact,校验文件 checksum,处理重名并写入 manifest.json。
"""
from __future__ import annotations
import hashlib
import json
from datetime import datetime
from pathlib import Path
from tempfile import SpooledTemporaryFile
from typing import BinaryIO
from zipfile import ZIP_DEFLATED, ZipFile
from app.core.errors import NotFoundError, ValidationError
from app.models import ShippingExportArtifact, ShippingTask
from app.services.shipping_notice.query_service import get_batch_for_user, get_task_for_user, list_sorted_batch_tasks
MAX_ARCHIVE_TASKS = 100
def _select_tasks(*, user_id: int, batch_no: str | None, task_nos: list[str] | None) -> tuple[list[ShippingTask], str]:
"""按批次或任务号选择当前用户任务;两种模式互斥且禁止部分越权成功。"""
normalized_batch = str(batch_no or '').strip()
normalized_tasks = list(dict.fromkeys(str(item or '').strip() for item in (task_nos or []) if str(item or '').strip()))
if bool(normalized_batch) == bool(normalized_tasks):
raise ValidationError('Provide exactly one of batch_no or task_nos', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
if normalized_batch:
batch = get_batch_for_user(normalized_batch, user_id)
if batch is None:
raise NotFoundError('Shipping batch not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND')
tasks = list_sorted_batch_tasks(batch)
archive_key = normalized_batch
else:
tasks = []
for task_no in normalized_tasks:
task = get_task_for_user(task_no, user_id)
if task is None:
raise NotFoundError('Shipping task not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND')
tasks.append(task)
archive_key = 'selected'
if not tasks:
raise ValidationError('No shipping tasks selected', code='SHIPPING.EXPORT_ARCHIVE_EMPTY')
if len(tasks) > MAX_ARCHIVE_TASKS:
raise ValidationError(
f'At most {MAX_ARCHIVE_TASKS} tasks can be downloaded at once',
code='SHIPPING.EXPORT_ARCHIVE_TOO_LARGE', details={'max_tasks': MAX_ARCHIVE_TASKS},
)
return tasks, archive_key
def _latest_ready_artifacts(tasks: list[ShippingTask]) -> dict[int, ShippingExportArtifact]:
"""批量查询每票最新 ready Artifact,避免 N+1。"""
task_ids = [int(task.id) for task in tasks if task.id is not None]
rows = ShippingExportArtifact.query.join(ShippingTask, ShippingTask.id == ShippingExportArtifact.task_id).filter(
ShippingExportArtifact.task_id.in_(task_ids), ShippingExportArtifact.status == 'ready',
ShippingTask.export_file_path == ShippingExportArtifact.file_path,
).order_by(ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc()).all()
result: dict[int, ShippingExportArtifact] = {}
for item in rows:
result.setdefault(int(item.task_id), item)
return result
def _archive_name(filename: str, task_no: str, used: set[str]) -> str:
"""保留原下载名;冲突时追加 task_no,仍冲突再追加序号。"""
safe = Path(filename or f'{task_no}.xlsx').name
candidate = safe
if candidate.lower() in used:
stem = Path(safe).stem
suffix = Path(safe).suffix or '.xlsx'
candidate = f'{stem}_{task_no}{suffix}'
sequence = 2
base = candidate
while candidate.lower() in used:
candidate = f'{Path(base).stem}_{sequence}{Path(base).suffix}'
sequence += 1
used.add(candidate.lower())
return candidate
def build_export_archive(
*, user_id: int, batch_no: str | None = None, task_nos: list[str] | None = None,
) -> tuple[BinaryIO, str, dict]:
"""
生成 ZIP 和 manifest;缺失/损坏票据保留在 manifest,但不阻止其余有效文件下载。
Returns:
(定位到开头的 ZIP 字节流, 下载文件名, manifest 字典)。
"""
tasks, archive_key = _select_tasks(user_id=user_id, batch_no=batch_no, task_nos=task_nos)
artifacts = _latest_ready_artifacts(tasks)
# 小包驻留内存,超过 16 MiB 自动落到系统临时目录,避免批次下载挤占 worker 内存。
stream = SpooledTemporaryFile(max_size=16 * 1024 * 1024, mode='w+b')
used_names: set[str] = {'manifest.json'}
entries: list[dict] = []
included = 0
with ZipFile(stream, mode='w', compression=ZIP_DEFLATED) as archive:
for task in tasks:
artifact = artifacts.get(int(task.id)) if task.id is not None else None
entry = {'task_no': task.task_no, 'status': 'missing_artifact', 'artifact_no': None, 'file_name': None}
if artifact is not None:
entry['artifact_no'] = artifact.artifact_no
path = Path(artifact.file_path)
if not path.is_file():
entry['status'] = 'missing_file'
else:
content = path.read_bytes()
if hashlib.sha256(content).hexdigest() != artifact.file_checksum:
entry['status'] = 'checksum_mismatch'
else:
name = _archive_name(artifact.file_name, task.task_no, used_names)
archive.writestr(name, content)
entry.update({'status': 'included', 'file_name': name, 'file_checksum': artifact.file_checksum})
included += 1
entries.append(entry)
manifest = {
'archive_version': 1, 'selection': {'batch_no': batch_no, 'task_nos': task_nos or []},
'generated_at': datetime.utcnow().isoformat(), 'total_tasks': len(tasks),
'included_count': included, 'excluded_count': len(tasks) - included, 'entries': entries,
}
archive.writestr('manifest.json', json.dumps(manifest, ensure_ascii=False, indent=2).encode('utf-8'))
stream.seek(0)
filename = f'shipping_exports_{archive_key}_{datetime.utcnow():%Y%m%d%H%M%S}.zip'
return stream, filename, manifest
@@ -105,9 +105,7 @@ def format_field_alignment_summary(
payload: dict[str, Any] | None = None,
) -> str:
"""
生成字段对齐确认的固定 Markdown 摘要(apply_inventory_mapping / align_review 用)。
Agent 须原文展示 message 给用户后再等待 confirm_inventory_mapping。
生成库存与订单字段对照的固定 Markdown 摘要,仅用于解析审计和结果展示。
"""
resolved = resolve_lang(payload) if payload is not None else resolve_lang({"lang": lang} if lang else None)
inv_count = inventory_row_count
@@ -9,6 +9,8 @@ services/shipping_notice/fulfillment_workflow.py
from __future__ import annotations
from pathlib import Path
from datetime import datetime
from typing import Any
@@ -17,11 +19,7 @@ from flask import current_app
from app import db
from app.models import ShippingTask, ShippingTaskEvent
from app.services.shipping_notice.constants import CP_UPLOADED, PH_UPLOAD_RPA_PENDING
from app.services.shipping_notice.export import generate_shipment_excel
from app.services.shipping_notice.inventory_mapping_workflow import (
awaiting_inventory_mapping_confirm,
inventory_mapping_checkpoint_response,
)
from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values
from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task
from app.services.shipping_notice.inventory_workflow import (
ensure_inventory,
@@ -34,7 +32,6 @@ from app.services.shipping_notice.query_service import (
task_export_error_message,
)
from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.reservation_id import is_valid_reservation_id
from app.services.shipping_notice.reservation_gate import reservation_gate_issues
from app.services.shipping_notice.task_field_gate import field_conflict_gate_response
from app.services.shipping_notice.task_line_store import read_task_order_lines
@@ -232,6 +229,27 @@ def try_auto_chain_after_match(
return result
def _order_extraction_gate_response(
task: ShippingTask,
*,
forbidden_next_tools: list[str],
) -> dict[str, Any] | None:
"""要求任务绑定已接受的动态订单解析版本,禁止旧固定字段任务进入履约副作用。"""
try:
order_field_id_values(task)
except ValueError as exc:
return tool_response(
status="failed",
task=task,
message=str(exc),
data=serialize_task_for_tool(task),
forbidden_next_tools=forbidden_next_tools,
next_required_action="请重新提交订单解析并确认动态订单字段后继续。",
stop_agent_turn=True,
)
return None
def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
"""
将发货通知订单行与库存快照进行 Reservation ID 匹配,并按结果推进任务状态。
@@ -272,12 +290,14 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if reservation_gate is not None:
return reservation_gate
# [STEP 1] 先确认字段对齐与库存快照是否已经就绪。
# 若还停在映射确认阶段或完全没有库存,就不能直接进入匹配计算。
if awaiting_inventory_mapping_confirm(task):
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
return inventory_mapping_checkpoint_response(task, lang=lang or None)
extraction_gate = _order_extraction_gate_response(
task,
forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"],
)
if extraction_gate is not None:
return extraction_gate
# [STEP 1] 正式库存已在载入阶段按 published Profile 校验;这里只确认库存快照是否就绪。
inventory_lines = parse_inventory_lines(payload)
if inventory_lines:
task.inventory_lines_json = inventory_lines
@@ -290,6 +310,12 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
inv_payload["lang"] = lang
return ensure_inventory(inv_payload)
notice_lines = read_task_order_lines(task)
_order_header_values, order_field_lines = order_field_id_values(task)
for index, order_line in enumerate(order_field_lines):
legacy_line = notice_lines[index] if index < len(notice_lines) else {}
order_line['__required_qty'] = legacy_line.get('qty')
order_line['__display_part_number'] = legacy_line.get('part_number')
order_line['__display_reservation_id'] = legacy_line.get('reservation_id')
total_notice_lines = len(notice_lines)
set_task_step_progress(
task,
@@ -304,13 +330,6 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
)
db.session.flush()
# [STEP 2] 订单侧 Reservation 已在任何库存副作用前校验;此处只统计库存侧缺失。
inv_missing_count = sum(
1
for row in (inventory_lines or [])
if not is_valid_reservation_id((row or {}).get("reservation_id"))
)
if not is_inventory_source_stable(task):
return tool_response(
status="needs_human",
@@ -339,13 +358,29 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if processed == total or processed % 50 == 0:
db.session.flush()
from app.models import ShippingInventoryField, ShippingInventorySource
source = ShippingInventorySource.query.filter_by(source_code=task.inventory_source_code).first()
definition = source.parsing_profile.definition_json if source and source.parsing_profile else {}
match_keys = definition.get('match_keys') if isinstance(definition, dict) else []
mapped_field_ids = [
int(field_id) for field_id in (definition.get('field_mapping') or {})
if str(field_id).isdigit()
] if isinstance(definition, dict) else []
quantity_fields = ShippingInventoryField.query.filter(
ShippingInventoryField.id.in_(mapped_field_ids),
ShippingInventoryField.status == 'active',
ShippingInventoryField.usage_type == 'inventory_quantity',
).all() if mapped_field_ids else []
if len(quantity_fields) != 1:
raise ValueError('库存解析方案必须且只能配置一个库存数量字段')
match_status, line_results, shortage = match_notice_lines(
notice_lines,
order_field_lines,
inventory_lines or [],
match_keys=match_keys,
quantity_field_id=str(quantity_fields[0].id),
progress_callback=_on_match_progress,
)
if inv_missing_count and isinstance(shortage, dict):
shortage.pop("warnings", None)
task.match_status = match_status
task.line_results_json = line_results
task.shortage_json = shortage
@@ -396,6 +431,18 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
)
def _commit_generated_export(path: str) -> None:
"""提交任务与 Artifact;提交失败时回滚并删除本次生成文件。"""
try:
db.session.commit()
except Exception:
db.session.rollback()
generated_path = Path(path)
if generated_path.is_file():
generated_path.unlink()
raise
def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
"""
基于已匹配任务生成货代发货 Excel 并推进至 waiting_upload。
@@ -430,6 +477,13 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
if reservation_gate is not None:
return reservation_gate
extraction_gate = _order_extraction_gate_response(
task,
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
)
if extraction_gate is not None:
return extraction_gate
if not is_inventory_source_stable(task):
return tool_response(
status="failed",
@@ -475,7 +529,16 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
# [STEP 3] 生成文件并把任务推进到等待上传阶段。
# 导出文件路径会成为后续 RPA 上传或人工下载的唯一输入。
path, filename = generate_shipment_excel(task)
try:
path, filename, artifact = generate_shipment_excel(task)
except ValueError as exc:
return tool_response(
status="failed",
task=task,
message=str(exc),
data=serialize_task_for_tool(task),
forbidden_next_tools=["upload_to_freight"],
)
task.export_file_path = path
task.export_file_name = filename
apply_task_transition(task, TaskTransition.WAITING_UPLOAD)
@@ -488,8 +551,8 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
progress_percent=100,
detail=filename,
)
log_task_event(task, "export_generated", {"file_name": filename})
db.session.commit()
log_task_event(task, "export_generated", {"file_name": filename, "artifact_no": artifact.artifact_no})
_commit_generated_export(path)
return tool_response(
status="ok",
task_id=task.task_no,
@@ -823,4 +886,3 @@ def run_auto_progress_fulfillment_steps(
return up
return None
+6 -51
View File
@@ -84,14 +84,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.decision.parse_confirmed_wait": "等待后台继续处理或稍后刷新任务状态",
"workflow.decision.parse_confirmed_manual_next": "ensure_inventory 或 parse_inventory",
"workflow.decision.matched_confirmed": "已确认,可继续生成 Excel 并上传货代系统。",
"workflow.decision.confirm_invalid_state": "当前状态无法使用 confirm。请先完成库存匹配,或使用 confirm_inventory_mapping / reparse。",
"workflow.decision.mapping_not_needed": "当前无需确认库存字段对齐。",
"workflow.decision.mapping_missing_reservation_warning": "库存表必须包含 Reservation ID 列标题(该列允许为空值)。请改用「更正映射」重新选择 Reservation ID 对应的列,或重新上传包含该列的库存 Excel。",
"workflow.decision.mapping_correction_invalid_state": "当前不在库存字段对齐确认步骤,无法更正映射。",
"workflow.decision.read_inventory_preview_failed": "读取库存表头失败: {error}",
"workflow.decision.mapping_preview_note": "无已上传 Excel;请粘贴库存小表或重新上传后 apply_inventory_mapping / parse_inventory。",
"workflow.decision.mapping_correction_needed": "已回到列映射步骤。请根据 schema_preview 提供新的 map_json,再调用 apply_inventory_mapping。",
"workflow.decision.mapping_correction_next": "apply_inventory_mapping(map_json=...)",
"workflow.decision.confirm_invalid_state": "当前状态无法使用确认。请先完成库存匹配,或选择重新解析订单。",
"workflow.decision.inventory_cleared": "已清除库存快照。请重新上传或粘贴库存,后续继续在当前任务中处理。",
"workflow.decision.unknown": "未知 decision: {decision}",
"workflow.inventory.task_not_found": "未找到任务编号",
@@ -99,23 +92,15 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.inventory.text_too_large": "库存文本过大({chars} 字符,上限 {max_chars})。请勿将 Excel 全文传入 LLM;请用 HTTP 节点调用 POST /tools/upload_inventory_file 上传,再 parse_inventory(use_uploaded_file=true)。",
"workflow.inventory.upload_then_parse": "upload_inventory_file (multipart) then parse_inventory(use_uploaded_file=true)",
"workflow.inventory.parse_failed": "未能解析库存明细。大 Excel 请 upload_inventory_file;小表可粘贴;无库存可走 RPA。",
"workflow.inventory.preview_read_failed": "读取库存表头失败: {error}",
"workflow.inventory.preview_ready": "已读取库存表头与样例行。请根据 schema_preview 推断列映射,调用 apply_inventory_mapping(map_json=...)。",
"workflow.inventory.preview_next": "根据 data.schema_preview.headers 与 sample_rows 推断 JSON:{\"part_number\":\"<Supplier Sku列>\",\"aws_part_number\":\"<AWS Sku列,可选>\",\"reservation_id\":\"<列名>\",\"available_qty\":\"<列名>\"},再调用 apply_inventory_mapping",
"workflow.inventory.uploaded_file_missing_short": "未找到已上传的库存文件。请先 upload_inventory_file。",
"workflow.inventory.mapping_invalid": "map_json 无效或不完整。需要提供 {\"part_number\":\"Supplier Sku列\",\"reservation_id\":\"列名\",\"available_qty\":\"列名\"};aws_part_number 可选。",
"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 / .csv 库存文件",
"workflow.inventory.file_type_unsupported": "仅支持 .xls / .xlsx / .csv 库存文件",
"workflow.inventory.uploading": "正在上传并解析库存文件",
"workflow.inventory.uploading_detail": "正在处理库存文件 {filename}",
"workflow.inventory.save_failed": "保存库存文件失败: {error}",
"workflow.inventory.completed_task_locked": "该任务已完成,不能再重新上传库存。请切换到仍待处理的任务后再上传库存文件。",
"workflow.inventory.uploaded": "库存文件已上传。",
"workflow.inventory.uploaded_suggested_complete": " suggested_mapping 已完整,画布可直通 apply_inventory_mapping(无需 LLM)。",
"workflow.inventory.uploaded_need_llm": " 请由画布 LLM 推断列映射后 apply_inventory_mapping。",
"workflow.inventory.apply_mapping_next": "apply_inventory_mapping(map_json=...)",
"workflow.inventory.ready_for_match": "已有库存快照且字段对齐已确认,可调用 match_inventory。",
"workflow.inventory.unavailable": "暂无可用库存数据。请重新获取库存,或手动上传货代库存 Excel。",
"workflow.fulfillment.task_not_found": "未找到任务编号",
@@ -222,14 +207,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.decision.parse_confirmed_wait": "Wait for backend processing or refresh the task status later.",
"workflow.decision.parse_confirmed_manual_next": "ensure_inventory or parse_inventory",
"workflow.decision.matched_confirmed": "Confirmed. You may continue to generate the Excel and upload to the freight system.",
"workflow.decision.confirm_invalid_state": "Confirm cannot be used in the current state. Please complete inventory matching first, or use confirm_inventory_mapping / reparse.",
"workflow.decision.mapping_not_needed": "Inventory field alignment confirmation is not needed right now.",
"workflow.decision.mapping_missing_reservation_warning": "The inventory sheet must contain a Reservation ID column header (the values in that column may be empty). Please use Fix Mapping to choose the Reservation ID column again, or re-upload an inventory Excel that contains that column.",
"workflow.decision.mapping_correction_invalid_state": "The task is not currently in the inventory field alignment confirmation step, so the mapping cannot be corrected.",
"workflow.decision.read_inventory_preview_failed": "Failed to read inventory headers: {error}",
"workflow.decision.mapping_preview_note": "No uploaded Excel was found. Please paste a small inventory table or re-upload, then call apply_inventory_mapping / parse_inventory.",
"workflow.decision.mapping_correction_needed": "The task has returned to the mapping step. Please provide a new map_json based on schema_preview, then call apply_inventory_mapping.",
"workflow.decision.mapping_correction_next": "apply_inventory_mapping(map_json=...)",
"workflow.decision.confirm_invalid_state": "Confirm cannot be used in the current state. Complete inventory matching first, or reparse the order.",
"workflow.decision.inventory_cleared": "The inventory snapshot has been cleared. Please re-upload or paste inventory data, then continue in the current task.",
"workflow.decision.unknown": "Unknown decision: {decision}",
"workflow.inventory.task_not_found": "Task ID not found.",
@@ -237,23 +215,15 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.inventory.text_too_large": "The inventory text is too large ({chars} characters, limit {max_chars}). Do not send the full Excel content to the LLM. Please call POST /tools/upload_inventory_file first, then parse_inventory(use_uploaded_file=true).",
"workflow.inventory.upload_then_parse": "upload_inventory_file (multipart) then parse_inventory(use_uploaded_file=true)",
"workflow.inventory.parse_failed": "Inventory lines could not be parsed. For large Excel files, use upload_inventory_file; for small tables, paste the content; if inventory is unavailable, use RPA.",
"workflow.inventory.preview_read_failed": "Failed to read inventory headers: {error}",
"workflow.inventory.preview_ready": "Inventory headers and sample rows have been loaded. Please infer the column mapping from schema_preview and call apply_inventory_mapping(map_json=...).",
"workflow.inventory.preview_next": "Infer JSON from data.schema_preview.headers and sample_rows: {\"part_number\":\"<Supplier Sku column>\",\"aws_part_number\":\"<AWS Sku column, optional>\",\"reservation_id\":\"<column>\",\"available_qty\":\"<column>\"}, then call apply_inventory_mapping",
"workflow.inventory.uploaded_file_missing_short": "No uploaded inventory file was found. Please call upload_inventory_file first.",
"workflow.inventory.mapping_invalid": "map_json is invalid or incomplete. Provide part_number (Supplier Sku), reservation_id, and available_qty mappings; aws_part_number is optional.",
"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 / .csv inventory files are supported.",
"workflow.inventory.file_type_unsupported": "Only .xls / .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}",
"workflow.inventory.completed_task_locked": "This task is already completed, so inventory cannot be uploaded again. Please switch to a task that still needs processing.",
"workflow.inventory.uploaded": "The inventory file has been uploaded.",
"workflow.inventory.uploaded_suggested_complete": " suggested_mapping is complete, so the canvas can call apply_inventory_mapping directly without using the LLM.",
"workflow.inventory.uploaded_need_llm": " Please let the canvas LLM infer the column mapping and then call apply_inventory_mapping.",
"workflow.inventory.apply_mapping_next": "apply_inventory_mapping(map_json=...)",
"workflow.inventory.ready_for_match": "An inventory snapshot already exists and the field alignment has been confirmed. You may call match_inventory.",
"workflow.inventory.unavailable": "No usable inventory data is available yet. Please retry the RPA export or upload the freight inventory Excel manually.",
"workflow.fulfillment.task_not_found": "Task ID not found.",
@@ -360,14 +330,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.decision.parse_confirmed_wait": "รอให้ระบบหลังบ้านดำเนินการต่อ หรือกลับมาตรวจสอบสถานะงานภายหลัง",
"workflow.decision.parse_confirmed_manual_next": "ensure_inventory หรือ parse_inventory",
"workflow.decision.matched_confirmed": "ยืนยันแล้ว สามารถดำเนินการสร้างไฟล์ Excel และอัปโหลดไปยังระบบขนส่งต่อได้",
"workflow.decision.confirm_invalid_state": "ไม่สามารถใช้ confirm ในสถานะปัจจุบันได้ โปรดทำ inventory matching ให้เสร็จก่อน หรือใช้ confirm_inventory_mapping / reparse",
"workflow.decision.mapping_not_needed": "ขณะนี้ยังไม่ต้องยืนยันการจับคู่คอลัมน์สต็อก",
"workflow.decision.mapping_missing_reservation_warning": "ไฟล์สต็อกต้องมีหัวคอลัมน์ Reservation ID (ค่าภายในคอลัมน์นี้สามารถเว้นว่างได้) โปรดใช้ Fix Mapping เพื่อเลือกคอลัมน์ Reservation ID ใหม่ หรืออัปโหลดไฟล์ Excel สต็อกที่มีคอลัมน์นี้อีกครั้ง",
"workflow.decision.mapping_correction_invalid_state": "ขณะนี้งานไม่ได้อยู่ในขั้นตอนยืนยันการจับคู่คอลัมน์สต็อก จึงไม่สามารถแก้ไข mapping ได้",
"workflow.decision.read_inventory_preview_failed": "อ่านหัวตารางสต็อกไม่สำเร็จ: {error}",
"workflow.decision.mapping_preview_note": "ไม่พบไฟล์ Excel ที่อัปโหลดไว้ โปรดวางตารางสต็อกขนาดเล็กหรืออัปโหลดใหม่ แล้วจึงเรียก apply_inventory_mapping / parse_inventory",
"workflow.decision.mapping_correction_needed": "งานได้ย้อนกลับมาที่ขั้นตอนจับคู่คอลัมน์แล้ว โปรดส่ง map_json ใหม่ตาม schema_preview แล้วเรียก apply_inventory_mapping",
"workflow.decision.mapping_correction_next": "apply_inventory_mapping(map_json=...)",
"workflow.decision.confirm_invalid_state": "ไม่สามารถยืนยันในสถานะปัจจุบันได้ โปรดจับคู่สต็อกให้เสร็จก่อน หรือแยกวิเคราะห์คำสั่งซื้อใหม่",
"workflow.decision.inventory_cleared": "ล้าง snapshot สต็อกแล้ว โปรดอัปโหลดใหม่หรือวางข้อมูลสต็อก แล้วดำเนินการต่อในงานปัจจุบัน",
"workflow.decision.unknown": "ไม่รู้จัก decision: {decision}",
"workflow.inventory.task_not_found": "ไม่พบรหัสงาน",
@@ -375,23 +338,15 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.inventory.text_too_large": "ข้อความสต็อกมีขนาดใหญ่เกินไป ({chars} ตัวอักษร, จำกัด {max_chars}) โปรดอย่าส่งเนื้อหา Excel ทั้งหมดเข้า LLM ให้เรียก POST /tools/upload_inventory_file ก่อน แล้วจึงใช้ parse_inventory(use_uploaded_file=true)",
"workflow.inventory.upload_then_parse": "upload_inventory_file (multipart) then parse_inventory(use_uploaded_file=true)",
"workflow.inventory.parse_failed": "ไม่สามารถแยกรายการสต็อกได้ สำหรับไฟล์ Excel ขนาดใหญ่ให้ใช้ upload_inventory_file; สำหรับตารางเล็กสามารถวางข้อความได้; หากไม่มีสต็อกให้ใช้ RPA",
"workflow.inventory.preview_read_failed": "อ่านหัวตารางสต็อกไม่สำเร็จ: {error}",
"workflow.inventory.preview_ready": "อ่านหัวตารางและแถวตัวอย่างของสต็อกแล้ว โปรดอนุมานการจับคู่คอลัมน์จาก schema_preview แล้วเรียก apply_inventory_mapping(map_json=...)",
"workflow.inventory.preview_next": "อนุมาน JSON จาก data.schema_preview.headers และ sample_rows โดยใช้ part_number จาก Supplier Sku, aws_part_number จาก AWS Sku (ไม่บังคับ), reservation_id และ available_qty แล้วเรียก apply_inventory_mapping",
"workflow.inventory.uploaded_file_missing_short": "ไม่พบไฟล์สต็อกที่อัปโหลดไว้ โปรดเรียก upload_inventory_file ก่อน",
"workflow.inventory.mapping_invalid": "map_json ไม่ถูกต้องหรือไม่ครบ ต้องระบุ part_number (Supplier Sku), reservation_id และ available_qty; aws_part_number เป็นตัวเลือก",
"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 / .csv",
"workflow.inventory.file_type_unsupported": "รองรับเฉพาะไฟล์สต็อก .xls / .xlsx / .csv",
"workflow.inventory.uploading": "กำลังอัปโหลดและ解析ไฟล์สต็อก",
"workflow.inventory.uploading_detail": "กำลังประมวลผลไฟล์สต็อก {filename}",
"workflow.inventory.save_failed": "บันทึกไฟล์สต็อกไม่สำเร็จ: {error}",
"workflow.inventory.completed_task_locked": "งานนี้เสร็จสิ้นแล้ว จึงไม่สามารถอัปโหลดสต็อกซ้ำได้ โปรดสลับไปยังงานที่ยังต้องดำเนินการ",
"workflow.inventory.uploaded": "อัปโหลดไฟล์สต็อกแล้ว",
"workflow.inventory.uploaded_suggested_complete": " suggested_mapping ครบแล้ว จึงสามารถเรียก apply_inventory_mapping ได้ตรงจาก canvas โดยไม่ต้องผ่าน LLM",
"workflow.inventory.uploaded_need_llm": " โปรดให้ LLM บน canvas อนุมานการจับคู่คอลัมน์ แล้วจึงเรียก apply_inventory_mapping",
"workflow.inventory.apply_mapping_next": "apply_inventory_mapping(map_json=...)",
"workflow.inventory.ready_for_match": "มี inventory snapshot อยู่แล้วและยืนยันการจับคู่คอลัมน์แล้ว สามารถเรียก match_inventory ได้",
"workflow.inventory.unavailable": "ยังไม่มีข้อมูลสต็อกที่ใช้งานได้ โปรดลองส่งออกผ่าน RPA ใหม่ หรืออัปโหลดไฟล์ Excel สต็อกของผู้ให้บริการขนส่งด้วยตนเอง",
"workflow.fulfillment.task_not_found": "ไม่พบรหัสงาน",
@@ -0,0 +1,167 @@
"""
services/shipping_notice/inventory_configuration_test.py
用途:编排库存站点测试导出、RPA 回调文件分析和管理员确认解析方案。
依赖:库存站点/RPA trigger、库存结构分析、库存解析方案模型。
逻辑:管理端仅对停用站点发起测试;RPA 文件只写测试运行和结构分析,不创建生产快照、不关联订单任务。
"""
from __future__ import annotations
import shutil
from datetime import datetime
from pathlib import Path
from typing import Any
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.extensions import db
from app.models import (
ShippingInventoryConfigurationTestRun,
ShippingInventoryParsingProfile,
ShippingInventorySource,
)
def _payload(run: ShippingInventoryConfigurationTestRun) -> dict[str, Any]:
"""投影测试运行状态,避免暴露 RPA 文件的服务器路径。"""
return {
'id': run.id, 'run_no': run.run_no, 'inventory_source_id': run.inventory_source_id,
'source_config_version': run.source_config_version, 'status': run.status, 'stage': run.stage,
'analysis_id': run.analysis_id, 'result': run.result_json or {}, 'error_message': run.error_message,
'created_at': run.created_at.isoformat() if run.created_at else None,
'completed_at': run.completed_at.isoformat() if run.completed_at else None,
}
def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""为停用库存站点写入专用测试 trigger;重复点击复用等待中的运行。"""
source = db.session.get(ShippingInventorySource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
if source.enabled:
raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_INVALID')
if source.rpa_profile is None or not source.rpa_profile.enabled:
raise ValidationError('Enabled RPA Profile is required', code='SHIPPING.RPA_PROFILE_DISABLED')
active = ShippingInventoryConfigurationTestRun.query.filter(
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
if active:
return _payload(active)
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
run_no = f'CONFIG-{source.source_code}-{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}'
run = ShippingInventoryConfigurationTestRun(
run_no=run_no, inventory_source_id=source.id, source_config_version=source.config_version,
status='awaiting_rpa', stage='waiting_worker', result_json={}, created_by=actor_id,
)
db.session.add(run)
db.session.flush()
source_payload = get_database_inventory_source(source.source_code, enabled_only=False)
if source_payload is None:
raise ValidationError('Inventory Source is invalid', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
try:
trigger = write_inventory_export_batch_trigger(run_no, [source_payload], payload={
'trigger_type': 'configuration_test', 'configuration_test_run_id': run.id,
})
except Exception:
db.session.rollback()
raise
if not trigger:
db.session.rollback()
raise ConflictError('RPA Worker is not ready', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_UNAVAILABLE')
run.result_json = {'trigger_written': True}
db.session.commit()
return _payload(run)
def get_test_run(source_id: int, run_no: str) -> dict[str, Any]:
"""读取指定库存站点的测试运行,防止跨站点查看结果。"""
run = ShippingInventoryConfigurationTestRun.query.filter_by(
inventory_source_id=source_id, run_no=str(run_no or '').strip(),
).first()
if run is None:
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND')
return _payload(run)
def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
"""处理 Worker 测试回调:分析文件并生成推荐,绝不创建生产库存快照。"""
run_no = str(payload.get('run_no') or '').strip()
run = ShippingInventoryConfigurationTestRun.query.filter_by(run_no=run_no).first()
if run is None:
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND')
if run.status == 'completed':
return _payload(run)
source = db.session.get(ShippingInventorySource, run.inventory_source_id)
if source is None or source.config_version != run.source_config_version:
run.status = 'failed'; run.stage = 'failed'; run.error_message = '库存站点配置已变更,请重新测试'; run.completed_at = datetime.utcnow()
db.session.commit()
return _payload(run)
status = str(payload.get('status') or 'success').lower()
if status != 'success':
run.status = 'failed'; run.stage = 'failed'; run.error_message = str(payload.get('error_message') or '测试导出失败')[:500]; run.completed_at = datetime.utcnow()
db.session.commit()
return _payload(run)
path = Path(str(payload.get('file_path') or ''))
if not path.is_file():
run.status = 'failed'; run.stage = 'failed'; run.error_message = '测试导出文件不存在'; run.completed_at = datetime.utcnow()
db.session.commit()
return _payload(run)
from app.services.shipping_notice.inventory_structure_analysis import _analyse_path, _analysis_root, serialize_analysis
from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix
from app.models import ShippingInventoryStructureAnalysis
import hashlib
import uuid
from app.services.shipping_notice.inventory_structure_fingerprint import compatibility_fingerprint, exact_fingerprint, structure_definition
from app.services.shipping_notice.inventory_profile_matching import recommend_profiles
run.status = 'processing'; run.stage = 'analysing_structure'; db.session.flush()
suffix = resolve_inventory_upload_suffix(path.name)
raw = path.read_bytes()
target_dir = _analysis_root() / uuid.uuid4().hex
target_dir.mkdir(parents=True, exist_ok=False)
target = target_dir / f'test{suffix}'
try:
shutil.copy2(path, target)
structure, suggested, summary, warnings = _analyse_path(target, suffix)
definition = structure_definition(file_format=suffix.lstrip('.'), sheet_name=structure.get('selected_sheet_name'), header_row_index=structure.get('selected_header_row_index') or 1, headers=structure.get('selected_headers', []))
analysis = ShippingInventoryStructureAnalysis(
source_kind='configuration_test', source_file_name=path.name, storage_path=str(target), file_checksum=hashlib.sha256(raw).hexdigest(),
file_format=suffix.lstrip('.'), analysis_status='ready', structure_json=structure, suggested_mapping_json=suggested,
validation_summary_json=summary, warning_json=warnings, created_by=run.created_by,
exact_structure_fingerprint=exact_fingerprint(definition), compatibility_fingerprint=compatibility_fingerprint(definition=definition, field_mapping=suggested, match_keys=[]),
)
db.session.add(analysis); db.session.flush()
analysis.match_result_json = recommend_profiles({'structure': structure, 'suggested_mapping': suggested, 'exact_structure_fingerprint': analysis.exact_structure_fingerprint, 'compatibility_fingerprint': analysis.compatibility_fingerprint})
run.analysis_id = analysis.id; run.status = 'completed'; run.stage = 'ready_for_confirmation'; run.result_json = {'analysis': serialize_analysis(analysis)}; run.completed_at = datetime.utcnow()
db.session.commit()
except Exception:
shutil.rmtree(target_dir, ignore_errors=True)
db.session.rollback()
raise
return _payload(run)
def confirm_test_profile(source_id: int, run_no: str, profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""管理员确认测试结果使用的已发布方案,才更新停用库存站点的解析方案绑定。"""
run = ShippingInventoryConfigurationTestRun.query.filter_by(inventory_source_id=source_id, run_no=run_no).first()
if run is None or run.status != 'completed' or run.analysis_id is None:
raise ConflictError('Configuration test is not ready for confirmation', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_READY')
source = db.session.get(ShippingInventorySource, source_id)
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
if source is None or profile is None or profile.status != 'published':
raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
if source.enabled or source.config_version != run.source_config_version:
raise ConflictError('Inventory Source configuration changed', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_STALE')
from app.services.shipping_notice.inventory_structure_analysis import adopt_published_profile
adopt_published_profile(run.analysis_id, profile_id)
source.parsing_profile_id = profile.id
source.updated_by = actor_id
source.config_version += 1
run.source_config_version = source.config_version
run.result_json = {**(run.result_json or {}), 'confirmed_profile_id': profile.id, 'confirmed_profile_checksum': profile.checksum}
db.session.commit()
return {'test_run': _payload(run), 'parsing_profile_id': source.parsing_profile_id}
@@ -0,0 +1,38 @@
"""
services/shipping_notice/inventory_external_mapping.py
用途:解析库存来源与已确定 Warehouse 对应的外部系统仓库。
依赖:ShippingInventoryExternalMapping、ShippingInventorySource。
逻辑:Excel 与后续调拨 Agent 可复用本内部服务;本模块不提供 Tool API,也不决定是否调拨。
"""
from __future__ import annotations
from typing import Any
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
def resolve_external_warehouse(*, source_code: str | None, freight_warehouse_id: str | None) -> dict[str, Any] | None:
"""按精确 Warehouse 映射优先、Source 默认映射兜底的顺序解析外部系统仓库。"""
code = str(source_code or '').strip().upper()
warehouse = str(freight_warehouse_id or '').strip().upper()
if not code:
return None
source = ShippingInventorySource.query.filter_by(source_code=code, enabled=True).first()
if source is None:
return None
query = ShippingInventoryExternalMapping.query.filter_by(inventory_source_id=source.id, enabled=True)
mapping = query.filter_by(freight_warehouse_id=warehouse).first() if warehouse else None
mapping = mapping or query.filter(ShippingInventoryExternalMapping.freight_warehouse_id.is_(None)).first()
if mapping is None:
return None
return {
'external_system_code': mapping.external_system_code,
'external_organization_code': mapping.external_organization_code,
'external_site_code': mapping.external_site_code,
'external_warehouse_code': mapping.external_warehouse_code,
'external_warehouse_name': mapping.external_warehouse_name,
'freight_warehouse_id': warehouse or None,
'mapping_id': mapping.id,
}
@@ -0,0 +1,190 @@
"""
services/shipping_notice/inventory_field_catalog.py
用途:维护货代库存统一业务字段目录,供后续库存解析方案和发货模板安全引用。
依赖:ShippingInventoryField、统一业务异常和 SQLAlchemy 事务。
逻辑:目录初始为空;管理员维护字段名称与业务用途,引用保护只依据实际配置和历史使用情况。
"""
from __future__ import annotations
import re
from hashlib import sha1
from typing import Any
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.extensions import db
from app.models import ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryParsingProfile
ALLOWED_VALUE_TYPES = {'text', 'integer', 'decimal', 'date'}
ALLOWED_USAGE_TYPES = {'match_identity', 'inventory_quantity', 'warehouse_identity', 'general'}
def _payload(item: ShippingInventoryField) -> dict[str, Any]:
"""输出业务字段目录记录,不向管理端暴露内部字段编码。"""
return {
'id': item.id,
'display_name': item.display_name,
'description': item.description or '',
'value_type': item.value_type,
'usage_type': item.usage_type,
'status': item.status,
'sort_order': item.sort_order,
'created_at': item.created_at.isoformat() if item.created_at else None,
'updated_at': item.updated_at.isoformat() if item.updated_at else None,
}
def list_fields(*, include_retired: bool = False) -> list[dict[str, Any]]:
"""按业务展示顺序返回库存字段目录;当前配置默认不显示已归档字段。"""
query = ShippingInventoryField.query
if not include_retired:
query = query.filter_by(status='active')
return [_payload(item) for item in query.order_by(
ShippingInventoryField.sort_order, ShippingInventoryField.id,
).all()]
def _normalized_payload(data: dict[str, Any], *, existing: ShippingInventoryField | None = None) -> dict[str, Any]:
"""校验管理员输入,稳定编码只在创建时由显示名称生成并在后台保存。"""
display_name = str(data.get('display_name') or '').strip()
description = str(data.get('description') or '').strip() or None
value_type = str(data.get('value_type') or 'text').strip().lower()
usage_type = str(data.get('usage_type') or 'general').strip().lower()
try:
sort_order = int(data.get('sort_order') if data.get('sort_order') is not None else 100)
except (TypeError, ValueError) as exc:
raise ValidationError('Inventory field sort_order is invalid', code='SHIPPING.INVENTORY_FIELD_INVALID') from exc
if not display_name or len(display_name) > 128 or value_type not in ALLOWED_VALUE_TYPES or usage_type not in ALLOWED_USAGE_TYPES:
raise ValidationError('Inventory field data is invalid', code='SHIPPING.INVENTORY_FIELD_INVALID')
if sort_order < 0 or sort_order > 9999:
raise ValidationError('Inventory field sort_order is invalid', code='SHIPPING.INVENTORY_FIELD_INVALID')
return {
'display_name': display_name,
'description': description,
'value_type': value_type,
'usage_type': usage_type,
'sort_order': sort_order,
}
def _field_code(display_name: str) -> str:
"""为扩展字段生成稳定内部编码;重复时追加序号,管理员无需维护该技术值。"""
stem = re.sub(r'[^a-z0-9]+', '_', display_name.lower()).strip('_')
if not stem:
# Chinese business names have no ASCII transliteration requirement; derive a stable opaque code instead.
stem = f'custom_{sha1(display_name.encode("utf-8")).hexdigest()[:12]}'
stem = stem[:52]
code = stem
sequence = 2
while ShippingInventoryField.query.filter_by(field_code=code).first() is not None:
suffix = f'_{sequence}'
code = f'{stem[:64 - len(suffix)]}{suffix}'
sequence += 1
return code
def create_field(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""创建用户定义的库存字段;内部编码仅供审计,不参与运行判断。"""
values = _normalized_payload(data)
if ShippingInventoryField.query.filter_by(display_name=values['display_name']).first() is not None:
raise ConflictError('Inventory field display name already exists', code='SHIPPING.INVENTORY_FIELD_CONFLICT')
item = ShippingInventoryField(
field_code=_field_code(values['display_name']), status='active', created_by=actor_id, updated_by=actor_id,
**values,
)
db.session.add(item)
db.session.commit()
return _payload(item)
def update_field(field_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""更新未退役字段;存在运行配置引用时禁止改变数据格式或业务用途。"""
item = db.session.get(ShippingInventoryField, field_id)
if item is None:
raise NotFoundError('Inventory field not found', code='SHIPPING.INVENTORY_FIELD_NOT_FOUND')
if item.status != 'active':
raise ConflictError('Retired inventory field cannot be edited', code='SHIPPING.INVENTORY_FIELD_IMMUTABLE')
values = _normalized_payload(data, existing=item)
references = _runtime_references(item.id)
if references and (values['value_type'] != item.value_type or values['usage_type'] != item.usage_type):
raise ConflictError(
'Referenced inventory field type or usage cannot be changed',
code='SHIPPING.INVENTORY_FIELD_IMMUTABLE', details={'references': references},
)
duplicate = ShippingInventoryField.query.filter(
ShippingInventoryField.display_name == values['display_name'],
ShippingInventoryField.id != item.id,
).first()
if duplicate is not None:
raise ConflictError('Inventory field display name already exists', code='SHIPPING.INVENTORY_FIELD_CONFLICT')
for key, value in values.items():
setattr(item, key, value)
item.updated_by = actor_id
db.session.commit()
return _payload(item)
def delete_field(field_id: int) -> dict[str, Any]:
"""物理删除从未被配置引用的用户字段。"""
item = db.session.get(ShippingInventoryField, field_id)
if item is None:
raise NotFoundError('Inventory field not found', code='SHIPPING.INVENTORY_FIELD_NOT_FOUND')
references = _runtime_references(item.id)
if references:
raise ConflictError(
'Inventory field is referenced by runtime configuration',
code='SHIPPING.INVENTORY_FIELD_DELETE_BLOCKED', details={'references': references},
)
db.session.delete(item)
db.session.commit()
return {'action': 'deleted'}
def retire_field(field_id: int) -> dict[str, Any]:
"""退役不再用于新配置的用户字段;被当前配置引用时必须先解除引用。"""
item = db.session.get(ShippingInventoryField, field_id)
if item is None:
raise NotFoundError('Inventory field not found', code='SHIPPING.INVENTORY_FIELD_NOT_FOUND')
references = _runtime_references(item.id)
if references:
raise ConflictError(
'Inventory field is referenced by runtime configuration',
code='SHIPPING.INVENTORY_FIELD_RETIRE_BLOCKED', details={'references': references},
)
item.status = 'retired'
db.session.commit()
return _payload(item)
def _runtime_references(field_id: int) -> list[str]:
"""列出字段目录的运行配置引用;阶段三会在此处补充发货模板引用。"""
reference = str(field_id)
parsing_profiles = [
f'parsing_profile:{item.profile_code}:v{item.version}'
for item in ShippingInventoryParsingProfile.query.filter(
ShippingInventoryParsingProfile.status.in_(['draft', 'published']),
).all()
if reference in {
str(key) for key in ((item.definition_json or {}).get('field_mapping') or {}).keys()
}
or any(
str(key.get('inventory_field_id') or '') == reference
for key in ((item.definition_json or {}).get('match_keys') or [])
if isinstance(key, dict)
)
]
templates = [
f'excel_template:{item.template_code}:v{item.version}'
for item in ShippingExcelTemplate.query.filter(
ShippingExcelTemplate.status.in_(['draft', 'published']),
).all()
if any(
isinstance(mapping, dict)
and mapping.get('source_kind') == 'inventory_field'
and str(mapping.get('source_key') or '') == reference
for mapping in ((item.definition_json or {}).get('mappings') or [])
)
]
return parsing_profiles + templates
@@ -2,7 +2,7 @@
services/shipping_notice/inventory_file_identity.py
用途:校验库存 Excel/CSV 文件内容与任务/快照预期库位是否一致。
依赖:openpyxl、csv、app.core.errors.AppError。
依赖:openpyxl、xlrd、csv、app.core.errors.AppError。
逻辑:RPA 回调、人工上传、快照入库前统一调用;流式扫描 Warehouse 列,避免大文件全量加载。
"""
@@ -107,6 +107,54 @@ def _iter_xlsx_warehouse_values(path: Path, *, header_row_idx: int, col_idx: int
wb.close()
def _load_xls_header_rows(path: Path, *, max_rows: int = _HEADER_SCAN_ROWS) -> list[tuple[Any, ...]]:
"""仅读取旧 xls 前若干行供 Warehouse 表头定位。"""
import xlrd
try:
book = xlrd.open_workbook(filename=str(path), on_demand=True)
except Exception:
return []
try:
sheet = book.sheet_by_index(0)
return [
tuple(_xls_cell_value(book, sheet.cell(row_index, column_index)) for column_index in range(sheet.ncols))
for row_index in range(min(max_rows, sheet.nrows))
]
finally:
book.release_resources()
def _iter_xls_warehouse_values(path: Path, *, header_row_idx: int, col_idx: int) -> Iterator[str]:
"""流式遍历旧 xls Warehouse 列非空值。"""
import xlrd
book = xlrd.open_workbook(filename=str(path), on_demand=True)
try:
sheet = book.sheet_by_index(0)
for row_index in range(header_row_idx + 1, sheet.nrows):
if col_idx >= sheet.ncols:
continue
value = str(_xls_cell_value(book, sheet.cell(row_index, col_idx)) or '').strip().upper()
if value:
yield value
finally:
book.release_resources()
def _xls_cell_value(book: Any, cell: Any) -> Any:
"""将 xlrd 旧 Excel 单元格转换为与 xlsx 读取一致的值。"""
import xlrd
if cell.ctype == xlrd.XL_CELL_EMPTY:
return None
if cell.ctype == xlrd.XL_CELL_DATE:
return xlrd.xldate_as_datetime(cell.value, book.datemode)
if cell.ctype == xlrd.XL_CELL_NUMBER and float(cell.value).is_integer():
return int(cell.value)
return cell.value
def _detect_csv_dialect(sample: str) -> csv.Dialect:
"""探测 CSV 分隔符(逗号/分号/Tab 等),失败时回退 excel 方言。"""
try:
@@ -219,7 +267,13 @@ def extract_warehouse_ids_from_inventory_excel(path: Path) -> set[str]:
_iter_xlsx_warehouse_values(path, header_row_idx=header_row_idx, col_idx=col_idx)
)
if suffix == ".xls":
return set()
header_rows = _load_xls_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_xls_warehouse_values(path, header_row_idx=header_row_idx, col_idx=col_idx)
)
return set()
@@ -254,10 +308,10 @@ def assert_inventory_excel_warehouse_identity(
)
suffix = path.suffix.lower()
if suffix not in {".xlsx", ".csv"}:
if suffix not in {".xls", ".xlsx", ".csv"}:
raise AppError(
code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
message="库存源身份校验仅支持 .xlsx / .csv,请转换后重新上传",
message="库存源身份校验仅支持 .xls / .xlsx / .csv",
http_status=409,
details={"operation": operation, "file_suffix": suffix},
)
@@ -28,7 +28,7 @@ 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.inventory_source_repository import inventory_sources_runtime_version
from app.services.shipping_notice.query_service import list_sorted_batch_tasks
_TERMINAL_PROCESS_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
@@ -50,16 +50,17 @@ def generate_inventory_file_no() -> str:
return f"SIF-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
_ALLOWED_INVENTORY_UPLOAD_SUFFIXES = frozenset({".xlsx", ".csv"})
_ALLOWED_INVENTORY_UPLOAD_SUFFIXES = frozenset({".xls", ".xlsx", ".csv"})
def resolve_inventory_upload_suffix(filename: str) -> str:
"""
解析人工上传库存文件的合法落盘后缀。
核心逻辑:仅允许 .xlsx / .csv;.xls 明确拒绝,避免按 xlsx 误读导致身份校验失败。
核心逻辑:允许 .xls / .xlsx / .csv;旧 Excel 由库存解析器使用 xlrd 读取,
不将 .xls 伪装为 .xlsx 处理。
Raises:
AppError: 后缀缺失、不支持或为 .xls。
AppError: 后缀缺失或不支持。
"""
name = str(filename or "").strip().lower()
if not name or "." not in name:
@@ -73,14 +74,10 @@ def resolve_inventory_upload_suffix(filename: str) -> str:
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,
)
return ".xls"
raise AppError(
code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
message="库存上传仅支持 .xlsx / .csv",
message="库存上传仅支持 .xls / .xlsx / .csv",
http_status=409,
)
@@ -161,7 +158,6 @@ def _same_stable_inventory_identity(lhs: ShippingTask, rhs: ShippingTask) -> boo
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"]
)
@@ -171,7 +167,8 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship
保存库存 Excel 并创建批次级库存快照。
【AI 触发时机】:用户为一批发货需求上传库存快照时调用;有 batch 时默认 link 本批全部票。
核心逻辑:快照须携带任务正式库存源身份;批次 link 仅覆盖与上传票库存源一致的可重链任务。
核心逻辑:文件必须通过库存站点 published 解析方案的结构门禁并完成确定性解析;
快照须携带任务正式库存源身份,批次 link 仅覆盖与上传票库存源一致的可重链任务。
"""
if not is_inventory_source_stable(task):
raise AppError(
@@ -182,7 +179,6 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship
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
@@ -192,17 +188,44 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship
path.parent.mkdir(parents=True, exist_ok=True)
try:
upload.save(str(path))
from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure
structure_check = validate_production_inventory_structure(source_code=source_code, path=path)
inventory_lines, column_meta = parse_inventory_excel_with_meta(
path,
field_mapping=structure_check['field_mapping'],
mapping_source='parsing_profile',
header_row_index=structure_check['header_row_index'],
sheet_name=structure_check['sheet_name'],
)
column_meta.update({
'sheet_name': structure_check['sheet_name'],
'header_row_index': structure_check['header_row_index'],
'structure_validation': {
'level': structure_check['level'],
'difference': structure_check['difference'],
'warnings': structure_check['warnings'],
},
})
if not inventory_lines:
raise AppError(
code='SHIPPING.INVENTORY_FILE_EMPTY',
message='库存文件没有可用于匹配的有效库存数据',
http_status=409,
)
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",
)
if str(warehouse_id or '').strip():
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)
preview['structure_validation'] = column_meta['structure_validation']
except AppError:
if path.is_file():
try:
@@ -230,12 +253,15 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship
storage_path=str(path),
schema_preview_json=preview,
share_mode="task_only",
line_count=0,
line_count=len(inventory_lines),
inventory_lines_json=inventory_lines,
field_mapping_json=dict(structure_check['field_mapping']),
mapping_source='parsing_profile',
mapping_confirmed=True,
source_code=source_code,
source_type=str(task.inventory_connector_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(),
source_config_version=task.inventory_source_config_version or inventory_sources_runtime_version(),
identity_status="pending",
snapshot_status="ready",
exported_at=datetime.utcnow(),
@@ -387,31 +413,35 @@ def read_linked_inventory_schema_preview(task: ShippingTask) -> dict[str, Any]:
return preview
def parse_linked_inventory_file(
task: ShippingTask,
*,
field_mapping: dict[str, str] | None = None,
mapping_source: str = "rules",
header_row_index: int | None = None,
llm_match_rule: str | None = None,
llm_match_key: list[str] | None = None,
) -> tuple[list[dict[str, Any]], dict[str, Any], Path, ShippingInventoryFile]:
"""解析任务 active 库存快照 Excel,并返回解析行、列元数据、文件路径和快照对象。"""
inv_file = active_inventory_file_for_task(task)
if not inv_file:
raise FileNotFoundError(f"未找到任务 {task.task_no} 的库存快照")
def parse_inventory_snapshot_file(inv_file: ShippingInventoryFile) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""以快照所属库存站点的已发布解析方案重读文件,禁止正式快照猜列。
仅供快照复用、动态仓识别和路由证据恢复调用。不存在已发布方案时直接失败,
促使管理员修复库存站点配置而不是让运行期静默采用旧规则或 LLM 映射。
"""
path = Path(inv_file.storage_path)
if not path.is_file():
raise FileNotFoundError(f"未找到库存快照文件 {inv_file.inventory_file_no}")
lines, column_meta = parse_inventory_excel_with_meta(
from app.models import ShippingInventorySource
from app.services.shipping_notice.inventory_parsing_profile import require_source_profile
from app.core.errors import ValidationError
source = ShippingInventorySource.query.filter_by(source_code=inv_file.source_code).first()
profile = require_source_profile(source)
actual_format = path.suffix.lower().lstrip('.')
if actual_format != profile.file_format:
raise ValidationError(
f'Inventory file format {actual_format} does not match parsing profile {profile.file_format}',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
)
definition = dict(profile.definition_json or {})
return parse_inventory_excel_with_meta(
path,
field_mapping=field_mapping,
mapping_source=mapping_source,
header_row_index=header_row_index,
llm_match_rule=llm_match_rule,
llm_match_key=llm_match_key,
field_mapping=dict(definition.get('field_mapping') or {}),
mapping_source=f"parsing_profile:{profile.profile_code}:v{profile.version}",
header_row_index=definition.get('header_row_index'),
sheet_name=str(definition.get('sheet_name') or '').strip() or None,
)
return lines, column_meta, path, inv_file
def apply_inventory_parse_result_to_linked_tasks(
@@ -1,23 +1,71 @@
"""
services/shipping_notice/inventory_mapping.py
用途:标准化库存字段映射,补充匹配规则说明,并校验映射是否完整。
依赖:match_rule_desc、标准 `json`/`typing` 能力。
逻辑:由 inventory_workflow、inventory_mapping_workflow 等上游模块调用本文件解析 map_json,再进入库存解析和匹配链路。
用途:按用户维护的库存字段 ID 标准化列映射,并校验字段能力是否完整。
依赖:ShippingInventoryField、match_rule_desc、标准 `json`/`typing` 能力。
逻辑:正式库存链始终保留字段 ID;临时候选也只能引用库存字段目录 ID。
"""
from __future__ import annotations
from typing import Any
from app.models import ShippingInventoryField
from app.services.shipping_notice.match_rule_desc import resolve_match_rule
SYSTEM_FIELDS = ("part_number", "aws_part_number", "reservation_id", "available_qty")
REQUIRED_SYSTEM_FIELDS = ("part_number", "reservation_id", "available_qty")
LEGACY_SYSTEM_FIELDS = ("part_number", "aws_part_number", "reservation_id", "available_qty", "warehouse_id")
LEGACY_REQUIRED_FIELDS = ("part_number", "reservation_id", "available_qty")
def _catalog_by_id(field_mapping: dict[str, Any]) -> dict[str, ShippingInventoryField]:
"""读取映射中的库存字段目录记录;非 ID 映射仅保留给临时上传的旧链路。"""
try:
ids = {int(key) for key in field_mapping}
except (TypeError, ValueError):
return {}
if not ids or any(item <= 0 for item in ids):
return {}
rows = ShippingInventoryField.query.filter(
ShippingInventoryField.id.in_(ids), ShippingInventoryField.status == 'active',
).all()
return {str(row.id): row for row in rows}
def _uses_catalog_ids(field_mapping: dict[str, Any]) -> bool:
"""判断映射键是否为字段目录 ID;纯数字键绝不能回退成旧运行字段。"""
if not field_mapping:
return False
try:
return all(int(key) > 0 for key in field_mapping)
except (TypeError, ValueError):
return False
def runtime_field_mapping(field_mapping: dict[str, str]) -> tuple[dict[str, str], dict[str, ShippingInventoryField]]:
"""验证“目录 ID → 原始表头”并保留字段 ID,禁止运行期依赖字段名称或内部编码。"""
catalog = _catalog_by_id(field_mapping)
if _uses_catalog_ids(field_mapping):
if len(catalog) != len(field_mapping):
return {}, {}
return ({str(item.id): str(field_mapping[str(item.id)]).strip() for item in catalog.values()}, catalog)
# 临时会话上传尚未绑定库存站点时沿用受控旧格式;正式解析方案不会走该分支。
return ({str(key): str(value).strip() for key, value in field_mapping.items()}, {})
def usage_field_ids() -> dict[str, set[str]]:
"""按业务用途返回启用字段 ID;程序校验能力角色而不限定字段名称。"""
rows = ShippingInventoryField.query.filter(
ShippingInventoryField.status == 'active',
).all()
result: dict[str, set[str]] = {}
for row in rows:
result.setdefault(row.usage_type, set()).add(str(row.id))
return result
def normalize_field_mapping(raw: Any) -> dict[str, str] | None:
"""将 map_json 规范为库存 v2 字段映射;缺内部料号、Reservation 或可用量时返回 None。"""
"""规范库存字段目录 ID 到来源栏位的映射;缺必要用途字段时返回 None。"""
data: dict[str, Any] | None = None
if isinstance(raw, dict):
data = raw
@@ -38,17 +86,17 @@ def normalize_field_mapping(raw: Any) -> dict[str, str] | None:
return None
result: dict[str, str] = {}
for key in SYSTEM_FIELDS:
for key in LEGACY_SYSTEM_FIELDS:
value = inner.get(key)
if value is None:
continue
text = str(value).strip()
if text:
result[key] = text
return result if all(field in result for field in REQUIRED_SYSTEM_FIELDS) else None
return result if all(field in result for field in LEGACY_REQUIRED_FIELDS) else None
def suggest_field_mapping(headers: list[str]) -> dict[str, str]:
def _suggest_runtime_field_mapping(headers: list[str]) -> dict[str, str]:
"""基于表头名称的规则推断列映射(LLM 不可用时的 fallback)。"""
from app.services.shipping_notice.inventory_snapshot import _column_map, _map_header
@@ -105,12 +153,41 @@ def suggest_field_mapping(headers: list[str]) -> dict[str, str]:
if qty:
mapping["available_qty"] = qty
warehouse = pick("warehouse_id", "Warehouse ID", "Warehouse", "Warehouse Code", "WH ID")
if warehouse:
mapping["warehouse_id"] = warehouse
return mapping
def suggest_field_mapping(headers: list[str], *, as_catalog: bool = False) -> dict[str, str]:
"""按用户字段显示名称确定性推荐表头;正式配置不内置任何字段名称词典。"""
if not as_catalog:
return _suggest_runtime_field_mapping(headers)
from app.services.shipping_notice.inventory_structure_fingerprint import normalise_header
rows = ShippingInventoryField.query.filter_by(status='active').all()
header_by_name: dict[str, list[str]] = {}
for header in headers:
normalized = normalise_header(header)
if normalized:
header_by_name.setdefault(normalized, []).append(str(header).strip())
result: dict[str, str] = {}
for row in rows:
candidates = header_by_name.get(normalise_header(row.display_name), [])
if len(candidates) == 1:
result[str(row.id)] = candidates[0]
return result
def mapping_is_complete(field_mapping: dict[str, str]) -> bool:
"""映射是否同时包含内部料号、Reservation ID 与可用数量。"""
return all(bool(field_mapping.get(field)) for field in REQUIRED_SYSTEM_FIELDS)
"""映射是否至少提供一个匹配字段和且仅一个库存数量字段。"""
runtime_mapping, catalog = runtime_field_mapping(field_mapping)
if catalog:
mapped = set(runtime_mapping)
usages = usage_field_ids()
return bool(mapped & usages.get('match_identity', set())) and len(mapped & usages.get('inventory_quantity', set())) == 1
return all(bool(runtime_mapping.get(field)) for field in LEGACY_REQUIRED_FIELDS)
def validate_field_mapping_against_headers(
@@ -121,16 +198,17 @@ def validate_field_mapping_against_headers(
norm_headers = [str(h or "").strip() for h in headers]
lower_set = {h.lower() for h in norm_headers if h}
errors: list[str] = []
labels = {
"part_number": "part_number",
"aws_part_number": "aws_part_number",
"reservation_id": "reservation_id",
"available_qty": "available_qty",
}
for key, label in labels.items():
name = str(field_mapping.get(key) or "").strip()
runtime_mapping, catalog = runtime_field_mapping(field_mapping)
if not runtime_mapping:
return ['库存字段目录中存在已停用或不存在的字段']
required_codes = set(LEGACY_REQUIRED_FIELDS)
if catalog:
usages = usage_field_ids()
required_codes = (set(runtime_mapping) & usages.get('match_identity', set())) | (set(runtime_mapping) & usages.get('inventory_quantity', set()))
for key, name in runtime_mapping.items():
label = catalog.get(key).display_name if key in catalog else key
if not name:
if key in REQUIRED_SYSTEM_FIELDS:
if key in required_codes:
errors.append(f"缺少 {label} 列映射")
continue
if name not in norm_headers and name.lower() not in lower_set:
@@ -145,9 +223,7 @@ def resolve_columns_from_field_mapping(
headers: list[str],
field_mapping: dict[str, str],
) -> dict[str, int | None]:
"""将显式 field_mapping 转为系统字段 → 列索引映射(保留自动检测的可选列)。"""
from app.services.shipping_notice.inventory_snapshot import DEFAULT_COLUMN_MAP, _resolve_inventory_columns
"""将显式 field_mapping 转为库存字段 ID → 列索引;未配置字段不自动猜测。"""
norm_headers = [str(h or "").strip() for h in headers]
lower_to_idx = {h.lower(): i for i, h in enumerate(norm_headers) if h}
@@ -161,19 +237,10 @@ def resolve_columns_from_field_mapping(
return norm_headers.index(name)
return lower_to_idx.get(name.lower())
# Keep auto-detected optional columns (e.g. odm_id / qty) even when the
# required mapping is provided explicitly by LLM or user.
columns = _resolve_inventory_columns(norm_headers, DEFAULT_COLUMN_MAP)
columns.update({
"part_number": idx_for(field_mapping.get("part_number")),
"aws_part_number": idx_for(field_mapping.get("aws_part_number")),
"reservation_id": idx_for(field_mapping.get("reservation_id")),
"available_qty": None,
})
avail_header = field_mapping.get("available_qty")
if avail_header:
columns["available_qty"] = idx_for(avail_header)
return columns
runtime_mapping, _catalog = runtime_field_mapping(field_mapping)
if not runtime_mapping:
return {}
return {field_code: idx_for(header_name) for field_code, header_name in runtime_mapping.items()}
def build_column_meta_from_mapping(
@@ -181,10 +248,9 @@ def build_column_meta_from_mapping(
field_mapping: dict[str, str],
*,
mapping_source: str = "rules",
llm_match_rule: str | None = None,
llm_match_key: list[str] | None = None,
) -> dict[str, Any]:
"""由用户/LLM 确认的 field_mapping 构建 column_meta(含 match_rule 与 source_column)。"""
"""由规则建议或已发布方案构建 column_meta(含匹配说明与来源栏位)。"""
runtime_mapping, catalog = runtime_field_mapping(field_mapping)
columns = resolve_columns_from_field_mapping(headers, field_mapping)
def source_column(index: int | None) -> str | None:
@@ -193,38 +259,19 @@ def build_column_meta_from_mapping(
text = str(headers[index] or "").strip()
return text or None
qty_header = field_mapping.get("available_qty")
match_rule, match_key, match_rule_source = resolve_match_rule(
field_mapping,
llm_match_rule=llm_match_rule,
llm_match_key=llm_match_key,
)
labels = {str(item.id): item.display_name for item in catalog.values()}
match_rule, match_key, match_rule_source = resolve_match_rule(runtime_mapping)
return {
"headers": [str(h or "").strip() for h in headers],
"mapping_source": mapping_source,
"field_mapping": dict(field_mapping),
"mapping": {
"part_number": {
"system_field": "part_number",
"label": "Supplier Sku / 内部料号",
"source_column": source_column(columns.get("part_number")),
},
"aws_part_number": {
"system_field": "aws_part_number",
"label": "AWS Sku / AWS 料号",
"source_column": source_column(columns.get("aws_part_number")),
},
"reservation_id": {
"system_field": "reservation_id",
"label": "Reservation ID",
"source_column": source_column(columns.get("reservation_id")),
},
"available_qty": {
"system_field": "available_qty",
"label": "可用数量",
"source_column": qty_header or source_column(columns.get("available_qty")),
"qty_preference": "available_qty",
},
field_id: {
"inventory_field_id": int(field_id) if field_id.isdigit() else None,
"label": labels.get(field_id, field_id),
"source_column": source_column(index),
}
for field_id, index in columns.items()
},
"match_key": match_key,
"match_rule": match_rule,
@@ -1,91 +0,0 @@
"""
services/shipping_notice/inventory_mapping_store.py
用途:持久化库存字段映射模板,并按客户与表头哈希做查询复用。
依赖:db、ShippingInventoryMapping 模型、hashlib/json。
逻辑:由 inventory_mapping_workflow 或库存上传链路调用本文件,把用户确认过的映射保存下来供后续同模板复用。
"""
from __future__ import annotations
import json
from datetime import datetime
from hashlib import sha256
from typing import Any
from app import db
from app.models import ShippingInventoryMapping
_GLOBAL_CUSTOMER_CODE = "GLOBAL"
def _customer_key(customer_code: str | None) -> str:
key = str(customer_code or "").strip()
return key or _GLOBAL_CUSTOMER_CODE
def compute_inventory_header_hash(headers: list[str], header_row_index: int | None = None) -> str:
"""对表头行与 header_row_index 计算 SHA256,用作映射模板去重键。"""
norm_headers = [str(h or "").strip() for h in headers]
payload = {
"header_row_index": int(header_row_index or 1),
"headers": norm_headers,
}
raw = json.dumps(payload, ensure_ascii=False, separators=(",", ":"), sort_keys=True).encode("utf-8")
return sha256(raw).hexdigest()
def find_inventory_mapping(customer_code: str | None, header_hash: str) -> ShippingInventoryMapping | None:
"""按 customer_code + header_hash 查找已保存的列映射模板。"""
customer = _customer_key(customer_code)
if not header_hash:
return None
return ShippingInventoryMapping.query.filter_by(customer_code=customer, header_hash=header_hash).first()
def resolve_inventory_mapping(
customer_code: str | None,
*,
preview: dict[str, Any],
) -> dict[str, str] | None:
"""从 schema preview 匹配历史映射模板;命中时更新 last_used_at。"""
customer = _customer_key(customer_code)
headers = preview.get("headers") if isinstance(preview.get("headers"), list) else []
header_hash = compute_inventory_header_hash(headers, preview.get("header_row_index"))
record = find_inventory_mapping(customer, header_hash)
if not record:
return None
record.last_used_at = datetime.utcnow()
if isinstance(record.field_mapping_json, dict) and record.field_mapping_json:
return {str(k): str(v) for k, v in record.field_mapping_json.items() if v}
return None
def upsert_inventory_mapping(
customer_code: str | None,
*,
preview: dict[str, Any],
field_mapping: dict[str, str],
) -> ShippingInventoryMapping | None:
"""保存或更新客户+表头哈希对应的列映射模板。"""
customer = _customer_key(customer_code)
headers = preview.get("headers") if isinstance(preview.get("headers"), list) else []
header_hash = compute_inventory_header_hash(headers, preview.get("header_row_index"))
record = find_inventory_mapping(customer, header_hash)
now = datetime.utcnow()
if record:
record.field_mapping_json = dict(field_mapping)
record.headers_json = [str(h or "").strip() for h in headers]
record.updated_at = now
record.last_used_at = now
return record
record = ShippingInventoryMapping(
customer_code=customer,
header_hash=header_hash,
headers_json=[str(h or "").strip() for h in headers],
field_mapping_json=dict(field_mapping),
last_used_at=now,
)
db.session.add(record)
return record
@@ -1,275 +1,28 @@
"""
services/shipping_notice/inventory_mapping_workflow.py
用途:库存字段对齐确认、自动映射推进与库存载入后的 auto-chain 编排。
依赖:inventory_snapshot、inventory_mapping_store、query_service、task_line_store、tool_common、state_machine。
逻辑:inventory_workflow / inventory_rpa_workflow 在解析/上传后委托本模块;
task_workflow / fulfillment_workflow 在决策与 auto_progress 中调用映射门禁;
订单行对齐预览经 read_task_order_lines 读取。
用途:将已按 published Profile 解析完成的正式库存写回任务并推进到待匹配状态。
依赖:inventory_file_store、inventory_snapshot、query_service、state_machine、tool_common。
逻辑:正式库存不存在任务级字段推断或映射确认;调用方必须先完成结构校验和确定性解析。
"""
from __future__ import annotations
from typing import Any
from flask import current_app
from app import db
from app.models import ShippingTask, ShippingTaskEvent
from app.services.shipping_notice.field_alignment_summary import format_field_alignment_summary
from app.models import ShippingTask
from app.services.shipping_notice.inventory_file_store import (
active_inventory_file_for_task,
apply_inventory_parse_result_to_linked_tasks,
start_inventory_file_linked_tasks,
)
from app.services.shipping_notice.inventory_mapping import mapping_is_complete
from app.services.shipping_notice.inventory_mapping_store import upsert_inventory_mapping
from app.services.shipping_notice.inventory_snapshot import build_field_alignment_preview
from app.services.shipping_notice.query_service import serialize_task_for_tool
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
from app.services.shipping_notice.task_line_store import read_task_order_lines
from app.services.shipping_notice.tool_common import (
auto_mapping_allow_llm,
auto_match_enabled,
auto_progress_enabled,
log_task_event,
payload_wants_auto_chain_fallback,
set_task_step_progress,
)
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
from app.services.shipping_notice.constants import RS_ALIGN_REVIEW
def mapping_review_enabled() -> bool:
"""是否启用库存字段对齐人审(SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW,默认 true)。"""
val = current_app.config.get("SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW")
if val is None:
return True
return str(val).lower() not in {"0", "false", "no", "off"}
def awaiting_inventory_mapping_confirm(task: ShippingTask) -> bool:
"""任务是否停在 align_review 等待用户确认库存列映射。"""
return task.review_status == RS_ALIGN_REVIEW
def latest_inventory_column_meta(task: ShippingTask) -> dict[str, Any] | None:
"""从最近 30 条任务事件中回溯最新的 column_meta。"""
if task.id is None:
return None
events = (
ShippingTaskEvent.query.filter_by(task_id=task.id)
.order_by(ShippingTaskEvent.id.desc())
.limit(30)
.all()
)
for event in events:
detail = event.detail_json or {}
meta = detail.get("column_meta")
if isinstance(meta, dict) and meta:
return meta
return None
def field_alignment_for_task(task: ShippingTask, column_meta: dict[str, Any] | None = None) -> dict[str, Any]:
"""为当前任务生成 field_alignment 预览(订单行 vs 库存行 + warnings)。"""
meta = column_meta or latest_inventory_column_meta(task)
return build_field_alignment_preview(
task.inventory_lines_json or [],
read_task_order_lines(task),
column_meta=meta,
)
def mapping_confirm_blockers(task: ShippingTask) -> list[str]:
"""列映射尚不能自动/人工确认的原因列表(中文)。"""
blockers: list[str] = []
meta = latest_inventory_column_meta(task) or {}
inv_mapping = meta.get("mapping") if isinstance(meta.get("mapping"), dict) else {}
res_source = None
if isinstance(inv_mapping.get("reservation_id"), dict):
res_source = inv_mapping["reservation_id"].get("source_column")
if not str(res_source or "").strip():
blockers.append("缺少 Reservation ID 列映射")
field_alignment = field_alignment_for_task(task)
warnings = field_alignment.get("warnings") if isinstance(field_alignment.get("warnings"), list) else []
blockers.extend(str(w) for w in warnings if w)
return blockers
def can_auto_advance_mapping(task: ShippingTask) -> bool:
"""映射完整且无 blocker 时,auto_progress 可跳过 align_review 人审门禁。"""
if not auto_progress_enabled() or not auto_match_enabled():
return False
if not mapping_review_enabled():
return False
if not awaiting_inventory_mapping_confirm(task):
return False
if mapping_confirm_blockers(task):
return False
meta = latest_inventory_column_meta(task) or {}
mapping_source = str(meta.get("mapping_source") or "rules").strip().lower()
if mapping_source == "llm" and not auto_mapping_allow_llm():
return False
return True
def should_auto_chain_after_mapping(
task: ShippingTask,
payload: dict[str, Any] | None,
) -> bool:
"""库存映射完成后是否应自动串联 match_inventory(fallback 或 auto_advance)。"""
if payload_wants_auto_chain_fallback(payload):
return True
return can_auto_advance_mapping(task)
def inventory_mapping_checkpoint_response(
task: ShippingTask,
*,
column_meta: dict[str, Any] | None = None,
extra_data: dict[str, Any] | None = None,
lang: str | None = None,
) -> dict[str, Any]:
"""
返回 align_review 检查点响应,强制 Agent 停等用户确认字段对齐。
【AI 触发时机】:match_inventory 发现仍待映射确认时由内部调用;Agent 禁止主动调用。
"""
# [STEP 1] 先根据任务和列信息构建字段对齐视图。
# 这里要把库存列、订单字段和额外 warning 汇总成用户能直接确认的 message/data。
field_alignment = field_alignment_for_task(task, column_meta)
extra = extra_data or {}
message = format_field_alignment_summary(
task_no=task.task_no,
field_alignment=field_alignment,
inventory_row_count=extra.get("inventory_row_count"),
warnings=extra.get("warnings") if isinstance(extra.get("warnings"), list) else None,
lang=lang,
)
data = {
**serialize_task_for_tool(task),
"field_alignment": field_alignment,
**extra,
}
set_task_step_progress(
task,
step_key="step4_align_confirm",
step_title="确认字段对齐",
status="needs_human",
message="请确认库存字段对齐后再继续匹配",
progress_percent=100,
current=3,
total=3,
detail="系统已识别必填列映射,请先人工确认",
extra={"field_alignment": field_alignment},
)
db.session.flush()
# [STEP 2] 明确停在人审检查点。
# 返回值必须阻止同轮继续调用 match_inventory,确保用户先确认字段对齐。
return tool_response(
status="needs_human",
task=task,
message=message,
data=data,
next_required_action=(
"向用户原文展示 message(固定 Markdown)后停止本轮;"
"用户确认后调用 submit_decision(decision=confirm_inventory_mapping);"
"禁止在同一轮调用 match_inventory"
),
forbidden_next_tools=[
"match_inventory",
"generate_shipment_excel",
"upload_to_freight",
],
stop_agent_turn=True,
)
def maybe_auto_confirm_inventory_mapping(task: ShippingTask) -> bool:
"""auto_progress 路径下自动确认映射并推进 MAPPING_CONFIRMED;成功返回 True。"""
# [STEP 1] 先检查是否满足自动确认前提。
# 包括开关、当前检查点、阻塞项以及 LLM 映射是否被允许自动接受。
if not auto_progress_enabled():
return False
if not mapping_review_enabled():
return False
if not awaiting_inventory_mapping_confirm(task):
return False
if mapping_confirm_blockers(task):
return False
meta = latest_inventory_column_meta(task) or {}
mapping_source = str(meta.get("mapping_source") or "rules").strip().lower()
if mapping_source == "llm" and not auto_mapping_allow_llm():
return False
# [STEP 2] 若映射完整则先落模板,再推进状态机。
# 这样相同客户/表头的后续上传可以直接复用人工确认过的映射结果。
headers = meta.get("headers") if isinstance(meta.get("headers"), list) else []
field_mapping = meta.get("field_mapping") if isinstance(meta.get("field_mapping"), dict) else None
if headers and field_mapping and mapping_is_complete(field_mapping):
upsert_inventory_mapping(
task.customer_code,
preview={
"headers": headers,
"header_row_index": meta.get("header_row_index") or 1,
},
field_mapping={str(k): str(v).strip() for k, v in field_mapping.items() if str(v or "").strip()},
)
# [STEP 3] 最后把任务推进到 mapping_confirmed,并记录自动确认审计事件。
field_alignment = field_alignment_for_task(task)
apply_task_transition(task, TaskTransition.MAPPING_CONFIRMED)
log_task_event(task, "inventory_mapping_auto_confirmed", {"field_alignment": field_alignment})
inv_file = active_inventory_file_for_task(task)
if inv_file:
inv_file.mapping_confirmed = True
for link in inv_file.links or []:
linked_task = link.task
if not link.is_active or not linked_task or linked_task.id == task.id:
continue
if awaiting_inventory_mapping_confirm(linked_task):
apply_task_transition(linked_task, TaskTransition.MAPPING_CONFIRMED)
log_task_event(
linked_task,
"inventory_mapping_auto_confirmed",
{
"field_alignment": field_alignment,
"confirmed_by_task_no": task.task_no,
"inventory_file_no": inv_file.inventory_file_no,
},
)
db.session.commit()
if inv_file:
start_inventory_file_linked_tasks(inv_file)
return True
def _try_auto_chain_after_inventory_loaded(
task: ShippingTask,
*,
payload: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
"""Auto: confirm mapping → match → Excel → RPA upload when allowed."""
from app.services.shipping_notice.fulfillment_workflow import (
match_completed,
match_inventory,
try_auto_chain_after_match,
)
from app.services.shipping_notice.tool_common import merge_tool_payload, prepend_tool_message
if not should_auto_chain_after_mapping(task, payload):
return None
auto_confirmed = maybe_auto_confirm_inventory_mapping(task)
if auto_confirmed:
db.session.refresh(task)
if awaiting_inventory_mapping_confirm(task):
return None
if not auto_match_enabled() or match_completed(task):
return None
match_result = match_inventory(merge_tool_payload(task, payload))
if auto_confirmed:
match_result = prepend_tool_message(match_result, "字段对齐已自动确认。")
return try_auto_chain_after_match(task, match_result, payload=payload)
def inventory_loaded_response(
@@ -279,29 +32,28 @@ def inventory_loaded_response(
warnings: list[str] | None = None,
column_meta: dict[str, Any] | None = None,
source: str,
require_mapping_review: bool,
event_type: str,
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。
写入已经确定性解析的正式库存,并将关联任务推进到待匹配状态。
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()
task: 当前正式发货任务。
inventory_lines: 已通过 published Profile 结构校验和类型转换的库存行。
warnings: 非阻断解析提示。
column_meta: 解析审计元数据,仅用于展示和追溯。
source: 库存来源标识。
event_type: 库存载入审计事件类型。
field_mapping: published Profile 的字段映射快照。
mapping_source: 必须由调用方标明的映射来源,正式文件通常为 parsing_profile。
commit: False 时仅 flush,供批量回调维持外层事务边界。
# [STEP 1] 先把库存快照写回任务,并计算当前字段对齐视图。
# 后续无论走人工确认还是直接进入 inventory_ready,都需要统一复用这份 field_alignment。
Returns:
Tool 标准响应;成功后任务可直接进入库存匹配。
"""
inv_file = active_inventory_file_for_task(task)
linked_tasks: list[ShippingTask] = []
if inv_file:
@@ -310,84 +62,27 @@ def inventory_loaded_response(
inventory_lines,
field_mapping=field_mapping,
mapping_source=mapping_source,
mapping_confirmed=False,
mapping_confirmed=True,
)
else:
task.inventory_lines_json = inventory_lines
field_alignment = field_alignment_for_task(task, column_meta)
field_alignment = build_field_alignment_preview(
inventory_lines,
read_task_order_lines(task),
column_meta=column_meta,
)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
step_title="获取库存",
status="running" if require_mapping_review else "completed",
status="completed",
message=f"已载入库存 {len(inventory_lines)} 行",
progress_percent=100,
current=len(inventory_lines),
total=len(inventory_lines),
detail="库存快照已就绪,正在进入字段对齐阶段" if require_mapping_review else "库存快照已就绪,可进入匹配阶段",
detail="库存结构校验与解析已完成,可进入匹配阶段",
)
# [STEP 2] 如果当前策略要求映射复核,则先进入对齐确认检查点。
# 同时尝试自动串联;只有自动串联没有吃掉结果时,才真正返回给用户确认映射。
if require_mapping_review and mapping_review_enabled():
apply_task_transition(task, TaskTransition.INVENTORY_ALIGN_REVIEW)
log_task_event(
task,
event_type,
{
"row_count": len(inventory_lines),
"warnings": warnings or [],
"source": source,
"mapping_review": True,
"column_meta": column_meta,
"inventory_file_no": inv_file.inventory_file_no if inv_file else None,
"linked_task_nos": [item.task_no for item in linked_tasks],
},
)
for linked_task in linked_tasks:
if linked_task.id == task.id:
continue
apply_task_transition(linked_task, TaskTransition.INVENTORY_ALIGN_REVIEW)
log_task_event(
linked_task,
event_type,
{
"row_count": len(inventory_lines),
"warnings": warnings or [],
"source": source,
"mapping_review": True,
"inventory_file_no": inv_file.inventory_file_no if inv_file else None,
"owner_task_no": task.task_no,
"column_meta": column_meta,
},
)
_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
if chain_payload:
lang = str(
chain_payload.get("lang")
or chain_payload.get("locale")
or chain_payload.get("language")
or ""
).strip() or None
return inventory_mapping_checkpoint_response(
task,
column_meta=column_meta,
extra_data={
"inventory_row_count": len(inventory_lines),
"warnings": warnings or [],
},
lang=lang,
)
# [STEP 3] 无需映射复核时,直接推进到 inventory_ready。
# 这条路径主要服务于明确结构化库存输入,尽快把任务交给后续匹配阶段。
apply_task_transition(task, TaskTransition.INVENTORY_READY)
for linked_task in linked_tasks:
if linked_task.id != task.id:
@@ -404,7 +99,10 @@ def inventory_loaded_response(
"linked_task_nos": [item.task_no for item in linked_tasks],
},
)
_persist_inventory_loaded()
if commit:
db.session.commit()
else:
db.session.flush()
if commit and inv_file:
start_inventory_file_linked_tasks(inv_file)
return tool_response(
@@ -0,0 +1,208 @@
"""
backend/app/services/shipping_notice/inventory_parsing_profile.py
用途:管理可跨库存源复用的版本化库存解析 Profile,并为运行期提供确定性解析定义。
依赖:ShippingInventoryParsingProfile、ShippingInventorySource、ShippingOrderField、inventory_mapping。
逻辑:管理员保存草稿并发布不可变版本;库存源仅绑定 published Profile,解析链直接使用定义中的列映射与订单字段匹配键。
"""
from __future__ import annotations
import hashlib
import json
from datetime import datetime
from typing import Any
from sqlalchemy import func
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.extensions import db
from app.models import (
ShippingInventoryField,
ShippingInventoryParsingProfile,
ShippingInventorySource,
ShippingOrderField,
)
def _catalog_fields(field_mapping: dict[str, Any]) -> dict[str, ShippingInventoryField]:
"""解析字段目录 ID 并确认均为可用于新方案的启用库存业务字段。"""
field_ids: list[int] = []
for raw_id in field_mapping:
try:
field_id = int(raw_id)
except (TypeError, ValueError) as exc:
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') from exc
if field_id <= 0:
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
field_ids.append(field_id)
rows = ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(set(field_ids))).all() if field_ids else []
fields = {str(row.id): row for row in rows if row.status == 'active'}
if len(fields) != len(set(str(item) for item in field_ids)):
raise ValidationError('Parsing profile inventory field is unavailable', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
return fields
def _required_catalog_field_ids(fields: dict[str, ShippingInventoryField]) -> set[str]:
"""校验解析方案具备匹配与库存数量能力,不限定字段名称。"""
match_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'match_identity'}
quantity_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'inventory_quantity'}
if not match_ids or len(quantity_ids) != 1:
raise ValidationError(
'Parsing profile requires at least one match field and exactly one inventory quantity field',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
)
return match_ids | quantity_ids
def _validate_definition(raw: Any) -> dict[str, Any]:
"""校验字段目录 ID 到来源表头的映射及订单明细匹配键,禁止自由脚本。"""
if not isinstance(raw, dict):
raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
field_mapping = raw.get('field_mapping')
if not isinstance(field_mapping, dict) or not field_mapping:
raise ValidationError('Parsing profile requires complete field mapping', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
if any(not str(value or '').strip() for value in field_mapping.values()):
raise ValidationError('Parsing profile field mapping is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
catalog_fields = _catalog_fields(field_mapping)
_required_catalog_field_ids(catalog_fields)
match_keys = raw.get('match_keys')
if not isinstance(match_keys, list) or not match_keys:
raise ValidationError('Parsing profile requires match keys', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
normalized_keys: list[dict[str, str]] = []
seen_order_fields: set[str] = set()
seen_inventory_fields: set[str] = set()
for item in match_keys:
field = db.session.get(ShippingOrderField, str(item.get('order_field_id') or '')) if isinstance(item, dict) else None
inventory_field = str(item.get('inventory_field_id') or item.get('inventory_field') or '') if isinstance(item, dict) else ''
inventory = catalog_fields.get(inventory_field)
if (
field is None or field.status != 'active' or field.scope != 'line'
or inventory is None or inventory.usage_type != 'match_identity'
):
raise ValidationError('Parsing profile match key is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
if field.id in seen_order_fields or inventory_field in seen_inventory_fields:
raise ValidationError('Parsing profile match keys must be unique', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
seen_order_fields.add(field.id)
seen_inventory_fields.add(inventory_field)
normalized_keys.append({'order_field_id': field.id, 'inventory_field_id': inventory_field})
header_row_index = raw.get('header_row_index')
if header_row_index is not None and (not isinstance(header_row_index, int) or header_row_index < 1):
raise ValidationError('header_row_index is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
return {
'sheet_name': str(raw.get('sheet_name') or '').strip() or None,
'header_row_index': header_row_index,
'field_mapping': {str(int(key)): str(value).strip() for key, value in field_mapping.items()},
'match_keys': normalized_keys,
}
def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]:
"""序列化解析 Profile 管理 DTO。"""
return {
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
'version': profile.version, 'status': profile.status, 'file_format': profile.file_format,
'definition': profile.definition_json or {}, 'checksum': profile.checksum,
'published_at': profile.published_at.isoformat() if profile.published_at else None,
'source_count': len(profile.sources),
}
def list_profiles() -> list[dict[str, Any]]:
"""列出全部解析 Profile 版本。"""
return [payload(item) for item in ShippingInventoryParsingProfile.query.order_by(
ShippingInventoryParsingProfile.profile_code, ShippingInventoryParsingProfile.version.desc(),
).all()]
def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
"""创建或更新解析 Profile 草稿;published 版本不可原地修改。"""
profile = db.session.get(ShippingInventoryParsingProfile, profile_id) if profile_id else None
if profile_id and profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
if profile is not None and profile.status != 'draft':
raise ConflictError('Published parsing profile is immutable', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE')
code = str(data.get('profile_code') or '').strip().upper()
if not code:
raise ValidationError('profile_code is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
if profile is not None and code != profile.profile_code:
raise ConflictError('Draft profile_code is immutable', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE')
if profile is None:
next_version = int(db.session.query(func.max(ShippingInventoryParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1
profile = ShippingInventoryParsingProfile(profile_code=code, version=next_version, created_by=actor_id)
db.session.add(profile)
profile.display_name = str(data.get('display_name') or code).strip()
profile.file_format = str(data.get('file_format') or 'xlsx').lower()
if profile.file_format not in {'xls', 'xlsx', 'csv'}:
raise ValidationError('file_format is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
definition = _validate_definition(data.get('definition'))
if profile.file_format == 'csv' and definition.get('sheet_name'):
raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
profile.definition_json = definition
db.session.commit()
return payload(profile)
def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""发布解析 Profile;既有 published 版本继续供已绑定库存源稳定使用。"""
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
if profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
if profile.status != 'draft':
raise ConflictError('Only draft parsing profile can be published', code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID')
from app.services.shipping_notice.order_schema import service as order_schema_service
published_field_ids = {
str(item.get('field_id') or '')
for item in order_schema_service.get_published_contract().get('fields', [])
}
referenced_field_ids = {
str(item.get('order_field_id') or '')
for item in (profile.definition_json or {}).get('match_keys', [])
if isinstance(item, dict)
}
if not referenced_field_ids or not referenced_field_ids <= published_field_ids:
raise ValidationError(
'Parsing profile match keys must reference the current published order schema',
code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID',
)
encoded = json.dumps(profile.definition_json, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
profile.checksum = hashlib.sha256(encoded).hexdigest()
profile.status = 'published'
profile.published_by = actor_id
profile.published_at = datetime.utcnow()
db.session.commit()
return payload(profile)
def retire(profile_id: int) -> dict[str, Any]:
"""退役无库存源引用的 published Profile,避免使现有 Source 静默失效。"""
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
if profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
if profile.status != 'published':
raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_INVALID')
if ShippingInventorySource.query.filter_by(parsing_profile_id=profile.id).count():
raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED')
profile.status = 'retired'
db.session.commit()
return payload(profile)
def delete_draft(profile_id: int) -> None:
"""删除从未发布的解析 Profile 草稿。"""
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
if profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
if profile.status != 'draft':
raise ConflictError('Only draft parsing profile can be deleted', code='SHIPPING.INVENTORY_PARSING_PROFILE_DELETE_BLOCKED')
db.session.delete(profile)
db.session.commit()
def require_source_profile(source: Any) -> ShippingInventoryParsingProfile:
"""读取库存源绑定的 published 解析 Profile;缺失或非发布状态时阻断自动解析。"""
profile = getattr(source, 'parsing_profile', None)
if profile is None or profile.status != 'published':
raise ConflictError('Inventory source parsing profile is not published', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
return profile
@@ -0,0 +1,74 @@
"""
services/shipping_notice/inventory_profile_matching.py
用途:将库存文件结构分析与已发布库存文件解析方案进行确定性比对。
依赖:ShippingInventoryParsingProfile、库存结构指纹服务。
逻辑:返回完全相同、结构兼容、需要新版本或无匹配;只提供管理员建议,绝不自动绑定库存站点。
"""
from __future__ import annotations
from typing import Any
from app.models import ShippingInventoryParsingProfile
from app.services.shipping_notice.inventory_structure_fingerprint import normalise_header
def _profile_headers(profile: ShippingInventoryParsingProfile) -> list[str]:
"""读取已发布方案保存的结构表头,缺失时不参与新方案复用推荐。"""
structure = profile.structure_definition_json if isinstance(profile.structure_definition_json, dict) else {}
return [str(header) for header in structure.get('headers', [])]
def _difference(analysis: dict[str, Any], profile: ShippingInventoryParsingProfile) -> dict[str, list[str]]:
"""以业务栏位名称展示新增、缺少和顺序变化,避免只给相似度百分比。"""
structure = analysis.get('structure') if isinstance(analysis.get('structure'), dict) else {}
observed = [normalise_header(header) for header in structure.get('selected_headers', [])]
expected = [normalise_header(header) for header in _profile_headers(profile)]
return {
'added_columns': [header for header in observed if header and header not in expected],
'missing_columns': [header for header in expected if header and header not in observed],
'column_order_changed': ['yes'] if set(observed) == set(expected) and observed != expected else [],
}
def _core_mapping_matches(analysis: dict[str, Any], profile: ShippingInventoryParsingProfile) -> bool:
"""确认既有方案的匹配与数量来源表头仍存在,不依赖字段名称猜测。"""
from app.services.shipping_notice.inventory_mapping import runtime_field_mapping, usage_field_ids
structure = analysis.get('structure') if isinstance(analysis.get('structure'), dict) else {}
observed_headers = {normalise_header(header) for header in structure.get('selected_headers', [])}
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
expected = definition.get('field_mapping') if isinstance(definition.get('field_mapping'), dict) else {}
expected_runtime, _ = runtime_field_mapping(expected)
usages = usage_field_ids()
expected_ids = set(expected_runtime)
required = expected_ids & (usages.get('match_identity', set()) | usages.get('inventory_quantity', set()))
if not (required & usages.get('match_identity', set())) or len(required & usages.get('inventory_quantity', set())) != 1:
return False
return all(normalise_header(expected_runtime.get(field)) in observed_headers for field in required)
def recommend_profiles(analysis: dict[str, Any]) -> dict[str, Any]:
"""查找已发布方案并返回可解释推荐;库存数据内容、文件名和内容 hash 均不参与判断。"""
exact = str(analysis.get('exact_structure_fingerprint') or '')
compatible = str(analysis.get('compatibility_fingerprint') or '')
profiles = ShippingInventoryParsingProfile.query.filter_by(status='published').all()
candidates: list[dict[str, Any]] = []
for profile in profiles:
level = None
if exact and profile.exact_structure_fingerprint == exact:
level = 'exact'
elif _core_mapping_matches(analysis, profile):
difference = _difference(analysis, profile)
if not difference['missing_columns']:
level = 'compatible'
if level:
candidates.append({
'profile_id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
'version': profile.version, 'level': level, 'difference': _difference(analysis, profile),
'source_count': len(profile.sources),
})
candidates.sort(key=lambda item: (0 if item['level'] == 'exact' else 1, -item['source_count'], item['profile_code']))
result = {'status': candidates[0]['level'] if candidates else 'no_match', 'candidates': candidates}
return result
@@ -0,0 +1,113 @@
"""
services/shipping_notice/inventory_routing_engine.py
用途:执行已发布的通用库存源路由规则并生成可解释的 Source 候选。
依赖:库存路由模型、routing_facts、routing_operators。
逻辑:只评估最高优先级命中的规则层;规则仅输出候选或人工复核,不执行 RPA 或 Warehouse 判定。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from typing import Any
from app.models import ShippingInventoryRoutingRule, ShippingOrderFieldValue, ShippingOrderLine
from app.services.shipping_notice.routing_facts import build_routing_facts, read_system_fact
from app.services.shipping_notice.routing_operators import matches_operator
ALLOWED_ACTIONS = frozenset({'add_source_candidates', 'exclude_source_candidates', 'require_manual_review'})
@dataclass(frozen=True)
class InventoryRoutingResult:
"""路由引擎输出;evidence 可持久化到任务审计快照。"""
status: str
source_codes: tuple[str, ...]
matched_rule_ids: tuple[int, ...]
evidence: dict[str, Any]
def _condition_value(condition: Any, *, task: Any, line: dict[str, Any] | None,
facts: dict[str, dict[str, Any]]) -> Any:
"""读取受控系统事实或 Task 当前 Extraction 的动态订单字段值。"""
if condition.source_kind == 'system_fact':
return read_system_fact(facts, condition.system_fact_key)
extraction_id = getattr(task, 'current_order_extraction_id', None)
if not extraction_id:
return None
query = ShippingOrderFieldValue.query.filter_by(
extraction_id=int(extraction_id), field_id=condition.order_field_id,
)
if line is None:
value = query.filter(ShippingOrderFieldValue.line_id.is_(None)).first()
else:
position = int(line.get('_position', 0))
value = query.join(ShippingOrderLine, ShippingOrderLine.id == ShippingOrderFieldValue.line_id).filter(
ShippingOrderLine.position == position,
).first()
return value.value_json if value is not None else None
def _rule_matches(rule: ShippingInventoryRoutingRule, *, task: Any, line: dict[str, Any] | None,
facts: dict[str, dict[str, Any]]) -> bool:
"""判断规则条件按 all/any 语义是否命中。"""
results = [
matches_operator(_condition_value(condition, task=task, line=line, facts=facts), condition.operator, condition.expected_value_json)
for condition in rule.conditions
]
if not results:
return False
return all(results) if rule.match_mode == 'all' else any(results)
def evaluate_inventory_source_rules(*, task: Any, line: dict[str, Any] | None = None, now: datetime | None = None) -> InventoryRoutingResult:
"""
评估已发布规则并返回最高优先级的 Source 候选集合。
Args:
task: 已解析的货代任务。
line: 行级规则的订单行;任务级规则传 None。
now: 测试可注入的评估时间,默认当前 UTC 时间。
Returns:
InventoryRoutingResult: resolved/unresolved/ambiguous/conflicted 状态及可审计证据。
"""
moment = now or datetime.utcnow()
scope = 'line' if line is not None else 'task'
facts = build_routing_facts(task=task, line=line)
query = ShippingInventoryRoutingRule.query.filter_by(status='published', scope=scope)
rules = [
rule for rule in query.order_by(ShippingInventoryRoutingRule.priority.desc(), ShippingInventoryRoutingRule.id.asc()).all()
if (rule.effective_from is None or rule.effective_from <= moment)
and (rule.effective_to is None or rule.effective_to >= moment)
]
matched = [rule for rule in rules if _rule_matches(rule, task=task, line=line, facts=facts)]
if not matched:
return InventoryRoutingResult('unresolved', (), (), {'facts': facts, 'matched_rules': []})
priority = matched[0].priority
top_rules = [rule for rule in matched if rule.priority == priority]
source_codes: set[str] = set()
excluded: set[str] = set()
manual = False
for rule in top_rules:
if rule.action_type not in ALLOWED_ACTIONS:
return InventoryRoutingResult('conflicted', (), tuple(item.id for item in top_rules), {'reason': 'unsupported_action'})
payload = rule.action_payload_json if isinstance(rule.action_payload_json, dict) else {}
codes = {str(code or '').strip().upper() for code in payload.get('source_codes', []) if str(code or '').strip()}
if rule.action_type == 'add_source_candidates':
source_codes.update(codes)
elif rule.action_type == 'exclude_source_candidates':
excluded.update(codes)
else:
manual = True
source_codes.difference_update(excluded)
status = 'conflicted' if manual else ('resolved' if len(source_codes) == 1 else 'ambiguous' if source_codes else 'unresolved')
return InventoryRoutingResult(
status,
tuple(sorted(source_codes)),
tuple(rule.id for rule in top_rules),
{'facts': facts, 'priority': priority, 'matched_rules': [rule.rule_code for rule in top_rules]},
)
@@ -3,7 +3,7 @@ services/shipping_notice/inventory_rpa_workflow.py
用途:发货通知库存 RPA 编排(触发导出、等待/超时、回调落盘)。
依赖:customer_identity_gate、reservation_gate、rpa、rpa_attempts、inventory_snapshot、inventory_mapping_workflow、query_service、task_line_store、tool_common、state_machine、tool_response。
逻辑:inventory_workflow.ensure_inventory 在 mode=auto/retry_rpa 时委托本模块;tools 门面 re-export rpa_report_inventory;
逻辑:inventory_workflow.ensure_inventory 在 auto 时仅复用快照、在 retry_rpa 时委托本模块触发刷新;tools 门面 re-export rpa_report_inventory;
Reservation 门禁订单行经 read_task_order_lines 读取。
"""
@@ -23,7 +23,6 @@ from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent
from app.services.shipping_notice.constants import (
CP_INVENTORY_SOURCE_REVIEW,
CP_PARSE_OK,
CP_PARSE_REVIEW,
CP_UPLOAD_REQ,
PH_INVENTORY_SOURCE_UNRESOLVED,
PH_RPA_PENDING,
@@ -53,14 +52,12 @@ from app.services.shipping_notice.inventory_source_gate import (
confirm_task_inventory_source,
inventory_identities_match,
is_inventory_source_stable,
task_needs_parse_review,
)
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
from app.services.shipping_notice.customer_identity_gate import (
assert_customer_identity_gate,
customer_gate_tool_response,
)
from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source
from app.services.shipping_notice.query_service import (
resolve_task_from_payload,
serialize_task_for_tool,
@@ -141,21 +138,16 @@ def _try_reuse_inventory_snapshot(
优先复用未过期库存快照,避免重复触发 RPA。
【AI 触发时机】:ensure_inventory_via_rpa 已确定库存源且 mode 非 retry_rpa 时调用。
核心逻辑:按 source_code + 发货 Excel warehouse id 查找 ready 快照;命中则 link 并进入映射/匹配。
核心逻辑:按 source_code + 发货 Excel warehouse id 查找 ready 快照;命中则 link 并进入待匹配状态。
retry_rpa 必须跳过缓存强制重新导出。
"""
if mode == "retry_rpa":
return None
from app.services.shipping_notice.inventory_mapping_workflow import (
awaiting_inventory_mapping_confirm,
inventory_loaded_response,
inventory_mapping_checkpoint_response,
)
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
snapshot = find_latest_ready_snapshot(
str(rpa_source.get("source_code") or ""),
str(rpa_source.get("site_id") or ""),
str(rpa_source.get("warehouse_id") or ""),
)
if not snapshot:
@@ -187,21 +179,19 @@ def _try_reuse_inventory_snapshot(
]
if cached_lines:
task.inventory_lines_json = cached_lines
if awaiting_inventory_mapping_confirm(task):
db.session.commit()
return inventory_mapping_checkpoint_response(task)
return inventory_loaded_response(
task,
cached_lines,
column_meta={"source": "snapshot_reuse"},
source="snapshot_reuse",
require_mapping_review=not snapshot.mapping_confirmed,
event_type="inventory_snapshot_reused",
)
path = Path(snapshot.storage_path)
if path.is_file():
lines, column_meta = ingest_inventory_file(path, move_to=None)
from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file
lines, column_meta = parse_inventory_snapshot_file(snapshot)
if lines:
snapshot.inventory_lines_json = lines
snapshot.line_count = len(lines)
@@ -210,7 +200,6 @@ def _try_reuse_inventory_snapshot(
lines,
column_meta=column_meta,
source="snapshot_reuse",
require_mapping_review=True,
event_type="inventory_snapshot_reused",
)
@@ -218,7 +207,7 @@ def _try_reuse_inventory_snapshot(
return tool_response(
status="running",
task_id=task.task_no,
message="已关联最新库存快照,正在读取字段映射。",
message="已关联最新库存快照,正在读取库存数据。",
data=serialize_task_for_tool(task),
)
@@ -331,21 +320,19 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingTask, *, source: str = "works
return ensure_inventory_via_rpa(task, mode="auto")
def _expected_snapshot_identity_from_task(task: ShippingTask) -> tuple[str, str, str]:
"""从任务正式库存身份推导快照预期三元组。"""
def _expected_snapshot_identity_from_task(task: ShippingTask) -> tuple[str, str]:
"""从任务正式库存身份推导快照预期二元组。"""
return (
str(task.inventory_source_code or "").strip().upper(),
str(task.inventory_site_id or "").strip().upper(),
str(task.inventory_warehouse_id or "").strip().upper(),
)
def _expected_snapshot_identity_from_source(source: dict[str, Any]) -> tuple[str, str, str]:
"""从 RPA/配置源推导快照预期身份三元组,供回调入库前预检。"""
def _expected_snapshot_identity_from_source(source: dict[str, Any]) -> tuple[str, str]:
"""从 RPA/配置源推导快照预期身份二元组,供回调入库前预检。"""
code = str(source.get("source_code") or "").strip().upper()
site = str(source.get("site_id") or "").strip().upper()
warehouse = str(source.get("warehouse_id") or "").strip().upper()
return code, site, warehouse
return code, warehouse
def _rollback_orphan_inventory_snapshot(
@@ -748,8 +735,8 @@ def _validate_rpa_callback_gate(task: ShippingTask) -> dict[str, Any] | None:
def _validate_rpa_callback_success_identity(task: ShippingTask, payload: dict[str, Any]) -> dict[str, Any] | None:
"""
成功回调的身份契约:source/site/warehouse/run_no 必须与任务一致。
核心逻辑:仅 success 路径调用;skipped/failed 允许 RPA 缺身份字段。
成功回调的身份契约:Source 必须与任务一致;fixed Source 的 Warehouse 还须一致。
核心逻辑:动态 Source 的 Warehouse 由库存行按 Reservation + PN 解析,回调不预先裁决。
"""
callback_source = str(payload.get("source_code") or "").strip().upper()
task_source = str(task.inventory_source_code or "").strip().upper()
@@ -768,18 +755,13 @@ def _validate_rpa_callback_success_identity(task: ShippingTask, payload: dict[st
data=serialize_task_for_tool(task),
)
callback_site = str(payload.get("site_id") or "").strip().upper()
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
source = get_database_inventory_source(task_source)
is_fixed = source and str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed'
callback_wh = str(payload.get("warehouse_id") or "").strip().upper()
task_site = str(task.inventory_site_id or "").strip().upper()
task_wh = str(task.inventory_warehouse_id or "").strip().upper()
if not callback_site or callback_site != task_site:
return tool_response(
status="failed",
task=task,
message="RPA 回调 site_id 与任务库存源不一致,已拒绝入库",
data=serialize_task_for_tool(task),
)
if not callback_wh or callback_wh != task_wh:
if is_fixed and (not callback_wh or callback_wh != task_wh):
return tool_response(
status="failed",
task=task,
@@ -853,9 +835,9 @@ def _resolve_batch_callback_source(
source_code = str(item.get("source_code") or "").strip().upper()
if not source_code:
return None
from app.services.shipping_notice.inventory_sources import get_inventory_source
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
return get_inventory_source(source_code)
return get_database_inventory_source(source_code)
def _batch_snapshot_verify_warehouse_id(
@@ -864,6 +846,8 @@ def _batch_snapshot_verify_warehouse_id(
item: dict[str, Any] | None = None,
) -> str | None:
"""推导批量快照入库前须校验的 Excel Warehouse ID。"""
if str(source.get('warehouse_resolution_mode') or '').lower() == 'inventory_match':
return None
if task:
warehouse_id = str(task.inventory_warehouse_id or "").strip().upper()
return warehouse_id or None
@@ -877,36 +861,21 @@ def _batch_snapshot_verify_warehouse_id(
def _validate_batch_callback_worker_identity(item: dict[str, Any], source: dict[str, Any]) -> str | None:
"""
校验批量回调 Worker 返回的四字段身份与启用配置一致。
核心逻辑:定时/无任务成功项必须显式携带 source/site/warehouse;动态库位源校验 allowed_warehouse_ids。
校验批量回调 Worker 返回的 Source/Warehouse 身份与启用配置一致。
核心逻辑:定时/无任务成功项必须显式携带 source/warehouse;动态仓接受库存文件返回的 Warehouse。
"""
from app.services.shipping_notice.inventory_sources import (
configured_allowed_warehouse_ids,
source_uses_dynamic_warehouse_id,
)
callback_source = str(item.get("source_code") or "").strip().upper()
callback_site = str(item.get("site_id") or "").strip().upper()
callback_wh = str(item.get("warehouse_id") or "").strip().upper()
if not callback_source:
return "source_code_missing"
if not callback_site:
return "site_id_missing"
if not callback_wh:
return "warehouse_id_missing"
cfg_source = str(source.get("source_code") or "").strip().upper()
cfg_site = str(source.get("site_id") or "").strip().upper()
cfg_wh = str(source.get("warehouse_id") or "").strip().upper()
cfg_wh = str(source.get("fixed_warehouse_id") or source.get("warehouse_id") or "").strip().upper()
if callback_source != cfg_source:
return "source_code_mismatch"
if callback_site != cfg_site:
return "site_id_mismatch"
if source_uses_dynamic_warehouse_id(source):
allowed = configured_allowed_warehouse_ids(source)
if allowed and callback_wh not in allowed:
return "warehouse_id_not_allowed"
if str(source.get('warehouse_resolution_mode') or '') == 'inventory_match':
return None
if callback_wh != cfg_wh:
@@ -916,10 +885,9 @@ def _validate_batch_callback_worker_identity(item: dict[str, Any], source: dict[
def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]:
"""
确认当前任务的库存 RPA 来源,并在门禁通过后继续触发库存导出。
确认当前任务的库存来源,并在门禁通过后等待库存文件可用。
【AI 触发时机】:当用户在库存源检查点(通常已先完成解析确认)选择 source_code 后调用。
兼容:存量任务若仍带 pending_parse_review_after_source,确认源后会回到 parse_review。
【AI 触发时机】:当用户完成解析确认并在库存源检查点选择 source_code 后调用。
"""
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
@@ -963,60 +931,22 @@ def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]:
{
"source_code": task.inventory_source_code,
"connector_type": task.inventory_connector_type,
"site_id": task.inventory_site_id,
"warehouse_id": task.inventory_warehouse_id,
"confirmed_by": confirmed_by or "integration_tool",
},
)
# 存量兼容:旧顺序先确认库存源时延后的低置信度解析复核。
if task_needs_parse_review(task):
step_payload = dict(task.step_payload_json or {})
step_payload.pop("pending_parse_review_after_source", None)
task.step_payload_json = step_payload
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
task.current_step = "step2_parse_confirm"
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message="库存源已确认,请继续确认解析结果。",
data=serialize_task_for_tool(task),
checkpoint=CP_PARSE_REVIEW,
stop_agent_turn=True,
)
apply_task_transition(task, TaskTransition.PARSED)
task.pending_human_reason = None
task.review_status = None
task.error_message = None
step_payload = dict(task.step_payload_json or {})
step_payload.pop("pending_parse_review_after_source", None)
task.step_payload_json = step_payload
task.current_step = "step3_inventory_prepare"
db.session.commit()
from app.services.shipping_notice.tool_common import auto_rpa_inventory_enabled
if (not task.inventory_lines_json) and auto_rpa_inventory_enabled():
rpa_result = ensure_inventory_via_rpa(task, mode=str(payload.get("mode") or "auto"))
rpa_status = str(rpa_result.get("status") or "").strip().lower()
if rpa_status in {"running", "ok"}:
return rpa_result
if rpa_status == "needs_human" and str(task.pending_human_reason or "").strip() == PH_RPA_PENDING:
return rpa_result
return tool_response(
status="ok",
task=task,
message="库存源已确认;自动获取库存暂未完成,请稍后重试或手动上传库存文件。",
data=serialize_task_for_tool(task),
checkpoint=CP_PARSE_OK,
)
return tool_response(
status="ok",
task=task,
message="库存源已确认。",
message="库存源已确认;将使用该来源已导出的有效库存文件。",
data=serialize_task_for_tool(task),
checkpoint=CP_PARSE_OK,
)
@@ -1577,7 +1507,28 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if link is None:
raise _RpaCallbackItemAbort("inventory_identity_mismatch")
lines, column_meta = ingest_inventory_file(ingest_path, move_to=None)
from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure
structure_check = validate_production_inventory_structure(
source_code=str(rpa_source['source_code']), path=ingest_path,
)
lines, column_meta = ingest_inventory_file(
ingest_path, move_to=None,
field_mapping=structure_check['field_mapping'], mapping_source='parsing_profile',
header_row_index=structure_check['header_row_index'], sheet_name=structure_check['sheet_name'],
)
column_meta.update({
'sheet_name': structure_check['sheet_name'],
'header_row_index': structure_check['header_row_index'],
'structure_validation': {
'level': structure_check['level'], 'difference': structure_check['difference'],
'warnings': structure_check['warnings'],
},
})
inv_file.schema_preview_json = {
**(inv_file.schema_preview_json or {}),
'structure_validation': column_meta['structure_validation'],
}
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
@@ -1598,6 +1549,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
"origin_file_path": str(path),
"inventory_file_no": inv_file.inventory_file_no,
"reused_existing_snapshot": not created_new,
"structure_validation": column_meta.get('structure_validation'),
},
)
_mark_inventory_rpa_run_no_consumed(task, run_no)
@@ -1606,7 +1558,6 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
lines,
column_meta=column_meta,
source="rpa_callback",
require_mapping_review=True,
event_type="inventory_rpa_ready",
commit=False,
)
@@ -1753,7 +1704,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
merged_item = _merge_batch_callback_item(payload, item)
source_code = str(merged_item.get("source_code") or "").strip().upper()
warehouse_id = str(merged_item.get("warehouse_id") or "").strip().upper()
site_id = str(merged_item.get("site_id") or "").strip().upper()
raw_status = _normalize_rpa_inventory_batch_item_status(merged_item)
task_no = str(merged_item.get("task_no") or "").strip()
task: ShippingTask | None = None
@@ -1762,7 +1712,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
if task is None:
failed.append({
"source_code": source_code,
"site_id": merged_item.get("site_id"),
"warehouse_id": warehouse_id,
"task_no": task_no,
"error": "task_not_found",
@@ -1775,7 +1724,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
if gate_resp is not None:
failed.append({
"source_code": source_code,
"site_id": merged_item.get("site_id"),
"warehouse_id": warehouse_id,
"task_no": task_no,
"error": gate_resp.get("message") or "inventory_source_gate_blocked",
@@ -1786,7 +1734,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
round_data = round_resp.get("data") if isinstance(round_resp.get("data"), dict) else {}
failed.append({
"source_code": source_code,
"site_id": merged_item.get("site_id"),
"warehouse_id": warehouse_id,
"task_no": task_no,
"error": round_data.get("run_no_error") or "run_no_invalid",
@@ -1797,7 +1744,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
_handle_rpa_inventory_skipped(task, merged_item, runtime, commit=False)
skipped.append({
"source_code": source_code,
"site_id": merged_item.get("site_id"),
"warehouse_id": warehouse_id,
"task_no": task_no,
"skip_reason": merged_item.get("skip_reason") or "skipped",
@@ -1807,7 +1753,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
_handle_rpa_inventory_failed(task, merged_item, runtime, commit=False)
failed.append({
"source_code": source_code,
"site_id": merged_item.get("site_id"),
"warehouse_id": warehouse_id,
"task_no": task_no,
"error_code": merged_item.get("error_code") or "rpa_export_failed",
@@ -1819,7 +1764,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
if not source:
error = {
"source_code": source_code,
"site_id": merged_item.get("site_id"),
"warehouse_id": warehouse_id,
"error": "unknown_or_disabled_source",
}
@@ -1841,7 +1785,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
if not path or not path.is_file():
failed.append({
"source_code": source_code,
"site_id": merged_item.get("site_id"),
"warehouse_id": warehouse_id,
"error": "file_missing",
})
@@ -1852,21 +1795,21 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
if gate_resp is not None:
failed.append({
"source_code": source_code,
"site_id": merged_item.get("site_id"),
"warehouse_id": warehouse_id,
"task_no": task_no,
"error": gate_resp.get("message") or "inventory_source_gate_blocked",
})
continue
if not inventory_identities_match(
task,
source_code=str(source.get("source_code") or ""),
site_id=str(source.get("site_id") or ""),
warehouse_id=str(source.get("warehouse_id") or ""),
if (
str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed'
and not inventory_identities_match(
task,
source_code=str(source.get("source_code") or ""),
warehouse_id=warehouse_id,
)
):
failed.append({
"source_code": source_code,
"site_id": merged_item.get("site_id"),
"warehouse_id": warehouse_id,
"task_no": task_no,
"error": "inventory_identity_mismatch",
@@ -1877,7 +1820,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
if identity_error:
failed.append({
"source_code": source_code,
"site_id": merged_item.get("site_id"),
"warehouse_id": warehouse_id,
"error": identity_error,
})
@@ -1916,25 +1858,27 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
):
item_orphan_path = str(inv_file.storage_path)
from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure
ingest_path = _snapshot_ingest_path(inv_file)
structure_check = validate_production_inventory_structure(
source_code=source_code, path=ingest_path,
)
created_entry = {
"inventory_file_no": inv_file.inventory_file_no,
"source_code": inv_file.source_code or source_code,
"site_id": inv_file.site_id or merged_item.get("site_id"),
"warehouse_id": inv_file.warehouse_id or warehouse_id,
"reused_existing_snapshot": not created_new,
"structure_validation": {
"level": structure_check["level"],
"difference": structure_check["difference"],
},
}
created.append(created_entry)
if item_orphan_path:
batch_new_storage_paths.append(item_orphan_path)
if task_no and task:
if not inventory_identities_match(
task,
source_code=inv_file.source_code,
site_id=inv_file.site_id,
warehouse_id=inv_file.warehouse_id,
):
raise _RpaCallbackItemAbort("inventory_identity_mismatch")
link = link_snapshot_to_task(
task,
inv_file,
@@ -1943,15 +1887,26 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
)
if link is None:
raise _RpaCallbackItemAbort("inventory_identity_mismatch")
ingest_path = _snapshot_ingest_path(inv_file)
lines, column_meta = ingest_inventory_file(ingest_path, move_to=None)
lines, column_meta = ingest_inventory_file(
ingest_path, move_to=None,
field_mapping=structure_check['field_mapping'], mapping_source='parsing_profile',
header_row_index=structure_check['header_row_index'], sheet_name=structure_check['sheet_name'],
)
column_meta.update({
'sheet_name': structure_check['sheet_name'],
'header_row_index': structure_check['header_row_index'],
'structure_validation': created_entry['structure_validation'],
})
inv_file.schema_preview_json = {
**(inv_file.schema_preview_json or {}),
'structure_validation': column_meta['structure_validation'],
}
if lines and task.process_status not in {"uploaded", "completed", "closed", "rejected"}:
inventory_loaded_response(
task,
lines,
column_meta=column_meta,
source="rpa_batch_callback",
require_mapping_review=True,
event_type="inventory_rpa_ready",
commit=False,
)
@@ -1982,7 +1937,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
created.pop()
failed.append({
"source_code": source_code,
"site_id": merged_item.get("site_id"),
"warehouse_id": warehouse_id,
"task_no": task_no or None,
"error": abort.error,
@@ -2000,7 +1954,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
created.pop()
failed.append({
"source_code": source_code,
"site_id": merged_item.get("site_id"),
"warehouse_id": warehouse_id,
"task_no": task_no,
"error": str(exc)[:200] or "batch_ingest_failed",
@@ -2009,7 +1962,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
elif raw_status == "skipped":
skipped.append({
"source_code": source_code,
"site_id": merged_item.get("site_id"),
"warehouse_id": warehouse_id,
"skip_reason": merged_item.get("skip_reason") or "skipped",
"message": merged_item.get("message") or merged_item.get("error_message") or "",
@@ -2017,7 +1969,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
else:
failed.append({
"source_code": str(source.get("source_code") or source_code),
"site_id": source.get("site_id"),
"warehouse_id": source.get("warehouse_id"),
"error_code": merged_item.get("error_code") or "rpa_export_failed",
"error": merged_item.get("error_message"),
@@ -2147,13 +2098,16 @@ def _validate_repair_inventory_snapshot(
return "snapshot_expired"
if not is_inventory_source_stable(task):
return "inventory_source_unstable"
if not inventory_identities_match(
task,
source_code=inv_file.source_code,
site_id=inv_file.site_id,
warehouse_id=inv_file.warehouse_id,
):
return "inventory_identity_mismatch"
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
source = get_database_inventory_source(task.inventory_source_code)
if source and str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed':
if not inventory_identities_match(
task,
source_code=inv_file.source_code,
warehouse_id=inv_file.warehouse_id,
):
return "inventory_identity_mismatch"
return None
@@ -2,7 +2,7 @@
services/shipping_notice/inventory_snapshot.py
用途:解析库存 Excel/文本快照,抽取表头、库存行与字段对齐预览,为库存映射与匹配流程提供基础数据。
依赖:openpyxl、reservation_id、Flask current_app 配置、Path 文件操作。
依赖:openpyxl、xlrd、reservation_id、Flask current_app 配置、Path 文件操作。
逻辑:由 inventory_workflow、inventory_mapping_workflow 等上游模块调用本文件读取库存附件,再把解析结果传给字段映射确认和库存匹配链路。
"""
@@ -65,6 +65,11 @@ DEFAULT_COLUMN_MAP = {
"Qty": "qty",
"qty": "qty",
"数量": "qty",
# Warehouse:动态 Source 必须保留行级 Warehouse,不能只记录整个文件的单一值。
"Warehouse ID": "warehouse_id",
"Warehouse": "warehouse_id",
"Warehouse Code": "warehouse_id",
"WH ID": "warehouse_id",
# ODM
"ODM ID": "odm_id",
"ODM Id": "odm_id",
@@ -121,7 +126,7 @@ def _map_header(header: str, col_map: dict[str, str]) -> str | None:
def _resolve_inventory_columns(headers: list[str], col_map: dict[str, str]) -> dict[str, int | None]:
idx_part_number = idx_aws_part_number = idx_reservation = idx_available = idx_qty = idx_odm = None
idx_part_number = idx_aws_part_number = idx_reservation = idx_available = idx_qty = idx_odm = idx_warehouse = None
for i, h in enumerate(headers):
mapped = _map_header(h, col_map)
if mapped == "part_number" and idx_part_number is None:
@@ -136,6 +141,8 @@ def _resolve_inventory_columns(headers: list[str], col_map: dict[str, str]) -> d
idx_qty = i
elif mapped == "odm_id" and idx_odm is None:
idx_odm = i
elif mapped == "warehouse_id" and idx_warehouse is None:
idx_warehouse = i
# 若 reservation 列未命中,按 AWS 模板常见列名再试
if idx_reservation is None:
@@ -152,6 +159,7 @@ def _resolve_inventory_columns(headers: list[str], col_map: dict[str, str]) -> d
"available_qty": idx_available,
"qty": idx_qty,
"odm_id": idx_odm,
"warehouse_id": idx_warehouse,
}
@@ -174,7 +182,38 @@ def _normalize_inventory_row(
*,
default_part_number_index: int | None = None,
default_qty_index: int = 1,
configured_mapping: bool = False,
) -> dict[str, Any] | None:
# Published profiles use inventory field IDs as row keys. Field purpose and
# value type come from the user-maintained catalog, never from a fixed code.
if configured_mapping and columns and all(str(field_id).isdigit() for field_id in columns):
from app.models import ShippingInventoryField
field_ids = {int(field_id) for field_id in columns if str(field_id).isdigit()}
catalog = {
str(item.id): item
for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all()
}
parsed = {
field_id: _cell(row, index)
for field_id, index in columns.items()
if index is not None and _cell(row, index) not in (None, '')
}
match_fields = [field_id for field_id, item in catalog.items() if item.usage_type == 'match_identity']
if not any(str(parsed.get(field_id) or '').strip() for field_id in match_fields):
return None
for field_id, value in list(parsed.items()):
field = catalog.get(field_id)
if field is None:
continue
if field.value_type in {'integer', 'decimal'}:
parsed[field_id] = _parse_qty(value)
elif field.value_type == 'date':
parsed[field_id] = value.isoformat() if hasattr(value, 'isoformat') else str(value).strip()
else:
parsed[field_id] = str(value).strip()
return parsed
idx_part_number = columns.get("part_number")
if idx_part_number is None:
idx_part_number = default_part_number_index
@@ -227,11 +266,16 @@ def _normalize_inventory_row(
odm_id = str(_cell(row, idx_odm) or "").strip()
if odm_id:
parsed["odm_id"] = odm_id
idx_warehouse = columns.get("warehouse_id")
if idx_warehouse is not None:
warehouse_id = str(_cell(row, idx_warehouse) or "").strip().upper()
if warehouse_id:
parsed["warehouse_id"] = warehouse_id
return parsed
def _score_header_candidate(cells: list[Any]) -> int:
"""Score how likely a row is the inventory column header (not a title row)."""
"""按通用表格结构给候选表头评分,固定库存词典只作为旧临时链加分项。"""
headers = [str(c or "").strip() for c in cells]
non_empty = [h for h in headers if h]
if len(non_empty) < 2:
@@ -244,7 +288,9 @@ def _score_header_candidate(cells: list[Any]) -> int:
if mapped:
mapped_fields.add(mapped)
score = len(mapped_fields) * 10
text_cells = sum(1 for value in non_empty if isinstance(value, str) and str(value).strip())
unique_cells = len({str(value).strip().casefold() for value in non_empty})
score = len(non_empty) + text_cells + unique_cells + len(mapped_fields) * 10
if "part_number" in mapped_fields and ("available_qty" in mapped_fields or "qty" in mapped_fields):
score += 30
return score
@@ -262,8 +308,10 @@ def find_inventory_header_row_index(rows: list[list[Any]], *, max_scan: int = 40
return best_idx if best_score > 0 else 0
def _load_excel_rows(path: Path, *, max_rows: int | None = None) -> tuple[list[list[Any]], int]:
"""Load worksheet or CSV rows; returns (rows, total_row_count_hint)."""
def _load_excel_rows(
path: Path, *, max_rows: int | None = None, sheet_name: str | None = None,
) -> tuple[list[list[Any]], int]:
"""Load configured worksheet or CSV rows; returns rows and total row count hint."""
suffix = path.suffix.lower()
if suffix == ".csv":
from app.services.shipping_notice.inventory_file_identity import load_inventory_csv_rows
@@ -275,9 +323,32 @@ def _load_excel_rows(path: Path, *, max_rows: int | None = None) -> tuple[list[l
total = len(rows)
return rows, int(total)
if suffix == ".xls":
import xlrd
book = xlrd.open_workbook(filename=str(path), on_demand=True)
try:
if sheet_name:
try:
sheet = book.sheet_by_name(sheet_name)
except xlrd.biffh.XLRDError as exc:
raise ValueError(f'Inventory worksheet not found: {sheet_name}') from exc
else:
sheet = book.sheet_by_index(0)
row_limit = sheet.nrows if max_rows is None else min(sheet.nrows, max_rows)
rows = [
[_xls_cell_value(book, sheet.cell(row_index, column_index)) for column_index in range(sheet.ncols)]
for row_index in range(row_limit)
]
return rows, int(sheet.nrows)
finally:
book.release_resources()
wb = load_workbook(filename=str(path), data_only=True, read_only=True)
try:
ws = wb.active
if sheet_name and sheet_name not in wb.sheetnames:
raise ValueError(f'Inventory worksheet not found: {sheet_name}')
ws = wb[sheet_name] if sheet_name else wb.active
rows: list[list[Any]] = []
for i, row in enumerate(ws.iter_rows(values_only=True)):
if max_rows is not None and i >= max_rows:
@@ -289,6 +360,19 @@ def _load_excel_rows(path: Path, *, max_rows: int | None = None) -> tuple[list[l
return rows, int(total)
def _xls_cell_value(book: Any, cell: Any) -> Any:
"""将 xlrd 单元格值规范为与 openpyxl 接近的 Python 值。"""
import xlrd
if cell.ctype == xlrd.XL_CELL_EMPTY:
return None
if cell.ctype == xlrd.XL_CELL_DATE:
return xlrd.xldate_as_datetime(cell.value, book.datemode)
if cell.ctype == xlrd.XL_CELL_NUMBER and float(cell.value).is_integer():
return int(cell.value)
return cell.value
def _rows_from_table_text(raw_text: str) -> list[list[str]]:
rows: list[list[str]] = []
for line in raw_text.splitlines():
@@ -315,10 +399,8 @@ def describe_inventory_columns(
*,
field_mapping: dict[str, str] | None = None,
mapping_source: str = "rules",
llm_match_rule: str | None = None,
llm_match_key: list[str] | None = None,
) -> dict[str, Any]:
"""生成库存列映射与匹配规则的可读描述,供字段对齐人审展示。"""
"""根据规则建议或已发布方案生成库存栏位与匹配规则的审计描述。"""
if field_mapping:
from app.services.shipping_notice.inventory_mapping import build_column_meta_from_mapping
@@ -326,8 +408,6 @@ def describe_inventory_columns(
headers,
field_mapping,
mapping_source=mapping_source,
llm_match_rule=llm_match_rule,
llm_match_key=llm_match_key,
)
from app.services.shipping_notice.match_rule_desc import resolve_match_rule
@@ -360,11 +440,7 @@ def describe_inventory_columns(
if qty_source:
inferred_mapping["available_qty"] = qty_source
match_rule, match_key, match_rule_source = resolve_match_rule(
inferred_mapping,
llm_match_rule=llm_match_rule,
llm_match_key=llm_match_key,
)
match_rule, match_key, match_rule_source = resolve_match_rule(inferred_mapping)
return {
"headers": [str(h or "").strip() for h in headers],
@@ -497,7 +573,9 @@ def parse_inventory_rows(
else:
col_map = _column_map()
columns = _resolve_inventory_columns(headers, col_map)
has_header = columns["part_number"] is not None or columns["available_qty"] is not None or columns["qty"] is not None
has_header = any(index is not None for index in columns.values()) if field_mapping else (
columns.get("part_number") is not None or columns.get("available_qty") is not None or columns.get("qty") is not None
)
if not has_header and headers and not field_mapping:
has_header = any(_map_header(h, _column_map()) for h in headers)
@@ -505,7 +583,7 @@ def parse_inventory_rows(
for row in data_rows:
if not row:
continue
parsed = _normalize_inventory_row(list(row), columns)
parsed = _normalize_inventory_row(list(row), columns, configured_mapping=bool(field_mapping))
if parsed:
lines.append(parsed)
return lines
@@ -540,7 +618,7 @@ def parse_inventory_text(
else:
col_map = _column_map()
columns = _resolve_inventory_columns(header, col_map)
has_header = columns["part_number"] is not None or any(_map_header(h, col_map) for h in header)
has_header = columns.get("part_number") is not None or any(_map_header(h, col_map) for h in header)
column_meta = describe_inventory_columns(header) if has_header else empty_meta
data_rows: list[list[Any]] = rows[1:] if has_header else rows
@@ -591,7 +669,6 @@ def read_inventory_schema_preview(
"aws_part_number": "AWS Sku / AWS 料号(可选)",
"reservation_id": "Reservation ID / COM ID(必填)",
"available_qty": "可用数量 / Qty Available / Qty",
"match_rule": "匹配规则说明(LLM 根据表头与订单字段生成,写入 map_json.match_rule)",
},
"row_count_hint": data_row_count,
}
@@ -603,15 +680,14 @@ def parse_inventory_excel_with_meta(
field_mapping: dict[str, str] | None = None,
mapping_source: str = "rules",
header_row_index: int | None = None,
llm_match_rule: str | None = None,
llm_match_key: list[str] | None = None,
sheet_name: str | None = None,
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""
解析库存 Excel 并返回标准化行与 column_meta。
核心逻辑:定位表头行 → describe_inventory_columns → parse_inventory_rows。
核心逻辑:选择工作表 → 定位表头行 → describe_inventory_columns → parse_inventory_rows。
"""
rows, _total = _load_excel_rows(path)
rows, _total = _load_excel_rows(path, sheet_name=sheet_name)
if not rows:
return [], {"headers": [], "mapping": {}, "match_key": ["part_number", "reservation_id"]}
@@ -640,10 +716,9 @@ def parse_inventory_excel_with_meta(
headers,
field_mapping=field_mapping,
mapping_source=mapping_source if field_mapping else "rules",
llm_match_rule=llm_match_rule,
llm_match_key=llm_match_key,
)
meta["header_row_index"] = header_idx + 1
meta["sheet_name"] = sheet_name
return lines, meta
@@ -659,6 +734,8 @@ def ingest_inventory_file(
move_to: Path | None = None,
field_mapping: dict[str, str] | None = None,
mapping_source: str = "rules",
header_row_index: int | None = None,
sheet_name: str | None = None,
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""
解析库存文件并可选择移动至 processed 目录(RPA drop 摄入用)。
@@ -670,6 +747,8 @@ def ingest_inventory_file(
source_path,
field_mapping=field_mapping,
mapping_source=mapping_source,
header_row_index=header_row_index,
sheet_name=sheet_name,
)
if move_to:
move_to.mkdir(parents=True, exist_ok=True)
@@ -71,33 +71,23 @@ def is_snapshot_fresh(inv_file: ShippingInventoryFile, *, now: datetime | None =
def find_latest_ready_snapshot(
source_code: str | None,
site_id: str | None,
warehouse_id: str | None = None,
) -> ShippingInventoryFile | None:
"""
查找指定 source/site/warehouse 最新 ready 且未过期的库存快照。
核心逻辑:库存身份须与任务正式库存源一致;site_id 与 warehouse_id 分别匹配,禁止混用。
查找指定 Source 的最新 ready 且未过期库存快照。
核心逻辑:固定 Source 限定 Warehouse;动态 Source 先复用文件,再由 reservation + PN 匹配确定 Warehouse。
"""
code = str(source_code or "").strip().upper()
site = str(site_id or "").strip().upper()
warehouse = str(warehouse_id or "").strip().upper()
if not code:
return None
if not site and not warehouse:
return None
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:
@@ -110,24 +100,21 @@ def find_ready_rpa_inventory_snapshot(
*,
rpa_run_no: str,
source_code: str,
site_id: str,
warehouse_id: str,
) -> ShippingInventoryFile | None:
"""
按 RPA 轮次 + 四字段身份查找已入库 ready 快照。
按 RPA 轮次 + Source/Warehouse 身份查找已入库 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:
if not run_no or not code 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,
)
@@ -162,13 +149,11 @@ def get_or_create_rpa_inventory_snapshot(
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:
if run_no and code and warehouse:
existing = find_ready_rpa_inventory_snapshot(
rpa_run_no=run_no,
source_code=code,
site_id=site,
warehouse_id=warehouse,
)
if existing:
@@ -202,11 +187,10 @@ def get_or_create_rpa_inventory_snapshot(
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:
if run_no and code and warehouse:
existing = find_ready_rpa_inventory_snapshot(
rpa_run_no=run_no,
source_code=code,
site_id=site,
warehouse_id=warehouse,
)
if existing:
@@ -291,12 +275,11 @@ def create_inventory_snapshot_from_rpa(
exported_at = datetime.utcnow()
inventory_file_no = generate_inventory_file_no()
source_code = str(source.get("source_code") or "").strip().upper()
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 = export_warehouse_id
warehouse_code = warehouse_id or configured_site_id
warehouse_code = warehouse_id
excel_verified = False
if success:
@@ -334,7 +317,7 @@ 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
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
inv_file = ShippingInventoryFile(
inventory_file_no=inventory_file_no,
@@ -345,10 +328,10 @@ def create_inventory_snapshot_from_rpa(
schema_preview_json=preview,
share_mode=share_mode or ("task_only" if trigger_type in {"on_demand", "manual_upload"} else "warehouse_pool"),
line_count=0,
# 动态 Source 的文件可含多个 Warehouse;具体 Warehouse 在 link 时从库存行解析。
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(),
source_config_version=inventory_sources_runtime_version(),
identity_status="pending" if success else "unknown",
source_code=source_code or None,
source_type=str(source.get("connector_type") or "").strip() or None,
@@ -361,7 +344,6 @@ def create_inventory_snapshot_from_rpa(
"query": source.get("query"),
"navigation": source.get("navigation"),
"parameters": source.get("parameters"),
"site_id": configured_site_id or None,
"export_warehouse_id": export_warehouse_id,
"excel_warehouse_id": excel_warehouse_id or None,
"warehouse_id_source": (
@@ -419,6 +401,32 @@ def link_snapshot_to_task(
if not is_snapshot_fresh(inv_file):
return None
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
source = get_database_inventory_source(task.inventory_source_code)
if source is None:
return None
resolved_warehouse_id = inv_file.warehouse_id
if str(source.get('warehouse_resolution_mode') or '').strip().lower() == 'inventory_match':
from app.services.shipping_notice.inventory_warehouse_resolution import resolve_dynamic_warehouse
lines = [row for row in (inv_file.inventory_lines_json or []) if isinstance(row, dict)]
if not lines and Path(inv_file.storage_path).is_file():
from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file
lines, _column_meta = parse_inventory_snapshot_file(inv_file)
inv_file.inventory_lines_json = lines
inv_file.line_count = len(lines)
resolution = resolve_dynamic_warehouse(
task=task,
inventory_lines=lines,
fallback_warehouse_id=inv_file.warehouse_id,
)
if not resolution.warehouse_id:
inv_file.identity_status = resolution.reason
return None
resolved_warehouse_id = resolution.warehouse_id
age_seconds: int | None = None
if inv_file.exported_at:
age_seconds = max(int((datetime.utcnow() - inv_file.exported_at).total_seconds()), 0)
@@ -428,25 +436,27 @@ def link_snapshot_to_task(
identity_ok = inventory_identities_match(
task,
source_code=inv_file.source_code,
site_id=inv_file.site_id,
warehouse_id=inv_file.warehouse_id,
warehouse_id=resolved_warehouse_id,
)
inv_file.identity_status = "verified" if identity_ok else "mismatch"
if not identity_ok:
return None
# 动态 Source 不预维护 Warehouse;以已校验库存文件的 Warehouse 固化本任务身份。
if not task.inventory_warehouse_id:
task.inventory_warehouse_id = resolved_warehouse_id
link = replace_task_inventory_link(task, inv_file, role=role)
link.link_reason = reason
link.matched_warehouse_id = inv_file.warehouse_id
link.matched_warehouse_id = resolved_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 {}),
"source_code": inv_file.source_code,
"warehouse_id": inv_file.warehouse_id,
"warehouse_id": resolved_warehouse_id,
"exported_at": inv_file.exported_at.isoformat() if inv_file.exported_at else None,
"expires_at": inv_file.expires_at.isoformat() if inv_file.expires_at else None,
"inventory_file_no": inv_file.inventory_file_no,
@@ -461,6 +471,7 @@ def link_snapshot_to_task(
"inventory_file_no": inv_file.inventory_file_no,
"link_reason": reason,
"snapshot_age_seconds": age_seconds,
"warehouse_id": resolved_warehouse_id,
**(audit_payload or {}),
},
)
@@ -484,7 +495,7 @@ def serialize_inventory_snapshot_link(task: ShippingTask) -> dict[str, Any] | No
return {
"inventory_file_no": inv_file.inventory_file_no,
"source_code": inv_file.source_code,
"warehouse_id": inv_file.warehouse_id,
"warehouse_id": link.matched_warehouse_id or inv_file.warehouse_id,
"warehouse_code": inv_file.warehouse_code,
"exported_at": inv_file.exported_at.isoformat() if inv_file.exported_at else None,
"expires_at": inv_file.expires_at.isoformat() if inv_file.expires_at else None,
@@ -2,7 +2,7 @@
services/shipping_notice/inventory_source_gate.py
用途:库存源稳定性门禁、独立字段写入与路由指纹管理。
依赖:inventory_source_rules、inventory_sources、models.ShippingTask、core.errors。
依赖:inventory_source_rules、inventory_source_repository、models.ShippingTask、core.errors。
逻辑:parse_notice 先裁决线索;解析确认通过后未稳定才进入 inventory_source_review;
RPA/库存/匹配/导出统一经本模块硬门禁,禁止散落判断。
"""
@@ -14,15 +14,18 @@ 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,
resolve_ambiguous_source_from_ready_snapshots,
)
from app.services.shipping_notice.inventory_source_repository import (
get_database_inventory_source,
inventory_sources_runtime_version,
)
from app.services.shipping_notice.inventory_sources import get_inventory_source, get_inventory_sources_config_version
STABLE_INVENTORY_SOURCE_STATUSES = frozenset({"resolved", "user_confirmed"})
@@ -40,9 +43,9 @@ INVENTORY_SOURCE_ERROR_CODES = {
def _inventory_source_config_current(task: ShippingTask) -> bool:
"""任务上记录的库存源配置版本须与当前 YAML 版本一致。"""
"""任务上记录的库存源配置版本须与当前数据库版本一致。"""
stored = str(task.inventory_source_config_version or "").strip()
current = get_inventory_sources_config_version()
current = inventory_sources_runtime_version()
if not stored:
return False
return stored == current
@@ -51,7 +54,7 @@ def _inventory_source_config_current(task: ShippingTask) -> bool:
def is_inventory_source_stable(task: ShippingTask) -> bool:
"""
判断任务库存源是否稳定,可供后续库存/RPA/匹配流程使用。
核心逻辑:独立字段齐全、配置版本一致、与启用配置身份一致;status 须为 resolved 或 user_confirmed。
核心逻辑:Source、Driver 与数据库配置一致即可稳定;动态 Warehouse 在库存行匹配后再确定。
"""
status = str(task.inventory_source_status or "").strip()
if status not in STABLE_INVENTORY_SOURCE_STATUSES:
@@ -64,22 +67,16 @@ def is_inventory_source_stable(task: ShippingTask) -> bool:
connector_type = str(task.inventory_connector_type or "").strip()
if not connector_type:
return False
source = get_inventory_source(code)
source = get_database_inventory_source(code)
if not source:
return False
if connector_type != str(source.get("connector_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),
):
mode = str(source.get('warehouse_resolution_mode') or '').strip().lower()
fixed_warehouse = str(source.get('fixed_warehouse_id') or '').strip().upper()
task_warehouse = str(task.inventory_warehouse_id or '').strip().upper()
if mode == 'fixed' and task_warehouse != fixed_warehouse:
return False
fingerprint = str(task.inventory_routing_fingerprint or "").strip()
@@ -105,7 +102,7 @@ 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()
return stored != inventory_sources_runtime_version()
def apply_destination_fields(task: ShippingTask, context: dict[str, Any]) -> None:
@@ -136,7 +133,6 @@ def _adjudication_from_stable_task(task: ShippingTask) -> InventorySourceAdjudic
method=str(task.inventory_source_method or "").strip() or None,
source_code=str(task.inventory_source_code or "").strip().upper() or None,
connector_type=str(task.inventory_connector_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()
@@ -162,12 +158,11 @@ def apply_inventory_source_adjudication(
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()
task.inventory_source_config_version = adjudication.config_version or inventory_sources_runtime_version()
if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code:
task.inventory_source_code = adjudication.source_code
task.inventory_connector_type = adjudication.connector_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
@@ -175,7 +170,6 @@ def apply_inventory_source_adjudication(
elif adjudication.status not in STABLE_INVENTORY_SOURCE_STATUSES:
task.inventory_source_code = None
task.inventory_connector_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)
@@ -194,9 +188,9 @@ def apply_inventory_source_adjudication(
"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
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
rpa_source = build_task_rpa_inventory_source(task)
rpa_source = task_rpa_inventory_source(task)
if rpa_source:
payload["rpa_inventory_source"] = rpa_source
else:
@@ -222,6 +216,9 @@ def adjudicate_and_apply_inventory_source(task: ShippingTask) -> InventorySource
return _adjudication_from_stable_task(task)
adjudication = adjudicate_inventory_source(task)
# Multiple routing candidates may be resolved only from already-exported
# snapshots; this never starts RPA or uses inventory quantity as a signal.
adjudication = resolve_ambiguous_source_from_ready_snapshots(task, adjudication)
if (
str(task.inventory_source_status or "").strip() == "user_confirmed"
and adjudication.status == "resolved"
@@ -234,7 +231,6 @@ def adjudicate_and_apply_inventory_source(task: ShippingTask) -> InventorySource
method="user_confirmed",
source_code=adjudication.source_code,
connector_type=adjudication.connector_type,
site_id=adjudication.site_id,
warehouse_id=adjudication.warehouse_id,
config_version=adjudication.config_version,
routing_fingerprint=adjudication.routing_fingerprint,
@@ -247,35 +243,17 @@ def adjudicate_and_apply_inventory_source(task: ShippingTask) -> InventorySource
return adjudication
def task_needs_parse_review(task: ShippingTask) -> bool:
"""
判断任务是否仍需完成低置信度解析人工确认。
核心逻辑:仅认显式标记——review/pending 为 parse_review / low_confidence,
或存量 pending_parse_review_after_source。禁止仅凭 parse_confidence 兜底,
否则「解析已确认 → 再确认库存源」会被误判回解析复核。
"""
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 {}
return bool(payload.get("pending_parse_review_after_source"))
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 展示确认按钮。
mark_pending_parse_review 仅用于存量/兼容路径(旧顺序先源后解析);
新路径应先完成 parse_review,再进入本检查点,通常不传 True。
解析复核必须在进入本检查点前完成,不保存延后复核标记。
"""
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
@@ -294,8 +272,6 @@ def transition_task_to_inventory_source_review(
"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
@@ -304,16 +280,11 @@ def ensure_inventory_source_review_state(task: ShippingTask) -> InventorySourceA
对已通过解析确认但库存源仍不稳定的任务,补做裁决并落库到 inventory_source_review。
【AI 触发时机】:confirm_parse / auto_progress / ensure_inventory 等入口发现门禁未通过时调用。
核心逻辑:新业务顺序是先解析后库存源;仅当仍检测到待解析复核(含存量延后标记)时,
才写入 pending_parse_review_after_source 以兼容旧任务。
核心逻辑:新业务顺序固定为先完成解析复核,再进入库存源确认。
"""
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),
)
transition_task_to_inventory_source_review(task, adjudication)
return adjudication
@@ -372,7 +343,6 @@ 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,
}
@@ -381,10 +351,9 @@ def inventory_identities_match(
task: ShippingTask,
*,
source_code: str | None,
site_id: str | None,
warehouse_id: str | None,
) -> bool:
"""校验库存文件/链接身份与任务正式库存源是否完全一致。"""
"""校验库存文件 Source;固定仓严格匹配,动态仓允许从库存文件中解析。"""
identity = task_inventory_identity(task)
if not is_inventory_source_stable(task):
return False
@@ -392,11 +361,8 @@ def inventory_identities_match(
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 ""):
if not file_wh:
return False
if not file_wh or file_wh != (identity["inventory_warehouse_id"] or ""):
return False
return True
expected = identity['inventory_warehouse_id']
return not expected or expected == file_wh
@@ -1,9 +1,9 @@
"""
services/shipping_notice/inventory_source_identity.py
用途:从库存源配置与订单路由上下文解析正式库存身份(source/site/warehouse)。
依赖:无业务模块反向依赖;normalize/match 工具在本文件内定义。
逻辑:裁决、门禁、RPA 与迁移回填统一调用本模块,禁止散落身份推导。
用途:校验库存源与 Warehouse 的两段式身份。
依赖:无业务模块反向依赖。
逻辑:路由阶段只确定 Source;fixed Source 立即确定 Warehouse,inventory_match Source 在库存行匹配后确定。
"""
from __future__ import annotations
@@ -14,143 +14,52 @@ 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()
"""将文本归一为可比较的路由 token。"""
return re.sub(r"[^A-Z0-9]+", " ", str(value or "").strip().upper()).strip()
def _matches_alias(candidate: str, alias: str) -> bool:
"""别名按词元匹配,避免短 token 误命中更长编码。"""
return _alias_token_match(normalize_destination(candidate), alias)
"""按完整词元匹配别名,避免短码误命中。"""
normalized = normalize_destination(alias)
return bool(normalized) and (normalize_destination(candidate) == normalized or normalized in normalize_destination(candidate).split())
@dataclass(frozen=True)
class ResolvedInventoryIdentity:
"""稳定库存源四元组中的站点/库位解析结果。"""
"""已确定的 Source 与可选 Warehouse 身份。"""
source_code: str
connector_type: str
site_id: str
warehouse_id: str
warehouse_id: str | None
@dataclass(frozen=True)
class InventoryIdentityResolution:
"""身份解析结果;失败时 reason 说明原因,ambiguous 时带 warehouse 候选。"""
"""身份解析结果;动态 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:
def resolve_inventory_source_identity(source: dict[str, Any], _context: dict[str, Any]) -> InventoryIdentityResolution:
"""解析 Source;仅 fixed 模式从配置直接提供 Warehouse。"""
code = str(source.get('source_code') or '').strip().upper()
connector = str(source.get('connector_type') or '').strip().lower()
mode = str(source.get('warehouse_resolution_mode') or '').strip().lower()
if not code or connector not in {'dbs', 'crane'} or mode not in {'fixed', 'inventory_match'}:
return InventoryIdentityResolution(False, reason='source_incomplete')
warehouse = str(source.get('fixed_warehouse_id') or '').strip().upper() or None
if mode == 'fixed' and not warehouse:
return InventoryIdentityResolution(False, reason='fixed_warehouse_missing')
return InventoryIdentityResolution(True, ResolvedInventoryIdentity(code, connector, warehouse))
def identity_matches_config(source: dict[str, Any], *, warehouse_id: str | None, context: dict[str, Any] | None = None) -> bool:
"""验证任务 Warehouse 与 Source 策略一致;动态仓由已匹配库存行决定。"""
resolution = resolve_inventory_source_identity(source, context or {})
if not resolution.ok or not resolution.identity:
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(),
connector_type=str(source.get("connector_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()
connector_type = str(source.get("connector_type") or "").strip()
if not source_code or not connector_type:
return InventoryIdentityResolution(ok=False, reason="source_incomplete")
if connector_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,
connector_type=connector_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
connector_type = str(source.get("connector_type") or "").strip()
if connector_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
expected = resolution.identity.warehouse_id
actual = str(warehouse_id or '').strip().upper() or None
return bool(actual) and (expected is None or expected == actual)
@@ -0,0 +1,148 @@
"""
services/shipping_notice/inventory_source_repository.py
用途:提供库存源主数据的最小一致性校验和受控读取入口。
依赖:models.ShippingInventorySource/ShippingRpaProfile、core.errors.ValidationError。
逻辑:管理服务保存 Source 前调用本模块校验 Source 与 Profile 的 Driver 一致;后续库存路由、排程与手动刷新统一复用读取入口。
"""
from __future__ import annotations
from app.core.errors import ValidationError
from app.models import ShippingInventorySource, ShippingRpaProfile
def validate_source_profile(source: ShippingInventorySource, profile: ShippingRpaProfile) -> None:
"""
校验库存源引用的 RPA Profile 与其 Driver 类型一致。
Args:
source: 待保存的库存源;connector_type 只能为 dbs 或 crane。
profile: Source 绑定的 RPA Profile。
Raises:
ValidationError: Source/Profile Driver 不一致或出现未知 Driver。
"""
source_type = str(source.connector_type or '').strip().lower()
profile_type = str(profile.connector_type or '').strip().lower()
if source_type not in {'dbs', 'crane'} or profile_type not in {'dbs', 'crane'}:
raise ValidationError('Unsupported inventory connector type', code='SHIPPING.INVENTORY_CONNECTOR_INVALID')
if source_type != profile_type:
raise ValidationError(
'Inventory Source connector_type must match its RPA Profile',
code='SHIPPING.INVENTORY_PROFILE_CONNECTOR_MISMATCH',
)
def get_database_inventory_source(source_code: str, *, enabled_only: bool = True) -> dict | None:
"""
按业务编码读取数据库库存源及其非敏感 RPA 配置。
Args:
source_code: 稳定库存源编码。
enabled_only: 为 True 时仅返回启用 Source 和 Profile。
Returns:
dict | None: 不含任何凭据密文/明文的 Source、Profile 与操作配置快照。
"""
code = str(source_code or '').strip().upper()
if not code:
return None
source = ShippingInventorySource.query.filter_by(source_code=code).first()
if source is None or (enabled_only and not source.enabled):
return None
profile = source.rpa_profile
if profile is None or (enabled_only and not profile.enabled):
return None
login_config = dict(profile.login_config_json or {'auth_mode': 'password'})
if login_config.get('auth_mode') != 'password':
return None
# Source owns report navigation and business query values. Driver behavior is
# code/template-owned and never travels through a login connection profile.
source_navigation = dict(source.report_path_json or {}) if source.connector_type == 'dbs' else {}
return {
'source_code': source.source_code,
'display_name': source.display_name,
'connector_type': source.connector_type,
'warehouse_resolution_mode': source.warehouse_resolution_mode,
'fixed_warehouse_id': source.fixed_warehouse_id,
# Worker 兼容字段:fixed Source 可直接作为导出目标;动态 Source 保持为空。
'warehouse_id': source.fixed_warehouse_id,
'snapshot_ttl_seconds': source.snapshot_ttl_seconds,
'config_version': source.config_version,
'parsing_profile_id': source.parsing_profile_id,
'excel_template_id': source.excel_template_id,
'report_path_json': dict(source.report_path_json or {}),
'query_parameters_json': list(source.query_parameters_json or []),
'match_aliases_json': list(source.match_aliases_json or []),
'rpa_profile_code': profile.profile_code,
# 与既有 worker 契约的适配层:不再从 Profile 取报表路径或查询参数。
'navigation': source_navigation,
'parameters': list(source.query_parameters_json or []),
'query': {},
'login_url': profile.login_url,
'login_config': login_config,
}
def get_rpa_trigger_inventory_source(source_code: str, *, enabled_only: bool = True) -> dict | None:
"""构造仅投递给 RPA worker 的 Source 快照;配置测试可显式读取停用站点。"""
source_config = get_database_inventory_source(source_code, enabled_only=enabled_only)
if source_config is None:
return None
source = ShippingInventorySource.query.filter_by(source_code=source_config['source_code']).first()
profile = source.rpa_profile if source else None
if profile is None or (enabled_only and not profile.enabled):
return None
result = dict(source_config)
result['credential_envelope'] = {
'username_ciphertext': profile.username_ciphertext,
'password_ciphertext': profile.password_ciphertext,
}
return result
def list_database_inventory_sources(*, enabled_only: bool = True) -> list[dict]:
"""列出数据库库存源的非敏感运行时快照,供路由和排程按 Source 选择。"""
query = ShippingInventorySource.query.order_by(ShippingInventorySource.source_code)
if enabled_only:
query = query.filter_by(enabled=True)
result = []
for source in query.all():
item = get_database_inventory_source(source.source_code, enabled_only=enabled_only)
if item:
result.append(item)
return result
def inventory_sources_runtime_version() -> str:
"""计算启用库存源与其 Profile 配置的稳定版本,用于任务路由失效判断。"""
import hashlib
import json
rows = []
for source in ShippingInventorySource.query.order_by(ShippingInventorySource.source_code).all():
profile = source.rpa_profile
rows.append({
'source_code': source.source_code,
'source_version': source.config_version,
'source_enabled': bool(source.enabled),
'profile_code': profile.profile_code if profile else None,
'profile_version': profile.config_version if profile else None,
'profile_enabled': bool(profile.enabled) if profile else False,
'source_config': {
'connector_type': source.connector_type,
'warehouse_resolution_mode': source.warehouse_resolution_mode,
'fixed_warehouse_id': source.fixed_warehouse_id,
'report_path_json': source.report_path_json or {},
'query_parameters_json': source.query_parameters_json or [],
'match_aliases_json': source.match_aliases_json or [],
'snapshot_ttl_seconds': source.snapshot_ttl_seconds,
},
'profile_config': {
'login_url': profile.login_url if profile else None,
'login_config': profile.login_config_json if profile else None,
},
})
payload = json.dumps(rows, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
return hashlib.sha256(payload.encode('ascii')).hexdigest()[:16]
@@ -1,42 +1,38 @@
"""
services/shipping_notice/inventory_source_rules.py
用途:根据发货通知路由线索对库存源做确定性裁决。
依赖:inventory_sources、ShippingTask 目的地字段、task_line_store、step_payload_json。
逻辑:Dify/LLM 只提供行级可选路由线索;本模块负责唯一性判断、冲突检测与人工确认复核;
订单行路由线索经 read_task_order_lines 读取。
用途:将通用路由规则的 Source 候选转为任务可持久化的裁决结果。
依赖:inventory_routing_engine、inventory_source_repository、task_line_store。
逻辑:规则只决定 Source;fixed Warehouse 由 Source 给出,inventory_match Warehouse 延后到库存行匹配。
"""
from __future__ import annotations
import hashlib
import json
from dataclasses import dataclass, field
from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import Any
from app.models import ShippingTask
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,
from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules
from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity
from app.services.shipping_notice.inventory_source_repository import (
get_database_inventory_source,
inventory_sources_runtime_version,
list_database_inventory_sources,
)
from app.services.shipping_notice.task_line_store import read_task_order_lines
@dataclass(frozen=True)
class InventorySourceAdjudication:
"""库存源裁决结构化结果。"""
"""库存源裁决结果;Warehouse 在动态模式下可为空。"""
status: str
method: str | None = None
source_code: str | None = None
connector_type: str | None = None
site_id: str | None = None
warehouse_id: str | None = None
config_version: str | None = None
routing_fingerprint: str | None = None
@@ -44,501 +40,230 @@ class InventorySourceAdjudication:
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 = ""
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。"""
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:
text = normalize_destination(value)
if text and text not in candidates:
candidates.append(text)
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", "destination_code"):
_append_candidate(candidates, value.get(key))
def extract_destination_candidates(task: ShippingTask) -> list[str]:
"""
从任务解析结果提取目的地/港口/仓库候选。
【AI 触发时机】:订单解析后由裁决服务调用,行级 inventory_source_hint 与目的地字段都作为候选证据。
核心逻辑:只读取 orders[].lines[].inventory_source_hint,禁止使用 Task.source_type;
Task.source_type 表示 PDF/manual 等接入来源,不是库存源路由证据。
Args:
task: 待裁决库存源的发货任务。
Returns:
去重并标准化后的 match_aliases 候选。
"""
candidates: list[str] = []
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
for item in payload.get("destination_candidates") or []:
_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 read_task_order_lines(task):
_extract_destination_object(candidates, line.get("destination"))
for key in ("destination_port", "destination_city", "destination_country", "warehouse_hint", "ship_to", "raw_text"):
_append_candidate(candidates, line.get(key))
_append_candidate(candidates, line.get("inventory_source_hint"))
return candidates
def extract_routing_context(task: ShippingTask) -> dict[str, Any]:
"""将任务解析结果标准化为库存路由上下文。"""
"""投影任务字段为路由审计上下文,不依赖 YAML 目的地别名。"""
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 {
"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),
'destination_code': task.destination_code,
'destination_city': task.destination_city,
'destination_country': task.destination_country,
'warehouse_hint': task.warehouse_hint,
'customer_code': task.customer_code,
'customer_name': task.customer_name,
'order_type': payload.get('order_type'),
'destination_candidates': [],
}
def _candidate_summary(source: dict[str, Any], *, score: int = 0, matched_by: str | None = None) -> dict[str, Any]:
"""人工确认候选项展示字段;前端必须提交 source_code。"""
def compute_routing_fingerprint(context: dict[str, Any]) -> str:
"""按路由事实和数据库配置版本生成稳定指纹。"""
payload = {'context': context, 'config_version': inventory_sources_runtime_version()}
return hashlib.sha256(json.dumps(payload, sort_keys=True, ensure_ascii=True, default=str).encode('ascii')).hexdigest()[:32]
def _candidate(source: dict[str, Any]) -> dict[str, Any]:
"""构造不泄露凭据的人工确认候选。"""
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"),
"connector_type": source.get("connector_type"),
"match_score": score,
"matched_by": matched_by,
'source_code': source['source_code'],
'display_name': source['display_name'],
'connector_type': source['connector_type'],
'warehouse_resolution_mode': source['warehouse_resolution_mode'],
'fixed_warehouse_id': source['fixed_warehouse_id'],
}
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。"""
def _from_source(*, status: str, source: dict[str, Any], method: str, context: dict[str, Any], evidence: list[dict[str, Any]] | None = None) -> InventorySourceAdjudication:
"""由数据库 Source 生成 resolved/user_confirmed 裁决。"""
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,
)
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 InventorySourceAdjudication('invalid', reason=resolution.reason, config_version=inventory_sources_runtime_version())
identity = resolution.identity
return InventorySourceAdjudication(
status="resolved",
status=status,
method=method,
source_code=identity.source_code,
connector_type=identity.connector_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,
config_version=inventory_sources_runtime_version(),
routing_fingerprint=compute_routing_fingerprint(context),
candidates=[_candidate(source)],
evidence=evidence or [],
)
def _result_to_adjudication(result: Any, context: dict[str, Any]) -> InventorySourceAdjudication:
"""将规则引擎候选集转换为可执行或待人工确认的裁决。"""
sources = [item for code in result.source_codes if (item := get_database_inventory_source(code))]
evidence = [{'rule_ids': list(result.matched_rule_ids), **result.evidence}]
if result.status == 'resolved' and len(sources) == 1:
return _from_source(status='resolved', source=sources[0], method='rule', context=context, evidence=evidence)
return InventorySourceAdjudication(
status=result.status,
config_version=inventory_sources_runtime_version(),
routing_fingerprint=compute_routing_fingerprint(context),
candidates=[_candidate(item) for item in (sources or list_database_inventory_sources())],
evidence=evidence,
reason='routing_rule_' + result.status,
)
def _snapshot_match_key(row: dict[str, Any]) -> tuple[str, str] | None:
"""构造库存快照与订单共用的 Reservation ID + Part Number 匹配键。"""
from app.services.shipping_notice.reservation_id import validated_reservation_id
part_number = str(row.get('part_number') or '').strip().upper()
reservation_id = validated_reservation_id(row.get('reservation_id'))
return (part_number, reservation_id) if part_number and reservation_id else None
def resolve_ambiguous_source_from_ready_snapshots(
task: ShippingTask,
adjudication: InventorySourceAdjudication,
) -> InventorySourceAdjudication:
"""
用已有有效快照从多个规则候选中确定唯一库存源,绝不比较库存数量或触发 RPA。
仅当规则已经给出明确的多个 Source 候选时执行。每个候选只检查其最新有效快照是否
覆盖订单全部 ``reservation_id + part_number`` 键;恰好一个候选命中才自动确定 Source。
快照缺失、多个候选命中或订单缺少匹配键时保留原人工确认状态。
"""
if adjudication.status != 'ambiguous':
return adjudication
candidate_codes = {
str(item.get('source_code') or '').strip().upper()
for item in adjudication.candidates
if isinstance(item, dict) and str(item.get('source_code') or '').strip()
}
order_keys = {
key for row in read_task_order_lines(task)
if isinstance(row, dict) and (key := _snapshot_match_key(row))
}
if not candidate_codes or not order_keys:
return adjudication
# A partial or malformed order cannot be silently routed from a file.
if len(order_keys) != len(read_task_order_lines(task)):
return adjudication
from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file
from app.services.shipping_notice.inventory_snapshot_store import find_latest_ready_snapshot
matched: list[tuple[dict[str, Any], Any]] = []
checked: list[dict[str, Any]] = []
for source_code in sorted(candidate_codes):
source = get_database_inventory_source(source_code)
if source is None:
continue
warehouse_id = source.get('fixed_warehouse_id') if source.get('warehouse_resolution_mode') == 'fixed' else None
snapshot = find_latest_ready_snapshot(source_code, warehouse_id)
if snapshot is None:
checked.append({'source_code': source_code, 'snapshot': 'missing'})
continue
lines = [row for row in (snapshot.inventory_lines_json or []) if isinstance(row, dict)]
if not lines:
try:
lines, _column_meta = parse_inventory_snapshot_file(snapshot)
except (OSError, ValueError):
lines = []
inventory_keys = {
key for row in lines
if isinstance(row, dict) and (key := _snapshot_match_key(row))
}
is_match = order_keys.issubset(inventory_keys)
checked.append({
'source_code': source_code,
'inventory_file_no': snapshot.inventory_file_no,
'matched': is_match,
})
if is_match:
matched.append((source, snapshot))
evidence = [*(adjudication.evidence or []), {
'snapshot_candidate_check': checked,
'match_key': ['reservation_id', 'part_number'],
'selection_basis': 'unique_exact_key_coverage',
}]
if len(matched) != 1:
return replace(adjudication, evidence=evidence)
source, snapshot = matched[0]
resolution = resolve_inventory_source_identity(source, extract_routing_context(task))
if not resolution.ok or not resolution.identity:
return replace(adjudication, evidence=evidence)
identity = resolution.identity
return InventorySourceAdjudication(
status='resolved',
method='snapshot_match',
source_code=identity.source_code,
connector_type=identity.connector_type,
warehouse_id=identity.warehouse_id,
config_version=inventory_sources_runtime_version(),
routing_fingerprint=compute_routing_fingerprint(extract_routing_context(task)),
candidates=adjudication.candidates,
destination_candidates=adjudication.destination_candidates,
evidence=evidence,
reason=f'unique_ready_snapshot:{snapshot.inventory_file_no}',
)
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
connector_type = str(source.get("connector_type") or "").strip()
if connector_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",
)
task_result = evaluate_inventory_source_rules(task=task)
if task_result.status != 'unresolved':
return _result_to_adjudication(task_result, context)
line_results = [evaluate_inventory_source_rules(task=task, line=line) for line in read_task_order_lines(task)]
resolved_codes = {item.source_codes[0] for item in line_results if item.status == 'resolved' and len(item.source_codes) == 1}
if len(resolved_codes) == 1 and all(item.status == 'resolved' for item in line_results):
return _result_to_adjudication(next(item for item in line_results if item.status == 'resolved'), context)
if len(resolved_codes) > 1:
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",
'ambiguous', config_version=inventory_sources_runtime_version(), routing_fingerprint=compute_routing_fingerprint(context),
candidates=[_candidate(item) for item in list_database_inventory_sources() if item['source_code'] in resolved_codes],
reason='line_rules_resolve_different_sources',
)
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",
)
return _result_to_adjudication(task_result, context)
def confirm_inventory_source_by_code(task: ShippingTask, source_code: str) -> InventorySourceAdjudication:
"""
用户只提交 source_code;站点与库位从配置生成。用户最终选择优先于自动裁决。
【AI 触发时机】:用户在 inventory_source_review 检查点选择正式库存源后调用。
"""
"""人工从已启用数据库 Source 中选择来源;不要求预先确定动态 Warehouse。"""
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:
source = get_database_inventory_source(source_code)
if not source:
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",
'invalid', config_version=inventory_sources_runtime_version(), routing_fingerprint=compute_routing_fingerprint(context),
candidates=[_candidate(item) for item in list_database_inventory_sources()], reason='source_code_not_found',
)
if str(source.get("connector_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,
connector_type=identity.connector_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}],
)
return _from_source(status='user_confirmed', source=source, method='user_confirmed', context=context)
# 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 source(静态配置 + 任务动态库位)。"""
from app.services.shipping_notice.inventory_sources import build_task_rpa_inventory_source
return build_task_rpa_inventory_source(task)
"""按任务 Source 从数据库读取 RPA 配置;动态仓由回调库存文件确定。"""
return get_database_inventory_source(task.inventory_source_code)
def save_task_rpa_inventory_source(
task: ShippingTask,
source: dict[str, Any],
*,
resolution: InventorySourceAdjudication | None = None,
) -> None:
"""把已确认库存源写入独立字段与 step_payload_json。"""
def save_task_rpa_inventory_source(task: ShippingTask, source: dict[str, Any], *, resolution: InventorySourceAdjudication | None = None) -> None:
"""兼容旧入口,将确认结果委托库存源门禁持久化。"""
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
if resolution:
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,
connector_type=identity.connector_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)
selected = resolution or confirm_inventory_source_by_code(task, str(source.get('source_code') or ''))
apply_inventory_source_adjudication(task, selected)
def mark_inventory_source_review(task: ShippingTask, resolution: InventorySourceAdjudication) -> None:
"""库存源无法唯一命中时写入候选项;委托 apply_inventory_source_adjudication。"""
"""兼容旧入口,写入待人工确认的 Source 候选。"""
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
apply_inventory_source_adjudication(task, resolution)
@@ -1,457 +0,0 @@
"""
services/shipping_notice/inventory_sources.py
用途:从 YAML/JSON 配置加载发货通知库存 RPA 源,并构造写入 trigger 的标准 rpa_inventory_source。
依赖:Flask current_app、pathlib、PyYAML/json;inventory_source_rules / inventory_rpa_workflow 调用本模块。
逻辑:新增 Warehouse 只改 backend/config/shipping_inventory_sources.yaml,不改 Python。
"""
from __future__ import annotations
import json
from copy import deepcopy
from pathlib import Path
from typing import Any
import yaml
from flask import current_app
_VALID_CONNECTOR_TYPES = {
"dsv360": "dsv360",
"crane_footprint": "crane_footprint",
}
_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"),
"connector_type": source.get("connector_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):
"""库存源配置校验失败。"""
def _config_path() -> Path:
"""解析库存源配置文件路径;优先 Flask config,其次默认 backend/config。"""
raw = str(current_app.config.get("SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG") or "").strip()
if raw:
path = Path(raw)
if not path.is_absolute():
from app.path_utils import resolve_backend_relative_path
path = Path(resolve_backend_relative_path(raw, path))
return path
from app.path_utils import resolve_backend_relative_path
default = Path(__file__).resolve().parents[3] / "config" / "shipping_inventory_sources.yaml"
return Path(resolve_backend_relative_path(None, default))
def _parse_config_payload(path: Path) -> dict[str, Any]:
"""
按文件后缀解析库存源配置(默认 YAML;测试夹具仍可用 .json)。
Raises:
InventorySourceConfigError: 后缀不支持或解析失败
"""
text = path.read_text(encoding="utf-8")
suffix = path.suffix.lower()
try:
if suffix in {".yaml", ".yml"}:
payload = yaml.safe_load(text)
elif suffix == ".json":
payload = json.loads(text)
else:
raise InventorySourceConfigError(
f"unsupported inventory sources config format: {path.suffix} (use .yaml, .yml, or .json)"
)
except (yaml.YAMLError, json.JSONDecodeError) as exc:
raise InventorySourceConfigError(f"failed to parse inventory sources config: {path}: {exc}") from exc
if not isinstance(payload, dict):
raise InventorySourceConfigError("inventory sources config root must be a mapping")
return payload
def _join_parameter_values(parameter: dict[str, Any]) -> str | None:
"""将 multi_text 参数值按 joiner 拼接为单字符串。"""
values = [str(item).strip() for item in (parameter.get("values") or []) if str(item).strip()]
if not values:
return None
joiner = str(parameter.get("joiner") or ",")
return joiner.join(values)
def _build_legacy_query(source: dict[str, Any]) -> dict[str, Any]:
"""
从 navigation + parameters 构造 worker 兼容的 query 字段。
核心逻辑:保留 DSV/Crane worker 现有读取口径,同时支持新版 parameters 驱动。
"""
navigation = dict(source.get("navigation") or {})
query: dict[str, Any] = {}
connector_type = str(source.get("connector_type") or "").strip().lower()
if connector_type == "dsv360":
for key in ("program_group", "program_label", "report_group", "report_name"):
if navigation.get(key):
query[key] = navigation[key]
elif connector_type == "crane_footprint":
if navigation.get("report_name"):
query["report_name"] = navigation["report_name"]
query["project_code"] = navigation.get("project_code")
warehouse_id = str(source.get("warehouse_id") or "").strip()
if warehouse_id:
query["warehouse_code"] = warehouse_id
for parameter in source.get("parameters") or []:
if not isinstance(parameter, dict):
continue
name = str(parameter.get("name") or "").strip()
mode = str(parameter.get("mode") or "single").strip().lower()
if mode == "multi_text":
joined = _join_parameter_values(parameter)
if not joined:
continue
if name.lower() == "owner":
query["owner_code"] = joined
elif name.lower() == "putawayzone":
query["putaway_zone"] = joined
elif name.lower() == "warehouse":
query["warehouse_code"] = joined
continue
values = [str(item).strip() for item in (parameter.get("values") or []) if str(item).strip()]
if not values:
continue
value = values[0]
if name.lower() == "owner":
query["owner_code"] = value
elif name.lower() == "putawayzone":
query["putaway_zone"] = value
elif name.lower() == "warehouse":
query["warehouse_code"] = value
elif name.lower() == "project":
query["project_code"] = value
return query
def 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()
if not source_code:
raise InventorySourceConfigError("source_code is required")
if source_code in seen_codes:
raise InventorySourceConfigError(f"duplicate source_code: {source_code}")
seen_codes.add(source_code)
connector_type = str(raw.get("connector_type") or "").strip().lower()
if connector_type not in _VALID_CONNECTOR_TYPES:
raise InventorySourceConfigError(
f"{source_code}: connector_type must be dsv360 or crane_footprint"
)
warehouse_id = str(raw.get("warehouse_id") or "").strip().upper()
site_id = str(raw.get("site_id") or "").strip().upper()
if connector_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 connector_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):
raise InventorySourceConfigError(f"{source_code}: parameters[] must be objects")
mode = str(item.get("mode") or "single").strip().lower()
if mode not in _VALID_PARAMETER_MODES:
raise InventorySourceConfigError(f"{source_code}: invalid parameter mode {mode}")
required = bool(item.get("required", False))
values = [str(v).strip() for v in (item.get("values") or []) if str(v).strip()]
if required and not values:
raise InventorySourceConfigError(f"{source_code}: required parameter {item.get('name')} has no values")
parameters.append({**item, "mode": mode, "values": values})
normalized = {
"source_code": source_code,
"connector_type": _VALID_CONNECTOR_TYPES[connector_type],
"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 {}),
"parameters": parameters,
"match_aliases": [
str(alias).strip()
for alias in (raw.get("match_aliases") or [])
if str(alias).strip()
],
}
if connector_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 connector_type == "crane_footprint" and raw.get("export"):
normalized["export"] = dict(raw.get("export") or {})
normalized["query"] = _build_legacy_query(normalized)
return normalized
def _load_config(*, force_reload: bool = False) -> dict[str, Any]:
"""加载并缓存 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):
raise InventorySourceConfigError("sources must be a list")
seen_codes: set[str] = set()
sources: dict[str, dict[str, Any]] = {}
for item in sources_raw:
if not isinstance(item, dict):
raise InventorySourceConfigError("each source must be an object")
normalized = _validate_source(item, seen_codes=seen_codes)
sources[normalized["source_code"]] = normalized
_CONFIG_CACHE = {
"version": _config_content_version(payload, sources),
"sources": sources,
"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)
def get_inventory_source(source_code: str | None) -> dict[str, Any] | None:
"""按 source_code 返回启用的库存源配置副本。"""
code = str(source_code or "").strip().upper()
if not code:
return None
source = _load_config()["sources"].get(code)
if not source or not source.get("enabled", True):
return None
return deepcopy(source)
def 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()
if enabled_only:
sources = [item for item in sources if item.get("enabled", True)]
return [deepcopy(item) for item in sources]
def build_rpa_inventory_source(
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。
【AI 触发时机】:HXOPS 已确定库存源后,写 RPA trigger 或确认人工选择时调用。
"""
source = get_inventory_source(source_code)
if not source:
return None
if query_override:
query = dict(source.get("query") or {})
for key, value in query_override.items():
if value is not None and str(value).strip():
query[key] = value
source["query"] = query
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
connector_type = str(merged.get("connector_type") or "").strip()
if connector_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)
@@ -0,0 +1,426 @@
"""
services/shipping_notice/inventory_structure_analysis.py
用途:安全分析库存样本文件的工作表、表头、列统计和字段建议。
依赖:openpyxl、inventory_snapshot 的受控表头词典、库存解析 Profile 服务、结构分析 ORM 模型。
逻辑:管理端上传 .xls/.xlsx/.csv 样本后调用本服务生成后端权威分析记录;后续 RPA 测试与运行期漂移检查复用同一分析契约。
"""
from __future__ import annotations
import csv
import hashlib
import re
import shutil
import uuid
from collections import Counter
from datetime import datetime
from pathlib import Path
from typing import Any
from openpyxl import load_workbook
from openpyxl.cell.cell import MergedCell
from werkzeug.datastructures import FileStorage
from app.core.errors import NotFoundError, ValidationError
from app.extensions import db
from app.models import ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventoryStructureAnalysis
from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix
from app.services.shipping_notice.inventory_mapping import suggest_field_mapping
from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index
from app.services.shipping_notice.inventory_structure_fingerprint import (
compatibility_fingerprint,
exact_fingerprint,
structure_definition,
)
MAX_UPLOAD_BYTES = 20 * 1024 * 1024
MAX_SCAN_ROWS = 40
MAX_SAMPLE_ROWS = 5
MAX_COLUMNS = 200
_SOURCE_KINDS = {'sample_upload', 'configuration_test', 'production_snapshot', 'temporary_conversation'}
def _has_required_suggestions(mapping: dict[str, str]) -> bool:
"""确认自动建议至少覆盖一个匹配字段和一个库存数量字段。"""
rows = ShippingInventoryField.query.filter(
ShippingInventoryField.status == 'active', ShippingInventoryField.id.in_([
int(field_id) for field_id in mapping if str(field_id).isdigit()
]),
).all() if mapping else []
usages = {row.usage_type for row in rows}
return 'match_identity' in usages and 'inventory_quantity' in usages
def _analysis_root() -> Path:
"""返回库存结构分析样本的受控托管目录。"""
from app.services.shipping_notice.export import _storage_root
return _storage_root() / 'inventory_structure_analyses'
def _safe_filename(value: str) -> str:
"""清理上传文件名,避免分析样本路径包含目录穿越字符。"""
return re.sub(r'[^A-Za-z0-9._-]+', '_', Path(str(value or '')).name) or 'inventory.xlsx'
def _normalise_header(value: Any) -> str:
"""规范表头展示文本;结构指纹阶段会在此基础上做更严格标准化。"""
return re.sub(r'\s+', ' ', str(value or '').replace('\u3000', ' ').strip())
def _value_type(values: list[Any]) -> str:
"""依据非空样本推断列类型,只供管理员确认,不能取代字段映射。"""
non_empty = [value for value in values if value not in (None, '')]
if not non_empty:
return 'empty'
numeric_count = 0
date_count = 0
for value in non_empty:
if hasattr(value, 'year') and hasattr(value, 'month'):
date_count += 1
continue
try:
float(str(value).replace(',', '').strip())
numeric_count += 1
except (TypeError, ValueError):
pass
if date_count == len(non_empty):
return 'date'
if numeric_count == len(non_empty):
return 'number'
return 'text'
def _column_summary(headers: list[str], sample_rows: list[list[Any]]) -> list[dict[str, Any]]:
"""生成来源栏位的业务预览,包括样例、空值率和建议字段。"""
suggestions = suggest_field_mapping(headers, as_catalog=True)
catalog = {
str(item.id): item for item in ShippingInventoryField.query.filter_by(status='active').all()
}
reverse_suggestions = {header: catalog[field_id].display_name for field_id, header in suggestions.items() if field_id in catalog}
duplicates = Counter(header for header in headers if header)
rows_total = len(sample_rows)
columns: list[dict[str, Any]] = []
for index, header in enumerate(headers, start=1):
values = [row[index - 1] if len(row) >= index else None for row in sample_rows]
non_empty = [value for value in values if value not in (None, '')]
columns.append({
'index': index,
'header': header,
'sample_values': [str(value)[:120] for value in non_empty[:MAX_SAMPLE_ROWS]],
'sample_empty_rate': round((rows_total - len(non_empty)) / rows_total, 4) if rows_total else 1,
'inferred_type': _value_type(non_empty),
'duplicate': bool(header and duplicates[header] > 1),
'suggested_inventory_field': reverse_suggestions.get(header),
})
return columns
def _workbook_structure(path: Path, *, legacy_xls: bool = False) -> tuple[dict[str, Any], dict[str, str], dict[str, Any], list[str]]:
"""读取 xlsx 或旧 xls 的所有工作表并选择最可能的库存表头。"""
if legacy_xls:
import xlrd
book = xlrd.open_workbook(filename=str(path), on_demand=True)
worksheets = [
(
str(book.sheet_by_index(index).name),
[
[
_xls_cell_value(book, book.sheet_by_index(index).cell(row_index, column_index))
for column_index in range(book.sheet_by_index(index).ncols)
]
for row_index in range(min(MAX_SCAN_ROWS, book.sheet_by_index(index).nrows))
],
book.sheet_by_index(index).nrows,
book.sheet_by_index(index).ncols,
)
for index in range(book.nsheets)
]
try:
return _build_workbook_structure(worksheets)
finally:
book.release_resources()
workbook = load_workbook(path, read_only=True, data_only=True)
try:
worksheets = []
for worksheet in workbook.worksheets:
rows = [list(row) for _, row in zip(range(MAX_SCAN_ROWS), worksheet.iter_rows(values_only=True))]
worksheets.append((worksheet.title, rows, worksheet.max_row or 0, worksheet.max_column or 0))
return _build_workbook_structure(worksheets)
finally:
workbook.close()
def _build_workbook_structure(
worksheets: list[tuple[str, list[list[Any]], int, int]],
) -> tuple[dict[str, Any], dict[str, str], dict[str, Any], list[str]]:
"""将任意 Excel 行迭代结果归一为统一的库存结构分析输出。"""
sheets: list[dict[str, Any]] = []
candidates: list[dict[str, Any]] = []
warnings: list[str] = []
for sheet_name, rows, row_count, column_count in worksheets:
if len(rows) and max(len(row) for row in rows) > MAX_COLUMNS:
warnings.append(f'工作表“{sheet_name}”栏位数超过分析上限,仅可人工处理')
continue
header_index = find_inventory_header_row_index(rows)
headers = [_normalise_header(value) for value in (rows[header_index] if rows else [])]
samples = rows[header_index + 1:header_index + 1 + MAX_SAMPLE_ROWS] if rows else []
suggested = suggest_field_mapping(headers, as_catalog=True)
score = len(suggested) * 10 + (30 if _has_required_suggestions(suggested) else 0)
candidate = {
'sheet_name': sheet_name,
'header_row_index': header_index + 1,
'headers': headers,
'columns': _column_summary(headers, samples),
'sample_row_count': len(samples),
'row_count_hint': row_count,
'score': score,
}
sheets.append({'sheet_name': sheet_name, 'row_count_hint': row_count, 'column_count': column_count})
if headers:
candidates.append(candidate)
if not candidates:
raise ValidationError('Inventory file has no analysable worksheet', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID')
selected = max(candidates, key=lambda item: (item['score'], item['sample_row_count']))
structure = {
'sheets': sheets,
'candidates': candidates,
'selected_sheet_name': selected['sheet_name'],
'selected_header_row_index': selected['header_row_index'],
'selected_headers': selected['headers'],
'selected_columns': selected['columns'],
}
mapping = suggest_field_mapping(selected['headers'], as_catalog=True)
summary = {
'candidate_count': len(candidates),
'sample_row_count': selected['sample_row_count'],
'valid_inventory_field_suggestions': len(mapping),
'has_required_suggestions': _has_required_suggestions(mapping),
}
return structure, mapping, summary, warnings
def _xlsx_structure(path: Path) -> tuple[dict[str, Any], dict[str, str], dict[str, Any], list[str]]:
"""读取 xlsx 工作簿的结构摘要。"""
return _workbook_structure(path)
def _xls_cell_value(book: Any, cell: Any) -> Any:
"""将 xlrd 单元格值转换为与 openpyxl 接近的 Python 值。"""
import xlrd
if cell.ctype == xlrd.XL_CELL_EMPTY:
return None
if cell.ctype == xlrd.XL_CELL_DATE:
return xlrd.xldate_as_datetime(cell.value, book.datemode)
if cell.ctype == xlrd.XL_CELL_NUMBER and float(cell.value).is_integer():
return int(cell.value)
return cell.value
def _xls_structure(path: Path) -> tuple[dict[str, Any], dict[str, str], dict[str, Any], list[str]]:
"""读取旧 .xls 工作簿结构;与 xlsx 产出完全相同的分析契约。"""
return _workbook_structure(path, legacy_xls=True)
def _csv_structure(path: Path) -> tuple[dict[str, Any], dict[str, str], dict[str, Any], list[str]]:
"""读取 CSV 样本,使用与 Excel 一致的表头和列统计逻辑。"""
try:
with path.open('r', encoding='utf-8-sig', errors='replace', newline='') as handle:
rows = [row for _, row in zip(range(MAX_SCAN_ROWS), csv.reader(handle))]
except OSError as exc:
raise ValidationError('Inventory CSV cannot be read', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') from exc
if not rows:
raise ValidationError('Inventory file is empty', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID')
header_index = find_inventory_header_row_index(rows)
headers = [_normalise_header(value) for value in rows[header_index]]
samples = rows[header_index + 1:header_index + 1 + MAX_SAMPLE_ROWS]
mapping = suggest_field_mapping(headers, as_catalog=True)
candidate = {
'sheet_name': None,
'header_row_index': header_index + 1,
'headers': headers,
'columns': _column_summary(headers, samples),
'sample_row_count': len(samples),
'row_count_hint': len(rows),
'score': len(mapping) * 10 + (30 if _has_required_suggestions(mapping) else 0),
}
return {
'sheets': [], 'candidates': [candidate], 'selected_sheet_name': None,
'selected_header_row_index': header_index + 1, 'selected_headers': headers,
'selected_columns': candidate['columns'],
}, mapping, {
'candidate_count': 1, 'sample_row_count': len(samples),
'valid_inventory_field_suggestions': len(mapping),
'has_required_suggestions': _has_required_suggestions(mapping),
}, []
def _analyse_path(path: Path, suffix: str) -> tuple[dict[str, Any], dict[str, str], dict[str, Any], list[str]]:
"""按受控文件格式分派结构分析,禁止根据内容猜测不支持的格式。"""
if suffix == '.xlsx':
return _xlsx_structure(path)
if suffix == '.xls':
return _xls_structure(path)
if suffix == '.csv':
return _csv_structure(path)
raise ValidationError('Inventory file format is unsupported', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID')
def serialize_analysis(item: ShippingInventoryStructureAnalysis) -> dict[str, Any]:
"""输出管理端需要的分析结果,不暴露服务器存储路径。"""
return {
'id': item.id,
'source_kind': item.source_kind,
'source_file_name': item.source_file_name,
'file_checksum': item.file_checksum,
'file_format': item.file_format,
'analysis_status': item.analysis_status,
'structure': item.structure_json or {},
'suggested_mapping': item.suggested_mapping_json or {},
'validation_summary': item.validation_summary_json or {},
'warnings': item.warning_json or [],
'match_result': item.match_result_json or {},
'created_at': item.created_at.isoformat() if item.created_at else None,
}
def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) -> dict[str, Any]:
"""上传并分析管理员选择的库存样本文件,创建后端权威分析记录。"""
if upload is None or not str(upload.filename or '').strip():
raise ValidationError('Inventory sample file is required', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_FILE_REQUIRED')
suffix = resolve_inventory_upload_suffix(str(upload.filename))
raw = upload.stream.read(MAX_UPLOAD_BYTES + 1)
if len(raw) > MAX_UPLOAD_BYTES:
raise ValidationError('Inventory sample file is too large', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_FILE_TOO_LARGE')
if not raw:
raise ValidationError('Inventory sample file is empty', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID')
analysis_dir = _analysis_root() / uuid.uuid4().hex
analysis_dir.mkdir(parents=True, exist_ok=False)
path = analysis_dir / f'sample{suffix}'
try:
path.write_bytes(raw)
structure, suggested, summary, warnings = _analyse_path(path, suffix)
except ValidationError:
shutil.rmtree(analysis_dir, ignore_errors=True)
raise
except Exception as exc:
shutil.rmtree(analysis_dir, ignore_errors=True)
raise ValidationError('Inventory sample file cannot be analysed', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') from exc
selected_headers = structure.get('selected_headers', [])
selected_definition = structure_definition(
file_format=suffix.lstrip('.'), sheet_name=structure.get('selected_sheet_name'),
header_row_index=structure.get('selected_header_row_index') or 1, headers=selected_headers,
)
item = ShippingInventoryStructureAnalysis(
source_kind='sample_upload', source_file_name=_safe_filename(str(upload.filename)), storage_path=str(path),
file_checksum=hashlib.sha256(raw).hexdigest(), file_format=suffix.lstrip('.'), analysis_status='ready',
structure_json=structure, suggested_mapping_json=suggested, validation_summary_json=summary,
warning_json=warnings, created_by=actor_id,
exact_structure_fingerprint=exact_fingerprint(selected_definition),
compatibility_fingerprint=compatibility_fingerprint(
definition=selected_definition, field_mapping=suggested, match_keys=[],
),
)
db.session.add(item)
db.session.flush()
from app.services.shipping_notice.inventory_profile_matching import recommend_profiles
item.match_result_json = recommend_profiles({
'structure': structure,
'suggested_mapping': suggested,
'exact_structure_fingerprint': item.exact_structure_fingerprint,
'compatibility_fingerprint': item.compatibility_fingerprint,
})
db.session.commit()
return serialize_analysis(item)
def get_analysis(analysis_id: int) -> dict[str, Any]:
"""读取既有结构分析,供管理员选择工作表、表头和来源栏位。"""
item = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
if item is None:
raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND')
return serialize_analysis(item)
def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""用已分析的真实栏位创建库存文件解析方案草稿,禁止前端编造来源栏位。"""
analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
if analysis is None:
raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND')
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
sheet_name = str(data.get('sheet_name') or structure.get('selected_sheet_name') or '').strip() or None
header_row_index = data.get('header_row_index') or structure.get('selected_header_row_index')
candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else []
candidate = next((item for item in candidates if isinstance(item, dict) and item.get('sheet_name') == sheet_name and item.get('header_row_index') == header_row_index), None)
if candidate is None and sheet_name is None:
candidate = next((item for item in candidates if isinstance(item, dict) and item.get('sheet_name') is None and item.get('header_row_index') == header_row_index), None)
if not isinstance(candidate, dict):
raise ValidationError('Selected worksheet or header row is not in the analysis', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID')
headers = {str(value).strip() for value in candidate.get('headers', []) if str(value).strip()}
mapping = data.get('field_mapping') if isinstance(data.get('field_mapping'), dict) else analysis.suggested_mapping_json or {}
if any(str(value or '').strip() not in headers for value in mapping.values()):
raise ValidationError('Parsing field mapping must use analysed headers', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID')
duplicates = {
str(column.get('header') or '').strip()
for column in candidate.get('columns', [])
if isinstance(column, dict) and column.get('duplicate')
}
if any(str(value or '').strip() in duplicates for value in mapping.values()):
raise ValidationError('Parsing field mapping cannot use duplicate headers', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID')
from app.services.shipping_notice import inventory_parsing_profile
saved = inventory_parsing_profile.save_draft({
'profile_code': data.get('profile_code'),
'display_name': data.get('display_name'),
'file_format': analysis.file_format,
'definition': {
'sheet_name': sheet_name,
'header_row_index': header_row_index,
'field_mapping': mapping,
'match_keys': data.get('match_keys'),
},
}, actor_id=actor_id, profile_id=data.get('profile_id'))
profile = db.session.get(ShippingInventoryParsingProfile, saved['id'])
selected_definition = structure_definition(
file_format=analysis.file_format, sheet_name=sheet_name, header_row_index=header_row_index,
headers=[str(value) for value in candidate.get('headers', [])],
)
profile.structure_definition_json = selected_definition
profile.exact_structure_fingerprint = exact_fingerprint(selected_definition)
profile.compatibility_fingerprint = compatibility_fingerprint(
definition=selected_definition, field_mapping=mapping,
match_keys=data.get('match_keys') if isinstance(data.get('match_keys'), list) else [],
)
profile.fingerprint_version = selected_definition['fingerprint_version']
db.session.commit()
return inventory_parsing_profile.payload(profile)
def adopt_published_profile(analysis_id: int, profile_id: int) -> dict[str, Any]:
"""确认分析结果采用指定已发布方案;只记录确认,不自动绑定任何库存站点。"""
analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
if analysis is None:
raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND')
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
if profile is None or profile.status != 'published':
raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
match = analysis.match_result_json if isinstance(analysis.match_result_json, dict) else {}
candidate_ids = {int(item.get('profile_id')) for item in match.get('candidates', []) if isinstance(item, dict) and item.get('profile_id')}
same_test_structure = bool(
analysis.exact_structure_fingerprint
and analysis.exact_structure_fingerprint == profile.exact_structure_fingerprint
)
if profile_id not in candidate_ids and not same_test_structure:
raise ValidationError('Profile is not a compatible recommendation', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID')
analysis.match_result_json = {
**match,
'adopted_profile_id': profile.id,
'adopted_profile_checksum': profile.checksum,
}
db.session.commit()
return serialize_analysis(analysis)
@@ -0,0 +1,92 @@
"""
services/shipping_notice/inventory_structure_drift.py
用途:在正式库存文件入库前核验其结构是否仍符合库存站点已绑定的解析方案。
依赖:库存源/解析方案模型、库存结构分析和方案复用服务。
逻辑:RPA 与后续人工受控入库复用本服务;一致文件可继续解析,核心栏位变化必须阻断,绝不回退至猜列。
"""
from __future__ import annotations
from pathlib import Path
from typing import Any
from app.core.errors import ConflictError
from app.models import ShippingInventorySource
def validate_production_inventory_structure(*, source_code: str, path: Path) -> dict[str, Any]:
"""核验正式库存文件结构并返回已绑定方案的确定性解析参数。
Args:
source_code: 已启用库存站点编码,必须绑定已发布解析方案。
path: RPA 下载的库存文件,必须是受控 xls/xlsx/csv 格式且存在。
Returns:
包含 mapping、sheet_name、header_row_index 和可展示差异的字典。
Raises:
ConflictError: 文件结构缺关键栏位、格式不一致或与已绑定方案不兼容时抛出。
"""
source = ShippingInventorySource.query.filter_by(source_code=str(source_code or '').strip().upper()).first()
profile = source.parsing_profile if source is not None else None
if source is None or not source.enabled or profile is None or profile.status != 'published':
raise ConflictError('Inventory source parsing profile is unavailable', code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED')
from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix
from app.services.shipping_notice.inventory_structure_analysis import _analyse_path
from app.services.shipping_notice.inventory_structure_fingerprint import exact_fingerprint, structure_definition
from app.services.shipping_notice.inventory_profile_matching import recommend_profiles
suffix = resolve_inventory_upload_suffix(path.name)
actual_format = suffix.lstrip('.')
if actual_format != profile.file_format:
raise ConflictError('Inventory file format changed', code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED')
structure, suggested, _summary, warnings = _analyse_path(path, suffix)
configured = profile.definition_json if isinstance(profile.definition_json, dict) else {}
expected_sheet = configured.get('sheet_name')
expected_header_row = configured.get('header_row_index')
candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else []
selected = next((item for item in candidates if isinstance(item, dict)
and item.get('sheet_name') == expected_sheet
and item.get('header_row_index') == expected_header_row), None)
if selected is None:
raise ConflictError(
'Configured inventory worksheet or header row is unavailable',
code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED',
details={'source_code': source.source_code, 'profile_id': profile.id},
)
# Compare the configured worksheet rather than the analyser's best guess.
structure = {**structure, 'selected_sheet_name': selected['sheet_name'],
'selected_header_row_index': selected['header_row_index'],
'selected_headers': selected.get('headers', []), 'selected_columns': selected.get('columns', [])}
from app.services.shipping_notice.inventory_mapping import suggest_field_mapping
suggested = suggest_field_mapping(structure['selected_headers'], as_catalog=True)
definition = structure_definition(
file_format=actual_format, sheet_name=structure.get('selected_sheet_name'),
header_row_index=structure.get('selected_header_row_index') or 1,
headers=structure.get('selected_headers', []),
)
analysis = {
'structure': structure,
'suggested_mapping': suggested,
'exact_structure_fingerprint': exact_fingerprint(definition),
'compatibility_fingerprint': '',
}
recommendation = recommend_profiles(analysis)
candidate = next((item for item in recommendation.get('candidates', []) if item.get('profile_id') == profile.id), None)
if candidate is None:
raise ConflictError(
'Inventory file structure is incompatible with the bound parsing profile',
code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED',
details={'source_code': source.source_code, 'profile_id': profile.id, 'warnings': warnings},
)
return {
'field_mapping': dict(configured.get('field_mapping') or {}),
'sheet_name': configured.get('sheet_name'),
'header_row_index': configured.get('header_row_index'),
'level': candidate.get('level'),
'difference': candidate.get('difference') or {},
'warnings': warnings,
}
@@ -0,0 +1,71 @@
"""
services/shipping_notice/inventory_structure_fingerprint.py
用途:为库存文件结构和解析定义生成稳定、可审计的指纹。
依赖:标准 hashlib/json/unicodedata;输入来自 inventory_structure_analysis 与 inventory_parsing_profile。
逻辑:精确指纹判断文件布局相同;兼容指纹只保留核心栏位,用于推荐而非自动绑定。
"""
from __future__ import annotations
import hashlib
import json
import re
import unicodedata
from typing import Any
FINGERPRINT_VERSION = 'inventory-structure-v1'
def normalise_header(value: Any) -> str:
"""将表头统一为可比文本,处理全半角、大小写、空白和常见分隔符。"""
text = unicodedata.normalize('NFKC', str(value or '')).strip().lower()
text = re.sub(r'[\s_\-./\\]+', ' ', text)
return re.sub(r'\s+', ' ', text).strip()
def _digest(payload: dict[str, Any]) -> str:
"""对排序后的确定性结构内容生成 SHA-256,不含库存业务数据。"""
encoded = json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
return hashlib.sha256(encoded).hexdigest()
def structure_definition(*, file_format: str, sheet_name: str | None, header_row_index: int, headers: list[str]) -> dict[str, Any]:
"""提取文件客观结构;列顺序和重复列保留,确保完全相同判断严格。"""
return {
'fingerprint_version': FINGERPRINT_VERSION,
'file_format': str(file_format).lower(),
'sheet_name': str(sheet_name or ''),
'header_row_index': int(header_row_index),
'headers': [normalise_header(header) for header in headers],
}
def exact_fingerprint(definition: dict[str, Any]) -> str:
"""生成完整文件结构指纹,用于准确识别相同库存模板布局。"""
return _digest(definition)
def compatibility_fingerprint(*, definition: dict[str, Any], field_mapping: dict[str, str], match_keys: list[dict[str, Any]]) -> str:
"""按匹配与数量用途生成兼容指纹,忽略普通导出列但保留用户字段 ID。"""
from app.services.shipping_notice.inventory_mapping import runtime_field_mapping, usage_field_ids
runtime_mapping, catalog = runtime_field_mapping(field_mapping)
usages = usage_field_ids()
capability_ids = usages.get('match_identity', set()) | usages.get('inventory_quantity', set())
core_mapping = {
field_id: normalise_header(runtime_mapping.get(field_id))
for field_id in sorted(capability_ids)
if field_id in catalog and runtime_mapping.get(field_id)
}
return _digest({
'fingerprint_version': FINGERPRINT_VERSION,
'file_format': definition.get('file_format'),
'core_mapping': core_mapping,
'match_keys': sorted([
{
'order_field_id': str(item.get('order_field_id') or ''),
'inventory_field_id': str(item.get('inventory_field_id') or item.get('inventory_field') or ''),
}
for item in match_keys if isinstance(item, dict)
], key=lambda item: (item['order_field_id'], item['inventory_field_id'])),
})
@@ -0,0 +1,553 @@
"""
services/shipping_notice/inventory_temporary_session.py
用途:处理对话上传库存候选文件的身份初检与临时会话状态。
依赖:ChatSession、FileAsset、库存结构分析、库存站点模型、FileAsset 私有存储服务。
逻辑:Dify 先用统一运行态上下文创建会话;后端验证文件归属并分析结构,
仅返回脱敏表头预览和候选站点,不创建生产库存快照或修改库存站点配置。
"""
from __future__ import annotations
import hashlib
import copy
import math
import shutil
import uuid
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
from app.extensions import db
from app.models import (
Agent,
ChatSession,
FileAsset,
ShippingInventoryStructureAnalysis,
ShippingTemporaryInventorySession,
ShippingInventoryField,
ShippingInventoryParsingProfile,
)
from app.services.agent_runtime_context.parser import parse_agent_runtime_context
from app.services.file_assets.service import read_asset_bytes
from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix
from app.services.shipping_notice.inventory_structure_analysis import (
MAX_UPLOAD_BYTES,
_analyse_path,
_analysis_root,
_safe_filename,
serialize_analysis,
)
from app.services.shipping_notice.inventory_structure_fingerprint import (
compatibility_fingerprint,
exact_fingerprint,
structure_definition,
)
from app.services.shipping_notice.inventory_mapping import (
mapping_is_complete,
runtime_field_mapping,
suggest_field_mapping,
validate_field_mapping_against_headers,
)
from app.services.shipping_notice.inventory_snapshot import parse_inventory_excel_with_meta
_CONTEXT_PATHS = ['agent_code', 'platform.session_id']
_TTL_HOURS = 24
def _runtime_session(raw_context: str | dict[str, Any]) -> ChatSession:
"""从 Dify 运行态上下文解析货代会话,并以本地会话反查用户身份。"""
parsed = parse_agent_runtime_context(raw_context, _CONTEXT_PATHS)
values = parsed.get('data') if isinstance(parsed.get('data'), dict) else {}
if str(values.get('agent_code') or '') != 'shipping_notice':
raise ForbiddenError('Current context is not shipping notice', code='SHIPPING.TEMP_INVENTORY_CONTEXT_INVALID')
session_id = str(values.get('platform.session_id') or '').strip()
session = (
db.session.query(ChatSession)
.join(Agent, Agent.id == ChatSession.agent_id)
.filter(ChatSession.session_id == session_id, Agent.agent_code == 'shipping_notice')
.one_or_none()
)
if session is None:
raise NotFoundError('Shipping chat session not found', code='SHIPPING.TEMP_INVENTORY_CONTEXT_INVALID')
return session
def _session_no() -> str:
"""生成临时库存会话编号;编号仅用于审计和 Tool 引用,不承载业务单号语义。"""
return f'TIS-{datetime.utcnow().strftime("%Y%m%d")}-{uuid.uuid4().hex[:10].upper()}'
def _serialize(item: ShippingTemporaryInventorySession) -> dict[str, Any]:
"""输出 Dify 和工作台可消费的临时会话,不泄露对象存储路径和完整库存行。"""
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
return {
'session_no': item.session_no,
'status': item.status,
'file_classification_status': item.file_classification_status,
'classification_reason': item.classification_reason,
'analysis': _serialize_dify_analysis_preview(analysis) if analysis else None,
'available_inventory_fields': _available_inventory_fields(),
'mapping_suggestion': _mapping_suggestion(item),
'confirmed_usage': _confirmed_usage(item),
'expires_at': item.expires_at.isoformat() if item.expires_at else None,
}
def _available_inventory_fields() -> list[dict[str, Any]]:
"""返回 Dify 可建议的库存业务字段目录,不暴露稳定内部字段编码。"""
return [{
'id': item.id,
'display_name': item.display_name,
'description': item.description or '',
'value_type': item.value_type,
'usage_type': item.usage_type,
} for item in ShippingInventoryField.query.filter_by(status='active').order_by(
ShippingInventoryField.sort_order, ShippingInventoryField.id,
).all()]
def _mapping_suggestion(item: ShippingTemporaryInventorySession) -> dict[str, Any] | None:
"""提取已保存的候选映射;未建议时返回空,不伪造可运行的映射。"""
result = item.result_json if isinstance(item.result_json, dict) else {}
value = result.get('mapping_suggestion')
return value if isinstance(value, dict) else None
def _confirmed_usage(item: ShippingTemporaryInventorySession) -> dict[str, Any] | None:
"""输出已确认的临时使用摘要,不返回库存行或文件内部路径。"""
result = item.result_json if isinstance(item.result_json, dict) else {}
value = result.get('confirmed_usage')
if not isinstance(value, dict):
return None
return {
'usage_scope': 'conversation',
'mapping_origin': value.get('mapping_origin'),
'profile_id': value.get('profile_id'),
'quality': value.get('quality'),
'confirmed_at': value.get('confirmed_at'),
}
def _serialize_dify_analysis_preview(analysis: ShippingInventoryStructureAnalysis) -> dict[str, Any]:
"""返回给 Dify 的库存结构预览,移除所有样例值以避免暴露库存明细。"""
preview = copy.deepcopy(serialize_analysis(analysis))
structure = preview.get('structure')
if not isinstance(structure, dict):
return preview
for candidate in structure.get('candidates') or []:
if not isinstance(candidate, dict):
continue
for column in candidate.get('columns') or []:
if isinstance(column, dict):
column.pop('sample_values', None)
for column in structure.get('selected_columns') or []:
if isinstance(column, dict):
column.pop('sample_values', None)
return preview
def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventoryStructureAnalysis:
"""对私有文件资产执行受控结构分析,仅保留结构、有限样例及字段建议。"""
if int(asset.file_size or 0) > MAX_UPLOAD_BYTES:
raise ValidationError(
'Temporary inventory file is too large',
code='SHIPPING.TEMP_INVENTORY_FILE_TOO_LARGE',
)
suffix = resolve_inventory_upload_suffix(asset.original_filename)
raw = read_asset_bytes(asset)
analysis_dir = _analysis_root() / uuid.uuid4().hex
analysis_dir.mkdir(parents=True, exist_ok=False)
path = analysis_dir / f'conversation{suffix}'
try:
path.write_bytes(raw)
structure, suggested_catalog, summary, warnings = _analyse_path(path, suffix)
except ValidationError:
shutil.rmtree(analysis_dir, ignore_errors=True)
raise
except Exception as exc:
shutil.rmtree(analysis_dir, ignore_errors=True)
raise ValidationError(
'Temporary inventory file cannot be analysed',
code='SHIPPING.TEMP_INVENTORY_ANALYSIS_INVALID',
) from exc
# 临时会话与正式配置一致地保留目录字段 ID,不生成固定运行字段名称。
suggested, _catalog = runtime_field_mapping(suggested_catalog)
definition = structure_definition(
file_format=suffix.lstrip('.'), sheet_name=structure.get('selected_sheet_name'),
header_row_index=structure.get('selected_header_row_index') or 1,
headers=structure.get('selected_headers', []),
)
analysis = ShippingInventoryStructureAnalysis(
source_kind='temporary_conversation', source_file_name=_safe_filename(asset.original_filename),
storage_path=str(path), file_checksum=hashlib.sha256(raw).hexdigest(), file_format=suffix.lstrip('.'),
analysis_status='ready', structure_json=structure, suggested_mapping_json=suggested,
validation_summary_json=summary, warning_json=warnings, created_by=owner_id,
exact_structure_fingerprint=exact_fingerprint(definition),
compatibility_fingerprint=compatibility_fingerprint(
definition=definition, field_mapping=suggested, match_keys=[],
),
)
db.session.add(analysis)
db.session.flush()
from app.services.shipping_notice.inventory_profile_matching import recommend_profiles
analysis.match_result_json = recommend_profiles({
'structure': structure,
'suggested_mapping': suggested,
'exact_structure_fingerprint': analysis.exact_structure_fingerprint,
'compatibility_fingerprint': analysis.compatibility_fingerprint,
})
return analysis
def _classify(analysis: ShippingInventoryStructureAnalysis) -> tuple[str, str]:
"""在用户已明确声明库存文件后,仅按通用表格结构判断是否可进入候选映射。"""
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
headers = structure.get('selected_headers') if isinstance(structure.get('selected_headers'), list) else []
columns = structure.get('selected_columns') if isinstance(structure.get('selected_columns'), list) else []
has_sample_values = any(
isinstance(column, dict) and bool(column.get('sample_values')) for column in columns
)
if len([item for item in headers if str(item).strip()]) >= 2 and columns and has_sample_values:
return 'inventory_candidate', '已识别可维护的表格结构,待确认库存字段映射后才能使用。'
return 'not_inventory', '文件缺少可确认的表头或数据行,不能作为库存候选。'
def create_temporary_inventory_session(payload: dict[str, Any]) -> dict[str, Any]:
"""
创建对话库存候选会话并执行后端结构初检。
【AI 触发时机】:用户在货代对话中明确说明上传的 .xls/.xlsx/.csv 是库存文件时调用。
核心逻辑:通过 agent_runtime_context 反查真实会话和用户,验证 FileAsset 所有权,分析受控副本;
不创建库存快照、不绑定库存站点、不执行订单匹配。
Args:
payload: 必须含 agent_runtime_context 与 asset_no;asset_no 必须属于当前会话用户。
Returns:
临时会话编号、分类结论和脱敏结构分析。
"""
session = _runtime_session(payload.get('agent_runtime_context'))
asset_no = str(payload.get('asset_no') or '').strip().upper()
if not asset_no:
raise ValidationError('Temporary inventory asset is required', code='SHIPPING.TEMP_INVENTORY_ASSET_REQUIRED')
asset = FileAsset.query.filter_by(asset_no=asset_no, deleted_at=None).one_or_none()
if asset is None or int(asset.owner_user_id) != int(session.user_id):
raise NotFoundError('Temporary inventory asset not found', code='SHIPPING.TEMP_INVENTORY_ASSET_NOT_FOUND')
if str(asset.upload_status or '') != 'ready':
raise ConflictError('Temporary inventory asset is not ready', code='SHIPPING.TEMP_INVENTORY_ASSET_NOT_READY')
try:
resolve_inventory_upload_suffix(asset.original_filename)
except Exception as exc:
raise ValidationError('Temporary inventory only supports xls, xlsx or csv', code='SHIPPING.TEMP_INVENTORY_FILE_TYPE_INVALID') from exc
active = ShippingTemporaryInventorySession.query.filter(
ShippingTemporaryInventorySession.user_id == session.user_id,
ShippingTemporaryInventorySession.conversation_id == session.session_id,
ShippingTemporaryInventorySession.asset_id == asset.id,
ShippingTemporaryInventorySession.status.in_([
'created', 'awaiting_profile_confirmation', 'awaiting_mapping_suggestion',
'awaiting_mapping_confirmation',
]),
ShippingTemporaryInventorySession.expires_at > datetime.utcnow(),
).order_by(ShippingTemporaryInventorySession.id.desc()).first()
if active:
return _serialize(active)
analysis = _persist_analysis(asset=asset, owner_id=int(session.user_id))
classification, reason = _classify(analysis)
expires_at = datetime.utcnow() + timedelta(hours=_TTL_HOURS)
# 临时会话和上传资产在同一有效期内存活,避免清理任务提前删除仍待确认的文件。
if asset.expires_at is None or asset.expires_at < expires_at:
asset.expires_at = expires_at
match_result = analysis.match_result_json if isinstance(analysis.match_result_json, dict) else {}
has_exact_profile = classification == 'inventory_candidate' and str(match_result.get('status') or '') == 'exact'
item = ShippingTemporaryInventorySession(
session_no=_session_no(), user_id=int(session.user_id), conversation_id=session.session_id,
asset_id=int(asset.id), analysis_id=analysis.id, declared_intent='inventory_candidate',
file_classification_status=classification,
status=(
'awaiting_profile_confirmation' if has_exact_profile
else ('awaiting_mapping_suggestion' if classification == 'inventory_candidate' else 'rejected')
),
classification_reason=reason,
candidate_source_ids_json=[],
result_json={}, expires_at=expires_at,
)
db.session.add(item)
db.session.commit()
return _serialize(item)
def get_temporary_inventory_session(payload: dict[str, Any]) -> dict[str, Any]:
"""
查询临时库存会话的脱敏分析状态。
【AI 触发时机】:创建临时库存会话后,需要读取结构预览、方案候选或后端分类结论时调用。
Args:
payload: 必须含 agent_runtime_context 与 temporary_session_no。
Returns:
仅属于当前会话用户的临时会话投影。
"""
session = _runtime_session(payload.get('agent_runtime_context'))
session_no = str(payload.get('temporary_session_no') or '').strip().upper()
item = ShippingTemporaryInventorySession.query.filter_by(
session_no=session_no, user_id=int(session.user_id), conversation_id=session.session_id,
).one_or_none()
if item is None:
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND')
if item.expires_at <= datetime.utcnow() and item.status not in {'rejected', 'expired'}:
item.status = 'expired'
db.session.commit()
return _serialize(item)
def submit_temporary_inventory_mapping_suggestion(payload: dict[str, Any]) -> dict[str, Any]:
"""
保存 Dify 给出的临时库存映射建议,但不使其进入正式库存运行链路。
【AI 触发时机】:仅当临时会话没有可直接复用的 published 方案,且 LLM 已基于真实表头和字段目录给出候选时调用。
核心逻辑:校验当前会话、字段目录 ID、真实来源表头、重复映射和匹配/数量能力;只保存待用户确认的建议。
Args:
payload: 必须含 agent_runtime_context、temporary_session_no 与 field_mapping(库存字段目录 ID 到真实表头)。
Returns:
更新后的临时会话投影;不含发布、库存站点绑定或订单匹配结果。
"""
session = _runtime_session(payload.get('agent_runtime_context'))
session_no = str(payload.get('temporary_session_no') or '').strip().upper()
item = ShippingTemporaryInventorySession.query.filter_by(
session_no=session_no, user_id=int(session.user_id), conversation_id=session.session_id,
).one_or_none()
if item is None:
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND')
if item.status != 'awaiting_mapping_suggestion':
raise ConflictError('Temporary inventory session cannot accept a mapping suggestion', code='SHIPPING.TEMP_INVENTORY_MAPPING_STATE_INVALID')
raw_mapping = payload.get('field_mapping')
if not isinstance(raw_mapping, dict) or not raw_mapping:
raise ValidationError('Temporary inventory mapping suggestion is required', code='SHIPPING.TEMP_INVENTORY_MAPPING_INVALID')
mapping = {
str(field_id).strip(): str(header).strip()
for field_id, header in raw_mapping.items()
if str(field_id).strip() and str(header).strip()
}
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
structure = analysis.structure_json if analysis and isinstance(analysis.structure_json, dict) else {}
headers = [str(header).strip() for header in structure.get('selected_headers', []) if str(header).strip()]
if not headers or len(mapping) != len(raw_mapping) or len(set(mapping.values())) != len(mapping):
raise ValidationError('Temporary inventory mapping suggestion is invalid', code='SHIPPING.TEMP_INVENTORY_MAPPING_INVALID')
errors = validate_field_mapping_against_headers(headers, mapping)
if errors or not mapping_is_complete(mapping):
raise ValidationError(
'Temporary inventory mapping suggestion is incomplete or invalid',
code='SHIPPING.TEMP_INVENTORY_MAPPING_INVALID', details={'errors': errors},
)
item.result_json = {
**(item.result_json if isinstance(item.result_json, dict) else {}),
'mapping_suggestion': {'field_mapping': mapping, 'origin': 'dify_candidate'},
}
item.status = 'awaiting_mapping_confirmation'
db.session.commit()
return _serialize(item)
def _select_confirmed_mapping(
item: ShippingTemporaryInventorySession,
*,
selected_profile_id: Any,
) -> tuple[dict[str, str], str, int | None]:
"""按会话状态选择 exact 已发布方案或已校验建议,禁止请求直接传映射覆盖。"""
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
if analysis is None:
raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID')
if item.status == 'awaiting_profile_confirmation':
try:
profile_id = int(selected_profile_id)
except (TypeError, ValueError) as exc:
raise ValidationError('A published parsing profile must be selected', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID') from exc
candidates = (analysis.match_result_json or {}).get('candidates', []) if isinstance(analysis.match_result_json, dict) else []
exact_ids = {
int(candidate.get('profile_id'))
for candidate in candidates if isinstance(candidate, dict)
and str(candidate.get('level') or '') == 'exact'
and str(candidate.get('profile_id') or '').isdigit()
}
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
if profile is None or profile.status != 'published' or profile_id not in exact_ids:
raise ValidationError('Selected parsing profile is not an exact published candidate', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID')
return dict((profile.definition_json or {}).get('field_mapping') or {}), f'published_profile:{profile.profile_code}:v{profile.version}', profile.id
if item.status == 'awaiting_mapping_confirmation':
suggestion = _mapping_suggestion(item) or {}
mapping = suggestion.get('field_mapping') if isinstance(suggestion.get('field_mapping'), dict) else {}
if not mapping:
raise ConflictError('Temporary inventory mapping suggestion is missing', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID')
return dict(mapping), 'dify_candidate', None
raise ConflictError('Temporary inventory session cannot be confirmed', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID')
def _quality_report(lines: list[dict[str, Any]], field_mapping: dict[str, str]) -> dict[str, Any]:
"""按字段目录用途验证临时解析行;旧编码仅保留给无目录映射的受控内部调用。"""
runtime_mapping, catalog = runtime_field_mapping(field_mapping)
if catalog:
match_fields = [field_id for field_id, item in catalog.items() if item.usage_type == 'match_identity']
quantity_fields = [field_id for field_id, item in catalog.items() if item.usage_type == 'inventory_quantity']
else:
match_fields = ['part_number', 'reservation_id']
quantity_fields = ['available_qty']
invalid_rows = 0
for line in lines:
try:
quantities = [line.get(field_id) for field_id in quantity_fields]
quantity_valid = len(quantities) == 1 and math.isfinite(float(quantities[0])) and float(quantities[0]) >= 0
except (TypeError, ValueError):
quantity_valid = False
identities_valid = bool(match_fields) and all(str(line.get(field_id) or '').strip() for field_id in match_fields)
if not identities_valid or not quantity_valid:
invalid_rows += 1
return {
'parsed_line_count': len(lines),
'valid_line_count': len(lines) - invalid_rows,
'invalid_line_count': invalid_rows,
'passed': bool(lines) and invalid_rows == 0,
}
def confirm_temporary_inventory_use(payload: dict[str, Any]) -> dict[str, Any]:
"""
经用户明确确认后,锁定当前会话临时库存文件的确定性解析定义与质量结果。
【AI 触发时机】:仅在用户明确确认“本次使用此库存文件/方案”后调用,Dify 不得自行确认。
核心逻辑:选择 exact published 方案或已校验映射,重新解析受控原文件并执行质量门禁;
只写临时会话审计,不创建 ShippingInventoryFile、不修改库存站点、不回填任务库存行、不执行匹配。
Args:
payload: 必须含 agent_runtime_context、temporary_session_no;exact 方案需 selected_profile_id。
Returns:
已确认临时使用会话的安全投影,含质量摘要但不含库存行。
"""
session = _runtime_session(payload.get('agent_runtime_context'))
session_no = str(payload.get('temporary_session_no') or '').strip().upper()
item = ShippingTemporaryInventorySession.query.filter_by(
session_no=session_no, user_id=int(session.user_id), conversation_id=session.session_id,
).one_or_none()
if item is None:
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND')
if item.expires_at <= datetime.utcnow():
item.status = 'expired'
db.session.commit()
raise ConflictError('Temporary inventory session has expired', code='SHIPPING.TEMP_INVENTORY_SESSION_EXPIRED')
mapping, mapping_origin, profile_id = _select_confirmed_mapping(item, selected_profile_id=payload.get('selected_profile_id'))
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
if analysis is None:
raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID')
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
try:
lines, column_meta = parse_inventory_excel_with_meta(
Path(analysis.storage_path), field_mapping=mapping, mapping_source=mapping_origin,
header_row_index=structure.get('selected_header_row_index'), sheet_name=structure.get('selected_sheet_name'),
)
except Exception as exc:
raise ValidationError('Temporary inventory file cannot pass deterministic parsing', code='SHIPPING.TEMP_INVENTORY_QUALITY_INVALID') from exc
quality = _quality_report(lines, mapping)
if not quality['passed']:
raise ValidationError('Temporary inventory file does not meet quality requirements', code='SHIPPING.TEMP_INVENTORY_QUALITY_INVALID', details={'quality': quality})
item.task_id = None
item.result_json = {
**(item.result_json if isinstance(item.result_json, dict) else {}),
'confirmed_usage': {
'usage_scope': 'conversation',
'mapping_origin': mapping_origin, 'profile_id': profile_id, 'field_mapping': mapping,
'column_meta': column_meta, 'quality': quality, 'file_checksum': analysis.file_checksum,
'confirmed_at': datetime.utcnow().isoformat(),
},
}
item.status = 'confirmed_for_temporary_use'
db.session.commit()
return _serialize(item)
def list_confirmed_temporary_inventory_sessions(*, limit: int = 100) -> list[dict[str, Any]]:
"""返回管理员可沉淀为解析方案草稿的已确认临时会话,不暴露库存行或对象存储路径。"""
rows = ShippingTemporaryInventorySession.query.filter_by(
status='confirmed_for_temporary_use',
).order_by(ShippingTemporaryInventorySession.updated_at.desc()).limit(max(1, min(int(limit or 100), 200))).all()
result: list[dict[str, Any]] = []
for item in rows:
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
confirmed = _confirmed_usage(item)
result.append({
'session_no': item.session_no,
'analysis_id': item.analysis_id,
'source_file_name': analysis.source_file_name if analysis else None,
'file_format': analysis.file_format if analysis else None,
'analysis': _serialize_dify_analysis_preview(analysis) if analysis else None,
'confirmed_usage': confirmed,
'locked_mapping': ((item.result_json or {}).get('confirmed_usage', {}).get('field_mapping', {}) if isinstance(item.result_json, dict) else {}),
'created_at': item.created_at.isoformat() if item.created_at else None,
'expires_at': item.expires_at.isoformat() if item.expires_at else None,
'promoted_profile_draft_id': ((item.result_json or {}).get('promoted_profile_draft_id') if isinstance(item.result_json, dict) else None),
})
return result
def create_parsing_profile_draft_from_temporary_session(
session_no: str,
data: dict[str, Any],
*,
actor_id: int | None,
) -> dict[str, Any]:
"""
管理员把已确认临时库存会话沉淀为库存文件解析方案草稿。
核心逻辑:只接受已通过确定性质量校验的临时会话,强制复用其锁定映射和结构;
管理员仍需维护方案编码、显示名称和订单匹配键。创建结果始终是 draft,不能绕过原有发布/站点启用门禁。
Args:
session_no: 已确认的临时库存会话编号。
data: 管理员填写的 profile_code、display_name、match_keys;字段映射由后端忽略客户端输入并锁定会话版本。
actor_id: 当前管理员用户 ID。
Returns:
新建的库存文件解析方案草稿。
"""
normalized_no = str(session_no or '').strip().upper()
item = ShippingTemporaryInventorySession.query.filter_by(session_no=normalized_no).one_or_none()
if item is None:
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND')
if item.status != 'confirmed_for_temporary_use':
raise ConflictError('Temporary inventory session is not confirmed', code='SHIPPING.TEMP_INVENTORY_PROMOTION_INVALID')
confirmed = (item.result_json or {}).get('confirmed_usage') if isinstance(item.result_json, dict) else None
if not isinstance(confirmed, dict) or not isinstance(confirmed.get('field_mapping'), dict):
raise ConflictError('Temporary inventory confirmation is incomplete', code='SHIPPING.TEMP_INVENTORY_PROMOTION_INVALID')
existing_draft_id = (item.result_json or {}).get('promoted_profile_draft_id') if isinstance(item.result_json, dict) else None
if existing_draft_id:
existing_draft = db.session.get(ShippingInventoryParsingProfile, existing_draft_id)
if existing_draft is not None:
from app.services.shipping_notice.inventory_parsing_profile import payload as profile_payload
return profile_payload(existing_draft)
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
if analysis is None:
raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_INVENTORY_PROMOTION_INVALID')
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
payload = {
'profile_code': data.get('profile_code'),
'display_name': data.get('display_name'),
'sheet_name': structure.get('selected_sheet_name'),
'header_row_index': structure.get('selected_header_row_index'),
'field_mapping': confirmed['field_mapping'],
'match_keys': data.get('match_keys'),
}
from app.services.shipping_notice import inventory_structure_analysis
draft = inventory_structure_analysis.create_profile_draft(analysis.id, payload, actor_id=actor_id)
item.result_json = {
**(item.result_json if isinstance(item.result_json, dict) else {}),
'promoted_profile_draft_id': draft['id'],
'promoted_at': datetime.utcnow().isoformat(),
'promoted_by': actor_id,
}
db.session.commit()
return draft
@@ -22,12 +22,7 @@ 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_SUFFIXES = (".xls", ".xlsx", ".csv")
_TASK_INVENTORY_MARKER = ".current_inventory"
_TASK_INVENTORY_VERSION_PREFIX = "inventory_"
@@ -214,7 +209,7 @@ def _task_inventory_upload_dir(task_no: str) -> Path:
def task_inventory_upload_path(task_no: str, *, suffix: str | None = None) -> Path:
"""
任务级库存附件标准落盘路径(默认 inventory.xlsx)。
suffix 仅允许 .xlsx / .csv,用于 RPA 回调保留源文件格式。
suffix 仅允许 .xls / .xlsx / .csv,用于 RPA 回调保留源文件格式。
"""
normalized = (suffix or ".xlsx").lower()
if normalized not in _TASK_INVENTORY_SUFFIXES:
@@ -261,8 +256,8 @@ def save_task_inventory_upload(task_no: str, upload: FileStorage) -> Path:
"""保存 werkzeug FileStorage 库存上传并返回落盘路径。"""
suffix = ".xlsx"
filename = str(getattr(upload, "filename", "") or "").lower()
if filename.endswith(".csv"):
suffix = ".csv"
if filename.endswith((".xls", ".csv")):
suffix = Path(filename).suffix
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}"
@@ -278,8 +273,8 @@ def save_task_inventory_local_file(task_no: str, source_path: str | Path) -> Pat
保存本地已存在的库存文件到任务标准库存目录。
【AI 触发时机】:当 RPA 或其他后台流程已经拿到本地 Excel,需要把它正式纳入系统托管目录时调用。
核心逻辑:校验 source_path 存在后,统一复制到 inventory_uploads/{task_no}/inventory.xlsx,
让 RPA 下载与人工上传共用同一套任务级库存附件路径。
核心逻辑:校验 source_path 存在后,按源文件格式复制到版本化任务附件路径,
让 RPA 下载与人工上传共用同一套任务级库存附件路径,并保留 .xls/.xlsx/.csv 格式。
Args:
task_no: 发货任务号,禁止为空。
@@ -314,7 +309,7 @@ def stage_task_inventory_callback_file(
) -> Path:
"""
将 RPA 回调文件复制到本轮唯一 staging 路径,避免在校验前覆盖任务正式附件。
核心逻辑:落盘至 inventory_uploads/{task_no}/.staging/rpa_callback_{token}.xlsx。
核心逻辑:按源文件格式落盘至 inventory_uploads/{task_no}/.staging/rpa_callback_{token}{suffix}。
Args:
task_no: 发货任务号。
@@ -393,47 +388,3 @@ def delete_staged_task_inventory_file(staging_path: str | Path | None) -> None:
path.parent.rmdir()
except OSError:
pass
def read_task_inventory_schema_preview(task_no: str) -> dict[str, Any]:
"""读取已上传库存文件的表头与样本行 preview(供映射表单/LLM 用)。"""
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
return preview
def parse_uploaded_task_inventory(
task_no: str,
*,
field_mapping: dict[str, str] | None = None,
mapping_source: str = "rules",
header_row_index: int | None = None,
llm_match_rule: str | None = None,
llm_match_key: list[str] | None = None,
) -> tuple[list[dict[str, Any]], dict[str, Any], Path]:
"""
解析已上传的任务库存 Excel。
Returns:
tuple: (inventory_lines, column_meta, 文件路径)。
"""
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,
field_mapping=field_mapping,
mapping_source=mapping_source,
header_row_index=header_row_index,
llm_match_rule=llm_match_rule,
llm_match_key=llm_match_key,
)
return lines, column_meta, path
def has_uploaded_task_inventory(task_no: str) -> bool:
"""任务是否已有落盘的库存附件(.xlsx 或 .csv)。"""
return resolve_task_inventory_upload_path(task_no) is not None
@@ -0,0 +1,70 @@
"""
services/shipping_notice/inventory_warehouse_resolution.py
用途:按库存解析方案的匹配关系,从订单行与库存行确定动态 Warehouse。
依赖:ShippingInventoryField/Source、动态订单字段投影、task_line_store。
逻辑:仅在 inventory_match Source 链接库存快照时调用;字段 ID 和用途决定匹配及仓库取值。
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
from app.models import ShippingInventoryField, ShippingInventorySource
from app.services.shipping_notice.export import order_field_id_values
@dataclass(frozen=True)
class WarehouseResolution:
"""动态 Warehouse 决策结果;不唯一或缺失时不可继续链接。"""
warehouse_id: str | None
reason: str = ''
def _key(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None:
"""按配置字段 ID 构造大小写不敏感的精确匹配键。"""
values = tuple(str(row.get(field) or '').strip().casefold() for field in fields)
return values if values and all(values) else None
def resolve_dynamic_warehouse(*, task: Any, inventory_lines: list[dict[str, Any]], fallback_warehouse_id: str | None = None) -> WarehouseResolution:
"""按站点已发布解析方案为全部订单行寻找唯一 Warehouse。"""
source = ShippingInventorySource.query.filter_by(source_code=task.inventory_source_code).first()
definition = source.parsing_profile.definition_json if source and source.parsing_profile else {}
match_keys = definition.get('match_keys') if isinstance(definition, dict) else []
order_fields = [str(item.get('order_field_id') or '') for item in match_keys if isinstance(item, dict)]
inventory_fields = [str(item.get('inventory_field_id') or '') for item in match_keys if isinstance(item, dict)]
mapped_ids = {
int(field_id) for field_id in (definition.get('field_mapping') or {})
if str(field_id).isdigit()
} if isinstance(definition, dict) else set()
warehouse_fields = ShippingInventoryField.query.filter(
ShippingInventoryField.id.in_(mapped_ids), ShippingInventoryField.status == 'active',
ShippingInventoryField.usage_type == 'warehouse_identity',
).all() if mapped_ids else []
if not order_fields or len(order_fields) != len(inventory_fields) or len(warehouse_fields) != 1:
return WarehouseResolution(None, 'warehouse_configuration_invalid')
warehouse_field_id = str(warehouse_fields[0].id)
rows_by_key: dict[tuple[str, ...], set[str]] = {}
fallback = str(fallback_warehouse_id or '').strip().upper()
for row in inventory_lines:
if not isinstance(row, dict):
continue
key = _key(row, inventory_fields)
warehouse = str(row.get(warehouse_field_id) or fallback).strip().upper()
if key and warehouse:
rows_by_key.setdefault(key, set()).add(warehouse)
warehouses: set[str] = set()
_header_values, order_lines = order_field_id_values(task)
for order_line in order_lines:
key = _key(order_line, order_fields)
if not key or not rows_by_key.get(key):
return WarehouseResolution(None, 'warehouse_not_found_for_order_line')
warehouses.update(rows_by_key[key])
if len(warehouses) != 1:
return WarehouseResolution(None, 'warehouse_ambiguous' if warehouses else 'warehouse_not_found')
return WarehouseResolution(next(iter(warehouses)))
@@ -1,10 +1,9 @@
"""
services/shipping_notice/inventory_workflow.py
用途:发货通知库存阶段编排(解析、上传、ensure_inventory);RPA 见 inventory_rpa_workflow。
依赖:customer_identity_gate、reservation_gate、inventory_*、inventory_mapping_workflow、inventory_rpa_workflow、query_service、state_machine、task_line_store。
逻辑:tools.py 门面 re-export;解析/上传完成后委托 inventory_mapping_workflow 做对齐与 auto-chain;
Reservation 门禁订单行经 read_task_order_lines 读取。
用途:发货通知正式库存阶段编排(上传、复用已解析库存文件);RPA 见 inventory_rpa_workflow。
依赖:customer_identity_gate、reservation_gate、inventory_file_store、inventory_mapping_workflow、query_service、state_machine、task_line_store。
逻辑:正式库存仅按库存站点 published Profile 确定性解析;任务级列推断和映射确认入口已移除。
"""
from __future__ import annotations
@@ -16,43 +15,12 @@ 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,
payload_map_json,
)
from app.services.shipping_notice.inventory_mapping import (
mapping_is_complete,
normalize_field_mapping,
validate_field_mapping_against_headers,
)
from app.services.shipping_notice.inventory_mapping_store import (
resolve_inventory_mapping,
upsert_inventory_mapping,
)
from app.services.shipping_notice.inventory_mapping_workflow import (
awaiting_inventory_mapping_confirm,
inventory_loaded_response,
inventory_mapping_checkpoint_response,
)
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
from app.services.shipping_notice.inventory_file_store import (
active_inventory_file_for_task,
has_uploaded_inventory_file,
parse_linked_inventory_file,
read_linked_inventory_schema_preview,
save_batch_inventory_upload,
)
from app.services.shipping_notice.inventory_snapshot import parse_inventory_text
from app.services.shipping_notice.inventory_upload import (
has_uploaded_task_inventory,
inventory_text_max_chars,
parse_uploaded_task_inventory,
read_task_inventory_schema_preview,
save_task_inventory_upload,
)
from app.services.shipping_notice.match_rule_desc import extract_mapping_payload_extras
from app.services.shipping_notice.query_service import (
get_task_by_ref,
resolve_task_from_payload,
@@ -89,43 +57,6 @@ def parse_inventory_lines(payload: dict[str, Any]) -> list[dict[str, Any]] | Non
return None
def _resolve_inventory_field_mapping(payload: dict[str, Any]) -> tuple[dict[str, str] | None, str]:
raw = payload_map_json(payload)
field_mapping = normalize_field_mapping(raw)
if field_mapping:
return field_mapping, "llm"
return None, "rules"
def _extract_partial_inventory_field_mapping(raw: Any) -> dict[str, str]:
data: dict[str, Any] | None = None
if isinstance(raw, dict):
data = raw
elif isinstance(raw, str) and raw.strip():
try:
parsed = json.loads(raw)
if isinstance(parsed, dict):
data = parsed
except json.JSONDecodeError:
data = None
if not data:
return {}
inner = data.get("mapping") if isinstance(data.get("mapping"), dict) else data
if not isinstance(inner, dict):
return {}
result: dict[str, str] = {}
for key in ("part_number", "aws_part_number", "reservation_id", "available_qty"):
value = inner.get(key)
if value is None:
continue
text = str(value).strip()
if text:
result[key] = text
return result
def _reservation_gate_response(task: ShippingTask, *, lang: str) -> dict[str, Any] | None:
"""
库存入口统一检查订单侧 Reservation ID。
@@ -192,312 +123,8 @@ def _inventory_source_gate_response(task: ShippingTask, *, operation: str, lang:
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)
task = resolve_task_from_payload(payload)
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 {
"1",
"true",
"yes",
}
raw_text = str(payload.get("raw_inventory_text") or "").strip()
inventory_lines = parse_inventory_lines(payload)
warnings: list[str] = []
column_meta: dict[str, Any] | None = None
source = "parse"
field_mapping, mapping_source = _resolve_inventory_field_mapping(payload)
mapping_extras = extract_mapping_payload_extras(payload_map_json(payload))
if mapping_extras.get("match_rule"):
mapping_source = "llm"
# [STEP 2] 按来源解析库存内容。
# 优先复用已上传文件;否则再回退到 structured 或 raw_text,避免大 Excel 直接走 LLM 文本链路。
has_uploaded_file = has_uploaded_inventory_file(task) or has_uploaded_task_inventory(task.task_no)
if use_uploaded or (not inventory_lines and not raw_text and has_uploaded_file):
if not has_uploaded_file:
return tool_response(
status="needs_human",
task=task,
message=t("workflow.inventory.uploaded_file_missing", lang=lang),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
stop_agent_turn=True,
)
inv_file = active_inventory_file_for_task(task)
if inv_file:
inventory_lines, column_meta, path, _inv_file = parse_linked_inventory_file(
task,
field_mapping=field_mapping,
mapping_source=mapping_source,
llm_match_rule=mapping_extras.get("match_rule"),
llm_match_key=mapping_extras.get("match_key"),
)
else:
inventory_lines, column_meta, path = parse_uploaded_task_inventory(
task.task_no,
field_mapping=field_mapping,
mapping_source=mapping_source,
llm_match_rule=mapping_extras.get("match_rule"),
llm_match_key=mapping_extras.get("match_key"),
)
source = "uploaded_file"
warnings.append(f"parsed from uploaded file: {path.name}")
elif not inventory_lines:
structured = payload.get("structured") if isinstance(payload.get("structured"), dict) else None
if structured and isinstance(structured.get("lines"), list):
inventory_lines = structured["lines"]
source = "structured"
elif raw_text:
max_chars = inventory_text_max_chars()
if len(raw_text) > max_chars:
log_task_event(
task,
"inventory_text_too_large",
{"chars": len(raw_text), "max_chars": max_chars},
)
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=t("workflow.inventory.text_too_large", lang=lang).format(
chars=len(raw_text),
max_chars=max_chars,
),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
next_required_action=t("workflow.inventory.upload_then_parse", lang=lang),
forbidden_next_tools=["match_inventory"],
stop_agent_turn=True,
)
inventory_lines, warnings, column_meta = parse_inventory_text(
raw_text,
field_mapping=field_mapping,
)
# [STEP 3] 对解析失败和成功分别进入下一阶段。
# 失败时停在人审检查点;成功时统一委托 inventory_loaded_response 进入字段对齐/自动串联。
if not inventory_lines:
log_task_event(task, "inventory_parse_failed", {"warnings": warnings, "use_uploaded": use_uploaded})
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=t("workflow.inventory.parse_failed", lang=lang),
data={**serialize_task_for_tool(task), "warnings": warnings},
checkpoint=CP_MAP_INFER,
)
return inventory_loaded_response(
task,
inventory_lines,
warnings=warnings,
column_meta=column_meta,
source=source,
require_mapping_review=True,
event_type="inventory_parsed",
chain_payload=payload,
)
def get_inventory_schema_preview(payload: dict[str, Any]) -> dict[str, Any]:
"""Return headers + sample rows for LLM column mapping (small payload)."""
lang = resolve_lang(payload)
task = resolve_task_from_payload(payload)
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",
task=task,
message=t("workflow.inventory.uploaded_file_missing", lang=lang),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
stop_agent_turn=True,
)
try:
if has_uploaded_inventory_file(task):
preview = read_linked_inventory_schema_preview(task)
else:
preview = read_task_inventory_schema_preview(task.task_no)
except OSError as exc:
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.inventory.preview_read_failed", lang=lang).format(error=exc),
)
log_task_event(task, "inventory_schema_preview", {"headers": preview.get("headers")})
db.session.commit()
return tool_response(
status="ok",
task=task,
message=t("workflow.inventory.preview_ready", lang=lang),
data={**serialize_task_for_tool(task), "schema_preview": preview},
checkpoint=CP_MAP_INFER,
next_required_action=t("workflow.inventory.preview_next", lang=lang),
forbidden_next_tools=["match_inventory"],
)
def apply_inventory_mapping(payload: dict[str, Any]) -> dict[str, Any]:
"""Apply LLM/manual column mapping and parse full uploaded inventory file."""
lang = resolve_lang(payload)
task = resolve_task_from_payload(payload)
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):
return tool_response(
status="needs_human",
task=task,
message=t("workflow.inventory.uploaded_file_missing_short", lang=lang),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
stop_agent_turn=True,
)
try:
if has_uploaded_inventory_file(task):
preview = read_linked_inventory_schema_preview(task)
else:
preview = read_task_inventory_schema_preview(task.task_no)
except OSError as exc:
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.inventory.preview_read_failed", lang=lang).format(error=exc),
)
raw = payload_map_json(payload)
# [STEP 2] 汇总映射候选来源。
# direct/partial 来自本次 map_json,template/suggested 来自历史模板和表头预判,按完整度决定优先级。
direct = normalize_field_mapping(raw)
partial = _extract_partial_inventory_field_mapping(raw)
template: dict[str, str] = {}
if task.customer_code:
resolved = resolve_inventory_mapping(task.customer_code, preview=preview)
if isinstance(resolved, dict):
template = {k: str(v).strip() for k, v in resolved.items() if str(v or "").strip()}
suggested = preview.get("suggested_mapping") if isinstance(preview.get("suggested_mapping"), dict) else {}
suggested = {k: str(v).strip() for k, v in suggested.items() if str(v or "").strip()}
base: dict[str, str] = {}
if mapping_is_complete(template):
base = template
elif mapping_is_complete(suggested):
base = suggested
else:
base = {**template, **suggested}
field_mapping = direct or {**base, **partial}
mapping_extras = extract_mapping_payload_extras(raw)
if direct or partial or mapping_extras.get("match_rule"):
mapping_source = "llm"
else:
mapping_source = "rules"
if not mapping_is_complete(field_mapping):
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.inventory.mapping_invalid", lang=lang),
data={
**serialize_task_for_tool(task),
"schema_preview": preview,
"suggested_mapping": suggested,
"template_mapping": template if template else None,
"received_mapping": partial or None,
},
)
# [STEP 3] 确认映射与真实表头一致,再解析整份上传文件。
# 只有列名校验通过后才允许落地库存明细,避免错误映射污染后续匹配链路。
mapping_errors = validate_field_mapping_against_headers(
preview.get("headers") or [],
field_mapping,
)
if mapping_errors:
header_row = preview.get("header_row_index") or 1
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.inventory.mapping_header_mismatch", lang=lang).format(
row=header_row,
errors=" ".join(mapping_errors),
),
data={**serialize_task_for_tool(task), "schema_preview": preview},
)
try:
inv_file = active_inventory_file_for_task(task)
if inv_file:
inventory_lines, column_meta, path, _inv_file = parse_linked_inventory_file(
task,
field_mapping=field_mapping,
mapping_source=mapping_source,
header_row_index=preview.get("header_row_index"),
llm_match_rule=mapping_extras.get("match_rule"),
llm_match_key=mapping_extras.get("match_key"),
)
else:
inventory_lines, column_meta, path = parse_uploaded_task_inventory(
task.task_no,
field_mapping=field_mapping,
mapping_source=mapping_source,
header_row_index=preview.get("header_row_index"),
llm_match_rule=mapping_extras.get("match_rule"),
llm_match_key=mapping_extras.get("match_key"),
)
except FileNotFoundError as exc:
return tool_response(status="failed", task_id=task.task_no, message=str(exc))
except OSError as exc:
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.inventory.parse_failed_detail", lang=lang).format(error=exc),
)
warnings = [f"parsed with mapping from uploaded file: {path.name}"]
upsert_inventory_mapping(task.customer_code, preview=preview, field_mapping=field_mapping)
return inventory_loaded_response(
task,
inventory_lines,
warnings=warnings,
column_meta=column_meta,
source="uploaded_file_mapping",
require_mapping_review=True,
event_type="inventory_mapping_applied",
chain_payload=payload,
field_mapping=field_mapping,
mapping_source=mapping_source,
)
def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
"""Save multipart Excel; return schema preview for LLM mapping (no full parse)."""
"""按任务库存站点的 published Profile 保存并确定性解析人工库存文件。"""
task = get_task_by_ref(str(task_id or ""))
if not task:
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang="zh"))
@@ -522,7 +149,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", ".csv")):
if not filename.lower().endswith((".xls", ".xlsx", ".csv")):
return tool_response(
status="failed",
task_id=task.task_no,
@@ -541,14 +168,20 @@ 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)
inventory_lines = [
item for item in (inv_file.inventory_lines_json or []) if isinstance(item, dict)
]
preview = dict(inv_file.schema_preview_json or {})
except AppError as exc:
db.session.rollback()
message = str(exc.message or "库存上传被拒绝")
if exc.code == 'SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED':
message = '库存文件结构与该库存站点已发布的解析方案不一致,请重新导出正确文件或由管理员发布新方案。'
return tool_response(
status="failed",
task=task,
task_id=task.task_no,
message=str(exc.message or "库存上传被拒绝"),
message=message,
data=serialize_task_for_tool(task),
stop_agent_turn=True,
)
@@ -560,39 +193,18 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
message=t("workflow.inventory.save_failed", lang=lang).format(error=exc),
)
template_mapping = resolve_inventory_mapping(task.customer_code, preview=preview)
if template_mapping and mapping_is_complete(template_mapping):
try:
inventory_lines, column_meta, path, _inv_file = parse_linked_inventory_file(
task,
field_mapping=template_mapping,
mapping_source="template",
)
if inventory_lines:
warnings = [f"parsed from template mapping: {path.name}"]
return inventory_loaded_response(
task,
inventory_lines,
warnings=warnings,
column_meta=column_meta,
source="uploaded_file_template",
require_mapping_review=True,
event_type="inventory_template_mapping_used",
field_mapping=template_mapping,
mapping_source="template",
)
except Exception:
pass
suggested = preview.get("suggested_mapping") if isinstance(preview.get("suggested_mapping"), dict) else {}
suggested_clean = {k: str(v).strip() for k, v in suggested.items() if str(v).strip()}
suggested_complete = mapping_is_complete(suggested_clean)
auto_map = (
json.dumps(suggested_clean, ensure_ascii=False) if suggested_complete else None
)
apply_task_transition(task, TaskTransition.MAP_INFER)
log_task_event(task, "inventory_file_uploaded", {"filename": filename, "headers": preview.get("headers")})
structure_validation = preview.get('structure_validation') if isinstance(
preview.get('structure_validation'), dict
) else {}
column_meta = {
'structure_validation': structure_validation,
}
log_task_event(task, "inventory_file_uploaded", {
"filename": filename,
"headers": preview.get("headers"),
"structure_validation": structure_validation,
"parser_contract": "published_profile",
})
log_task_event(
task,
"inventory_snapshot_created",
@@ -602,33 +214,15 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
"batch_no": task.batch.batch_no if task.batch else None,
},
)
db.session.commit()
upload_message = t("workflow.inventory.uploaded", lang=lang)
if suggested_complete:
upload_message += t("workflow.inventory.uploaded_suggested_complete", lang=lang)
else:
upload_message += t("workflow.inventory.uploaded_need_llm", lang=lang)
return tool_response(
status="ok",
task=task,
message=upload_message,
data={
**serialize_task_for_tool(task),
"batch_no": task.batch.batch_no if task.batch else None,
"batch": serialize_batch_for_tool(task.batch) if task.batch else None,
"schema_preview": preview,
"inventory_file_no": inv_file.inventory_file_no,
"share_mode": inv_file.share_mode,
"linked_task_nos": [
link.task.task_no
for link in (inv_file.links or [])
if link.is_active and link.task
],
SUGGEST_OK: suggested_complete,
AUTO_MAP: auto_map,
},
next_required_action=t("workflow.inventory.apply_mapping_next", lang=lang),
forbidden_next_tools=["match_inventory"],
return inventory_loaded_response(
task,
inventory_lines,
warnings=list(structure_validation.get('warnings') or []),
column_meta=column_meta,
source='manual_upload_published_profile',
event_type='inventory_manual_upload_ready',
field_mapping=dict(inv_file.field_mapping_json or {}),
mapping_source='parsing_profile',
)
@@ -652,23 +246,31 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
task,
inventory_lines,
source="manual_json",
require_mapping_review=False,
event_type="inventory_uploaded",
)
# [STEP 2] 如果允许自动模式,就优先交给 RPA 获取库存。
# auto / retry_rpa 都属于“先尝试系统拉取库存”,避免不必要地要求用户手工上传。
if mode == "retry_rpa" or mode == "auto":
# [STEP 2] 正常流程只复用已完成的库存快照,绝不隐式触发 RPA。
# 库存导出由独立排程生产;用户明确选择 retry_rpa 才允许本任务发起刷新。
if mode == "retry_rpa":
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
return ensure_inventory_via_rpa(task, mode=mode)
# [STEP 3] 最后处理已有快照与彻底缺库存两种兜底分支。
if mode == "auto":
from app.services.shipping_notice.inventory_rpa_workflow import _try_reuse_inventory_snapshot
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
reused = _try_reuse_inventory_snapshot(
task,
task_rpa_inventory_source(task) or {},
mode=mode,
)
if reused is not None:
return reused
# [STEP 3] 最后处理已有任务库存与彻底缺库存两种兜底分支。
# 已有库存则推进到 inventory_ready;仍无库存则明确停在人审提示用户补数据。
if task.inventory_lines_json:
if awaiting_inventory_mapping_confirm(task):
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
return inventory_mapping_checkpoint_response(task, lang=lang or None)
apply_task_transition(task, TaskTransition.INVENTORY_READY)
db.session.commit()
return tool_response(
@@ -679,6 +281,15 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
)
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
step_title="获取库存",
status="needs_human",
message=t("workflow.inventory.unavailable", lang=lang),
progress_percent=0,
detail=t("workflow.inventory.unavailable", lang=lang),
)
log_task_event(task, "inventory_missing", {})
db.session.commit()
return tool_response(
+33 -44
View File
@@ -1,9 +1,9 @@
"""
services/shipping_notice/match.py
用途:执行订单行与库存行的匹配、缺货判断与匹配结果汇总。
依赖:shipping_notice.i18n、reservation_id 归一化工具、标准聚合逻辑。
逻辑:由 fulfillment_workflow.match_inventory 调用本文件,把通知订单行与库存快照比对后返回匹配状态和缺货明细。
用途:按解析方案配置的字段关系执行库存匹配、缺货判断与结果汇总。
依赖:shipping_notice.i18n、动态订单字段投影、标准聚合逻辑。
逻辑:由 fulfillment_workflow 传入订单字段 ID、库存字段 ID 和数量字段 ID,字段名称不参与匹配。
"""
from __future__ import annotations
@@ -11,69 +11,56 @@ from __future__ import annotations
from typing import Any, Callable
from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.reservation_id import validated_reservation_id
def _norm(value: Any) -> str:
return str(value or "").strip()
def _norm_reservation(value: Any) -> str:
return validated_reservation_id(value)
def _line_key(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None:
"""按配置字段列表构造确定性匹配键;任一字段为空时该行不可匹配。"""
values = tuple(_norm(row.get(field)).casefold() for field in fields)
return values if values and all(values) else None
def _line_key(part_number: str, reservation_id: str | None) -> tuple[str, str]:
"""构造内部料号与 Reservation 的库存定位键。"""
return (_norm(part_number), _norm_reservation(reservation_id))
def _aggregate_inventory(inventory_lines: list[dict[str, Any]]) -> dict[tuple[str, str], float]:
"""按库存 part_number 与 reservation_id 汇总 available_qty。"""
totals: dict[tuple[str, str], float] = {}
def _aggregate_inventory(
inventory_lines: list[dict[str, Any]], *, match_fields: list[str], quantity_field: str,
) -> dict[tuple[str, ...], float]:
"""按用户配置的库存匹配字段组合汇总唯一数量字段。"""
totals: dict[tuple[str, ...], float] = {}
for row in inventory_lines:
part_number = _norm(row.get("part_number"))
if not part_number:
continue
reservation_id = _norm_reservation(row.get("reservation_id"))
if not reservation_id:
key = _line_key(row, match_fields)
if key is None:
continue
try:
qty = float(row.get("available_qty") or 0)
qty = float(row.get(quantity_field) or 0)
except (TypeError, ValueError):
qty = 0.0
key = _line_key(part_number, reservation_id)
totals[key] = totals.get(key, 0.0) + qty
return totals
def _available_for_notice_line(
part_number: str,
reservation_id: str | None,
inv_totals: dict[tuple[str, str], float],
) -> float:
part_number_normalized = _norm(part_number)
rid = _norm_reservation(reservation_id)
if not rid:
return 0.0
return inv_totals.get((part_number_normalized, rid), 0.0)
def match_notice_lines(
notice_lines: list[dict[str, Any]],
inventory_lines: list[dict[str, Any]],
*,
match_keys: list[dict[str, str]],
quantity_field_id: str,
progress_callback: Callable[[int, int], None] | None = None,
) -> tuple[str, list[dict[str, Any]], dict[str, Any]]:
"""
将订单行与库存行按 (part_number, reservation_id) 匹配,计算 fulfillable/partial/unfulfillable。
按订单字段 ID 到库存字段 ID 的配置关系匹配,计算 fulfillable/partial/unfulfillable。
核心逻辑:聚合库存 → 逐行比对 required vs available → 汇总 match_status 与 shortages。
Returns:
tuple: (match_status, line_results, shortage_json)。
"""
# [STEP 1] 库存 Supplier Sku 已规范为 part_number,与订单内部料号直接配对。
inv_totals = _aggregate_inventory(inventory_lines)
order_fields = [str(item.get('order_field_id') or '') for item in match_keys]
inventory_fields = [str(item.get('inventory_field_id') or '') for item in match_keys]
if not order_fields or any(not item for item in order_fields + inventory_fields) or not quantity_field_id:
raise ValueError('库存解析方案缺少有效的匹配字段或库存数量字段')
inv_totals = _aggregate_inventory(
inventory_lines, match_fields=inventory_fields, quantity_field=quantity_field_id,
)
line_results: list[dict[str, Any]] = []
shortages: list[dict[str, Any]] = []
@@ -83,14 +70,13 @@ def match_notice_lines(
# [STEP 2] 逐订单行计算 ok/partial/shortage 并收集缺口明细。
total_lines = len(notice_lines)
for index, line in enumerate(notice_lines, start=1):
part_number = _norm(line.get("part_number"))
reservation_id = _norm_reservation(line.get("reservation_id")) or None
order_key = _line_key(line, order_fields)
try:
required = float(line.get("qty") or 0)
required = float(line.get("__required_qty") or 0)
except (TypeError, ValueError):
required = 0.0
available = _available_for_notice_line(part_number, reservation_id, inv_totals)
available = inv_totals.get(order_key, 0.0) if order_key is not None else 0.0
if available >= required:
line_status = "ok"
shortage = 0.0
@@ -104,8 +90,11 @@ def match_notice_lines(
has_shortage = True
result = {
"part_number": part_number,
"reservation_id": reservation_id or "",
"part_number": _norm(line.get("__display_part_number")),
"reservation_id": _norm(line.get("__display_reservation_id")),
"order_match_values": {
order_field: line.get(order_field) for order_field in order_fields
},
"required_qty": required,
"available_qty": available,
"shortage_qty": shortage,
@@ -1,65 +1,13 @@
"""
services/shipping_notice/match_rule_desc.py
用途:解析 map_json 中的匹配规则扩展字段,并生成用户可读的匹配规则说明。
依赖:标准 `json` 解析与 `typing` 工具。
逻辑:由 inventory_mapping、field_alignment_summary 等模块调用本文件,把匹配规则和附加说明渲染成展示文案。
用途:根据已确认的库存栏位映射生成用户可读的匹配规则说明。
依赖:标准类型能力。
逻辑:由 inventory_mapping、field_alignment_summary 等模块调用,说明订单字段与库存栏位的确定性对应关系。
"""
from __future__ import annotations
from typing import Any
def _payload_root(raw: Any) -> dict[str, Any] | None:
data: dict[str, Any] | None = None
if isinstance(raw, dict):
data = raw
elif isinstance(raw, str) and raw.strip():
import json
try:
parsed = json.loads(raw)
if isinstance(parsed, dict):
data = parsed
except json.JSONDecodeError:
return None
return data
def extract_mapping_payload_extras(raw: Any) -> dict[str, Any]:
"""从 map_json 读取 match_rule / match_key 等 LLM 扩展字段(非列名映射)。"""
data = _payload_root(raw)
if not data:
return {}
inner = data.get("mapping") if isinstance(data.get("mapping"), dict) else data
if not isinstance(inner, dict):
inner = data
match_rule = str(
data.get("match_rule")
or data.get("matching_rule")
or inner.get("match_rule")
or inner.get("matching_rule")
or ""
).strip()
match_key_raw = data.get("match_key") or inner.get("match_key")
match_key: list[str] | None = None
if isinstance(match_key_raw, list):
match_key = [str(k).strip() for k in match_key_raw if str(k).strip()]
elif isinstance(match_key_raw, str) and match_key_raw.strip():
match_key = [part.strip() for part in match_key_raw.split(",") if part.strip()]
extras: dict[str, Any] = {}
if match_rule:
extras["match_rule"] = match_rule
if match_key:
extras["match_key"] = match_key
return extras
def infer_match_key(field_mapping: dict[str, str]) -> list[str]:
"""根据库存列映射推断业务匹配键列表(默认 part_number + reservation_id)。"""
keys = ["part_number"]
@@ -73,7 +21,7 @@ def build_match_rule_fallback(
*,
match_key: list[str] | None = None,
) -> str:
"""LLM 未提供 match_rule 时,根据列映射动态生成中文规则说明。"""
"""根据已确认的栏位映射动态生成中文规则说明。"""
part_number_col = str(field_mapping.get("part_number") or "Supplier Sku").strip() or "Supplier Sku"
qty_col = str(field_mapping.get("available_qty") or "可用数量").strip() or "可用数量"
keys = match_key or infer_match_key(field_mapping)
@@ -92,12 +40,7 @@ def build_match_rule_fallback(
def resolve_match_rule(
field_mapping: dict[str, str],
*,
llm_match_rule: str | None = None,
llm_match_key: list[str] | None = None,
) -> tuple[str, list[str], str]:
"""返回 (match_rule, match_key, match_rule_source);优先 LLM 规则,否则 fallback。"""
keys = llm_match_key or infer_match_key(field_mapping)
if llm_match_rule and str(llm_match_rule).strip():
return str(llm_match_rule).strip(), keys, "llm"
return build_match_rule_fallback(field_mapping, match_key=keys), keys, "fallback"
"""返回由已确认栏位映射生成的匹配说明、匹配键及规则来源。"""
keys = infer_match_key(field_mapping)
return build_match_rule_fallback(field_mapping, match_key=keys), keys, "configured_mapping"
@@ -10,9 +10,6 @@ from __future__ import annotations
from typing import Any
from app.services.shipping_notice.constants import MAP_JSON
def _str_prop(description: str, *, enum: list[str] | None = None) -> dict[str, Any]:
prop: dict[str, Any] = {"type": "string", "description": description}
if enum:
@@ -77,6 +74,30 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
runtime_context = _str_prop(
"HXOPS 注入的完整 agent_runtime_context JSON 字符串;必须原样透传,禁止由 LLM 构造或修改"
)
observation_schema = {
"type": "object",
"required": ["value", "document_id", "quote"],
"properties": {
"value": {"description": "从证据原文提取的字段值,类型必须符合动态字段契约"},
"document_id": _int_prop("证据来源 Document ID,必须来自抽取上下文"),
"quote": _str_prop("证据原文中的逐字引用,HXOPS 将验证其确实存在"),
"confidence": {"type": "number", "minimum": 0, "maximum": 1},
},
"additionalProperties": False,
}
extracted_field_schema = {
"type": "object",
"required": ["field_id", "observations"],
"properties": {
"field_id": _str_prop("动态字段契约中的稳定 field_id,禁止传 field_code 或显示名称"),
"observations": {
"type": "array",
"minItems": 1,
"items": observation_schema,
},
},
"additionalProperties": False,
}
return {
"openapi": "3.0.0",
@@ -107,7 +128,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
required=["agent_runtime_context"],
description=(
"仅在 refs.capability=order_extraction 分支调用。Tool 从 platform.session_id 反查当前用户,"
"并返回 input_snapshot_hash、documents 与固定输出契约;禁止让 LLM 传 user_id。"
"并返回 input_snapshot_hash、documents 与当前 published 动态 Schema 契约;禁止让 LLM 传 user_id。"
),
),
"/tools/submit_order_extraction": _post_op(
@@ -123,61 +144,43 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"items": {
"type": "object",
"required": [
"schema_version_id",
"schema_checksum",
"source_intake_no",
"primary_document_id",
"classification",
"classification_confidence",
"field_confidence",
"header_fields",
"lines",
"evidence",
],
"properties": {
"source_intake_no": _str_prop("来源 Intake 编号,必须来自上下文"),
"schema_version_id": _int_prop("context.contract.schema_version_id,必须原样回传"),
"schema_checksum": _str_prop("context.contract.checksum,必须原样回传"),
"primary_document_id": _int_prop("主来源 Document ID,必须来自上下文"),
"candidate_key_hint": _str_prop("可选稳定订单标识,如 PO/订单号;不得使用随机值"),
"classification": _str_prop("仅 shipping_request 可自动建单", enum=["shipping_request", "non_shipping_request", "uncertain"]),
"classification_confidence": {"type": "number", "minimum": 0, "maximum": 1},
"field_confidence": {
"type": "object",
"required": ["part_number", "qty"],
"properties": {
"part_number": {"type": "number", "minimum": 0, "maximum": 1},
"qty": {"type": "number", "minimum": 0, "maximum": 1},
},
"header_fields": {
"type": "array",
"description": "Header scope 动态字段;仅可使用 context.contract.fields 中的稳定 field_id",
"items": extracted_field_schema,
},
"po_number": _str_prop("可为空的 PO/订单号"),
"lines": {
"type": "array",
"items": {
"type": "object",
"required": ["part_number", "qty"],
"required": ["fields"],
"properties": {
"part_number": _str_prop("内部料号/主匹配料号"),
"qty": {"type": "number", "exclusiveMinimum": 0},
"reservation_id": _str_prop("可为空,缺失时 Task 停在补字段门禁"),
"inventory_source_hint": _str_prop(
"可选库存来源提示;仅在原文有可靠证据时填写,"
"不代表任务通知来源或已确认的库存连接器类型"
),
"customer_part_number": _str_prop("可选客户料号"),
"aws_part_number": _str_prop("可选 AWS 料号"),
"fields": {
"type": "array",
"description": "Line scope 动态字段;每项含 field_id 与 observations[]",
"items": extracted_field_schema,
},
},
"additionalProperties": False,
},
},
"evidence": {
"type": "array",
"description": "至少分别提供内部料号与 Qty 原文证据,元素含 field 与非空 quote",
"items": {
"type": "object",
"required": ["field", "quote"],
"properties": {
"field": _str_prop("证据字段,如 lines[0].part_number 或 lines[0].qty"),
"quote": _str_prop("原文片段,禁止改写"),
"document_id": _int_prop("证据来源 Document ID"),
},
},
},
"conflicts": {
"type": "array",
"items": {"type": "object", "additionalProperties": True},
@@ -189,13 +192,73 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
},
required=["agent_runtime_context", "input_snapshot_hash", "orders"],
description=(
"只接受 get_order_extraction_context 的同一快照。HXOPS 仅在分类、内部料号/Qty 置信度及原文证据均达标,"
"且无阻断冲突/修订决策时自动建单;Reservation ID 允许缺失,"
"订单行 inventory_source_hint 是可选路由线索并独立持久化。"
"只接受同一快照和同一 Schema checksum。Dify 必须逐字段返回稳定 field_id 与 observations[];"
"每个 Observation 包含 value、document_id、逐字 quote 和可选 confidence。"
"HXOPS 验证原文、执行类型/validator/证据策略与跨 Document 裁决后,才按 field_code 投影给下游。"
"响应以持久化结果分别返回 created_count、opened_existing_count、pending_count、"
"non_shipping_count;auto_created_count 仅为兼容字段且等于 created_count。"
),
),
"/tools/create_temporary_inventory_session": _post_op(
"create_temporary_inventory_session",
"创建对话上传库存文件的临时分析会话",
{
"agent_runtime_context": runtime_context,
"asset_no": _str_prop("当前用户上传的 FileAsset 编号;必须是 xls、xlsx 或 csv"),
},
required=["agent_runtime_context", "asset_no"],
description=(
"仅在用户明确说明附件为库存文件的 temporary_inventory 分支调用。"
"后端按会话用户校验资产归属并执行结构初检;不会创建生产库存快照、"
"不会绑定库存站点、不会执行库存匹配。"
),
),
"/tools/get_temporary_inventory_session": _post_op(
"get_temporary_inventory_session",
"读取临时库存文件的脱敏结构分析和方案候选",
{
"agent_runtime_context": runtime_context,
"temporary_session_no": _str_prop("create_temporary_inventory_session 返回的临时会话编号"),
},
required=["agent_runtime_context", "temporary_session_no"],
description=(
"返回后端已分析的工作表、表头、字段目录和已发布方案候选,不返回样例库存值。"
"Dify 不得读取文件路径、全量库存行,也不得据此直接宣称库存已可用于订单匹配。"
),
),
"/tools/submit_temporary_inventory_mapping_suggestion": _post_op(
"submit_temporary_inventory_mapping_suggestion",
"保存对话临时库存的候选字段映射",
{
"agent_runtime_context": runtime_context,
"temporary_session_no": _str_prop("临时库存会话编号"),
"field_mapping": {
"type": "object",
"description": "库存字段目录 ID 到真实来源表头的映射;只能使用 get_temporary_inventory_session 返回的字段 ID 和表头",
"additionalProperties": {"type": "string"},
},
},
required=["agent_runtime_context", "temporary_session_no", "field_mapping"],
description=(
"仅在没有 exact 已发布方案可复用时调用。HXOPS 校验字段目录、真实表头、重复列和核心字段完整性,"
"只保存待用户确认的候选;不会发布方案、绑定库存站点、创建库存快照或执行订单匹配。"
),
),
"/tools/confirm_temporary_inventory_use": _post_op(
"confirm_temporary_inventory_use",
"确认当前对话临时库存文件使用",
{
"agent_runtime_context": runtime_context,
"temporary_session_no": _str_prop("临时库存会话编号"),
"selected_profile_id": _int_prop("仅 exact 已发布方案候选时由用户选择的方案 ID"),
},
required=["agent_runtime_context", "temporary_session_no"],
description=(
"仅在用户明确确认本次使用后调用。HXOPS 重新确定性解析文件并校验料号、预约号、库存数量;"
"只锁定当前对话的临时会话审计,不接受任务编号,绝不创建生产库存快照、绑定库存站点、"
"写入任务库存行或执行库存匹配。"
),
),
"/tools/parse_notice": _post_op(
"parse_notice",
"解析发货通知文本",
@@ -267,38 +330,18 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
},
required=["task_id", "line_index"],
),
"/tools/get_inventory_schema_preview": _post_op(
"get_inventory_schema_preview",
"读取已上传库存 Excel 的表头与样例行(小 payload,供 LLM 推断列映射)",
{"task_id": task_id},
required=["task_id"],
),
"/tools/apply_inventory_mapping": _post_op(
"apply_inventory_mapping",
"应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认,后续主流程由后台任务续跑",
{
"task_id": task_id,
MAP_JSON: _str_prop(
"Dify Tool 参数使用 JSON 字符串,内容含 part_number/reservation_id/available_qty,"
"可选 aws_part_number;"
"可选 match_rule(LLM 自然语言匹配说明)与 match_key(匹配键列表)。"
),
},
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 由后端根据配置与订单路由解析,禁止前端直传"
"启用配置中的库存源编码;Warehouse 由 fixed Source 配置或库存行匹配解析,禁止前端直传"
),
},
required=["task_id", "source_code"],
description=(
"库存连接器门禁:稳定身份须同时具备 source_code、connector_type、site_id、warehouse_id,"
"库存连接器门禁:稳定身份须具备 source_code、connector_type;fixed Source 同时具备 warehouse_id,"
"且 routing_fingerprint 与当前配置版本一致。"
"Tool API 使用集成密钥鉴权,确认人审计由宿主会话内部链路写入,不接受外部 user_id。"
"若返回 needs_human,说明身份未完整解析或需先完成解析确认。"
@@ -324,8 +367,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"task_id": task_id,
"conversation_id": _str_prop("Dify 会话 ID;用户仅回复「确认」时用于定位任务"),
"decision": _str_prop(
"confirm=确认继续;reject=驳回;retry_rpa=重新获取库存(清理旧库存解析状态并重新触发 RPA);rematch=重新匹配;reparse=重新解析;"
"confirm_inventory_mapping=确认库存字段对齐;correct_inventory_mapping=更正列映射;reparse_inventory=重新上传库存",
"confirm=确认继续;reject=驳回;retry_rpa=按已发布解析方案重新获取库存;rematch=重新匹配;reparse=重新解析",
enum=[
"confirm",
"confirm_parse",
@@ -333,9 +375,6 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"retry_rpa",
"rematch",
"reparse",
"confirm_inventory_mapping",
"correct_inventory_mapping",
"reparse_inventory",
],
),
"comment": _str_prop("备注(可选)"),
@@ -358,7 +397,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"conversation_id": _str_prop("Dify 会话 ID"),
},
description=(
"返回 inventory_source_code、inventory_connector_type、inventory_site_id、"
"返回 inventory_source_code、inventory_connector_type、"
"inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|"
"user_confirmed|invalid|conflicted)、inventory_source_method、"
"inventory_source_config_version、inventory_routing_fingerprint、"
@@ -0,0 +1,246 @@
"""
backend/app/services/shipping_notice/order_customer_matching.py
用途:将订单解析出的 Bill-to / Ship-to 名称和外部编码匹配到客户及送货站点主数据。
依赖:ShippingCustomer、外部编码、客户站点/标识、ShippingOrderCustomerMatch、客户名称规范化。
逻辑:外部编码优先于名称;Bill-to 匹配标准客户,Ship-to 匹配客户站点,唯一命中保存简称快照。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import (
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingCustomerSite,
ShippingCustomerSiteIdentifier,
ShippingOrderCustomerMatch,
ShippingOrderExtraction,
)
from app.services.shipping_notice.customer_normalization import normalize_customer_name
ROLE_FIELDS = {
'bill_to': {'name': 'bill_to_customer', 'code': 'bill_to_customer_code', 'source': 'bill_to_source_system'},
'ship_to': {'name': 'ship_to_customer', 'code': 'ship_to_code', 'source': 'ship_to_source_system'},
}
def _normalized_code(value: Any) -> str:
"""规范外部客户/站点编码,保留业务符号并统一大小写。"""
return str(value or '').strip().upper()
def _customer_candidates(raw_name: str) -> list[dict[str, Any]]:
"""按标准名称和 approved 名称别名返回稳定去重的启用客户候选。"""
normalized = normalize_customer_name(raw_name)
if not normalized:
return []
customers = db.session.query(ShippingCustomer).filter_by(status='active').all()
matched: dict[int, dict[str, Any]] = {}
for customer in customers:
if normalize_customer_name(customer.standard_name) == normalized:
matched[customer.id] = {
'customer_id': customer.id,
'standard_name': customer.standard_name,
'short_code': customer.short_code,
'matched_by': ['standard_name'],
}
aliases = db.session.query(ShippingCustomerIdentifier).filter_by(
identifier_type='name_alias', normalized_value=normalized, status='approved',
).all()
active_by_id = {customer.id: customer for customer in customers}
for alias in aliases:
customer = active_by_id.get(int(alias.customer_id))
if customer is None:
continue
candidate = matched.setdefault(customer.id, {
'customer_id': customer.id,
'standard_name': customer.standard_name,
'short_code': customer.short_code,
'matched_by': [],
})
if 'name_alias' not in candidate['matched_by']:
candidate['matched_by'].append('name_alias')
return sorted(matched.values(), key=lambda item: (item['standard_name'], item['customer_id']))
def _bill_to_candidates(raw_name: str, external_code: str, source_system: str) -> list[dict[str, Any]]:
"""优先按来源系统和外部客户编码匹配 Bill-to,再回退名称匹配。"""
code = _normalized_code(external_code)
source = _normalized_code(source_system)
if code and source:
refs = db.session.query(ShippingCustomerExternalRef).filter_by(
source_system=source, legacy_customer_key=code,
).all()
candidates = []
for ref in refs:
customer = db.session.get(ShippingCustomer, int(ref.customer_id))
if customer and customer.status == 'active':
candidates.append({
'customer_id': customer.id, 'standard_name': customer.standard_name,
'short_code': customer.short_code, 'site_id': None, 'site_name': None,
'site_code': None, 'matched_by': ['external_customer_code'],
})
if candidates:
return candidates
return [{**item, 'site_id': None, 'site_name': None, 'site_code': None} for item in _customer_candidates(raw_name)]
def _ship_to_candidates(raw_name: str, external_code: str, source_system: str) -> list[dict[str, Any]]:
"""优先按 Ship-to Code 匹配启用站点,再按站点名称或已审核别名匹配。"""
code = _normalized_code(external_code)
source = _normalized_code(source_system)
sites = db.session.query(ShippingCustomerSite).filter_by(status='active').all()
matched: dict[int, dict[str, Any]] = {}
matched_site_ids: dict[int, str] = {}
if code:
identifiers = db.session.query(ShippingCustomerSiteIdentifier).filter_by(
identifier_type='external_code', source_system=source, normalized_value=code, status='approved',
).all()
for identifier in identifiers:
matched_site_ids[int(identifier.site_id)] = 'external_site_code'
for site in sites:
if _normalized_code(site.site_code) == code:
matched_site_ids[site.id] = 'site_code'
if not matched_site_ids:
normalized = normalize_customer_name(raw_name) if raw_name else ''
for site in sites:
if normalized and normalize_customer_name(site.site_name) == normalized:
matched_site_ids[site.id] = 'site_name'
if normalized:
identifiers = db.session.query(ShippingCustomerSiteIdentifier).filter_by(
identifier_type='name_alias', source_system='', normalized_value=normalized, status='approved',
).all()
for identifier in identifiers:
matched_site_ids[int(identifier.site_id)] = 'site_name_alias'
by_id = {site.id: site for site in sites}
for site_id, matched_by in matched_site_ids.items():
site = by_id.get(site_id)
customer = db.session.get(ShippingCustomer, int(site.customer_id)) if site else None
if site is None or customer is None or customer.status != 'active':
continue
matched[site.id] = {
'customer_id': customer.id, 'standard_name': customer.standard_name,
'short_code': customer.short_code, 'site_id': site.id, 'site_name': site.site_name,
'site_code': site.site_code, 'matched_by': [matched_by],
}
return sorted(matched.values(), key=lambda item: (item['standard_name'], item['site_name'], item['site_id']))
def refresh_order_customer_matches(
extraction: ShippingOrderExtraction,
header: dict[str, Any],
) -> list[dict[str, Any]]:
"""
根据订单头原文幂等刷新 Bill-to / Ship-to 客户匹配结果。
Args:
extraction: 已持久化的动态订单解析记录。
header: 已通过证据裁决的订单头字段投影。
Returns:
两种角色的匹配摘要;客户简称只来自客户主数据快照。
"""
results: list[dict[str, Any]] = []
for role, fields in ROLE_FIELDS.items():
raw_name = str(header.get(fields['name']) or '').strip()
external_code = _normalized_code(header.get(fields['code']))
source_system = _normalized_code(header.get(fields['source']))
candidates = (
_bill_to_candidates(raw_name, external_code, source_system)
if role == 'bill_to'
else _ship_to_candidates(raw_name, external_code, source_system)
)
row = db.session.query(ShippingOrderCustomerMatch).filter_by(
extraction_id=extraction.id, role=role,
).one_or_none()
if row is None:
row = ShippingOrderCustomerMatch(extraction_id=extraction.id, role=role)
db.session.add(row)
row.raw_name = raw_name or None
row.normalized_name = normalize_customer_name(raw_name) if raw_name else None
row.source_system = source_system or None
row.external_code = external_code or None
row.candidates_json = candidates
if len(candidates) == 1:
candidate = candidates[0]
row.status = 'unique_candidate'
row.customer_id = int(candidate['customer_id'])
row.site_id = int(candidate['site_id']) if candidate.get('site_id') else None
row.customer_name_snapshot = str(candidate['standard_name'])
row.customer_short_code_snapshot = str(candidate['short_code'])
row.resolution_method = str(candidate['matched_by'][0])
else:
row.status = 'ambiguous' if candidates else 'unmatched'
row.customer_id = None
row.site_id = None
row.customer_name_snapshot = None
row.customer_short_code_snapshot = None
row.resolution_method = None
row.confirmed_by_id = None
row.confirmed_at = None
row.updated_at = datetime.utcnow()
db.session.flush()
results.append(serialize_order_customer_match(row))
return results
def confirm_order_customer_match(
extraction_id: int,
*,
role: str,
customer_id: int,
site_id: int | None = None,
actor_id: int | None,
) -> dict[str, Any]:
"""人工确认某个订单客户角色;Ship-to 必须同时选择所属客户的启用站点。"""
if role not in ROLE_FIELDS:
raise ValidationError('Customer role is invalid', code='SHIPPING.ORDER_CUSTOMER_ROLE_INVALID')
row = db.session.query(ShippingOrderCustomerMatch).filter_by(
extraction_id=extraction_id, role=role,
).one_or_none()
if row is None:
raise NotFoundError('Order customer match not found', code='SHIPPING.ORDER_CUSTOMER_MATCH_NOT_FOUND')
customer = db.session.get(ShippingCustomer, int(customer_id))
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if customer.status != 'active':
raise ValidationError('Inactive customer cannot be used', code='SHIPPING.CUSTOMER_INACTIVE')
selected_site = None
if role == 'ship_to':
selected_site = db.session.get(ShippingCustomerSite, int(site_id)) if site_id is not None else None
if selected_site is None or selected_site.customer_id != customer.id or selected_site.status != 'active':
raise ValidationError('Active Ship-to site is required', code='SHIPPING.ORDER_CUSTOMER_SITE_INVALID')
row.status = 'confirmed'
row.customer_id = customer.id
row.site_id = selected_site.id if selected_site else None
row.customer_name_snapshot = customer.standard_name
row.customer_short_code_snapshot = customer.short_code
row.resolution_method = 'manual'
row.confirmed_by_id = actor_id
row.confirmed_at = datetime.utcnow()
db.session.commit()
return serialize_order_customer_match(row)
def serialize_order_customer_match(row: ShippingOrderCustomerMatch) -> dict[str, Any]:
"""输出前端可直接展示的角色匹配摘要,不暴露内部 ORM 状态。"""
return {
'id': row.id,
'extraction_id': row.extraction_id,
'role': row.role,
'raw_name': row.raw_name,
'status': row.status,
'customer_id': row.customer_id,
'site_id': row.site_id,
'source_system': row.source_system,
'external_code': row.external_code,
'standard_name': row.customer_name_snapshot,
'short_code': row.customer_short_code_snapshot,
'candidates': list(row.candidates_json or []),
'resolution_method': row.resolution_method,
}
@@ -27,6 +27,8 @@ from app.models import (
ShippingNoticeCandidate,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingOrderExtraction,
ShippingTask,
)
from app.services.agent_runtime_context.parser import parse_agent_runtime_context
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates
@@ -42,16 +44,7 @@ from app.services.shipping_notice.duplicate_detection import (
detect_duplicates_for_candidate,
)
from app.services.shipping_notice.document_candidate_persist import generate_candidate_no
from app.services.shipping_notice.order_extraction_evidence import (
adjudicate_order_reservations,
verify_reservation_evidence,
)
from app.services.shipping_notice.field_adjudication import (
adjudicate_order_fields,
merge_observation_history,
trusted_required_fields,
)
from app.services.shipping_notice.reservation_id import validated_reservation_id
from app.services.shipping_notice.order_schema.runtime import dify_contract, persist_dynamic_order, published_version
_CONTEXT_PATHS = [
'agent_code',
@@ -120,9 +113,15 @@ def _load_intakes(
for row in rows:
if row.conversation_id and row.conversation_id != session.session_id:
raise ForbiddenError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='发货通知已绑定其他会话')
if row.parse_status == 'consumed' or row.consumed_at is not None:
if allow_consumed:
continue
raise ConflictError(
code='SHIPPING_NOTICE.ORDER_EXTRACTION_ALREADY_CONSUMED',
message='该邮件或附件的订单抽取已完成,请查看已有任务或订单抽取结果',
)
ready = row.parse_status == 'parsed' and row.consumed_at is None
replayable = allow_consumed and row.parse_status == 'consumed'
if not ready and not replayable:
if not ready:
raise ConflictError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING', message='邮件或附件尚未完成预处理')
if row.conversation_id is None:
row.conversation_id = session.session_id
@@ -276,7 +275,13 @@ def start_order_extraction(
now = datetime.utcnow()
intake_ids: list[int] = []
for intake in intakes:
if intake.parse_status != 'parsed' or intake.consumed_at is not None:
if intake.parse_status == 'consumed' or intake.consumed_at is not None:
db.session.rollback()
raise ConflictError(
code='SHIPPING_NOTICE.ORDER_EXTRACTION_ALREADY_CONSUMED',
message='该邮件或附件的订单抽取已完成,请查看已有任务或订单抽取结果',
)
if intake.parse_status != 'parsed':
db.session.rollback()
raise ConflictError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING', message='邮件或附件尚未完成预处理')
if intake.conversation_id and intake.conversation_id != session_value:
@@ -686,13 +691,7 @@ def get_order_extraction_context(payload: dict[str, Any]) -> dict[str, Any]:
row.intake_no: dict(row.structured_result_json or {}).get('rule_hints') or {}
for row in intakes
},
'contract': {
'required_order_fields': ['source_intake_no', 'primary_document_id', 'classification', 'lines'],
'auto_create_required_line_fields': ['part_number', 'qty'],
'required_process_line_fields': ['reservation_id'],
'optional_routing_line_fields': ['inventory_source_hint'],
'allowed_missing_process_fields': ['reservation_id'],
},
'contract': dify_contract(published_version()),
}
@@ -900,52 +899,32 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
document_non_shipping_indexes[int(document.id)].append(index)
continue
summary = dict(raw_order)
summary.pop('evidence', None)
summary.pop('field_confidence', None)
summary.pop('classification_confidence', None)
summary.pop('candidate_key_hint', None)
summary.pop('classification', None)
summary.pop('source_intake_no', None)
summary.pop('primary_document_id', None)
field_confidence = raw_order.get('field_confidence') if isinstance(raw_order.get('field_confidence'), dict) else {}
field_adjudication = adjudicate_order_fields(
summary,
dynamic = persist_dynamic_order(
raw_order=raw_order,
intake_id=int(intake.id),
snapshot_hash=current_snapshot,
documents=owned_docs,
field_confidence=field_confidence,
actor_id=int(session.user_id),
)
normalized = field_adjudication['summary']
blocking_conflicts.extend(field_adjudication['conflicts'])
assessment = assess_candidate_business_summary(normalized)
normalized, backend_conflicts = adjudicate_order_reservations(
assessment['normalized_summary'],
documents=owned_docs,
)
assessment = assess_candidate_business_summary(normalized)
summary = {**dynamic['header'], 'lines': dynamic['lines']}
# Bill-to 是业务归属客户原文;简称只保存在 customer_matches 主数据快照中。
if summary.get('bill_to_customer'):
summary['customer_name'] = summary['bill_to_customer']
if dynamic['blocked_fields']:
blocking_conflicts.extend([
{
'field': item.get('field_code'),
'severity': 'blocking',
'reason': item.get('reason_code') or 'dynamic_schema_required_or_evidence_gate',
}
for item in dynamic['decisions']
if item.get('status') not in {'accepted', 'corroborated'}
] or [{
'field': ','.join(dynamic['blocked_fields']), 'severity': 'blocking',
'reason': 'dynamic_schema_required_or_evidence_gate',
}])
assessment = assess_candidate_business_summary(summary)
normalized = assessment['normalized_summary']
blocking_conflicts.extend(backend_conflicts)
# [STEP] 证据核验对齐裁决后的行值,门禁比较 (line_index, reservation_id) pair,
# 避免仅比 index 时把被裁决改写过的 Reservation 误判为已核验。
order_for_evidence = dict(raw_order)
order_for_evidence['lines'] = list(normalized.get('lines') or [])
verified_reservation_evidence = verify_reservation_evidence(
order_for_evidence,
documents=owned_docs,
)
reservation_pairs = {
(line_index, reservation_id)
for line_index, line in enumerate(normalized.get('lines') or [])
if isinstance(line, dict)
for reservation_id in [validated_reservation_id(line.get('reservation_id'))]
if reservation_id
}
verified_reservation_pairs = {
(int(item['line_index']), validated_reservation_id(item.get('reservation_id')))
for item in verified_reservation_evidence
if str(item.get('line_index', '')).isdigit()
and validated_reservation_id(item.get('reservation_id'))
}
reasons: list[str] = []
if classification != 'shipping_request':
reasons.append('not_shipping_request')
@@ -953,10 +932,8 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
reasons.append('missing_or_invalid_part_number_qty')
if classification_confidence < class_threshold:
reasons.append('low_classification_confidence')
if not trusted_required_fields(field_adjudication):
reasons.append('untrusted_part_number_qty_adjudication')
if reservation_pairs - verified_reservation_pairs:
reasons.append('unverified_reservation_evidence')
if dynamic['blocked_fields']:
reasons.append('dynamic_schema_gate')
if blocking_conflicts:
reasons.append('blocking_conflict')
@@ -978,32 +955,13 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
candidate_key=candidate_key,
)
db.session.add(candidate)
previous_structured = (
candidate.structured_result_json
if isinstance(candidate.structured_result_json, dict)
else {}
)
previous_extraction = (
previous_structured.get('extraction')
if isinstance(previous_structured.get('extraction'), dict)
else {}
)
previous_adjudication = (
previous_extraction.get('field_adjudication')
if isinstance(previous_extraction.get('field_adjudication'), dict)
else {}
)
observation_history = merge_observation_history(
previous_adjudication.get('observation_history') or previous_adjudication.get('observations'),
field_adjudication['observations'],
)
candidate.primary_document_id = int(document.id)
candidate.source_order_index = index
candidate.extraction_source = 'dify_chatflow'
candidate.classification_confidence = classification_confidence
candidate.field_confidence_json = dict(field_confidence)
candidate.field_confidence_json = {}
candidate.missing_fields_json = list(assessment['missing_required_fields']) + list(assessment['missing_process_fields'])
candidate.evidence_json = [item for item in (raw_order.get('evidence') or []) if isinstance(item, dict)]
candidate.evidence_json = list(dynamic['observations'])
candidate.po_number = str(normalized.get('po_number') or '').strip() or None
candidate.confidence = classification_confidence
candidate.conflicts_json = blocking_conflicts
@@ -1024,19 +982,36 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
'request_id': request_id,
'classification': classification,
'classification_confidence': classification_confidence,
'field_confidence': field_confidence,
'field_confidence': {},
'field_adjudication': {
'schema_version': field_adjudication['schema_version'],
'observations': field_adjudication['observations'],
'observation_history': observation_history,
'decisions': field_adjudication['decisions'],
'conflicts': field_adjudication['conflicts'],
'schema_version_id': int(dynamic['extraction'].schema_version_id),
'extraction_id': int(dynamic['extraction'].id),
'observations': dynamic['observations'],
'decisions': dynamic['decisions'],
'conflicts': blocking_conflicts,
},
'customer_matches': dynamic['customer_matches'],
'missing_required_fields': assessment['missing_required_fields'],
'missing_process_fields': assessment['missing_process_fields'],
'process_issues': assessment['process_issues'],
'auto_create_reasons': reasons,
'verified_reservation_evidence': verified_reservation_evidence,
'verified_reservation_evidence': [
{
'line_index': int(item.get('line_position') or 0),
'reservation_id': item.get('value'),
'document_id': next(
(
observation.get('document_id')
for observation in dynamic['observations']
if observation.get('id') in set(item.get('observation_ids') or [])
),
None,
),
}
for item in dynamic['decisions']
if item.get('status') in {'accepted', 'corroborated'}
and item.get('field_code') == 'reservation_id'
],
},
}
duplicate = detect_duplicates_for_candidate(
@@ -1135,6 +1110,21 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
candidate_nos=auto_candidate_nos,
create_idempotency_key=idem,
)
# [STEP 4A] Candidate 被创建或打开到 Task 后,回填当前动态订单真相版本。
for candidate in auto_candidates:
if candidate.consumed_task_id is None:
continue
extraction_data = (
candidate.structured_result_json.get('extraction', {}).get('field_adjudication', {})
if isinstance(candidate.structured_result_json, dict)
else {}
)
extraction_id = extraction_data.get('extraction_id') if isinstance(extraction_data, dict) else None
task = db.session.get(ShippingTask, int(candidate.consumed_task_id))
if task is not None and str(extraction_id or '').isdigit():
task.current_order_extraction_id = int(extraction_id)
db.session.get(ShippingOrderExtraction, int(extraction_id)).task_id = int(task.id)
db.session.commit()
else:
# [STEP 4] 没有待处理订单时(空数组或仅明确非发货内容),消费 Intake 但不产生 Batch/Task。
if not pending:
@@ -0,0 +1,11 @@
"""
backend/app/services/shipping_notice/order_schema/__init__.py
用途:货代订单唯一 Schema 领域服务入口。
依赖:registry、service。
逻辑:管理 API 和后续订单抽取链从本包读取受控字段能力与已发布契约。
"""
from app.services.shipping_notice.order_schema.service import get_published_contract
__all__ = ['get_published_contract']
@@ -0,0 +1,114 @@
"""
backend/app/services/shipping_notice/order_schema/diff.py
用途:计算订单 Schema 版本定义之间可直接展示的语义化字段差异。
依赖:无数据库依赖,仅处理 version definition JSON。
逻辑:以稳定 field_id 配对字段;集合属性与顺序分别比较,避免字段重命名被误判为删除和新增。
"""
from __future__ import annotations
from typing import Any
_SCALAR_KEYS = (
'field_code', 'scope', 'value_type', 'enabled', 'display_name', 'description',
'required', 'normalizer_key', 'relation_role', 'comparator_key',
'extraction_instruction', 'sequence',
)
_SET_KEYS = ('aliases', 'validator_keys', 'enum_options')
_EVIDENCE_POLICY_KEYS = ('required', 'source_precedence', 'conflict_policy', 'allow_single_source')
def _field_map(definition: dict[str, Any] | None) -> dict[str, dict[str, Any]]:
"""按稳定 field_id 索引字段,忽略不完整的历史快照条目。"""
return {
str(field['field_id']): field
for field in (definition or {}).get('fields', [])
if isinstance(field, dict) and field.get('field_id') is not None
}
def _set_change(key: str, before: Any, after: Any) -> dict[str, Any] | None:
"""比较无序字符串集合,并显式返回新增、移除和原始值以便界面呈现。"""
before_items = list(before or [])
after_items = list(after or [])
before_set = set(before_items)
after_set = set(after_items)
if before_set == after_set and before_items == after_items:
return None
return {
'key': key,
'kind': 'set',
'before': before_items,
'after': after_items,
'added': sorted(after_set - before_set),
'removed': sorted(before_set - after_set),
'order_changed': before_set == after_set and before_items != after_items,
}
def _field_changes(before: dict[str, Any], after: dict[str, Any]) -> list[dict[str, Any]]:
"""返回同一字段的属性级变更,证据策略按子属性而非整个对象展示。"""
changes: list[dict[str, Any]] = []
for key in _SCALAR_KEYS:
if before.get(key) != after.get(key):
changes.append({'key': key, 'kind': 'value', 'before': before.get(key), 'after': after.get(key)})
for key in _SET_KEYS:
change = _set_change(key, before.get(key), after.get(key))
if change:
changes.append(change)
before_policy = before.get('evidence_policy') or {}
after_policy = after.get('evidence_policy') or {}
for key in _EVIDENCE_POLICY_KEYS:
qualified_key = f'evidence_policy.{key}'
if key == 'source_precedence':
change = _set_change(qualified_key, before_policy.get(key), after_policy.get(key))
if change:
changes.append(change)
elif before_policy.get(key) != after_policy.get(key):
changes.append({
'key': qualified_key,
'kind': 'value',
'before': before_policy.get(key),
'after': after_policy.get(key),
})
return changes
def compare_definitions(before: dict[str, Any] | None, after: dict[str, Any] | None) -> dict[str, Any]:
"""
计算两个 Schema 定义的字段级差异。
Args:
before: 作为基线的完整版本 definition。
after: 用来比较的完整版本 definition。
Returns:
包含新增、移除、修改和未变字段及属性变更列表的稳定 JSON 结构。
"""
before_fields = _field_map(before)
after_fields = _field_map(after)
field_ids = sorted(set(before_fields) | set(after_fields))
fields: list[dict[str, Any]] = []
counts = {'added': 0, 'removed': 0, 'modified': 0, 'unchanged': 0}
for field_id in field_ids:
previous = before_fields.get(field_id)
current = after_fields.get(field_id)
if previous is None:
change_type = 'added'
changes: list[dict[str, Any]] = []
elif current is None:
change_type = 'removed'
changes = []
else:
changes = _field_changes(previous, current)
change_type = 'modified' if changes else 'unchanged'
counts[change_type] += 1
fields.append({
'field_id': field_id,
'change_type': change_type,
'before': previous,
'after': current,
'changes': changes,
})
return {'summary': counts, 'fields': fields}
@@ -0,0 +1,74 @@
"""
backend/app/services/shipping_notice/order_schema/registry.py
用途:维护订单字段类型、规范化器、校验器、比较器和证据策略白名单。
依赖:无。
逻辑:管理员配置只能引用本模块声明的安全能力;运行期解析器在后续阶段复用同一目录。
"""
from __future__ import annotations
FIELD_TYPES = {'string', 'decimal', 'integer', 'date', 'boolean', 'enum'}
FIELD_SCOPES = {'header', 'line'}
NORMALIZERS = {
'trim', 'uppercase_trim', 'lowercase_trim', 'decimal', 'integer', 'iso_date',
'boolean', 'reservation_id',
}
VALIDATORS = {
'non_empty', 'positive_decimal', 'non_negative_decimal', 'positive_integer',
'reservation_id', 'atomic_part_number', 'iso_date',
}
COMPARATORS = {'normalized_text', 'case_insensitive_text', 'decimal', 'integer', 'date', 'boolean', 'reservation_id'}
RELATION_ROLES = {None, 'primary_link', 'secondary_link', 'line_match'}
SOURCE_TYPES = {
'attachment_table', 'attachment_text', 'email_body_table', 'email_body_text',
'backend_table', 'dify_llm',
}
CONFLICT_POLICIES = {'block', 'review', 'prefer_attachment', 'prefer_email'}
TYPE_NORMALIZERS = {
'string': {'trim', 'uppercase_trim', 'lowercase_trim', 'reservation_id'},
'decimal': {'decimal'},
'integer': {'integer'},
'date': {'iso_date'},
'boolean': {'boolean'},
'enum': {'trim', 'uppercase_trim', 'lowercase_trim'},
}
TYPE_COMPARATORS = {
'string': {'normalized_text', 'case_insensitive_text', 'reservation_id'},
'decimal': {'decimal'},
'integer': {'integer'},
'date': {'date'},
'boolean': {'boolean'},
'enum': {'normalized_text', 'case_insensitive_text'},
}
TYPE_VALIDATORS = {
'string': {'non_empty', 'reservation_id', 'atomic_part_number'},
'decimal': {'non_empty', 'positive_decimal', 'non_negative_decimal'},
'integer': {'non_empty', 'positive_integer'},
'date': {'non_empty', 'iso_date'},
'boolean': set(),
'enum': {'non_empty'},
}
ADMIN_HIDDEN_RULES = {'reservation_id'}
def _admin_rules(values: set[str]) -> list[str]:
"""隐藏字段专用的内部兼容规则,避免管理员将其误用到普通文本字段。"""
return sorted(values - ADMIN_HIDDEN_RULES)
def catalog() -> dict[str, list[str] | dict[str, list[str]]]:
"""返回管理端字段编辑器可选目录及按字段类型收窄后的兼容矩阵。"""
return {
'field_types': sorted(FIELD_TYPES),
'field_scopes': sorted(FIELD_SCOPES),
'normalizers': _admin_rules(NORMALIZERS),
'validators': _admin_rules(VALIDATORS),
'comparators': _admin_rules(COMPARATORS),
'relation_roles': sorted(item for item in RELATION_ROLES if item),
'source_types': sorted(SOURCE_TYPES),
'conflict_policies': sorted(CONFLICT_POLICIES),
'type_normalizers': {key: _admin_rules(value) for key, value in TYPE_NORMALIZERS.items()},
'type_validators': {key: _admin_rules(value) for key, value in TYPE_VALIDATORS.items()},
'type_comparators': {key: _admin_rules(value) for key, value in TYPE_COMPARATORS.items()},
}
@@ -0,0 +1,423 @@
"""
backend/app/services/shipping_notice/order_schema/runtime.py
用途:编译已发布订单 Schema,并裁决 Dify 返回的动态字段 Observation。
依赖:订单 Schema 动态模型、ShippingNoticeDocument、registry、订单客户匹配服务。
逻辑:提交时先验证原文证据和字段规则,再以已裁决订单头匹配 Bill-to/Ship-to 客户主数据并输出业务投影。
"""
from __future__ import annotations
from datetime import date, datetime
from decimal import Decimal, InvalidOperation
from typing import Any
from app.core.errors import ConflictError, ValidationError
from app.extensions import db
from app.models import (
ShippingNoticeDocument,
ShippingOrderExtraction,
ShippingOrderFieldDecision,
ShippingOrderFieldObservation,
ShippingOrderFieldValue,
ShippingOrderLine,
ShippingOrderSchemaVersion,
)
from app.services.shipping_notice.notice_lines import parse_notice_table_text
from app.services.shipping_notice.order_customer_matching import refresh_order_customer_matches
from app.services.shipping_notice.reservation_id import validated_reservation_id
def published_version() -> ShippingOrderSchemaVersion:
"""读取当前唯一 published 订单 Schema;未发布时阻断解析。"""
version = ShippingOrderSchemaVersion.query.filter_by(status='published').first()
if version is None:
raise ConflictError('No published shipping order schema', code='SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED')
return version
def dify_contract(version: ShippingOrderSchemaVersion) -> dict[str, Any]:
"""编译 Dify 动态抽取契约;仅输出发布快照中 enabled 的字段。"""
fields = [
dict(item) for item in (version.definition_json or {}).get('fields') or []
if item.get('enabled', True)
]
return {
'schema_version_id': int(version.id),
'schema_version': int(version.version),
'checksum': version.checksum,
'fields': fields,
'submission_contract': {
'field': {'field_id': '<stable uuid>', 'observations': '<one or more observation objects>'},
'observation': {
'value': '<typed candidate value>',
'document_id': '<id from documents[]>',
'quote': '<verbatim source quote>',
'confidence': '<optional 0..1>',
},
'order': {'header_fields': '<field[]>', 'lines': [{'fields': '<field[]>'}]},
},
}
def _json_value(value: Any) -> Any:
"""将 Decimal/date 转为 JSON 可安全持久化的标量。"""
if isinstance(value, Decimal):
return format(value, 'f')
if isinstance(value, date):
return value.isoformat()
return value
def _input_snapshot(*, intake_id: int, snapshot_hash: str, documents: list[ShippingNoticeDocument]) -> dict[str, Any]:
"""冻结本次裁决使用的文档文本和指纹,供管理员重建输入证据而不回读可变 Document。"""
return {
'intake_id': intake_id,
'snapshot_hash': snapshot_hash,
'documents': [
{
'id': int(document.id),
'filename': document.filename,
'document_type': document.document_type,
'content_hash': document.content_hash,
'extracted_text': document.extracted_text,
}
for document in documents
],
}
def _normalize(value: Any, config: dict[str, Any]) -> Any:
"""按发布字段类型与 normalizer 规范化候选值。"""
if value in (None, ''):
return None
value_type = str(config['value_type'])
normalizer = str(config.get('normalizer_key') or 'trim')
try:
if value_type == 'decimal':
return Decimal(str(value).replace(',', '').strip())
if value_type == 'integer':
return int(str(value).replace(',', '').strip())
if value_type == 'date':
return date.fromisoformat(str(value).strip())
if value_type == 'boolean':
if isinstance(value, bool):
return value
lowered = str(value).strip().lower()
if lowered in {'true', '1', 'yes', 'y'}:
return True
if lowered in {'false', '0', 'no', 'n'}:
return False
raise ValueError('invalid boolean')
except (InvalidOperation, ValueError, TypeError) as exc:
raise ValidationError(
'Dynamic field value type is invalid', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT'
) from exc
text = str(value).strip()
if normalizer == 'uppercase_trim':
text = text.upper()
elif normalizer == 'lowercase_trim':
text = text.lower()
if normalizer == 'reservation_id':
text = validated_reservation_id(text) or ''
if value_type == 'enum' and text not in set(config.get('enum_options') or []):
raise ValidationError('Dynamic enum value is invalid', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT')
return text or None
def _validate(value: Any, config: dict[str, Any]) -> bool:
"""执行发布契约中受控 validator;返回值决定字段是否可被接受。"""
for key in config.get('validator_keys') or []:
if key == 'non_empty' and value in (None, ''):
return False
if key in {'positive_decimal', 'positive_integer'} and Decimal(str(value)) <= 0:
return False
if key == 'non_negative_decimal' and Decimal(str(value)) < 0:
return False
if key == 'reservation_id' and not validated_reservation_id(value):
return False
if key == 'atomic_part_number' and '/' in str(value):
return False
if key == 'iso_date' and not isinstance(value, date):
return False
return True
def _source_type(document: ShippingNoticeDocument) -> str:
"""把 Document 技术类型映射为 Schema 证据来源类型。"""
return 'email_body_text' if document.document_type == 'body' else 'attachment_text'
def _verified_observations(raw: dict[str, Any], config: dict[str, Any],
documents: dict[int, ShippingNoticeDocument]) -> list[dict[str, Any]]:
"""验证动态 Observation 的字段值、Document 归属、逐字 quote 与值包含关系。"""
items = raw.get('observations') if isinstance(raw.get('observations'), list) else []
verified: list[dict[str, Any]] = []
for item in items:
if not isinstance(item, dict) or not str(item.get('document_id') or '').isdigit():
continue
document = documents.get(int(item['document_id']))
value = _normalize(item.get('value'), config)
quote = str(item.get('quote') or '').strip()
if document is None or value is None or not _validate(value, config):
continue
if not quote or quote not in str(document.extracted_text or ''):
continue
if str(_json_value(value)).upper() not in quote.upper():
continue
try:
confidence = max(0.0, min(float(item.get('confidence')), 1.0))
except (TypeError, ValueError):
confidence = 0.0
verified.append({
'value': value,
'document': document,
'quote': quote,
'confidence': confidence,
'source_type': _source_type(document),
})
return verified
def _choose_value(observations: list[dict[str, Any]], config: dict[str, Any]) -> tuple[Any, str, str | None]:
"""按一致性、来源优先级和冲突策略选择字段值。"""
if not observations:
return None, 'missing', 'evidence_missing'
groups: dict[str, list[dict[str, Any]]] = {}
for item in observations:
groups.setdefault(str(_json_value(item['value'])), []).append(item)
policy = dict(config.get('evidence_policy') or {})
if len(groups) == 1:
value = observations[0]['value']
distinct_documents = {int(item['document'].id) for item in observations}
if not policy.get('allow_single_source', True) and len(distinct_documents) < 2:
return value, 'needs_review', 'cross_document_evidence_required'
return value, 'corroborated' if len(distinct_documents) > 1 else 'accepted', None
conflict_policy = str(policy.get('conflict_policy') or 'block')
preferred = {
'prefer_attachment': {'attachment_text', 'attachment_table'},
'prefer_email': {'email_body_text', 'email_body_table'},
}.get(conflict_policy)
if preferred:
hits = [item for item in observations if item['source_type'] in preferred]
preferred_values = {str(_json_value(item['value'])) for item in hits}
if len(preferred_values) == 1:
return hits[0]['value'], 'accepted', f'{conflict_policy}_resolved'
return observations[0]['value'], 'blocked' if conflict_policy == 'block' else 'needs_review', 'cross_source_conflict'
def _persist_field(*, extraction: ShippingOrderExtraction, line_id: int | None, raw: dict[str, Any],
config: dict[str, Any], documents: dict[int, ShippingNoticeDocument],
backend_candidates: list[dict[str, Any]]) -> tuple[Any, str, list[dict[str, Any]], dict[str, Any]]:
"""持久化字段全部 Observation、最终 Decision 和可查询类型化 Value。"""
candidates = _verified_observations(raw, config, documents)
candidates.extend(backend_candidates)
observation_rows: list[ShippingOrderFieldObservation] = []
for item in candidates:
row = ShippingOrderFieldObservation(
extraction_id=extraction.id, line_id=line_id, field_id=config['field_id'],
source_document_id=int(item['document'].id), source_type=item['source_type'],
extractor=item.get('extractor') or 'dify_dynamic_schema', raw_value_json=_json_value(item['value']),
normalized_value_json=_json_value(item['value']), evidence_quote=item['quote'],
confidence=Decimal(str(item['confidence'])), evidence_verified=True,
)
db.session.add(row)
observation_rows.append(row)
db.session.flush()
value, status, reason = _choose_value(candidates, config)
decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, line_id=line_id, field_id=config['field_id'], decision_status=status,
selected_observation_id=observation_rows[0].id if observation_rows else None,
supporting_observation_ids_json=[int(item.id) for item in observation_rows],
resolved_value_json=_json_value(value), reason_code=reason,
)
db.session.add(decision)
db.session.flush()
if value is not None and status in {'accepted', 'corroborated'}:
value_type = str(config['value_type'])
db.session.add(ShippingOrderFieldValue(
extraction_id=extraction.id, line_id=line_id, field_id=config['field_id'], decision_id=decision.id,
value_text=str(value) if value_type in {'string', 'enum'} else None,
value_decimal=value if value_type == 'decimal' else None,
value_integer=value if value_type == 'integer' else None,
value_date=value if value_type == 'date' else None,
value_boolean=value if value_type == 'boolean' else None,
value_json=_json_value(value),
))
observations = [{
'id': int(item.id), 'field_id': config['field_id'], 'line_id': line_id,
'source_type': item.source_type, 'document_id': item.source_document_id,
'value': item.normalized_value_json, 'evidence_verified': bool(item.evidence_verified),
} for item in observation_rows]
decision_payload = {
'id': int(decision.id), 'field_id': config['field_id'], 'field_code': config['field_code'], 'line_id': line_id,
'status': status, 'value': _json_value(value), 'reason_code': reason,
'observation_ids': list(decision.supporting_observation_ids_json or []),
}
return value, status, observations, decision_payload
def _backend_rows(documents: list[ShippingNoticeDocument]) -> list[dict[str, Any]]:
"""从 EML/PDF Document 保留列边界的文本生成后端表格观察原料。"""
rows: list[dict[str, Any]] = []
for document in documents:
for position, raw in enumerate(parse_notice_table_text(str(document.extracted_text or ''))):
if isinstance(raw, dict):
rows.append({**raw, '_document': document, '_position': position})
return rows
def _associated_backend_rows(raw_fields: list[Any], configs: dict[str, dict[str, Any]],
rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""使用当前动态行任一稳定字段值关联后端表格行,避免按行号或目标字段自证。"""
signatures: list[tuple[str, str]] = []
for raw in raw_fields:
if not isinstance(raw, dict):
continue
config = configs.get(str(raw.get('field_id') or ''))
if config is None:
continue
for item in raw.get('observations') or []:
if not isinstance(item, dict):
continue
value = _normalize(item.get('value'), config)
if value is not None:
signatures.append((str(config['field_code']), str(_json_value(value))))
matched = [
row for row in rows
if any(
row.get(code) not in (None, '')
and str(_json_value(_normalize(row.get(code), configs[next(
field_id for field_id, item in configs.items() if item['field_code'] == code
)]))) == value
for code, value in signatures
if any(item['field_code'] == code for item in configs.values())
)
]
return matched
def _backend_candidates(config: dict[str, Any], *, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""从已关联后端表格行读取当前字段候选,用于一致或冲突裁决。"""
if not rows:
return []
code = str(config['field_code'])
result: list[dict[str, Any]] = []
for row in rows:
if row.get(code) in (None, ''):
continue
value = _normalize(row.get(code), config)
if value is None or not _validate(value, config):
continue
result.append({
'value': value, 'document': row['_document'], 'quote': None, 'confidence': 0.9,
'source_type': 'backend_table', 'extractor': 'backend_table',
})
return result
def persist_dynamic_order(*, raw_order: dict[str, Any], intake_id: int, snapshot_hash: str,
documents: list[ShippingNoticeDocument], actor_id: int | None) -> dict[str, Any]:
"""裁决并保存一个动态订单,返回 field_code 下游投影与阻断字段。"""
version = published_version()
supplied_version = raw_order.get('schema_version_id')
supplied_checksum = str(raw_order.get('schema_checksum') or '')
if supplied_version != int(version.id) or supplied_checksum != str(version.checksum or ''):
raise ConflictError('Order schema changed', code='SHIPPING_NOTICE.CANDIDATE_SOURCE_CHANGED')
configs = {
str(item['field_id']): item for item in (version.definition_json or {}).get('fields') or []
if item.get('enabled', True)
}
extraction = ShippingOrderExtraction(
intake_id=intake_id, schema_version_id=version.id, input_snapshot_hash=snapshot_hash,
input_snapshot_json=_input_snapshot(
intake_id=intake_id, snapshot_hash=snapshot_hash, documents=documents,
),
status='extracting', raw_llm_output_json=raw_order, created_by_id=actor_id,
)
db.session.add(extraction)
db.session.flush()
document_map = {int(item.id): item for item in documents}
header: dict[str, Any] = {}
line_projections: list[dict[str, Any]] = []
blocked: list[str] = []
observations: list[dict[str, Any]] = []
decisions: list[dict[str, Any]] = []
backend_rows = _backend_rows(documents)
groups: list[tuple[int | None, int | None, str, list[Any], dict[str, Any]]] = [
(None, None, 'header', raw_order.get('header_fields') or [], header)
]
for position, raw_line in enumerate(raw_order.get('lines') or []):
if not isinstance(raw_line, dict):
raise ValidationError('Dynamic order line must be an object', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT')
line = ShippingOrderLine(extraction_id=extraction.id, position=position)
db.session.add(line)
db.session.flush()
projection: dict[str, Any] = {}
line_projections.append(projection)
groups.append((line.id, position, 'line', raw_line.get('fields') or [], projection))
# [STEP 1] 只接受发布契约内且 scope 正确的稳定字段 ID。
seen: set[tuple[int | None, str]] = set()
for line_id, position, scope, raw_fields, projection in groups:
if not isinstance(raw_fields, list):
raise ValidationError('Dynamic fields must be arrays', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT')
associated_rows = _associated_backend_rows(raw_fields, configs, backend_rows) if position is not None else []
for raw in raw_fields:
field_id = str(raw.get('field_id') or '') if isinstance(raw, dict) else ''
config = configs.get(field_id)
if config is None or config.get('scope') != scope or (line_id, field_id) in seen:
raise ValidationError('Dynamic field identity or scope is invalid', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT')
seen.add((line_id, field_id))
value, status, field_observations, decision = _persist_field(
extraction=extraction, line_id=line_id, raw=raw, config=config, documents=document_map,
backend_candidates=_backend_candidates(config, rows=associated_rows),
)
observations.extend(field_observations)
decision['line_position'] = position
decisions.append(decision)
if value is not None:
projection[str(config['field_code'])] = _json_value(value)
if status not in {'accepted', 'corroborated'}:
blocked.append(str(config['field_code']))
# [STEP 2] 未提交字段也必须形成 missing Decision,保证每个 Schema 字段都有可审计结果。
for config in configs.values():
field_id = str(config['field_id'])
if config.get('scope') != scope or (line_id, field_id) in seen:
continue
_value, status, field_observations, decision = _persist_field(
extraction=extraction, line_id=line_id, raw={}, config=config, documents=document_map,
backend_candidates=_backend_candidates(config, rows=associated_rows),
)
decision['line_position'] = position
observations.extend(field_observations)
decisions.append(decision)
if config.get('required') and status not in {'accepted', 'corroborated'}:
blocked.append(str(config['field_code']))
# [STEP 3] Required 按 Header/每一 Line 检查,缺值和冲突都阻断自动建单。
for config in configs.values():
if not config.get('required'):
continue
code = str(config['field_code'])
if config['scope'] == 'header' and code not in header:
blocked.append(code)
if config['scope'] == 'line' and (not line_projections or any(code not in line for line in line_projections)):
blocked.append(code)
extraction.normalized_result_json = {'header': header, 'lines': line_projections}
extraction.validation_result_json = {'blocked_fields': sorted(set(blocked))}
extraction.status = 'needs_review' if blocked else 'accepted'
extraction.updated_at = datetime.utcnow()
db.session.flush()
customer_matches = refresh_order_customer_matches(extraction, header)
return {
'extraction': extraction,
'header': header,
'lines': line_projections,
'blocked_fields': sorted(set(blocked)),
'observations': observations,
'decisions': decisions,
'customer_matches': customer_matches,
}
@@ -0,0 +1,876 @@
"""
backend/app/services/shipping_notice/order_schema/service.py
用途:管理唯一订单 Schema、稳定字段目录、不可变版本和追加式配置审计。
依赖:db、订单 Schema 模型、registry、统一 AppError。
逻辑:草稿与发布版本统一读写 definition_json;乐观锁阻止覆盖;发布冻结快照并追加审计事件。
"""
from __future__ import annotations
import hashlib
import json
import re
from datetime import datetime
from typing import Any
from sqlalchemy import func
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.extensions import db
from app.models import (
ShippingOrderField,
ShippingOrderFieldDecision,
ShippingOrderFieldObservation,
ShippingOrderFieldValue,
ShippingOrderSchema,
ShippingOrderSchemaAuditEvent,
ShippingOrderSchemaVersion,
ShippingOrderExtraction,
ShippingOrderFieldObservation,
ShippingOrderFieldDecision,
ShippingOrderFieldValue,
ShippingOrderLine,
User,
)
from app.services.shipping_notice.order_schema.registry import (
COMPARATORS,
CONFLICT_POLICIES,
FIELD_SCOPES,
FIELD_TYPES,
NORMALIZERS,
RELATION_ROLES,
SOURCE_TYPES,
TYPE_COMPARATORS,
TYPE_NORMALIZERS,
TYPE_VALIDATORS,
VALIDATORS,
catalog,
)
from app.services.shipping_notice.order_schema.diff import compare_definitions
SCHEMA_CODE = 'SHIPPING_ORDER'
FIELD_CODE_RE = re.compile(r'^[a-z][a-z0-9_]{1,63}$')
EVIDENCE_KEYS = {'required', 'source_precedence', 'conflict_policy', 'allow_single_source'}
def _iso(value: datetime | None) -> str | None:
"""将可空时间转换为 API 使用的 ISO 字符串。"""
return value.isoformat() if value else None
def _schema() -> ShippingOrderSchema | None:
"""读取唯一逻辑订单 Schema;不存在时返回 None。"""
return ShippingOrderSchema.query.filter_by(schema_code=SCHEMA_CODE).first()
def _require_schema() -> ShippingOrderSchema:
"""读取唯一订单 Schema,不存在时抛出领域 404。"""
row = _schema()
if row is None:
raise NotFoundError('Shipping order schema not found', code='SHIPPING.ORDER_SCHEMA_NOT_FOUND')
return row
def _field_payload(field: ShippingOrderField) -> dict[str, Any]:
"""序列化稳定字段身份,不混入具体版本的显示和抽取规则。"""
return {
'id': field.id,
'field_code': field.field_code,
'scope': field.scope,
'value_type': field.value_type,
'status': field.status,
'published_once': bool(field.published_once),
'created_at': _iso(field.created_at),
'updated_at': _iso(field.updated_at),
}
def _copy_json(value: Any) -> Any:
"""复制 JSON 兼容数据,避免 ORM 可变对象被后续修改污染审计快照。"""
return json.loads(json.dumps(value, ensure_ascii=True))
def _definition(version: ShippingOrderSchemaVersion) -> dict[str, Any]:
"""返回版本完整定义副本;草稿和发布版本均以此字段作为唯一配置真相。"""
return _copy_json(version.definition_json or {'schema_code': SCHEMA_CODE, 'version': version.version, 'fields': []})
def _enabled_fields(definition: dict[str, Any]) -> list[dict[str, Any]]:
"""筛选当前版本实际生效字段,供发布门禁和 Dify 运行契约复用。"""
return [dict(item) for item in definition.get('fields') or [] if item.get('enabled', True)]
def _audit_summary(before: dict[str, Any] | None, after: dict[str, Any] | None) -> dict[str, Any]:
"""生成阶段一审计摘要;阶段三在此基础上提供完整字段级语义差异。"""
before_fields = {str(item.get('field_id')): item for item in (before or {}).get('fields', [])}
after_fields = {str(item.get('field_id')): item for item in (after or {}).get('fields', [])}
return {
'before_field_count': len(before_fields),
'after_field_count': len(after_fields),
'added_field_ids': sorted(set(after_fields) - set(before_fields)),
'removed_field_ids': sorted(set(before_fields) - set(after_fields)),
'changed_field_ids': sorted(
field_id for field_id in set(before_fields) & set(after_fields)
if before_fields[field_id] != after_fields[field_id]
),
}
def _write_audit(
*, schema_id: int, version_id: int | None, event_type: str, actor_id: int | None,
request_id: str | None, before: dict[str, Any] | None, after: dict[str, Any] | None,
) -> None:
"""追加配置审计事件;调用方与业务变更共用同一数据库事务。"""
db.session.add(ShippingOrderSchemaAuditEvent(
schema_id=schema_id,
version_id=version_id,
event_type=event_type,
actor_id=actor_id,
before_snapshot_json=_copy_json(before) if before is not None else None,
after_snapshot_json=_copy_json(after) if after is not None else None,
change_summary_json=_audit_summary(before, after),
request_id=request_id,
))
def _version_payload(
version: ShippingOrderSchemaVersion, *, include_definition: bool = True,
actors: dict[int, User] | None = None,
) -> dict[str, Any]:
"""序列化 Schema 版本;列表可省略完整快照,详情始终读取不可分叉的 definition_json。"""
definition = _definition(version)
def actor_payload(user_id: int | None) -> dict[str, Any] | None:
"""返回版本操作者的安全展示信息,避免历史页面暴露用户敏感字段。"""
user = actors.get(user_id) if actors and user_id else (db.session.get(User, user_id) if user_id else None)
if user is None:
return None
return {'id': user.id, 'display_name': user.real_name or user.username}
payload = {
'id': version.id,
'version': version.version,
'status': version.status,
'checksum': version.checksum,
'lock_version': version.lock_version,
'change_note': version.change_note,
'source_version_id': version.source_version_id,
'published_at': _iso(version.published_at),
'retired_at': _iso(version.retired_at),
'created_at': _iso(version.created_at),
'updated_at': _iso(version.updated_at),
'created_by': actor_payload(version.created_by_id),
'published_by': actor_payload(version.published_by_id),
'field_count': sum(1 for item in definition.get('fields') or [] if item.get('enabled', True)),
}
if include_definition:
payload['definition'] = definition
return payload
def get_state() -> dict[str, Any]:
"""返回编辑工作区所需当前草稿/发布版本,历史版本由分页接口按需读取。"""
schema = _schema()
if schema is None:
return {'schema': None, 'fields': [], 'versions': [], 'catalog': catalog()}
return {
'schema': {
'id': schema.id,
'schema_code': schema.schema_code,
'display_name': schema.display_name,
'description': schema.description,
'status': schema.status,
},
# Retired fields remain available to historical records, not the current configuration workspace.
'fields': [_field_payload(item) for item in ShippingOrderField.query.filter_by(
schema_id=schema.id, status='active',
).order_by(ShippingOrderField.field_code).all()],
'versions': [
_version_payload(item)
for item in reversed(schema.versions)
if item.status in {'draft', 'published'}
],
'catalog': catalog(),
}
def list_versions(
*, page: int = 1, page_size: int = 20, version_number: int | None = None,
) -> dict[str, Any]:
"""分页返回 Schema 版本概要;可按业务版本号精确定位历史链接。"""
schema = _require_schema()
safe_page = max(page, 1)
safe_page_size = min(max(page_size, 1), 100)
query = ShippingOrderSchemaVersion.query.filter_by(schema_id=schema.id)
if version_number is not None:
query = query.filter(ShippingOrderSchemaVersion.version == version_number)
total = query.count()
rows = query.order_by(ShippingOrderSchemaVersion.version.desc()).offset(
(safe_page - 1) * safe_page_size
).limit(safe_page_size).all()
actor_ids = {
actor_id for row in rows for actor_id in (row.created_by_id, row.published_by_id) if actor_id is not None
}
actors = {user.id: user for user in User.query.filter(User.id.in_(actor_ids)).all()} if actor_ids else {}
return {
'items': [_version_payload(item, include_definition=False, actors=actors) for item in rows],
'page': safe_page,
'page_size': safe_page_size,
'total': total,
}
def get_version_detail(version_id: int) -> dict[str, Any]:
"""返回指定版本的完整不可变快照;不存在或跨 Schema 时拒绝访问。"""
schema = _require_schema()
version = db.session.get(ShippingOrderSchemaVersion, version_id)
if version is None or version.schema_id != schema.id:
raise NotFoundError('Shipping order schema version not found', code='SHIPPING.ORDER_SCHEMA_VERSION_NOT_FOUND')
return _version_payload(version)
def _require_version(version_id: int, *, schema: ShippingOrderSchema | None = None) -> ShippingOrderSchemaVersion:
"""读取属于唯一订单 Schema 的版本,防止 ID 被用于访问其他未来 Schema。"""
owner = schema or _require_schema()
version = db.session.get(ShippingOrderSchemaVersion, version_id)
if version is None or version.schema_id != owner.id:
raise NotFoundError('Shipping order schema version not found', code='SHIPPING.ORDER_SCHEMA_VERSION_NOT_FOUND')
return version
def get_version_diff(version_id: int, *, against_version_id: int) -> dict[str, Any]:
"""比较任意两个订单 Schema 版本;字段重命名依靠 field_id 保持为一次修改。"""
schema = _require_schema()
version = _require_version(version_id, schema=schema)
against = _require_version(against_version_id, schema=schema)
return {
'base_version': _version_payload(version),
'compare_version': _version_payload(against),
**compare_definitions(_definition(version), _definition(against)),
}
def _audit_event_payload(
event: ShippingOrderSchemaAuditEvent, *, actors: dict[int, User], versions: dict[int, ShippingOrderSchemaVersion],
) -> dict[str, Any]:
"""序列化审计时间线的最小安全字段,不暴露完整配置快照或用户敏感信息。"""
actor = actors.get(event.actor_id) if event.actor_id else None
version = versions.get(event.version_id) if event.version_id else None
return {
'id': event.id,
'event_type': event.event_type,
'version': {'id': version.id, 'version': version.version} if version else None,
'actor': {'id': actor.id, 'display_name': actor.real_name or actor.username} if actor else None,
'change_summary': _copy_json(event.change_summary_json or {}),
'request_id': event.request_id,
'created_at': _iso(event.created_at),
}
def list_audit_events(*, page: int = 1, page_size: int = 20, version_id: int | None = None) -> dict[str, Any]:
"""分页读取只追加的 Schema 审计时间线,可按版本过滤且批量加载操作者。"""
schema = _require_schema()
safe_page = max(page, 1)
safe_page_size = min(max(page_size, 1), 100)
query = ShippingOrderSchemaAuditEvent.query.filter_by(schema_id=schema.id)
if version_id is not None:
_require_version(version_id, schema=schema)
query = query.filter(ShippingOrderSchemaAuditEvent.version_id == version_id)
total = query.count()
rows = query.order_by(
ShippingOrderSchemaAuditEvent.created_at.desc(), ShippingOrderSchemaAuditEvent.id.desc(),
).offset((safe_page - 1) * safe_page_size).limit(safe_page_size).all()
actor_ids = {item.actor_id for item in rows if item.actor_id is not None}
version_ids = {item.version_id for item in rows if item.version_id is not None}
actors = {item.id: item for item in User.query.filter(User.id.in_(actor_ids)).all()} if actor_ids else {}
versions = {
item.id: item for item in ShippingOrderSchemaVersion.query.filter(
ShippingOrderSchemaVersion.id.in_(version_ids)
).all()
} if version_ids else {}
return {
'items': [_audit_event_payload(item, actors=actors, versions=versions) for item in rows],
'page': safe_page,
'page_size': safe_page_size,
'total': total,
}
def _extraction_summary(extraction: ShippingOrderExtraction) -> dict[str, Any]:
"""序列化版本使用记录概要,不返回原始 LLM 和证据正文以控制历史列表体积。"""
return {
'id': extraction.id,
'task_id': extraction.task_id,
'intake_id': extraction.intake_id,
'status': extraction.status,
'input_snapshot_hash': extraction.input_snapshot_hash,
'created_at': _iso(extraction.created_at),
'updated_at': _iso(extraction.updated_at),
}
def get_version_usage(version_id: int, *, page: int = 1, page_size: int = 20) -> dict[str, Any]:
"""统计并分页读取实际使用指定 Schema 版本的解析记录,供发布影响评估和审计追溯。"""
schema = _require_schema()
version = _require_version(version_id, schema=schema)
safe_page = max(page, 1)
safe_page_size = min(max(page_size, 1), 100)
query = ShippingOrderExtraction.query.filter_by(schema_version_id=version.id)
total = query.count()
status_counts = {
status: count for status, count in db.session.query(
ShippingOrderExtraction.status, func.count(ShippingOrderExtraction.id),
).filter_by(schema_version_id=version.id).group_by(ShippingOrderExtraction.status).all()
}
first_used_at, last_used_at = db.session.query(
func.min(ShippingOrderExtraction.created_at), func.max(ShippingOrderExtraction.created_at),
).filter_by(schema_version_id=version.id).one()
rows = query.order_by(
ShippingOrderExtraction.created_at.desc(), ShippingOrderExtraction.id.desc(),
).offset((safe_page - 1) * safe_page_size).limit(safe_page_size).all()
return {
'version': _version_payload(version, include_definition=False),
'summary': {
'total': total,
'status_counts': status_counts,
'first_used_at': _iso(first_used_at),
'last_used_at': _iso(last_used_at),
},
'items': [_extraction_summary(row) for row in rows],
'page': safe_page,
'page_size': safe_page_size,
'total': total,
}
def _field_identity_map(version: ShippingOrderSchemaVersion) -> dict[str, dict[str, Any]]:
"""从提取时锁定的 Schema 快照读取字段身份,避免后续目录重命名污染运行审计。"""
return {
str(item['field_id']): item for item in _definition(version).get('fields') or []
if isinstance(item, dict) and item.get('field_id')
}
def _extraction_value(value: ShippingOrderFieldValue) -> Any:
"""返回运行时已保存的统一 JSON 值,避免读取已失效的类型字段组合。"""
return _copy_json(value.value_json)
def get_extraction_audit(extraction_id: int) -> dict[str, Any]:
"""返回单次订单解析的完整只读审计链:冻结输入、LLM 候选、裁决和证据。"""
extraction = db.session.get(ShippingOrderExtraction, extraction_id)
if extraction is None:
raise NotFoundError('Shipping order extraction not found', code='SHIPPING.ORDER_EXTRACTION_NOT_FOUND')
schema = _require_schema()
version = _require_version(extraction.schema_version_id, schema=schema)
identities = _field_identity_map(version)
lines = ShippingOrderLine.query.filter_by(extraction_id=extraction.id).order_by(ShippingOrderLine.position).all()
observations = ShippingOrderFieldObservation.query.filter_by(extraction_id=extraction.id).order_by(
ShippingOrderFieldObservation.id,
).all()
decisions = ShippingOrderFieldDecision.query.filter_by(extraction_id=extraction.id).order_by(
ShippingOrderFieldDecision.id,
).all()
values = ShippingOrderFieldValue.query.filter_by(extraction_id=extraction.id).order_by(
ShippingOrderFieldValue.id,
).all()
def identity(field_id: str) -> dict[str, Any]:
field = identities.get(field_id, {})
return {
'field_id': field_id,
'field_code': field.get('field_code'),
'display_name': field.get('display_name'),
'scope': field.get('scope'),
'value_type': field.get('value_type'),
}
return {
'extraction': _extraction_summary(extraction),
'schema_version': _version_payload(version),
'input_snapshot': (
_copy_json(extraction.input_snapshot_json) | {'snapshot_available': True}
if extraction.input_snapshot_json else {
'snapshot_hash': extraction.input_snapshot_hash,
'documents': [],
'snapshot_available': False,
}
),
'raw_llm_output': _copy_json(extraction.raw_llm_output_json),
'normalized_result': _copy_json(extraction.normalized_result_json),
'validation_result': _copy_json(extraction.validation_result_json),
'lines': [{'id': row.id, 'position': row.position, 'line_key': row.line_key} for row in lines],
'observations': [
identity(row.field_id) | {
'id': row.id, 'line_id': row.line_id, 'source_document_id': row.source_document_id,
'source_type': row.source_type, 'extractor': row.extractor,
'raw_value': _copy_json(row.raw_value_json), 'normalized_value': _copy_json(row.normalized_value_json),
'evidence_quote': row.evidence_quote, 'confidence': str(row.confidence) if row.confidence is not None else None,
'evidence_verified': bool(row.evidence_verified), 'created_at': _iso(row.created_at),
}
for row in observations
],
'decisions': [
identity(row.field_id) | {
'id': row.id, 'line_id': row.line_id, 'decision_status': row.decision_status,
'selected_observation_id': row.selected_observation_id,
'supporting_observation_ids': list(row.supporting_observation_ids_json or []),
'resolved_value': _copy_json(row.resolved_value_json), 'reason_code': row.reason_code,
'decided_at': _iso(row.decided_at),
}
for row in decisions
],
'field_values': [
identity(row.field_id) | {
'id': row.id, 'line_id': row.line_id, 'decision_id': row.decision_id,
'value': _extraction_value(row), 'created_at': _iso(row.created_at),
}
for row in values
],
}
def initialize_schema(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""初始化全局唯一订单 Schema;重复初始化明确拒绝。"""
if ShippingOrderSchema.query.count():
raise ConflictError('Only one shipping order schema is allowed', code='SHIPPING.ORDER_SCHEMA_EXISTS')
display_name = str(data.get('display_name') or '').strip()
if not display_name:
raise ValidationError('display_name is required', details={'field': 'display_name'})
schema = ShippingOrderSchema(
schema_code=SCHEMA_CODE,
display_name=display_name,
description=str(data.get('description') or '').strip() or None,
created_by_id=actor_id,
updated_by_id=actor_id,
)
db.session.add(schema)
db.session.commit()
return get_state()
def save_field(
data: dict[str, Any], *, actor_id: int | None, field_id: str | None = None,
request_id: str | None = None,
) -> dict[str, Any]:
"""创建或更新稳定字段;系统标识可重命名,首次发布后仍锁定 scope 和 type。"""
schema = _require_schema()
field = db.session.get(ShippingOrderField, field_id) if field_id else None
if field_id and (field is None or field.schema_id != schema.id):
raise NotFoundError('Shipping order field not found', code='SHIPPING.ORDER_FIELD_NOT_FOUND')
code = str(data.get('field_code') or '').strip().lower()
scope = str(data.get('scope') or '').strip().lower()
value_type = str(data.get('value_type') or '').strip().lower()
if not FIELD_CODE_RE.fullmatch(code):
raise ValidationError('field_code must use lower snake_case', code='SHIPPING.ORDER_FIELD_INVALID')
if scope not in FIELD_SCOPES or value_type not in FIELD_TYPES:
raise ValidationError('scope or value_type is invalid', code='SHIPPING.ORDER_FIELD_INVALID')
if field and field.published_once and (field.scope, field.value_type) != (scope, value_type):
raise ConflictError('Published field scope and type are immutable', code='SHIPPING.ORDER_FIELD_IMMUTABLE')
previous_code = field.field_code if field else None
field = field or ShippingOrderField(
schema_id=schema.id,
field_code=code,
scope=scope,
value_type=value_type,
created_by_id=actor_id,
)
field.field_code = code
field.scope = scope
field.value_type = value_type
if not field_id:
db.session.add(field)
try:
db.session.flush()
draft = ShippingOrderSchemaVersion.query.filter_by(schema_id=schema.id, status='draft').first()
before = _definition(draft) if draft else None
if draft and previous_code != code:
definition = _definition(draft)
for item in definition.get('fields') or []:
if str(item.get('field_id')) == field.id:
item['field_code'] = code
draft.definition_json = definition
draft.lock_version += 1
_write_audit(
schema_id=schema.id, version_id=draft.id if draft else None, event_type='field_saved',
actor_id=actor_id, request_id=request_id, before=before,
after=_definition(draft) if draft else None,
)
db.session.commit()
except Exception as exc:
db.session.rollback()
raise ConflictError('field_code already exists', code='SHIPPING.ORDER_FIELD_CONFLICT') from exc
return _field_payload(field)
def retire_field(
field_id: str, *, actor_id: int | None = None, request_id: str | None = None,
) -> dict[str, Any]:
"""退役无运行配置引用的稳定字段;历史 Extraction/Schema 版本可继续审计。"""
field = db.session.get(ShippingOrderField, field_id)
if field is None or field.schema_id != _require_schema().id:
raise NotFoundError('Shipping order field not found', code='SHIPPING.ORDER_FIELD_NOT_FOUND')
draft = ShippingOrderSchemaVersion.query.filter_by(schema_id=field.schema_id, status='draft').first()
if draft and any(str(item.get('field_id')) == field.id for item in _definition(draft).get('fields') or []):
raise ConflictError('Field is referenced by a draft schema version', code='SHIPPING.ORDER_FIELD_RETIRE_BLOCKED')
if _field_runtime_references(field.id):
raise ConflictError('Field is referenced by downstream runtime configuration', code='SHIPPING.ORDER_FIELD_RETIRE_BLOCKED')
field.status = 'retired'
_write_audit(
schema_id=field.schema_id, version_id=None, event_type='field_retired', actor_id=actor_id,
request_id=request_id, before={'field': _field_payload(field) | {'status': 'active'}},
after={'field': _field_payload(field)},
)
db.session.commit()
return _field_payload(field)
def delete_field(
field_id: str, *, actor_id: int | None = None, request_id: str | None = None,
) -> dict[str, Any]:
"""
删除当前配置不再需要的字段。
未发布且没有业务/下游引用时物理删除;已进入历史 Schema 或解析记录时仅归档。
草稿中的字段配置和字段目录在同一事务内变更,避免删除失败却提前改坏草稿。
"""
field = db.session.get(ShippingOrderField, field_id)
if field is None or field.schema_id != _require_schema().id:
raise NotFoundError('Shipping order field not found', code='SHIPPING.ORDER_FIELD_NOT_FOUND')
if _field_runtime_references(field.id):
raise ConflictError('Field is referenced by downstream runtime configuration', code='SHIPPING.ORDER_FIELD_RETIRE_BLOCKED')
historical_schema_reference = any(
any(str(item.get('field_id')) == field.id for item in _definition(version).get('fields') or [])
for version in ShippingOrderSchemaVersion.query.filter(
ShippingOrderSchemaVersion.schema_id == field.schema_id,
ShippingOrderSchemaVersion.status.in_(['published', 'retired']),
).all()
)
extraction_reference = any((
db.session.query(ShippingOrderFieldObservation.id).filter_by(field_id=field.id).first(),
db.session.query(ShippingOrderFieldDecision.id).filter_by(field_id=field.id).first(),
db.session.query(ShippingOrderFieldValue.id).filter_by(field_id=field.id).first(),
))
draft = ShippingOrderSchemaVersion.query.filter_by(schema_id=field.schema_id, status='draft').first()
before = _definition(draft) if draft else None
if draft:
definition = _definition(draft)
definition['fields'] = [
item for item in definition.get('fields') or [] if str(item.get('field_id')) != field.id
]
draft.definition_json = definition
draft.lock_version += 1
if field.published_once or historical_schema_reference or extraction_reference:
field.status = 'retired'
action = 'archived'
else:
db.session.delete(field)
action = 'deleted'
_write_audit(
schema_id=field.schema_id, version_id=draft.id if draft else None, event_type='field_deleted',
actor_id=actor_id, request_id=request_id, before=before,
after=_definition(draft) if draft else None,
)
db.session.commit()
return {'field_id': field_id, 'action': action}
def _field_runtime_references(field_id: str) -> list[str]:
"""返回字段仍被哪些可运行下游配置引用,供退役与 Schema 发布共用。"""
from app.models import (
ShippingExcelTemplate, ShippingInventoryParsingProfile,
ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition,
)
references: list[str] = []
if db.session.query(ShippingInventoryRoutingRuleCondition).join(ShippingInventoryRoutingRule).filter(
ShippingInventoryRoutingRuleCondition.order_field_id == field_id,
ShippingInventoryRoutingRule.status.in_(['draft', 'published']),
).count():
references.append('inventory_routing_rule')
parsing_reference = any(
any(str(item.get('order_field_id') or '') == field_id for item in (profile.definition_json or {}).get('match_keys', []))
for profile in ShippingInventoryParsingProfile.query.filter(
ShippingInventoryParsingProfile.status.in_(['draft', 'published'])
).all()
)
if parsing_reference:
references.append('inventory_parsing_profile')
template_reference = any(
any(
item.get('source_kind') == 'order_field' and str(item.get('source_key') or '') == field_id
for item in (template.definition_json or {}).get('mappings', [])
)
for template in ShippingExcelTemplate.query.filter(
ShippingExcelTemplate.status.in_(['draft', 'published'])
).all()
)
if template_reference:
references.append('excel_template')
return references
def create_draft(
data: dict[str, Any], *, actor_id: int | None, request_id: str | None = None,
) -> dict[str, Any]:
"""创建下一版本草稿;从指定版本复制完整定义并记录来源和审计事件。"""
schema = _require_schema()
source_id = data.get('copy_from_version_id')
if source_id is not None and (not str(source_id).isdigit() or int(source_id) < 1):
raise ValidationError('copy_from_version_id is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
source = db.session.get(ShippingOrderSchemaVersion, int(source_id)) if source_id is not None else None
if source_id is not None and source is None:
raise ValidationError('copy_from_version_id is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
if source is not None and source.schema_id != schema.id:
raise ValidationError('copy_from_version_id is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
if source is not None and source.status not in {'published', 'retired'}:
raise ValidationError('copy_from_version_id must be immutable', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
if ShippingOrderSchemaVersion.query.filter_by(schema_id=schema.id, status='draft').count():
raise ConflictError('A draft schema version already exists', code='SHIPPING.ORDER_SCHEMA_DRAFT_EXISTS')
next_version = int(db.session.query(func.max(ShippingOrderSchemaVersion.version)).filter_by(schema_id=schema.id).scalar() or 0) + 1
definition = _definition(source) if source else {
'schema_code': schema.schema_code, 'version': next_version, 'fields': [],
}
definition['version'] = next_version
version = ShippingOrderSchemaVersion(
schema_id=schema.id,
version=next_version,
status='draft',
definition_json=definition,
source_version_id=source.id if source else None,
change_note=str(data.get('change_note') or '').strip() or None,
created_by_id=actor_id,
)
db.session.add(version)
db.session.flush()
_write_audit(
schema_id=schema.id, version_id=version.id,
event_type='cloned' if source else 'draft_created', actor_id=actor_id,
request_id=request_id, before=_definition(source) if source else None, after=definition,
)
db.session.commit()
return _version_payload(version)
def _string_list(value: Any, *, field: str) -> list[str]:
"""规范化去重字符串列表,非法结构抛出字段级校验错误。"""
if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
raise ValidationError(f'{field} must be a string list', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
result: list[str] = []
for item in value:
normalized = item.strip()
if normalized and normalized not in result:
result.append(normalized)
return result
def _evidence_policy(value: Any) -> dict[str, Any]:
"""校验证据策略,仅允许受控来源、冲突策略和布尔开关。"""
if not isinstance(value, dict) or set(value) - EVIDENCE_KEYS:
raise ValidationError('evidence_policy is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
sources = _string_list(value.get('source_precedence', []), field='source_precedence')
if set(sources) - SOURCE_TYPES:
raise ValidationError('source_precedence contains unsupported source', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
conflict_policy = str(value.get('conflict_policy') or 'block').strip()
if conflict_policy not in CONFLICT_POLICIES:
raise ValidationError('conflict_policy is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
required = value.get('required', True)
allow_single = value.get('allow_single_source', True)
if not isinstance(required, bool) or not isinstance(allow_single, bool):
raise ValidationError('evidence policy flags must be boolean', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
return {
'required': required,
'source_precedence': sources,
'conflict_policy': conflict_policy,
'allow_single_source': allow_single,
}
def save_draft(
version_id: int, data: dict[str, Any], *, actor_id: int | None = None,
request_id: str | None = None,
) -> dict[str, Any]:
"""校验并整体替换草稿定义;expected_lock_version 不匹配时拒绝覆盖。"""
version = db.session.get(ShippingOrderSchemaVersion, version_id)
if version is None or version.schema_id != _require_schema().id:
raise NotFoundError('Shipping order schema version not found', code='SHIPPING.ORDER_SCHEMA_VERSION_NOT_FOUND')
if version.status != 'draft':
raise ConflictError('Published schema version is immutable', code='SHIPPING.ORDER_SCHEMA_VERSION_IMMUTABLE')
expected_lock_version = data.get('expected_lock_version')
if not isinstance(expected_lock_version, int):
raise ValidationError(
'expected_lock_version is required', code='SHIPPING.ORDER_SCHEMA_LOCK_VERSION_REQUIRED',
details={'field': 'expected_lock_version'},
)
if expected_lock_version != version.lock_version:
raise ConflictError(
'Schema draft was changed by another user', code='SHIPPING.ORDER_SCHEMA_VERSION_CONFLICT',
details={'expected_lock_version': expected_lock_version, 'current_lock_version': version.lock_version},
)
configs = data.get('fields')
if not isinstance(configs, list):
raise ValidationError('fields must be a list', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
before = _definition(version)
active_fields = {
item.id: item for item in ShippingOrderField.query.filter_by(schema_id=version.schema_id, status='active').all()
}
seen: set[str] = set()
normalized_fields: list[dict[str, Any]] = []
for sequence, raw in enumerate(configs, start=1):
if not isinstance(raw, dict) or str(raw.get('field_id') or '') not in active_fields:
raise ValidationError('field_id is invalid or retired', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
field_id = str(raw['field_id'])
if field_id in seen:
raise ValidationError('field_id must be unique in a version', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
seen.add(field_id)
field = active_fields[field_id]
enabled = raw.get('enabled', True)
display_name = str(raw.get('display_name') or '').strip()
normalizer = str(raw.get('normalizer_key') or 'trim').strip()
comparator = str(raw.get('comparator_key') or 'normalized_text').strip()
validators = _string_list(raw.get('validator_keys', []), field='validator_keys')
aliases = _string_list(raw.get('aliases', []), field='aliases')
enum_options = _string_list(raw.get('enum_options', []), field='enum_options')
relation_role = str(raw.get('relation_role') or '').strip() or None
required = raw.get('required', False)
if not isinstance(enabled, bool) or not isinstance(required, bool):
raise ValidationError('required must be boolean', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
if not display_name or normalizer not in NORMALIZERS or comparator not in COMPARATORS:
raise ValidationError('field display or transformation config is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
if set(validators) - VALIDATORS or relation_role not in RELATION_ROLES:
raise ValidationError('field validator or relation role is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
if normalizer not in TYPE_NORMALIZERS[field.value_type]:
raise ValidationError('normalizer is incompatible with field type', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
if comparator not in TYPE_COMPARATORS[field.value_type]:
raise ValidationError('comparator is incompatible with field type', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
if set(validators) - TYPE_VALIDATORS[field.value_type]:
raise ValidationError('validator is incompatible with field type', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
if field.value_type == 'enum' and not enum_options:
raise ValidationError('enum field requires enum_options', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
if field.value_type != 'enum' and enum_options:
raise ValidationError('enum_options only applies to enum fields', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
normalized_fields.append({
'field_id': field_id,
'field_code': field.field_code,
'scope': field.scope,
'value_type': field.value_type,
'enabled': enabled,
'display_name': display_name,
'description': str(raw.get('description') or '').strip() or None,
'required': required,
'aliases': aliases,
'normalizer_key': normalizer,
'validator_keys': validators,
'enum_options': enum_options,
'evidence_policy': _evidence_policy(raw.get('evidence_policy', {})),
'relation_role': relation_role,
'comparator_key': comparator,
'extraction_instruction': str(raw.get('extraction_instruction') or '').strip() or None,
'sequence': sequence,
})
after = {'schema_code': version.schema.schema_code, 'version': version.version, 'fields': normalized_fields}
version.definition_json = after
version.lock_version += 1
version.change_note = str(data.get('change_note') or version.change_note or '').strip() or None
_write_audit(
schema_id=version.schema_id, version_id=version.id, event_type='draft_saved', actor_id=actor_id,
request_id=request_id, before=before, after=after,
)
db.session.commit()
return _version_payload(version)
def publish(
version_id: int, *, actor_id: int | None, expected_lock_version: int | None = None,
request_id: str | None = None,
) -> dict[str, Any]:
"""发布指定锁版本的草稿,生成不可变 checksum 并退役上一发布版本。"""
version = db.session.get(ShippingOrderSchemaVersion, version_id)
if version is None or version.schema_id != _require_schema().id:
raise NotFoundError('Shipping order schema version not found', code='SHIPPING.ORDER_SCHEMA_VERSION_NOT_FOUND')
if version.status != 'draft':
raise ConflictError('Only draft schema version can be published', code='SHIPPING.ORDER_SCHEMA_PUBLISH_INVALID')
if not isinstance(expected_lock_version, int):
raise ValidationError(
'expected_lock_version is required', code='SHIPPING.ORDER_SCHEMA_LOCK_VERSION_REQUIRED',
details={'field': 'expected_lock_version'},
)
if expected_lock_version != version.lock_version:
raise ConflictError(
'Schema draft was changed by another user', code='SHIPPING.ORDER_SCHEMA_VERSION_CONFLICT',
details={'expected_lock_version': expected_lock_version, 'current_lock_version': version.lock_version},
)
definition = _definition(version)
enabled_configs = _enabled_fields(definition)
if not enabled_configs:
raise ValidationError('Schema version requires at least one field', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
included_field_ids = {str(config.get('field_id')) for config in enabled_configs}
referenced_omissions: dict[str, list[str]] = {}
for field in ShippingOrderField.query.filter_by(schema_id=version.schema_id, status='active').all():
if field.id in included_field_ids:
continue
references = _field_runtime_references(field.id)
if references:
referenced_omissions[field.id] = references
if referenced_omissions:
raise ConflictError(
'Schema version omits fields referenced by downstream runtime configuration',
code='SHIPPING.ORDER_SCHEMA_PUBLISH_DEPENDENCY_BLOCKED',
details={'fields': referenced_omissions},
)
encoded = json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode('utf-8')
now = datetime.utcnow()
previous = ShippingOrderSchemaVersion.query.filter_by(schema_id=version.schema_id, status='published').first()
if previous is not None:
previous.status = 'retired'
previous.retired_at = now
db.session.flush()
for config in enabled_configs:
field = db.session.get(ShippingOrderField, str(config.get('field_id')))
if field is not None:
field.published_once = True
version.checksum = hashlib.sha256(encoded).hexdigest()
version.status = 'published'
version.published_by_id = actor_id
version.published_at = now
_write_audit(
schema_id=version.schema_id, version_id=version.id, event_type='published', actor_id=actor_id,
request_id=request_id, before=definition, after=definition,
)
db.session.commit()
return _version_payload(version)
def delete_draft(
version_id: int, *, actor_id: int | None = None, request_id: str | None = None,
) -> None:
"""删除错误草稿并保留删除前快照审计;发布和退役版本不可删除。"""
version = db.session.get(ShippingOrderSchemaVersion, version_id)
if version is None or version.schema_id != _require_schema().id:
raise NotFoundError('Shipping order schema version not found', code='SHIPPING.ORDER_SCHEMA_VERSION_NOT_FOUND')
if version.status != 'draft':
raise ConflictError('Only draft schema version can be deleted', code='SHIPPING.ORDER_SCHEMA_VERSION_DELETE_BLOCKED')
_write_audit(
schema_id=version.schema_id, version_id=None, event_type='draft_deleted', actor_id=actor_id,
request_id=request_id, before=_definition(version), after=None,
)
db.session.delete(version)
db.session.commit()
def get_published_contract() -> dict[str, Any]:
"""返回当前发布订单字段契约,供阶段 2 的 Dify 输入编译器使用。"""
schema = _require_schema()
version = ShippingOrderSchemaVersion.query.filter_by(schema_id=schema.id, status='published').first()
if version is None:
raise ConflictError('No published shipping order schema', code='SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED')
return {
'schema_version_id': version.id,
'schema_code': schema.schema_code,
'version': version.version,
'checksum': version.checksum,
'fields': _enabled_fields(_definition(version)),
}
@@ -1,8 +1,8 @@
"""
services/shipping_notice/progress_workflow.py
用途:承接发货通知任务的自动推进流程,包括解析确认检查、库存准备、字段映射确认与履约侧串联。
依赖:customer_identity_gate、tool_common、query_service、inventory_mapping_workflow、inventory_workflow、fulfillment_workflow、tool_response。
用途:承接发货通知任务的自动推进流程,包括解析确认检查、正式库存准备与履约侧串联。
依赖:customer_identity_gate、tool_common、query_service、inventory_workflow、fulfillment_workflow、tool_response。
逻辑:由 task_workflow 对外转调本文件;本文件按当前任务状态决定继续自动推进、停在人审检查点,或进入履约 workflow。
"""
@@ -16,7 +16,6 @@ from app.services.shipping_notice import fulfillment_workflow
from app import db
from app.services.shipping_notice.constants import (
CP_INVENTORY_SOURCE_REVIEW,
CP_UPLOAD_REQ,
PH_INVENTORY_SOURCE_UNRESOLVED,
PH_LOW_CONF,
PH_RSV_REQ,
@@ -27,25 +26,20 @@ 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,
maybe_auto_confirm_inventory_mapping,
)
from app.services.shipping_notice.inventory_workflow import ensure_inventory
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
from app.services.shipping_notice.tool_common import auto_progress_enabled, auto_rpa_inventory_enabled, set_task_step_progress
from app.services.shipping_notice.state_machine import resolve_task_ui_state
from app.services.shipping_notice.tool_common import auto_progress_enabled
from app.services.shipping_notice.tool_response import tool_response
from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response
def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
"""
按任务当前状态自动串联解析确认、库存准备、字段映射与履约动作。
按任务当前状态自动串联解析确认、正式库存准备与履约动作。
【AI 触发时机】:当用户要求“继续处理”“自动推进”“下一步全自动跑完能跑的步骤”时调用。
核心逻辑:先检查解析是否需要人工确认,再保证库存已就绪、字段映射已确认,最后委托 fulfillment workflow 继续推进。
核心逻辑:先检查解析是否需要人工确认,再保证正式库存已按 published Profile 就绪,最后委托 fulfillment workflow 继续推进。
Args:
payload: 必须能定位任务;可额外携带 lang/locale/language 以及 auto-chain 控制参数。
@@ -135,30 +129,8 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
)
# [STEP 2] 保证库存已经就绪。
# 若库存还没导入,则根据配置决定触发 RPA 拉取,或明确提示人工上传 Excel。
# 正常任务仅复用排程或手动刷新已导出的文件;这里不得隐式触发 RPA。
if not task.inventory_lines_json:
if not auto_rpa_inventory_enabled():
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
step_title="获取库存",
status="needs_human",
message="未开启自动 RPA 获取库存",
progress_percent=100,
current=0,
total=1,
detail="请手动上传货代库存 Excel,或开启自动 RPA 后重试。",
)
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message="未开启自动 RPA 获取库存。请手动上传货代库存 Excel。",
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
stop_agent_turn=True,
)
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
inv_payload: dict[str, Any] = {"task_id": task.task_no, "mode": "auto"}
if lang:
@@ -168,24 +140,11 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
steps.append("触发 RPA 库存导出")
return inv
if inv.get("status") != "ok":
if maybe_auto_confirm_inventory_mapping(task):
steps.append("自动确认字段对齐")
else:
return inv
return inv
else:
steps.append("载入库存")
# [STEP 3] 尝试自动完成字段映射确认。
# 当系统已经拿到足够可靠的列映射时,直接确认可减少一次人工往返。
if maybe_auto_confirm_inventory_mapping(task):
steps.append("自动确认字段对齐")
# [STEP 4] 如果映射仍需人工确认,则停在检查点,把确认动作交还给用户或 Agent。
if awaiting_inventory_mapping_confirm(task):
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
return inventory_mapping_checkpoint_response(task, lang=lang or None)
# [STEP 5] 库存与映射都就绪后,再进入履约侧自动推进。
# [STEP 3] 库存就绪后进入履约侧自动推进。
# 匹配、生成 Excel、上传货代等步骤统一交给 fulfillment workflow 处理,避免本文件继续膨胀。
fulfillment_result = fulfillment_workflow.run_auto_progress_fulfillment_steps(task, payload, steps)
if fulfillment_result is not None:
@@ -188,21 +188,29 @@ def get_task_in_batch(batch_no: str, task_no: str) -> ShippingTask | None:
def resolve_task_export_download(task: ShippingTask | None) -> tuple[Path, str] | None:
"""解析任务导出文件路径;文件不存在或路径无效时返回 None。"""
"""解析任务当前 ready Artifact;文件不存在或校验元数据无效时返回 None。"""
if not task or not task.export_file_path:
return None
path = Path(task.export_file_path)
from app.models import ShippingExportArtifact
artifact = ShippingExportArtifact.query.filter_by(
task_id=task.id, status='ready', file_path=task.export_file_path,
).order_by(
ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc(),
).first()
if artifact is None:
return None
path = Path(artifact.file_path)
if not path.is_file():
return None
return path, task.export_file_name or path.name
return path, artifact.file_name or path.name
def task_export_error_message(task: ShippingTask | None) -> str:
"""导出下载失败时的错误文案(与 Tool / Workspace API 保持一致)。"""
if not task or not task.export_file_path:
if not task or task.id is None or not task.export_file_path:
return "export file not found"
path = Path(task.export_file_path)
if not path.is_file():
resolved = resolve_task_export_download(task)
if resolved is None:
return "export file missing on disk"
return ""
@@ -536,7 +544,6 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
"warehouse_hint": task.warehouse_hint,
"inventory_source_code": task.inventory_source_code,
"inventory_connector_type": task.inventory_connector_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,
@@ -727,7 +734,7 @@ def list_tasks_for_user(
process_status: str | None = None,
limit: int = 100,
) -> list[dict[str, Any]]:
"""列出用户可见任务摘要,可按 batch_no / process_status 过滤。"""
"""列出用户可见任务摘要,可按批次或工作台用户态状态过滤。"""
q = ShippingTask.query.filter(
(ShippingTask.user_id == user_id) | (ShippingTask.user_id.is_(None))
)
@@ -737,7 +744,13 @@ def list_tasks_for_user(
return []
q = q.filter(ShippingTask.batch_id == batch.id)
if process_status:
q = q.filter(ShippingTask.process_status == process_status)
if process_status == "shortage_review":
q = q.filter(
(ShippingTask.review_status == "shortage_review")
| (ShippingTask.pending_human_reason.in_(("shortage", "shortage_review")))
)
else:
q = q.filter(ShippingTask.process_status == process_status)
rows = q.order_by(desc(ShippingTask.created_at)).limit(max(1, min(limit, 500))).all()
return [serialize_task_summary(c) for c in rows]
@@ -36,7 +36,6 @@ _ACTION_EVENT_MAP: dict[str, _ActionEventMeta] = {
"decision_rejected": _ActionEventMeta("reject", "用户已驳回 {task_no}", 40),
"focus_switched": _ActionEventMeta("switch_focus", "用户已切换 focus 到 {task_no}", 35),
"focus_auto_switched": _ActionEventMeta("auto_focus", "系统自动聚焦到 {task_no}", 10),
"inventory_mapping_confirmed": _ActionEventMeta("confirm_inventory_mapping", "用户已确认 {task_no} 库存映射", 30),
"inventory_source_confirmed": _ActionEventMeta("confirm_inventory_source", "用户已确认 {task_no} 库存源", 30),
}
@@ -0,0 +1,64 @@
"""
services/shipping_notice/routing_facts.py
用途:构造库存源路由规则可读取的受控业务事实。
依赖:无 ORM 写入依赖;调用方传入已完成解析和标准化的任务/订单行数据。
逻辑:规则引擎只能通过本模块的白名单读取事实,避免管理端规则访问任意模型字段。
"""
from __future__ import annotations
from typing import Any
ALLOWED_SYSTEM_FACT_KEYS = frozenset({
'task.customer_code', 'task.destination_country', 'task.destination_city', 'task.destination_port',
'task.warehouse_hint', 'task.order_type', 'task.sender_email', 'task.sender_domain',
'line.reservation_id', 'line.part_number', 'line.customer_part_number', 'line.aws_part_number',
'line.inventory_source_hint',
})
def build_routing_facts(*, task: Any, line: dict[str, Any] | None = None) -> dict[str, dict[str, Any]]:
"""
将任务和订单行投影为路由规则可读取的稳定事实。
Args:
task: ShippingTask 或提供同名属性的对象。
line: 单条规范订单行;任务级规则传 None。
Returns:
dict: 使用 task/line 两层命名空间的只读事实字典。
"""
line_data = dict(line or {})
sender_email = str(getattr(task, 'sender_email', '') or '').strip().lower()
sender_domain = sender_email.rsplit('@', 1)[-1] if '@' in sender_email else ''
return {
'task': {
'customer_code': str(getattr(task, 'customer_code', '') or '').strip().upper(),
'destination_country': str(getattr(task, 'destination_country', '') or '').strip().upper(),
'destination_city': str(getattr(task, 'destination_city', '') or '').strip().upper(),
'destination_port': str(getattr(task, 'destination_code', '') or '').strip().upper(),
'warehouse_hint': str(getattr(task, 'warehouse_hint', '') or '').strip().upper(),
'order_type': str(getattr(task, 'order_type', '') or '').strip().upper(),
'sender_email': sender_email,
'sender_domain': sender_domain,
},
'line': {
key: str(line_data.get(key) or '').strip().upper()
for key in ('reservation_id', 'part_number', 'customer_part_number', 'aws_part_number', 'inventory_source_hint')
},
}
def read_system_fact(facts: dict[str, dict[str, Any]], fact_path: str) -> Any:
"""
读取白名单路由事实。
Raises:
KeyError: 规则引用未注册字段时抛出,调用方应拒绝发布或执行该规则。
"""
if fact_path not in ALLOWED_SYSTEM_FACT_KEYS:
raise KeyError(f'Unsupported routing fact: {fact_path}')
namespace, field = fact_path.split('.', 1)
return facts.get(namespace, {}).get(field)
@@ -0,0 +1,62 @@
"""
services/shipping_notice/routing_operators.py
用途:执行库存源路由规则允许的比较操作。
依赖:无业务服务依赖;由 inventory_routing_engine 调用。
逻辑:操作符白名单限制规则表达能力,避免管理员配置任意代码、SQL 或正则执行。
"""
from __future__ import annotations
from typing import Any
ALLOWED_OPERATORS = frozenset({
'equals', 'not_equals', 'in', 'not_in', 'prefix', 'suffix', 'contains',
'numeric_length', 'string_length', 'is_empty', 'is_not_empty',
})
def matches_operator(actual: Any, operator: str, expected: Any = None) -> bool:
"""
按受控操作符匹配一个标准化事实值。
Args:
actual: 路由事实值。
operator: 白名单操作符。
expected: 规则期望值;空值判断操作符不使用该参数。
Returns:
bool: 当前条件是否命中。
Raises:
ValueError: 操作符未注册或期望值格式不合法。
"""
if operator not in ALLOWED_OPERATORS:
raise ValueError(f'Unsupported routing operator: {operator}')
value = str(actual or '').strip()
if operator == 'is_empty':
return not value
if operator == 'is_not_empty':
return bool(value)
if operator in {'in', 'not_in'}:
if not isinstance(expected, list):
raise ValueError(f'{operator} expects a list')
result = value in {str(item or '').strip().upper() for item in expected}
return not result if operator == 'not_in' else result
expected_text = str(expected or '').strip().upper()
if operator == 'equals':
return value.upper() == expected_text
if operator == 'not_equals':
return value.upper() != expected_text
if operator == 'prefix':
return value.upper().startswith(expected_text)
if operator == 'suffix':
return value.upper().endswith(expected_text)
if operator == 'contains':
return expected_text in value.upper()
if operator == 'numeric_length':
return value.isdigit() and len(value) == int(expected)
if operator == 'string_length':
return len(value) == int(expected)
raise ValueError(f'Unsupported routing operator: {operator}')
+32 -11
View File
@@ -9,7 +9,6 @@ services/shipping_notice/rpa.py
from __future__ import annotations
import json
import os
import shutil
from datetime import datetime
from pathlib import Path
@@ -35,7 +34,7 @@ def rpa_runtime_mode(runtime: dict[str, Any] | None = None) -> dict[str, str | b
mode = str(runtime.get("mode") or runtime.get("rpa_mode") or "").strip().lower()
if mode in {"browser", "mock"}:
return _runtime_summary(mode)
raw = str(os.getenv("FREIGHT_RPA_MOCK", current_app.config.get("FREIGHT_RPA_MOCK", "false")) or "false").strip().lower()
raw = str(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false") or "false").strip().lower()
return _runtime_summary("mock" if raw in {"1", "true", "yes", "on"} else "browser")
@@ -47,8 +46,8 @@ def _path(key: str) -> Path | None:
def inventory_drop_dir() -> Path | None:
"""RPA 库存 Excel 落盘目录(FREIGHT_INVENTORY_DROP_DIR)。"""
return _path("FREIGHT_INVENTORY_DROP_DIR")
"""RPA 库存 Excel 落盘目录(SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR)。"""
return _path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR")
def inventory_processed_dir() -> Path | None:
@@ -61,17 +60,17 @@ def inventory_processed_dir() -> Path | None:
def inventory_trigger_dir() -> Path | None:
"""RPA 库存导出触发 JSON 目录。"""
return _path("FREIGHT_RPA_INVENTORY_TRIGGER_DIR")
return _path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR")
def upload_queue_dir() -> Path | None:
"""货代上传 Excel 队列目录(RPA 从此处读取待上传文件)。"""
return _path("FREIGHT_UPLOAD_QUEUE_DIR")
return _path("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR")
def upload_trigger_dir() -> Path | None:
"""RPA 货代上传触发 JSON 目录。"""
return _path("FREIGHT_RPA_UPLOAD_TRIGGER_DIR")
return _path("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR")
def write_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None = None) -> str | None:
@@ -129,15 +128,27 @@ def write_inventory_export_batch_trigger(
for source in sources:
if not isinstance(source, dict) or not source.get("source_code"):
continue
# 调用方只持有非敏感快照;写 trigger 前在服务端按 Source 补入 Profile 密文。
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
configuration_test = str((payload or {}).get('trigger_type') or '') == 'configuration_test'
trigger_source = get_rpa_trigger_inventory_source(
str(source["source_code"]), enabled_only=not configuration_test,
) or source
source = {**source, **trigger_source}
business_connector = str(source.get("connector_type") or "").strip().lower()
worker_connector = {"dbs": "dsv360", "crane": "crane_footprint"}.get(business_connector, business_connector)
inventory_sources.append({
"source_code": source.get("source_code"),
"connector_type": source.get("connector_type"),
"site_id": source.get("site_id"),
"warehouse_id": source.get("warehouse_id"),
"entry_url": source.get("entry_url"),
"connector_type": business_connector,
"worker_connector_type": worker_connector,
"rpa_profile_code": source.get("rpa_profile_code"),
"warehouse_id": source.get("fixed_warehouse_id") or source.get("warehouse_id"),
"login_url": source.get("login_url"),
"entry_url": source.get("login_url"),
"navigation": source.get("navigation") or {},
"parameters": source.get("parameters") or [],
"query": source.get("query") or {},
"credential_envelope": source.get("credential_envelope") or {},
})
if not inventory_sources:
return None
@@ -176,6 +187,16 @@ def write_inventory_export_trigger_for_task(
核心逻辑:batch 模式写 inventory_export_batch(含 task_no);否则写 legacy inventory_export。
"""
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
source_code = str(rpa_source.get('source_code') or '').strip()
rpa_source = get_rpa_trigger_inventory_source(source_code) or rpa_source
# Legacy 单票 trigger 与 batch trigger 必须共享 worker 输入契约。
rpa_source = dict(rpa_source)
business_connector = str(rpa_source.get('connector_type') or '').strip().lower()
rpa_source.setdefault('worker_connector_type', {'dbs': 'dsv360', 'crane': 'crane_footprint'}.get(business_connector, business_connector))
rpa_source.setdefault('entry_url', rpa_source.get('login_url'))
rpa_source.setdefault('credential_envelope', {})
body = dict(payload or {})
if inventory_rpa_batch_enabled():
run_no = f"TASK-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}"
@@ -77,6 +77,8 @@ def _build_refs(
run_purpose: str | None,
intake_nos: list[str] | None = None,
capability: str | None = None,
temporary_inventory_asset_no: str | None = None,
temporary_inventory_session_no: str | None = None,
) -> dict[str, str]:
"""
构建新版 agent_runtime_context.refs。
@@ -111,6 +113,12 @@ def _build_refs(
refs["intake_nos"] = json.dumps(normalized_intakes, ensure_ascii=False, separators=(",", ":"))
if _clean_text(capability):
refs["capability"] = _clean_text(capability)
asset_no = _clean_text(temporary_inventory_asset_no).upper()
if asset_no:
refs["temporary_inventory_asset_no"] = asset_no
session_no = _clean_text(temporary_inventory_session_no).upper()
if session_no:
refs["temporary_inventory_session_no"] = session_no
return refs
@@ -208,6 +216,8 @@ def build_shipping_runtime_context(
run_purpose: str | None = None,
intake_nos: list[str] | None = None,
capability: str | None = None,
temporary_inventory_asset_no: str | None = None,
temporary_inventory_session_no: str | None = None,
) -> dict[str, Any]:
"""
构建货代发货通知 Agent 的 agent_runtime_context。
@@ -226,6 +236,8 @@ def build_shipping_runtime_context(
run_purpose: 本次 Dify run 的目的,如 parse_notice。
intake_nos: 尚未建 Task 时的 Intake 编号集合。
capability: 当前固定画布能力。
temporary_inventory_asset_no: 本轮对话临时库存文件资产编号;仅供 Dify 调用受控 Tool。
temporary_inventory_session_no: 已创建的临时库存会话编号。
Returns:
agent_runtime_context 字典;session_id 为空时返回空 dict。
@@ -253,6 +265,8 @@ def build_shipping_runtime_context(
run_purpose=run_purpose,
intake_nos=intake_nos,
capability=capability,
temporary_inventory_asset_no=temporary_inventory_asset_no,
temporary_inventory_session_no=temporary_inventory_session_no,
),
domain=domain,
reference_context=reference_context,
@@ -21,13 +21,11 @@ from typing import Any
from app.models import ShippingTask
from app.services.shipping_notice.task_line_store import read_task_order_lines
from app.services.shipping_notice.constants import (
CP_ALIGN_REVIEW,
CP_EXPORT_READY,
CP_EXPORT_GENERATED,
CP_INVENTORY_PENDING,
CP_INVENTORY_SOURCE_REVIEW,
CP_CUSTOMER_REVIEW,
CP_MAP_INFER,
CP_PARSE_REVIEW,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_READY_EXPORT,
@@ -39,11 +37,9 @@ from app.services.shipping_notice.constants import (
CP_UPLOAD_FAILED,
CP_UPLOAD_REQ,
CP_WAITING_UPLOAD,
PH_ALIGN_REVIEW,
PH_INV_UNAVAIL,
PH_INVENTORY_SOURCE_UNRESOLVED,
PH_LOW_CONF,
PH_MAP_INFER,
PH_NOTICE_TEXT_EXTRACTION_FAILED,
PH_RPA_EXHAUSTED,
PH_RPA_PENDING,
@@ -51,7 +47,6 @@ from app.services.shipping_notice.constants import (
PH_SHORTAGE,
PH_UPLOAD_RPA_FAILED,
PH_UPLOAD_RPA_PENDING,
RS_ALIGN_REVIEW,
RS_CONFIRMED,
RS_PARSE_REVIEW,
RS_REJECTED,
@@ -72,20 +67,12 @@ ACTION_SPECS: dict[str, dict[str, str]] = {
"reject": {"label": "驳回", "message": "驳回", "variant": "danger"},
"reparse": {"label": "重新解析", "message": "重新解析", "variant": "secondary"},
"replace_notice_file": {"label": "重新上传", "message": "重新上传发货通知", "variant": "primary"},
"confirm_inventory_mapping": {"label": "确认", "message": "确认", "variant": "primary"},
"correct_inventory_mapping": {"label": "更正映射", "message": "更正映射", "variant": "secondary"},
"reparse_inventory": {"label": "重新上传", "message": "重新上传库存", "variant": "secondary"},
"rematch": {"label": "重新匹配", "message": "重新匹配", "variant": "secondary"},
"retry_rpa": {"label": "重新获取库存", "message": "重新获取库存", "variant": "secondary"},
"confirm_inventory_source": {"label": "确认库存源", "message": "确认库存查询来源", "variant": "primary"},
"confirm_customer": {"label": "确认客户", "message": "选择并确认标准客户", "variant": "primary"},
"retry_resolve_inventory_source": {"label": "重新判断", "message": "重新判断库存查询来源", "variant": "secondary"},
"refresh": {"label": "刷新", "message": "刷新", "variant": "secondary"},
"upload_inventory_file": {
"label": "选择库存文件",
"message": "我要上传库存 Excel",
"variant": "secondary",
},
"retry_upload": {"label": "重试上传", "message": "重试上传货代", "variant": "secondary"},
"download_excel": {"label": "下载 Excel", "message": "下载发货 Excel", "variant": "secondary"},
"generate_excel": {"label": "生成发货 Excel", "message": "生成发货 Excel", "variant": "primary"},
@@ -94,16 +81,6 @@ ACTION_SPECS: dict[str, dict[str, str]] = {
"message": "已在货代系统手工上传完成",
"variant": "primary",
},
"paste_inventory_json": {
"label": "粘贴库存",
"message": "我粘贴库存小表",
"variant": "secondary",
},
"edit_inventory_mapping": {
"label": "修改映射",
"message": "修改库存列映射",
"variant": "primary",
},
"match_inventory": {
"label": "匹配库存",
"message": "匹配库存",
@@ -115,28 +92,14 @@ ACTION_SPECS: dict[str, dict[str, str]] = {
CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
CP_PARSE_REVIEW: ("confirm", "reject", "reparse"),
CP_CUSTOMER_REVIEW: ("confirm_customer",),
CP_ALIGN_REVIEW: (
"confirm_inventory_mapping",
"correct_inventory_mapping",
"reparse_inventory",
"retry_rpa",
"reject",
),
CP_MAP_INFER: (
"edit_inventory_mapping",
"upload_inventory_file",
"paste_inventory_json",
"retry_rpa",
),
CP_UPLOAD_REQ: ("upload_inventory_file", "retry_rpa", "paste_inventory_json"),
CP_INVENTORY_PENDING: ("upload_inventory_file", "retry_rpa", "paste_inventory_json"),
CP_UPLOAD_REQ: ("upload_inventory_file", "retry_rpa"),
CP_INVENTORY_PENDING: ("upload_inventory_file", "retry_rpa"),
CP_INVENTORY_SOURCE_REVIEW: (
"confirm_inventory_source",
"retry_resolve_inventory_source",
"upload_inventory_file",
),
CP_RSV_REQ: ("replace_notice_file", "reparse", "reject"),
RS_SHORTAGE_REVIEW: ("reparse_inventory", "rematch", "reject"),
RS_SHORTAGE_REVIEW: ("retry_rpa", "rematch", "reject"),
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("replace_notice_file", "reparse", "reject"),
CP_UPLOAD_FAILED: ("retry_upload", "download_excel", "mark_manual_uploaded"),
CP_WAITING_UPLOAD: ("refresh", "retry_upload", "download_excel", "mark_manual_uploaded"),
@@ -154,7 +117,7 @@ ALL_ACTION_IDS: frozenset[str] = frozenset(ACTION_SPECS.keys())
# Dynamic subsets of upload_req (RPA attempts); default full set is CHECKPOINT_REGISTRY[CP_UPLOAD_REQ]
OPTIONS_UPLOAD_FILE_ONLY: tuple[str, ...] = ("upload_inventory_file",)
OPTIONS_RPA_OR_UPLOAD: tuple[str, ...] = ("retry_rpa", "upload_inventory_file")
OPTIONS_RPA_OR_UPLOAD: tuple[str, ...] = ("upload_inventory_file", "retry_rpa")
@dataclass(frozen=True)
@@ -211,7 +174,7 @@ def inventory_source_action_buttons(task: ShippingTask) -> list[dict[str, str]]:
"variant": "primary",
"source_code": source_code,
},
*build_action_buttons(["retry_resolve_inventory_source", "upload_inventory_file"]),
*build_action_buttons(["retry_resolve_inventory_source"]),
]
return build_action_buttons(list(CHECKPOINT_REGISTRY[CP_INVENTORY_SOURCE_REVIEW]))
@@ -347,16 +310,6 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
)
# [STEP 5] 人审分支 — 按 pending_human_reason / review_status 映射 checkpoint。
if reason == PH_ALIGN_REVIEW or task.review_status == RS_ALIGN_REVIEW:
return TaskUiState(
checkpoint=CP_ALIGN_REVIEW,
human_options=list(CHECKPOINT_REGISTRY[CP_ALIGN_REVIEW]),
)
if reason == PH_MAP_INFER:
return TaskUiState(
checkpoint=CP_MAP_INFER,
human_options=list(CHECKPOINT_REGISTRY[CP_MAP_INFER]),
)
if reason == PH_INV_UNAVAIL:
return TaskUiState(
checkpoint=CP_UPLOAD_REQ,
@@ -454,8 +407,6 @@ class TaskTransition(StrEnum):
PARSED = "parsed"
PARSE_NEEDS_REVIEW = "parse_needs_review"
INVENTORY_READY = "inventory_ready"
INVENTORY_ALIGN_REVIEW = "inventory_align_review"
MAP_INFER = "map_infer"
RPA_EXHAUSTED = "rpa_exhausted"
RPA_PENDING = "rpa_pending"
INV_UNAVAIL = "inv_unavail"
@@ -467,11 +418,6 @@ class TaskTransition(StrEnum):
CLOSED = "closed"
CONFIRM_PARSE = "confirm_parse"
CONFIRM_MATCHED = "confirm_matched"
ALIGN_REVIEW_HOLD = "align_review_hold"
MAPPING_CONFIRMED = "mapping_confirmed"
CORRECT_MAPPING = "correct_mapping"
REPARSE_INVENTORY = "reparse_inventory"
REPARSE_INVENTORY_DEMOTE = "reparse_inventory_demote"
NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed"
REMATCH_REQUESTED = "rematch_requested"
WAITING_UPLOAD = "waiting_upload"
@@ -497,17 +443,6 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
pending_human_reason=None,
clear_error_message=True,
),
TaskTransition.INVENTORY_ALIGN_REVIEW: _TransitionSpec(
process_status="inventory_ready",
review_status=RS_ALIGN_REVIEW,
pending_human_reason=PH_ALIGN_REVIEW,
clear_error_message=True,
),
TaskTransition.MAP_INFER: _TransitionSpec(
process_status="waiting_inventory",
review_status=None,
pending_human_reason=PH_MAP_INFER,
),
TaskTransition.RPA_EXHAUSTED: _TransitionSpec(
process_status="waiting_inventory",
review_status=None,
@@ -563,28 +498,6 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
review_status=RS_CONFIRMED,
pending_human_reason=None,
),
TaskTransition.ALIGN_REVIEW_HOLD: _TransitionSpec(
review_status=RS_ALIGN_REVIEW,
pending_human_reason=PH_ALIGN_REVIEW,
),
TaskTransition.MAPPING_CONFIRMED: _TransitionSpec(
review_status=None,
pending_human_reason=None,
),
TaskTransition.CORRECT_MAPPING: _TransitionSpec(
process_status="waiting_inventory",
review_status=None,
pending_human_reason=PH_MAP_INFER,
),
TaskTransition.REPARSE_INVENTORY: _TransitionSpec(
review_status=None,
pending_human_reason=None,
),
TaskTransition.REPARSE_INVENTORY_DEMOTE: _TransitionSpec(
process_status="parsed",
review_status=None,
pending_human_reason=None,
),
TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED: _TransitionSpec(
process_status="pending_review",
review_status=None,
@@ -44,6 +44,26 @@ def cfg_int(key: str, default: int = 0, *, min_value: int | None = None) -> int:
return parsed
def cfg_float(
key: str,
default: float = 0.0,
*,
min_value: float | None = None,
max_value: float | None = None,
) -> float:
"""读取 Flask config 浮点值,并在异常配置时回退到安全默认值。"""
val = current_app.config.get(key)
try:
parsed = float(default if val is None else val)
except (TypeError, ValueError):
parsed = default
if min_value is not None:
parsed = max(parsed, min_value)
if max_value is not None:
parsed = min(parsed, max_value)
return parsed
def auto_progress_enabled() -> bool:
"""是否启用 auto_progress 自动推进(SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED)。"""
return cfg_bool("SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED", False)
+28 -3
View File
@@ -65,15 +65,40 @@ confirm_customer = customer_identity_gate.confirm_customer
# 库存阶段
ensure_inventory = inventory_workflow.ensure_inventory
parse_inventory = inventory_workflow.parse_inventory
get_inventory_schema_preview = inventory_workflow.get_inventory_schema_preview
apply_inventory_mapping = inventory_workflow.apply_inventory_mapping
upload_inventory_file = inventory_workflow.upload_inventory_file
rpa_report_inventory = inventory_rpa_workflow.rpa_report_inventory
rpa_report_inventory_batch = inventory_rpa_workflow.rpa_report_inventory_batch
repair_task_inventory_attachment = inventory_rpa_workflow.repair_task_inventory_attachment
confirm_inventory_source = inventory_rpa_workflow.confirm_inventory_source
def create_temporary_inventory_session(payload: dict):
"""创建对话上传库存候选会话;仅供 Dify 临时库存固定分支调用。"""
from app.services.shipping_notice.inventory_temporary_session import create_temporary_inventory_session as _create
return _create(payload)
def get_temporary_inventory_session(payload: dict):
"""读取临时库存候选会话的脱敏结构预览;仅供 Dify 固定分支调用。"""
from app.services.shipping_notice.inventory_temporary_session import get_temporary_inventory_session as _get
return _get(payload)
def submit_temporary_inventory_mapping_suggestion(payload: dict):
"""保存 Dify 临时库存映射候选;后端校验后仍须由用户确认。"""
from app.services.shipping_notice.inventory_temporary_session import submit_temporary_inventory_mapping_suggestion as _submit
return _submit(payload)
def confirm_temporary_inventory_use(payload: dict):
"""确认当前会话临时库存使用并执行后端确定性质量校验。"""
from app.services.shipping_notice.inventory_temporary_session import confirm_temporary_inventory_use as _confirm
return _confirm(payload)
# 履约阶段
match_inventory = fulfillment_workflow.match_inventory
generate_excel = fulfillment_workflow.generate_excel
@@ -13,12 +13,10 @@ from typing import Any
from app.models import ShippingBatch, ShippingTask
from app.services.shipping_notice.constants import (
CP_ALIGN_REVIEW,
CP_COMPLETED,
CP_EXPORT_READY,
CP_INVENTORY_PENDING,
CP_INVENTORY_SOURCE_REVIEW,
CP_MAP_INFER,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_PARSE_REVIEW,
CP_READY_EXPORT,
@@ -31,13 +29,11 @@ from app.services.shipping_notice.constants import (
CP_WAITING_UPLOAD,
PH_INV_UNAVAIL,
PH_INVENTORY_SOURCE_UNRESOLVED,
PH_MAP_INFER,
PH_RPA_EXHAUSTED,
PH_RPA_PENDING,
PH_RSV_REQ,
PH_SHORTAGE,
PH_UPLOAD_RPA_PENDING,
RS_ALIGN_REVIEW,
RS_PARSE_REVIEW,
RS_SHORTAGE_REVIEW,
)
@@ -59,7 +55,7 @@ WORKFLOW_STEPS: tuple[dict[str, str], ...] = (
{"id": "shipping-step-1", "code": "notice_submit", "label": "提交通知"},
{"id": "shipping-step-2", "code": "parse_confirm", "label": "确认解析"},
{"id": "shipping-step-3", "code": "inventory_prepare", "label": "获取库存"},
{"id": "shipping-step-4", "code": "align_confirm", "label": "确认字段对齐"},
{"id": "shipping-step-4", "code": "align_confirm", "label": "校验库存"},
{"id": "shipping-step-5", "code": "match_inventory", "label": "匹配库存"},
{"id": "shipping-step-6", "code": "generate_file", "label": "生成发货文件"},
{"id": "shipping-step-7", "code": "upload_freight", "label": "上传货代"},
@@ -86,7 +82,6 @@ _BLOCKED_CHECKPOINTS = {
CP_PARSE_REVIEW,
CP_RSV_REQ,
CP_INVENTORY_SOURCE_REVIEW,
CP_ALIGN_REVIEW,
RS_SHORTAGE_REVIEW,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_UPLOAD_REQ,
@@ -119,12 +114,9 @@ def _derive_current_step_index(task: ShippingTask) -> int:
return 4
if review_status == RS_SHORTAGE_REVIEW or pending_reason == PH_SHORTAGE:
return 4
if review_status == RS_ALIGN_REVIEW or pending_reason == CP_ALIGN_REVIEW:
return 3
if process_status == "inventory_ready" or match_status:
return 4
if process_status == "waiting_inventory" or pending_reason in {
PH_MAP_INFER,
PH_RPA_PENDING,
PH_INV_UNAVAIL,
PH_RPA_EXHAUSTED,
@@ -232,7 +224,6 @@ def _collect_parse_stage_issues(task: ShippingTask, checkpoint: str | None) -> l
核心逻辑:解析复核、RSV 缺失、库存源门禁、parse warnings 可能并发;
以前仅透出 error_message(多为库存源),导致其它解析问题被吞掉。
新顺序为先解析复核再库存源;存量 pending_parse_review_after_source 仍提示延后复核。
"""
checkpoint_value = str(checkpoint or "").strip()
if checkpoint_value not in _PARSE_STAGE_CHECKPOINTS:
@@ -277,12 +268,6 @@ def _collect_parse_stage_issues(task: ShippingTask, checkpoint: str | None) -> l
if isinstance(item, dict):
_append_unique_issue(issues, _parse_validation_issue_text(item))
# 存量兼容:旧顺序「先库存源后解析」延后的低置信度提示。
if payload.get("pending_parse_review_after_source") or (
checkpoint_value == CP_INVENTORY_SOURCE_REVIEW and task.review_status == RS_PARSE_REVIEW
):
_append_unique_issue(issues, "解析置信度不足,确认库存源后仍需复核解析结果。")
return issues
@@ -295,8 +280,6 @@ def _build_task_summary(task: ShippingTask, checkpoint: str | None) -> dict[str,
CP_UPLOAD_REQ: "当前需要提供库存数据或重试库存获取。",
CP_INVENTORY_PENDING: "发货通知已就绪,等待库存数据。",
CP_INVENTORY_SOURCE_REVIEW: "库存源尚未确定,请先选择正式库存源。",
CP_MAP_INFER: "库存列映射需要确认或重新选择。",
CP_ALIGN_REVIEW: "库存字段对齐需要人工确认。",
RS_SHORTAGE_REVIEW: "库存存在缺口,当前不能继续上传货代。",
CP_READY_MATCH: "库存已就绪,可以继续执行匹配。",
CP_READY_EXPORT: "库存匹配已满足发货条件,可以生成发货文件。",
@@ -10,10 +10,8 @@ from __future__ import annotations
from app.models import ShippingTask
from app.services.shipping_notice.constants import (
CP_ALIGN_REVIEW,
CP_EXPORT_READY,
CP_INVENTORY_PENDING,
CP_MAP_INFER,
CP_PARSE_REVIEW,
CP_READY_EXPORT,
CP_READY_MATCH,
@@ -46,8 +44,6 @@ TOOL_TASK_DATA_OMIT: frozenset[str] = frozenset(
_CHECKPOINT_LABELS: dict[str, str] = {
CP_PARSE_REVIEW: "待确认发货通知解析",
CP_ALIGN_REVIEW: "待确认库存字段对齐",
CP_MAP_INFER: "待确认库存列映射",
CP_UPLOAD_REQ: "待上传或获取库存",
CP_INVENTORY_PENDING: "待上传库存",
CP_RSV_REQ: "待补充 Reservation ID",