feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程

清理废弃的shipping xfa ocr automark相关代码和job配置
新增收料报表管理的前端页面、路由和侧边栏入口
新增后端收料报表配置接口、数据库模型和RPA脚本
优化发货通知流程的重试策略,将shipping相关job默认不自动重试
移除废弃的库存源确认相关逻辑,更新流程门禁规则
重构订单模板的值适配器模块,新增坐标OCR值适配器
清理前端shipping菜单和action的废弃选项
更新相关文档和测试用例,调整.gitignore忽略规则
This commit is contained in:
hugo committed 2026-08-20 20:23:10 +08:00
1 parent 260465b72d
commit 1b6483a4ea
466 files changed
+32115 -33796

No files matched your search

@@ -1,9 +1,9 @@
"""
services/shipping_notice/state_machine.py
用途:发货通知检查点(checkpoint)与工作台动作按钮的单一注册表,负责任务 DB 字段与 UI 状态映射。
用途:发货通知检查点(checkpoint)与内部流程状态映射,负责任务 DB 字段与流程事实映射。
依赖:models.ShippingNotice、constants(CP_*/PH_*/RS_*)、rpa_attempts、order_field_purposes。
逻辑:tools/workspace 经 apply_task_transition 写库;ui_state/query_service 读取 checkpoint_kind 与按钮;
逻辑:tools/workspace 经 apply_task_transition 写库;ui_state/query_service 读取 checkpoint_kind;
resolve_task_ui_state_from_fields 供待办轻量索引批量分类;履约写操作入口为任务处理工作台,
Chat 仅通知与跳转(Chat Turn 写路径已标记废弃)。
@@ -11,8 +11,8 @@ services/shipping_notice/state_machine.py
- checkpoint id 即 API `checkpoint` / Dify `flow_ckpt`
- checkpoint_kind 区分 auto_continue / must_human / wait_manual_upload / complete
(导出 CP_EXPORT_* → wait_manual_upload:Excel 后待人工上传登记)
- 动作按钮 id 定义于 ACTION_SPECS;DB 写入统一走 TaskTransition
- GET /tools/checkpoint-catalog 供文档/CI,不接入 Dify 画布
- 用户动作的定义、授权与审计统一由 process_gate_contract / Gate Attempt 负责;
checkpoint 不得派生、下发或执行用户按钮。
"""
from __future__ import annotations
@@ -59,10 +59,6 @@ from app.services.shipping_notice.constants import (
RS_RSV_REQ,
RS_SHORTAGE_REVIEW,
)
from app.services.shipping_notice.rpa_attempts import (
inventory_rpa_attempts,
max_rpa_inventory_attempts,
)
def _task_has_dynamic_order_lines(task: ShippingNotice) -> bool:
@@ -93,80 +89,14 @@ class CheckpointKind(StrEnum):
COMPLETE = "complete"
# ---------------------------------------------------------------------------
# Action buttons (id → label / message / variant) — 任务处理工作台动作目录
# ---------------------------------------------------------------------------
ACTION_SPECS: dict[str, dict[str, str]] = {
"confirm": {"label": "确认", "message": "确认", "variant": "primary"},
"reject": {"label": "驳回", "message": "驳回", "variant": "danger"},
"reparse": {"label": "重新解析", "message": "重新解析", "variant": "secondary"},
"replace_notice_file": {"label": "重新上传", "message": "重新上传发货通知", "variant": "primary"},
"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"},
"retry_upload": {"label": "重试上传", "message": "重试上传货代", "variant": "secondary"},
"upload_inventory_file": {
"label": "上传库存文件",
"message": "上传库存 Excel",
"variant": "primary",
},
"download_excel": {"label": "下载 Excel", "message": "下载发货 Excel", "variant": "secondary"},
"generate_excel": {"label": "生成发货 Excel", "message": "生成发货 Excel", "variant": "primary"},
"mark_manual_uploaded": {
"label": "已手工上传",
"message": "已在货代系统手工上传完成",
"variant": "primary",
},
"match_inventory": {
"label": "匹配库存",
"message": "匹配库存",
"variant": "primary",
},
"freeze_order": {
"label": "冻结订单",
"message": "冻结已复核订单",
"variant": "primary",
},
}
# checkpoint id → default human option ids
CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
CP_PARSE_REVIEW: ("confirm", "reject", "reparse"),
CP_CUSTOMER_REVIEW: ("confirm_customer",),
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",
),
CP_ORDER_FREEZE: ("freeze_order",),
CP_RSV_REQ: ("replace_notice_file", "reparse", "reject"),
RS_SHORTAGE_REVIEW: ("retry_rpa", "rematch", "reject"),
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("replace_notice_file", "reparse", "reject"),
# 上传失败仅允许下载;待上传/结果未知允许下载 + 人工凭据登记(禁 RPA retry_upload)。
CP_UPLOAD_FAILED: ("download_excel",),
CP_WAITING_UPLOAD: ("refresh", "download_excel", "mark_manual_uploaded"),
CP_UPLOAD_RESULT_UNKNOWN: ("refresh", "download_excel", "mark_manual_uploaded"),
CP_READY_MATCH: ("match_inventory",),
CP_READY_EXPORT: ("generate_excel",),
CP_EXPORT_READY: ("download_excel", "mark_manual_uploaded"),
CP_EXPORT_GENERATED: ("download_excel", "mark_manual_uploaded"),
CP_REJECTED: (),
CP_UPLOADED: (),
CP_COMPLETED: (),
}
# checkpoint id → STP kind(静态;无 checkpoint 时视为 auto_continue)
CHECKPOINT_KIND_REGISTRY: dict[str, CheckpointKind] = {
CP_PARSE_REVIEW: CheckpointKind.MUST_HUMAN,
CP_CUSTOMER_REVIEW: CheckpointKind.MUST_HUMAN,
CP_UPLOAD_REQ: CheckpointKind.MUST_HUMAN,
CP_INVENTORY_PENDING: CheckpointKind.AUTO_CONTINUE,
CP_INVENTORY_SOURCE_REVIEW: CheckpointKind.MUST_HUMAN,
# 库存源由规则自动裁决;未稳定只表示内部重算/治理等待,不能形成用户确认停点。
CP_INVENTORY_SOURCE_REVIEW: CheckpointKind.AUTO_CONTINUE,
CP_ORDER_FREEZE: CheckpointKind.AUTO_CONTINUE,
CP_RSV_REQ: CheckpointKind.MUST_HUMAN,
RS_SHORTAGE_REVIEW: CheckpointKind.MUST_HUMAN,
@@ -183,39 +113,16 @@ CHECKPOINT_KIND_REGISTRY: dict[str, CheckpointKind] = {
CP_COMPLETED: CheckpointKind.COMPLETE,
}
ALL_CHECKPOINT_IDS: frozenset[str] = frozenset(CHECKPOINT_REGISTRY.keys())
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, ...] = ("upload_inventory_file", "retry_rpa")
ALL_CHECKPOINT_IDS: frozenset[str] = frozenset(CHECKPOINT_KIND_REGISTRY.keys())
@dataclass(frozen=True)
class TaskUiState:
"""统一任务 UI 状态:checkpoint + STP kind + 工作台可用动作。"""
"""统一任务流程状态:checkpoint + STP kind,不包含用户动作。"""
checkpoint: str | None
human_options: list[str] | None
checkpoint_kind: CheckpointKind = CheckpointKind.AUTO_CONTINUE
@property
def action_buttons(self) -> list[dict[str, str]]:
return build_action_buttons(self.human_options)
def build_action_buttons(option_ids: list[str] | None) -> list[dict[str, str]]:
"""将 human_options 动作 id 列表转为前端/Dify 可用的 action_buttons 结构。"""
if not option_ids:
return []
buttons: list[dict[str, str]] = []
for option_id in option_ids:
spec = ACTION_SPECS.get(option_id)
if not spec:
continue
buttons.append({"id": option_id, **spec})
return buttons
def checkpoint_kind_for(checkpoint: str | None) -> CheckpointKind:
"""
@@ -228,100 +135,14 @@ def checkpoint_kind_for(checkpoint: str | None) -> CheckpointKind:
return CHECKPOINT_KIND_REGISTRY.get(str(checkpoint).strip(), CheckpointKind.MUST_HUMAN)
def _task_ui_state(checkpoint: str | None, human_options: list[str] | None) -> TaskUiState:
"""构造带 checkpoint_kind 的 TaskUiState。"""
def _task_ui_state(checkpoint: str | None) -> TaskUiState:
"""构造只含内部流程事实的 TaskUiState。"""
return TaskUiState(
checkpoint=checkpoint,
human_options=human_options,
checkpoint_kind=checkpoint_kind_for(checkpoint),
)
def inventory_source_action_buttons(task: ShippingNotice) -> list[dict[str, str]]:
"""
将库存源候选项转成工作台可直接点击的确认按钮。
核心逻辑:库存源待确认时,按钮必须携带 source_code,前端点击后可直接调用确认接口,
避免先把候选源文本发给 Agent 再等待二次确认。
"""
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
resolution = payload.get("inventory_source_resolution")
candidates = resolution.get("candidates") if isinstance(resolution, dict) else None
normalized_candidates: list[dict[str, Any]] = []
if isinstance(candidates, list):
for item in candidates:
if not isinstance(item, dict):
continue
source_code = str(item.get("source_code") or "").strip().upper()
if not source_code:
continue
normalized_candidates.append(item)
if len(normalized_candidates) == 1:
item = normalized_candidates[0]
source_code = str(item.get("source_code") or "").strip().upper()
display_name = str(item.get("display_name") or source_code).strip()
return [
{
"id": "confirm_inventory_source",
"label": f"确认:{display_name}",
"message": f"确认库存查询来源:{display_name}",
"variant": "primary",
"source_code": source_code,
},
*build_action_buttons(["retry_resolve_inventory_source"]),
]
return build_action_buttons(list(CHECKPOINT_REGISTRY[CP_INVENTORY_SOURCE_REVIEW]))
def human_options_for_checkpoint(checkpoint: str | None) -> list[str] | None:
"""按静态 checkpoint id 查 CHECKPOINT_REGISTRY 中的默认 human_options。"""
if not checkpoint:
return None
key = str(checkpoint).strip()
options = CHECKPOINT_REGISTRY.get(key)
if options is None:
return None
return list(options)
def action_buttons_for_checkpoint(checkpoint: str | None) -> list[dict[str, str]]:
"""checkpoint → action_buttons 的便捷封装(状态机 UI payload 用)。"""
return build_action_buttons(human_options_for_checkpoint(checkpoint))
def ui_state_for_checkpoint(checkpoint: str | None) -> TaskUiState:
"""无 DB 任务时,仅按 checkpoint id 构造 TaskUiState(Tool 早停响应用)。"""
options = human_options_for_checkpoint(checkpoint)
cp = str(checkpoint).strip() if checkpoint else None
if cp and cp not in CHECKPOINT_REGISTRY:
cp = None
return _task_ui_state(cp, options)
def upload_req_options_for_task(task: ShippingNotice) -> list[str]:
"""upload_req checkpoint 的动作子集,随 RPA 重试次数动态收缩。"""
if task.pending_human_reason == PH_RPA_EXHAUSTED:
return list(OPTIONS_RPA_OR_UPLOAD)
if inventory_rpa_attempts(task) >= max_rpa_inventory_attempts():
return list(OPTIONS_RPA_OR_UPLOAD)
if task.pending_human_reason in {PH_INV_UNAVAIL, PH_RPA_PENDING}:
return list(OPTIONS_RPA_OR_UPLOAD)
return list(CHECKPOINT_REGISTRY[CP_UPLOAD_REQ])
def human_options_for_task_or_checkpoint(
*,
task: ShippingNotice | None = None,
checkpoint: str | None = None,
) -> list[str] | None:
"""优先从 task DB 状态解析 human_options;无 task 时回退静态 checkpoint 注册表。"""
if task is not None:
opts = resolve_task_ui_state(task).human_options
if opts is not None:
return opts
return human_options_for_checkpoint(checkpoint)
def resolve_task_ui_state_from_fields(
*,
review_status: str | None,
@@ -341,55 +162,47 @@ def resolve_task_ui_state_from_fields(
核心逻辑:与 resolve_task_ui_state 同序分支;has_dynamic_order_lines 由调用方批量预计算,
供待办索引在不全量水合 Task 时保持与单任务路径一致的分类口径。
upload_req_options / upload_req_task 仅在命中 upload_req 分支时解析按钮列表。
upload_req_options / upload_req_task 是已废弃的兼容入参;checkpoint 不再解析用户动作。
"""
def _upload_opts() -> list[str]:
if upload_req_options is not None:
return list(upload_req_options)
if upload_req_task is not None:
return upload_req_options_for_task(upload_req_task)
return list(CHECKPOINT_REGISTRY[CP_UPLOAD_REQ])
del upload_req_options
upload_status = str(getattr(upload_req_task, "upload_status", None) if upload_req_task is not None else "").strip().lower()
has_export = bool(str(export_file_path or "").strip())
# [STEP 1] 终态:上传结果事实或生命周期处置 — 无履约写按钮。
if upload_status in {"uploaded", "succeeded", "success"}:
return _task_ui_state(CP_UPLOADED, [])
return _task_ui_state(CP_UPLOADED)
if upload_req_task is not None and str(getattr(upload_req_task, "lifecycle_status", "") or "").strip().lower() in {"archived", "deleted"}:
return _task_ui_state(CP_COMPLETED, [])
return _task_ui_state(CP_COMPLETED)
if review_status == "rejected":
return _task_ui_state(CP_REJECTED, [])
return _task_ui_state(CP_REJECTED)
# [STEP 2] 先完成订单解析复核,再暴露客户确认节点。
reason = pending_human_reason
if reason == PH_RSV_REQ or review_status == RS_RSV_REQ:
return _task_ui_state(CP_RSV_REQ, list(CHECKPOINT_REGISTRY[CP_RSV_REQ]))
return _task_ui_state(CP_RSV_REQ)
if reason == PH_LOW_CONF or review_status == RS_PARSE_REVIEW:
return _task_ui_state(CP_PARSE_REVIEW, list(CHECKPOINT_REGISTRY[CP_PARSE_REVIEW]))
return _task_ui_state(CP_PARSE_REVIEW)
if reason == PH_NOTICE_TEXT_EXTRACTION_FAILED:
return _task_ui_state(
CP_NOTICE_TEXT_EXTRACTION_FAILED,
list(CHECKPOINT_REGISTRY[CP_NOTICE_TEXT_EXTRACTION_FAILED]),
)
return _task_ui_state(CP_NOTICE_TEXT_EXTRACTION_FAILED)
if shipping_case_id is not None and customer_resolution_status != "confirmed":
return _task_ui_state(CP_CUSTOMER_REVIEW, list(CHECKPOINT_REGISTRY[CP_CUSTOMER_REVIEW]))
return _task_ui_state(CP_CUSTOMER_REVIEW)
# [STEP 3] 库存、Excel 与上传只能消费冻结快照;冻结由自动推进或任务工作台执行。
if not order_snapshot_id and has_dynamic_order_lines:
return _task_ui_state(CP_ORDER_FREEZE, list(CHECKPOINT_REGISTRY[CP_ORDER_FREEZE]))
return _task_ui_state(CP_ORDER_FREEZE)
# Excel 已生成即进入通知完成前的人工上传登记节点,即使历史任务未落 match_status,
# 也不能退回“处理中”或丢失下载/登记动作。
if has_export:
return _task_ui_state(CP_EXPORT_READY, list(CHECKPOINT_REGISTRY[CP_EXPORT_READY]))
return _task_ui_state(CP_EXPORT_READY)
# [STEP 4] 客户确认并冻结订单后,才进入库存和履约节点。
if reason == PH_RPA_EXHAUSTED:
return _task_ui_state(CP_UPLOAD_REQ, _upload_opts())
return _task_ui_state(CP_UPLOAD_REQ)
if (
inventory_lines_json
@@ -397,7 +210,7 @@ def resolve_task_ui_state_from_fields(
and not pending_human_reason
and not match_status
):
return _task_ui_state(CP_READY_MATCH, list(CHECKPOINT_REGISTRY[CP_READY_MATCH]))
return _task_ui_state(CP_READY_MATCH)
if (
not inventory_lines_json
@@ -405,45 +218,38 @@ def resolve_task_ui_state_from_fields(
and not pending_human_reason
and has_dynamic_order_lines
):
return _task_ui_state(CP_INVENTORY_PENDING, list(CHECKPOINT_REGISTRY[CP_INVENTORY_PENDING]))
return _task_ui_state(CP_INVENTORY_PENDING)
# [STEP 5] 匹配/导出阶段 — matched 后区分待生成与已生成 Excel(STP 停点)。
if match_status in {"fulfillable", "partial", "unfulfillable", "matched"}:
if has_export:
return _task_ui_state(CP_EXPORT_READY, list(CHECKPOINT_REGISTRY[CP_EXPORT_READY]))
return _task_ui_state(CP_READY_EXPORT, list(CHECKPOINT_REGISTRY[CP_READY_EXPORT]))
return _task_ui_state(CP_EXPORT_READY)
return _task_ui_state(CP_READY_EXPORT)
# [STEP 6] 人审分支 — 按 pending_human_reason / review_status 映射 checkpoint。
if reason == PH_INV_UNAVAIL:
return _task_ui_state(CP_UPLOAD_REQ, _upload_opts())
return _task_ui_state(CP_UPLOAD_REQ)
if reason == PH_INVENTORY_SOURCE_UNRESOLVED:
return _task_ui_state(
CP_INVENTORY_SOURCE_REVIEW,
list(CHECKPOINT_REGISTRY[CP_INVENTORY_SOURCE_REVIEW]),
)
return _task_ui_state(CP_INVENTORY_SOURCE_REVIEW)
if reason == PH_SHORTAGE or review_status == RS_SHORTAGE_REVIEW:
return _task_ui_state(RS_SHORTAGE_REVIEW, list(CHECKPOINT_REGISTRY[RS_SHORTAGE_REVIEW]))
return _task_ui_state(RS_SHORTAGE_REVIEW)
if reason == PH_UPLOAD_RPA_FAILED or upload_status == "failed":
return _task_ui_state(CP_UPLOAD_FAILED, list(CHECKPOINT_REGISTRY[CP_UPLOAD_FAILED]))
return _task_ui_state(CP_UPLOAD_FAILED)
if reason == PH_UPLOAD_RESULT_UNKNOWN:
return _task_ui_state(
CP_UPLOAD_RESULT_UNKNOWN,
list(CHECKPOINT_REGISTRY[CP_UPLOAD_RESULT_UNKNOWN]),
)
return _task_ui_state(CP_UPLOAD_RESULT_UNKNOWN)
if reason == PH_RPA_PENDING:
return _task_ui_state(CP_UPLOAD_REQ, _upload_opts())
return _task_ui_state(CP_UPLOAD_REQ)
if reason == PH_UPLOAD_RPA_PENDING or upload_status in {"pending", "uploading"}:
return _task_ui_state(CP_WAITING_UPLOAD, list(CHECKPOINT_REGISTRY[CP_WAITING_UPLOAD]))
return _task_ui_state(None, None)
return _task_ui_state(CP_WAITING_UPLOAD)
return _task_ui_state(None)
def resolve_task_ui_state(task: ShippingNotice) -> TaskUiState:
"""
将 ShippingNotice DB 字段映射为 checkpoint + checkpoint_kind + human_options。
将 ShippingNotice DB 字段映射为 checkpoint + checkpoint_kind。
核心逻辑:委托 resolve_task_ui_state_from_fields;订单行动态存在性按需查库;
upload_req 按钮仅在命中对应分支时惰性解析(兼容测试用轻量 stub)。
履约写操作由任务处理工作台消费 ui_state.actions;Chat 不再作为写入口。
履约写操作由 Gate 投影生成 ui_state.actions;Chat 不再作为写入口。
"""
return resolve_task_ui_state_from_fields(
review_status=task.review_status,
@@ -464,49 +270,9 @@ def checkpoint_for_task(task: ShippingNotice) -> str | None:
return resolve_task_ui_state(task).checkpoint
def human_options_for_task(task: ShippingNotice) -> list[str] | None:
"""从 ShippingNotice DB 字段解析当前可用 human_options(含 RPA 动态子集)。"""
return resolve_task_ui_state(task).human_options
def build_checkpoint_catalog() -> dict[str, Any]:
"""导出 checkpoint 注册表供文档/CI 校验(不接入 Dify 画布)。"""
checkpoints = []
for checkpoint_id, option_ids in CHECKPOINT_REGISTRY.items():
buttons = build_action_buttons(list(option_ids))
primary = next((button for button in buttons if button.get('variant') == 'primary'), None)
secondary = [button for button in buttons if button is not primary]
checkpoints.append(
{
"id": checkpoint_id,
"checkpoint_kind": str(checkpoint_kind_for(checkpoint_id)),
"human_options": list(option_ids),
"actions": {"primary": primary, "secondary": secondary},
}
)
return {
"checkpoints": checkpoints,
"action_specs": ACTION_SPECS,
"checkpoint_kinds": {k: str(v) for k, v in CHECKPOINT_KIND_REGISTRY.items()},
"dify_fallback": {
cp: build_action_buttons(list(opts)) for cp, opts in CHECKPOINT_REGISTRY.items()
},
}
def validate_registry() -> list[str]:
"""校验 CHECKPOINT_REGISTRY 动作完整性与 KIND 覆盖;测试用。"""
errors: list[str] = []
for checkpoint_id, option_ids in CHECKPOINT_REGISTRY.items():
for option_id in option_ids:
if option_id not in ACTION_SPECS:
errors.append(f"checkpoint {checkpoint_id}: unknown action id {option_id!r}")
if checkpoint_id not in CHECKPOINT_KIND_REGISTRY:
errors.append(f"checkpoint {checkpoint_id}: missing checkpoint_kind")
for checkpoint_id in CHECKPOINT_KIND_REGISTRY:
if checkpoint_id not in CHECKPOINT_REGISTRY:
errors.append(f"checkpoint_kind {checkpoint_id}: not in CHECKPOINT_REGISTRY")
return errors
"""校验每个内部 checkpoint 都有确定的流程分类;测试用。"""
return [] if ALL_CHECKPOINT_IDS == frozenset(CHECKPOINT_KIND_REGISTRY) else ["checkpoint registry mismatch"]
# ---------------------------------------------------------------------------