Compare commits

..
Author SHA1 Message Date
sophie 8c48329d4e Merge branch 'test' into prod 2026-10-27 19:21:05 +08:00
hugo a10ecc8073 Merge branch 'hugo-auto-transfer' into dev 2026-10-27 16:44:21 +08:00
hugo 79050d02ba feat(in-transit-transfer): 实现匹配静默顶替并完善单号与明细表体验 2026-10-27 16:35:56 +08:00
hugo f5611d6783 fix(shipping-notice): 打通短缺放行链路的证据读点、决策码迁移与整单放行导出
生产实证(OT-20261027-4BD4CEFF):料号兜底自动放行不触发的根因是 s18 改名
漏迁移放行证据读点,getattr(source,'parsing_profile') 恒 None,致自动/人工
放行全部静默失败。三段修复:

1. 放行证据解析改读 source.onhand_report_config.parsing_profile
   (与 require_source_profile 同口径)。
2. 补批次 S 漏网迁移 s20a1b2c3d4e:复核行决策码 inventory→onhand 值替换,
   重建 ck_shipping_review_line_decisions_code(dev 往返验证后已应用 prod)。
3. 导出链回链 OT:_notice_source_code/_notice_inventory_file_id 纳入已审计
   放行行事实(整单放行不再报「库存源不存在」/丢证据快照);
   prepare_export_match_inputs 放行/结案决定 join 按 confirmed_task_id(OT) 回链。

回归:test_export_released_shortage_only_notice_resolves_source_and_rows
(先红后绿)等 117 项全绿。
2026-10-27 16:07:41 +08:00
sophie 70c7f03a5a fix(conflicts): 管理控制台界面替换为element plus 2026-10-27 15:10:28 +08:00
hugo 440afe097f fix(in-transit-transfer): 证据文件改由当前站点下载以避免浏览器拦截 2026-10-26 20:28:03 +08:00
hugo dfd48e08e7 fix(file-assets): 预签名下载改用浏览器可访问的 MinIO 地址 2026-10-26 19:34:29 +08:00
hugo 00c52fdaae Merge branch 'hugo-auto-transfer' into dev 2026-10-26 17:58:09 +08:00
hugo 0331029ead feat(in-transit-transfer): 增强调拨类型管理与调度逻辑
- 新增批量获取最新可用入站文件的功能,支持按来源主键集合查询。
- 实现失效入站来源编码的批量查询,优化调拨状态投影。
- 更新调拨任务调度逻辑,支持动态选择调拨类型,留空时默认为全部启用类型。
- 调整相关文档,确保调拨类型配置的清晰性与一致性。
2026-10-26 17:36:14 +08:00
sophie b032bb6729 Merge branch 'test' into prod 2026-10-25 14:03:58 +08:00
sophie 5d0a79f5fb build: 修改迁移文件多head问题 2026-10-23 15:09:26 +08:00
hugoandCursor 3bb9938c05 feat(freight-rpa): 系统连接只保留上传开关并增加 Crane 一次回查
上传页、按钮和成功判断改由连接器固定。Crane 分配中只排一次 10 分钟状态回查,手动刷新不改到期时间。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 12:20:29 +08:00
hugo fa5d316b25 chore(freight-rpa): 合并来源站点复制新增分支
# Conflicts:
#	frontend/src/features/admin/modules/integration-connector/IntegrationConnectorPage.spec.ts
2026-10-23 10:17:24 +08:00
hugoandCursor 95e7db0831 feat(freight-rpa): 支持从来源站点复制为未保存草稿
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 10:12:53 +08:00
sophie 724cd74043 !26 Merge branch 'dev' into common-problems-fuzzy-query
Merge pull request !26 from 王瑞雪/common-problems-fuzzy-query
2026-10-23 01:58:46 +00:00
HTEWJ\26070045 d3204f1db8 Merge branch 'dev' into common-problems-fuzzy-query 2026-10-23 09:41:26 +08:00
HTEWJ\26070045 bce589eb96 feat(common problems): 一期B文档导入答案 二期ai自动维护 2026-10-23 09:39:07 +08:00
hugo 31434f8424 Merge branch 'hugo-auto-transfer' into dev
# Conflicts:
#	frontend/src/features/admin/modules/integration-connector/IntegrationConnectorPage.spec.ts
#	frontend/src/features/admin/modules/integration-connector/IntegrationConnectorPage.vue
2026-10-22 23:03:31 +08:00
hugo e15b7b1ac2 Merge branch 'hugo-auto-transfer' into dev 2026-10-22 22:35:15 +08:00
hugo 663f401873 feat(in-transit-transfer): 更新证据下载与待匹配清单逻辑
- 修改证据下载接口,分别签发预览地址与带保存名的下载地址,避免浏览器使用对象键哈希作为保存名。
- 待匹配清单接口调整,按外部单号合计数量,不再返回外部项次,提升数据展示的清晰度。
- 移除待匹配桶的「清空并重新解析」功能,简化操作流程,确保用户体验一致性。
- 新增跨页全选支持的 API,允许用户在待处理池中选择全部待处理明细 ID,优化批量操作体验。
2026-10-22 22:08:20 +08:00
sophie 627da80e65 fix(admin): 管理控制台全面替换为element plus 2026-10-22 19:27:03 +08:00
HTEWJ\26070045 5a269f940d feat(common problems fuzzy query): 增加常用问题模糊查询兜底 2026-10-22 17:25:01 +08:00
sophie b69c725992 !25 Merge branch 'dev' into chat-format
Merge pull request !25 from 王瑞雪/chat-format
2026-10-22 02:59:02 +00:00
HTEWJ\26070045 331a983476 Merge branch 'dev' into chat-format 2026-10-22 10:48:09 +08:00
hugoandCursor 4c2a7e2a23 feat(in-transit-transfer): 落地证据流重解析并纳入货代与排程配套改动
外部单号进入异动档自然键,圈档按 T-2 成熟封顶,当前归档可单独重解析。同批带上 Crane 禁整页刷新、ODM 白名单降级、排程抽屉与执行记录日期窗,以及 YAML 库存源下线。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-22 00:48:37 +08:00
sophie 11cfedcc62 Merge branch 'dev' into test 2026-10-21 20:20:08 +08:00
sophie 55e56e4dc9 fix: 在AGENTS.md约束增加element plus 2026-10-21 20:12:25 +08:00
sophie a5d7085c08 Merge branch 'dev' into test 2026-10-21 13:46:15 +08:00
sophie cdc8610ec1 fix(admin): 管理控制台界面使用element plus 2026-10-20 17:01:24 +08:00
hugo 911afa0f73 feat(freight-rpa): 增加出站报表配置与回调支持,重构相关服务
- 将 RPA 管理 API 扩展至出站报表配置,新增出站相关的回调接口。
- 重构 freight_rpa_report_config_service,支持入站与出站报表配置的管理。
- 更新 ORM 模型,增加出站报表相关的持久化模型。
- 统一命名规范,确保在手、入站与出站的概念一致性。
2026-10-19 18:45:16 +08:00
hugoandCursor 39fe3c05f2 feat(freight-rpa): 库存/收料改名在手/入站,报表归属RPA,类名统一FreightRpa
把 shipping 侧 inventory/receipt 词根迁到 onhand/inbound,29 张表与
枚举/权限/前端/i18n 同步改名;在手与入站报表配置及文件改由 freight_rpa
持有,发货与调拨仅按 source_code 消费;ORM 类加 FreightRpa 前缀,
上传动作改为 freight_rpa_upload。含类名与上传动作改名规格文档。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 10:46:06 +08:00
hugoandCursor ffc0d4a430 feat(freight-rpa): 批次R解耦编排层并切换 onhand/inbound 契约
将 RPA 编排收编至 freight_rpa,回调迁 /api/freight-rpa/*。
共享目录与 Worker 契约一次切换至 onhand/inbound/upload,
并补 outbound 骨架与 tt16 排程 job key 迁移。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 23:18:48 +08:00
hugo bf3154033b refactor(admin): 管理端组件库迁移 Element Plus
- App/ChatView 接入 ElConfigProvider 多语言(zh-CN/zh-TW/en),AdminLayout 间距壳层统一持有
- OrderProfile 全家 22 文件迁移:页头/按钮/徽标/自绘弹窗/表单控件统一 element-trial 范式
- schema/审计中心/字段资产/身份规则/库存源/连接器/调拨类型页面同步迁移,新增 __tests__ 回归
- 迁移遵循「业务脚本零改动」:事件内联适配保持原 handler 契约,焦点陷阱与关闭语义不变
- i18n admin/common 四语言补充组件文案,架构文档记录迁移范式
2026-10-16 19:44:16 +08:00
hugo 8102a1fe44 feat(in-transit-transfer): inbound/outbound 幂等重命名与解析用途分层
- receipt→inbound 三件套改名(回调桥/文件门禁/触发服务),回调链幂等去重,迁移 tt14 同步台账键与测试基建
- 库存解析用途分层 onhand/inbound/outbound(迁移 tt15):解析档案、文件存储与下载名按用途隔离,管理端表单同步
- 「成熟」概念退役(迁移 tt16):数据无成熟属性,日期边界由调用方入参严格判定
- backlog 新增重解析服务,在途重识别投影 processing,EML 父项不再停留处理中
- 收料 RPA 回调/归档/排程链路同步改名挂点,运维脚本复位假完成状态
- 文档随批:ADR 0003 模块边界决策、10-15/10-16 计划与设计、调拨文档族与 demand/tec/funclist
- 同步 chat/errors 文案四语言、调拨前端卡片与 e2e、测试全家
2026-10-16 19:43:49 +08:00
HTEWJ\26070045 9236f2949c style(chat-format): 修改回复样式为序号缩进等 2026-10-16 15:15:48 +08:00
sophie 47ff0107bd Merge branch 'test' into prod 2026-10-15 15:16:38 +08:00
sophie 050987692a Merge branch 'dev' into test 2026-10-15 15:13:34 +08:00
sophie 6c47d0639c build: 修改frontend lint报错 2026-10-15 15:13:10 +08:00
sophie 19d6b234ea Merge branch 'dev' into test 2026-10-15 14:49:39 +08:00
hugoandCursor 43dceaf027 chore(migrations): 合并设备验收与调拨两条迁移头
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 13:19:54 +08:00
hugo fc42bb14c9 Merge branch 'dev' into hugo-auto-transfer 2026-10-15 13:16:47 +08:00
hugo e4100815a0 feat(chat): 调拨工作台接入类型配置与待匹配面板
来源选择卡改为加载启用类型(单一飞行请求,空态引导先到管理页配置),
调拨类型为匹配必选项(422 提示);批次号派生接转换规则(deriveBatchNo 三态:
原始值/前缀替换/无规则),与后端转换引擎同口径。

首页面板新增第四张待匹配卡(indigo):待匹配桶=启用类型范围并集内无有效明细的
异动档记录,只读抽屉查看、去匹配直达;四语言文案补齐。
2026-10-15 13:08:04 +08:00
hugo 3a19f9c27d feat(admin): 新增在途调拨类型管理页
调拨类型四块配置的维护入口:基本信息(编码/多语言名称/排序/启停)、范围规则
(受控字段下拉+匹配方式+多值标签,规则间且/值间或)、仓库定义(拨出/拨入角色
映射档或固定仓)、字段转换(批号前缀替换)。列表含规则数与启用状态检索,
类型被调拨链路引用时编码与用途不可改(两段式校验),重复编码返回 422。

管理控制台注册导航与路由;新增 8 个 TRANSFER.* 错误码四语言文案。
2026-10-15 13:04:46 +08:00
hugo 52c71ee46a feat(in-transit-transfer): 调拨类型配置化与库存异动档原子切换
调拨类型从四处硬编码升级为管理页可配置:范围规则(受控字段白名单,规则间且/值间或)、
仓库定义(映射档/固定仓双模式角色解析)、字段转换(批号前缀替换,匹配时快照固化到 scope_json)。

新建 transfer_movement_ledger 库存异动档(参照 ERP inaj_t):自然键幂等增量落档
(插入/换证更新/跳过/缺席不删/执行封存永不触碰),圈档互斥保证一条档记录一生只绑一次明细;
收料证据落地改写档、停写 items。transfer_invoice_items 出生翻转为匹配时从档圈定创建
(一次匹配永久写入 matching_id+ledger_record_id),回查对账/取消释放/执行门禁/待匹配桶全链路适配。

迁移 tt10→tt13 单 head:类型配置表、异动档、items 档外键、transfer_runs.transfer_type 放宽 String(64)。

随行披露:设计文档与实施计划、ADR 0001/0002、in-transit-transfer 术语表、
demand/funclist/technical 文档更新同批入库。
2026-10-15 13:02:17 +08:00
hugo 28d6085d07 fix(shipping-inventory): 补齐异动字段四语言标签并加契约护栏测试
后端 MOVEMENT_FIELDS 2026-10-14 扩 7 个可选维度字段后,管理页标准异动字段
下拉把原始 i18n key 直接渲染给了用户。四语言 movementFields 补齐
line_seq/specification/order_type/odm_id/odm_name/carton_id/pallet_id,
新增 movementFieldLabels.spec 锁定四语言键集与后端 18 字段契约一致。

随行披露:admin.json 同步携带调拨类型管理页 transferTypes 文案键(供后续批次使用)。
2026-10-15 12:56:13 +08:00
hugo 68c944607c fix(shipping-notice): 工作台五阶段定位只进不退并保留最近投影
提交订单后的刷新窗口内,extractionLifecycleProgress 会被 Run 级
lifecycle_progress(两段模型,恒为 intake_parse)短暂覆盖,五阶段页签
闪回「接收解析」后再跳「通知准备」。

- lifecycleProgressForView 保持最近一次非空投影兜底,不再回落 Run 级旧值;
- 新增 lifecycleStageFloor 只进不退下限:自动定位永不回跳已越过的更早
  阶段;显式 route 请求(用户手动点击阶段入口)不受限,可回看前置阶段。
2026-10-15 09:47:36 +08:00
hugo 22bee49346 fix(shipping-notice): 工作台五阶段定位只进不退并保留最近投影
提交订单后的刷新窗口内,extractionLifecycleProgress 会被 Run 级
lifecycle_progress(两段模型,恒为 intake_parse)短暂覆盖,五阶段页签
闪回「接收解析」后再跳「通知准备」。

- lifecycleProgressForView 保持最近一次非空投影兜底,不再回落 Run 级旧值;
- 新增 lifecycleStageFloor 只进不退下限:自动定位永不回跳已越过的更早
  阶段;显式 route 请求(用户手动点击阶段入口)不受限,可回看前置阶段。
2026-10-15 09:45:14 +08:00
hugo 4225ed4d0b fix(shipping-notice): 工作台五阶段定位只进不退并保留最近投影
提交订单后的刷新窗口内,extractionLifecycleProgress 会被 Run 级
lifecycle_progress(两段模型,恒为 intake_parse)短暂覆盖,五阶段页签
闪回「接收解析」后再跳「通知准备」。

- lifecycleProgressForView 保持最近一次非空投影兜底,不再回落 Run 级旧值;
- 新增 lifecycleStageFloor 只进不退下限:自动定位永不回跳已越过的更早
  阶段;显式 route 请求(用户手动点击阶段入口)不受限,可回看前置阶段。
2026-10-15 09:43:40 +08:00
hugo d75f2e7d86 fix(shipping-notice): 预约单号兜底分作用域并镜像补写明细缺失行
订单级早退导致表头已有预约单号时明细行补写永不执行(回归
SNER-20261014-0AB6D98A doc 915 明细预约号空)。

- 兜底早退改分作用域:scope=header 表头有值才跳过;scope=line
  行级全有值才跳过,存在缺失行仍执行补写;
- 镜像语义:排除集移除表头已采纳的预约号值——它正是要写入缺失
  行级的值;其余订单观测值(尤其 PO)保持排除防误判;
- PO 行定位收敛不变:本单 PO 所在行的预约号唯一命中后写入。

真数据验证:9/9 PO 各自唯一写入本行预约号
(4510042199→1000161448 … 4510042208→1000131033),与表头一致。
2026-10-15 08:43:32 +08:00
hugo c27379d933 fix(shipping-notice): 预约单号兜底分作用域并镜像补写明细缺失行
订单级早退导致表头已有预约单号时明细行补写永不执行(回归
SNER-20261014-0AB6D98A doc 915 明细预约号空)。

- 兜底早退改分作用域:scope=header 表头有值才跳过;scope=line
  行级全有值才跳过,存在缺失行仍执行补写;
- 镜像语义:排除集移除表头已采纳的预约号值——它正是要写入缺失
  行级的值;其余订单观测值(尤其 PO)保持排除防误判;
- PO 行定位收敛不变:本单 PO 所在行的预约号唯一命中后写入。

真数据验证:9/9 PO 各自唯一写入本行预约号
(4510042199→1000161448 … 4510042208→1000131033),与表头一致。
2026-10-15 08:43:05 +08:00
hugo 89b32bcdb5 fix(shipping-notice): 预约单号兜底分作用域并镜像补写明细缺失行
订单级早退导致表头已有预约单号时明细行补写永不执行(回归
SNER-20261014-0AB6D98A doc 915 明细预约号空)。

- 兜底早退改分作用域:scope=header 表头有值才跳过;scope=line
  行级全有值才跳过,存在缺失行仍执行补写;
- 镜像语义:排除集移除表头已采纳的预约号值——它正是要写入缺失
  行级的值;其余订单观测值(尤其 PO)保持排除防误判;
- PO 行定位收敛不变:本单 PO 所在行的预约号唯一命中后写入。

真数据验证:9/9 PO 各自唯一写入本行预约号
(4510042199→1000161448 … 4510042208→1000131033),与表头一致。
2026-10-15 08:14:37 +08:00
hugo b8fe089b3d fix(shipping-notice): 识别收口自动解决已采纳字段的补充冲突
重识别 Run 收口时对本 Run 可复核 Case 原子激活文件 Stream
(batch_reparse_succeeded,含 Run 谱系证明与可选来源声明),
使工作台队列不再因 Stream 断链而丢失单据。

- persist 收口对本 Run 候选批量调用 resolve_satisfied_supplement_conflicts:
  supplement_field_conflict 的字段级裁决已 accepted(PO 行收敛唯一写入
  或正式值源)即标记 resolved,不再阻断提交订单;
- 投影过滤 resolved 冲突不下发待裁决面板;
- 同一 field_code 表头/行级双字段(如预约单号)任一位置 accepted 即满足;
- 新增测试环境失败 Run 重排队运维脚本(仅测试库硬校验、dry-run 默认)。
2026-10-15 02:27:51 +08:00
hugo f7734c8ccb fix(shipping-notice): 识别收口自动解决已采纳字段的补充冲突
重识别 Run 收口时对本 Run 可复核 Case 原子激活文件 Stream
(batch_reparse_succeeded,含 Run 谱系证明与可选来源声明),
使工作台队列不再因 Stream 断链而丢失单据。

- persist 收口对本 Run 候选批量调用 resolve_satisfied_supplement_conflicts:
  supplement_field_conflict 的字段级裁决已 accepted(PO 行收敛唯一写入
  或正式值源)即标记 resolved,不再阻断提交订单;
- 投影过滤 resolved 冲突不下发待裁决面板;
- 同一 field_code 表头/行级双字段(如预约单号)任一位置 accepted 即满足;
- 新增测试环境失败 Run 重排队运维脚本(仅测试库硬校验、dry-run 默认)。
2026-10-15 02:27:16 +08:00
hugo 9eb3749888 fix(shipping-notice): 识别收口自动解决已采纳字段的补充冲突
重识别 Run 收口时对本 Run 可复核 Case 原子激活文件 Stream
(batch_reparse_succeeded,含 Run 谱系证明与可选来源声明),
使工作台队列不再因 Stream 断链而丢失单据。

- persist 收口对本 Run 候选批量调用 resolve_satisfied_supplement_conflicts:
  supplement_field_conflict 的字段级裁决已 accepted(PO 行收敛唯一写入
  或正式值源)即标记 resolved,不再阻断提交订单;
- 投影过滤 resolved 冲突不下发待裁决面板;
- 同一 field_code 表头/行级双字段(如预约单号)任一位置 accepted 即满足;
- 新增测试环境失败 Run 重排队运维脚本(仅测试库硬校验、dry-run 默认)。
2026-10-15 02:25:48 +08:00
hugo 3e8b12b954 fix(shipping-notice): 收口激活按 run_id 取 Run 修变量作用域 2026-10-15 01:40:01 +08:00
hugo dde2093e06 fix(shipping-notice): 收口激活按 run_id 取 Run 修变量作用域 2026-10-15 01:39:37 +08:00
hugo f67fa6f09f fix(shipping-notice): 收口激活按 run_id 取 Run 修变量作用域 2026-10-15 01:39:13 +08:00
hugo 6502f73cb5 fix(shipping-notice): 重识别 Run 终态激活 Case 并收紧裸数字兜底口径
- 修复重解析延迟激活钩子未接线:Run 终态原子激活可复核 Case 为文件 Stream 当前版本,工作台队列不再空白
- 新增 run_is_reparse_successor_of_case 判定 Case 与重解析 Run 的后继关系
- 裸数字兜底口径收紧:仅扫「整格恰好 5/10 位纯数字」的正文 HTML 表格单元格,自由文本与带前后字符的值一律不取,防误绑签名与邮编
- 新增客户 PO 匹配变体集合(原值/归一/去前导零)纳入排除集,补充合并末段裁决更准
- 同步预约号启发式测试,business/technical 文档记录收紧决策
2026-10-15 01:27:00 +08:00
hugo e78f750db0 fix(shipping-notice): 重识别 Run 终态激活 Case 并收紧裸数字兜底口径
- 修复重解析延迟激活钩子未接线:Run 终态原子激活可复核 Case 为文件 Stream 当前版本,工作台队列不再空白
- 新增 run_is_reparse_successor_of_case 判定 Case 与重解析 Run 的后继关系
- 裸数字兜底口径收紧:仅扫「整格恰好 5/10 位纯数字」的正文 HTML 表格单元格,自由文本与带前后字符的值一律不取,防误绑签名与邮编
- 新增客户 PO 匹配变体集合(原值/归一/去前导零)纳入排除集,补充合并末段裁决更准
- 同步预约号启发式测试,business/technical 文档记录收紧决策
2026-10-15 01:26:23 +08:00
hugo 5746b1d220 fix(shipping-notice): 重识别 Run 终态激活 Case 并收紧裸数字兜底口径
- 修复重解析延迟激活钩子未接线:Run 终态原子激活可复核 Case 为文件 Stream 当前版本,工作台队列不再空白
- 新增 run_is_reparse_successor_of_case 判定 Case 与重解析 Run 的后继关系
- 裸数字兜底口径收紧:仅扫「整格恰好 5/10 位纯数字」的正文 HTML 表格单元格,自由文本与带前后字符的值一律不取,防误绑签名与邮编
- 新增客户 PO 匹配变体集合(原值/归一/去前导零)纳入排除集,补充合并末段裁决更准
- 同步预约号启发式测试,business/technical 文档记录收紧决策
2026-10-15 01:22:14 +08:00
hugo 1a2753d3b5 fix(shipping-notice): 调整XFA 身份指纹漂移降级软门禁并放行 datasets 取值
供应商换代重导 XFA 表单必变 template 包指纹,原硬拦截使视觉已唯一
命中的单据永远停在无数据人工复核。

- 身份校验改为状态判定写入 decision.xfa_identity_state
  (matched/incomplete/mismatch),漂移仅记 fallback 码不拦截;
- 放行后按模板既有 bindings 对新包 datasets 取值,仍强制
  validate_xfa_extraction 业务交叉校验兜底;
- 取值/业务校验失败时身份码前置转 Review,复核者可见漂移根因。
2026-10-15 00:32:03 +08:00
hugo 1efb165fd5 fix(shipping-notice): 调整XFA 身份指纹漂移降级软门禁并放行 datasets 取值
供应商换代重导 XFA 表单必变 template 包指纹,原硬拦截使视觉已唯一
命中的单据永远停在无数据人工复核。

- 身份校验改为状态判定写入 decision.xfa_identity_state
  (matched/incomplete/mismatch),漂移仅记 fallback 码不拦截;
- 放行后按模板既有 bindings 对新包 datasets 取值,仍强制
  validate_xfa_extraction 业务交叉校验兜底;
- 取值/业务校验失败时身份码前置转 Review,复核者可见漂移根因。
2026-10-15 00:31:43 +08:00
hugo 01ae63901a fix(shipping-notice): 调整XFA 身份指纹漂移降级软门禁并放行 datasets 取值
供应商换代重导 XFA 表单必变 template 包指纹,原硬拦截使视觉已唯一
命中的单据永远停在无数据人工复核。

- 身份校验改为状态判定写入 decision.xfa_identity_state
  (matched/incomplete/mismatch),漂移仅记 fallback 码不拦截;
- 放行后按模板既有 bindings 对新包 datasets 取值,仍强制
  validate_xfa_extraction 业务交叉校验兜底;
- 取值/业务校验失败时身份码前置转 Review,复核者可见漂移根因。
2026-10-15 00:26:59 +08:00
hugo 2250ac98e6 fix(shipping-notice): 批次投影收敛需人工未物化识别 Run 并下发重解析
收口 completed 且最新 Run review_required、但未物化 Case/OT 的附件
(如 XFA 身份门禁在唯一命中后拒绝、候选从未创建)原先落入兜底
running,批次进度中心误显示「处理中」且无任何动作入口。

- 文档级裁决新增 review_required 无 Task/Case 分支:waiting_human
  + candidate_creating(回归 SNER-20261014-E27D657F)
- 重解析入口与 failed 分支同源:无 OT/无 Case 且最新 Run 失败或
  需人工,均下发 reparse 动作
2026-10-14 23:23:40 +08:00
hugo 47ee68ed25 fix(shipping-notice): 批次投影收敛需人工未物化识别 Run 并下发重解析
收口 completed 且最新 Run review_required、但未物化 Case/OT 的附件
(如 XFA 身份门禁在唯一命中后拒绝、候选从未创建)原先落入兜底
running,批次进度中心误显示「处理中」且无任何动作入口。

- 文档级裁决新增 review_required 无 Task/Case 分支:waiting_human
  + candidate_creating(回归 SNER-20261014-E27D657F)
- 重解析入口与 failed 分支同源:无 OT/无 Case 且最新 Run 失败或
  需人工,均下发 reparse 动作
2026-10-14 23:23:26 +08:00
hugo 06c77d40c7 fix(shipping-notice): 批次投影收敛需人工未物化识别 Run 并下发重解析
收口 completed 且最新 Run review_required、但未物化 Case/OT 的附件
(如 XFA 身份门禁在唯一命中后拒绝、候选从未创建)原先落入兜底
running,批次进度中心误显示「处理中」且无任何动作入口。

- 文档级裁决新增 review_required 无 Task/Case 分支:waiting_human
  + candidate_creating(回归 SNER-20261014-E27D657F)
- 重解析入口与 failed 分支同源:无 OT/无 Case 且最新 Run 失败或
  需人工,均下发 reparse 动作
2026-10-14 23:18:41 +08:00
hugo 5f9df244c0 fix(shipping-notice): 抽取收口纠正失败文档状态并修复 OCR 救援资产读取
- 抽取收口读取 Run 内 Unit 级失败事实:全部 Unit 失败的附件不再按零 pending 误写 completed
- EML 父项跟随 Run 结果收敛:终态 Run 禁止停留「处理中」,运行中仅区分解析失败与处理中
- OCR 救援资产读取修复:read_asset_bytes 接收 id 时按 FileAsset 加载字节,传参口径纠正
- 同步抽取/投影测试并新增工作台投影测试
2026-10-14 22:43:39 +08:00
hugo 97059b336b fix(shipping-notice): 抽取收口纠正失败文档状态并修复 OCR 救援资产读取
- 抽取收口读取 Run 内 Unit 级失败事实:全部 Unit 失败的附件不再按零 pending 误写 completed
- EML 父项跟随 Run 结果收敛:终态 Run 禁止停留「处理中」,运行中仅区分解析失败与处理中
- OCR 救援资产读取修复:read_asset_bytes 接收 id 时按 FileAsset 加载字节,传参口径纠正
- 同步抽取/投影测试并新增工作台投影测试
2026-10-14 22:43:30 +08:00
hugo 9f132564d6 fix(shipping-notice): 抽取收口纠正失败文档状态并修复 OCR 救援资产读取
- 抽取收口读取 Run 内 Unit 级失败事实:全部 Unit 失败的附件不再按零 pending 误写 completed
- EML 父项跟随 Run 结果收敛:终态 Run 禁止停留「处理中」,运行中仅区分解析失败与处理中
- OCR 救援资产读取修复:read_asset_bytes 接收 id 时按 FileAsset 加载字节,传参口径纠正
- 同步抽取/投影测试并新增工作台投影测试
2026-10-14 22:40:37 +08:00
hugo 3b53a2219c feat(shipping-notice): 无表头文档抽取增强与复核深链身份修复
- 新增表头 OCR 救援:模板匹配落 layout_drift/no_match 时按表头带证据补洞重评候选身份,主抽取流程接入并落 identity_rescue 事实字段
- 预约号裸数字兜底:正文无表头且常规证据缺失时扫描 5/10 位纯数字候选,持久化预置、合并末段唯一/多候选裁决
- 修复复核深链仅带 run_no 时队列项显示未命名:Case 身份优先按当前工作面 displayCase 匹配队列项
- 同步抽取 Job/运行服务/候选持久化配套与 OCR 救援、预约号启发式、表头身份测试
2026-10-14 20:44:31 +08:00
sophie a92df4c38d Merge branch 'dev' of https://gitee.com/justop/hxops into dev 2026-10-14 20:25:53 +08:00
sophieandCursor 5f6fbcd76f feat: element plus UI组件库
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-14 20:25:35 +08:00
hugo d7d4819a42 feat(shipping-notice): 无表头文档抽取增强与复核深链身份修复
- 新增表头 OCR 救援:模板匹配落 layout_drift/no_match 时按表头带证据补洞重评候选身份,主抽取流程接入并落 identity_rescue 事实字段
- 预约号裸数字兜底:正文无表头且常规证据缺失时扫描 5/10 位纯数字候选,持久化预置、合并末段唯一/多候选裁决
- 修复复核深链仅带 run_no 时队列项显示未命名:Case 身份优先按当前工作面 displayCase 匹配队列项
- 同步抽取 Job/运行服务/候选持久化配套与 OCR 救援、预约号启发式、表头身份测试
2026-10-14 19:55:37 +08:00
hugo 92ed140739 feat(shipping-notice): 无表头文档抽取增强与复核深链身份修复
- 新增表头 OCR 救援:模板匹配落 layout_drift/no_match 时按表头带证据补洞重评候选身份,主抽取流程接入并落 identity_rescue 事实字段
- 预约号裸数字兜底:正文无表头且常规证据缺失时扫描 5/10 位纯数字候选,持久化预置、合并末段唯一/多候选裁决
- 修复复核深链仅带 run_no 时队列项显示未命名:Case 身份优先按当前工作面 displayCase 匹配队列项
- 同步抽取 Job/运行服务/候选持久化配套与 OCR 救援、预约号启发式、表头身份测试
2026-10-14 19:31:39 +08:00
sophie 041bb73b9a fix: update docs 2026-10-14 13:44:56 +08:00
sophie 5187b6105b Merge branch 'dev' into test 2026-10-14 08:47:36 +08:00
hugo 570d1c605c Merge branch 'hugo-auto-transfer' into test 2026-10-13 21:31:02 +08:00
hugo af2658e244 Merge branch 'hugo-auto-transfer' into dev 2026-10-13 21:18:25 +08:00
hugo 6ac2effac3 feat(shipping-notice): 支持已确认订单改绑客户并重冻结快照
- 客户识别面板两态化:已识别折叠为摘要条 +「修改客户」入口,前端管控复用编辑窗头级谓词
- 新增 rebind_confirmed_customer 链路:守卫→更新 resolution 行→审计→手动重冻结,改后重新生成 Excel
- 守卫保证仅在无发货通知/Excel 产物时可改,匹配与门禁零触碰、无失效连锁
- 路由引擎/建单资格/编辑窗服务同步适配,errors 补充改绑错误码四语言
- 同步客户面板测试、确认对话框与四语言文案,落设计与实施计划文档
2026-10-13 21:13:58 +08:00
sophie c305d0544b !24 Merge branch 'dev' into change
Merge pull request !24 from 王瑞雪/change
2026-10-13 08:19:18 +00:00
sophie 5879871ade Merge branch 'dev' of https://gitee.com/justop/hxops into dev 2026-10-13 15:52:38 +08:00
sophie b8cc0cbe77 fix: 设备验收预警优化 2026-10-13 15:52:09 +08:00
hugo 4a726fe8b2 Merge branch 'hugo-auto-transfer' into dev 2026-10-13 15:10:45 +08:00
HTEWJ\26070045 f38e940e3c Merge branch 'dev' into change
# Conflicts:
#	frontend/src/features/order-delivery-reply/api/orderDeliveryReply.api.ts
2026-10-13 15:07:19 +08:00
hugo ea94fb28db feat(shipping-notice): 人工重取库存前置候选刷新并放开行级库存源下拉
- 人工重试库存准备前置幂等重判:任务级整单重路由、行级定向重评目标行,复用裁决与冻结链路,零新动作码零契约变更
- 新版候选集 supersede 时内置失效旧库存事实,导出归档与查询服务同步适配
- 行级「库存源」下拉抽纯函数合并选项:歧义行候选置顶 + 全部已启用源去重兜底,任一已启用源可人工指定
- 库存源门禁归一 Notice→OT 身份解析;任务中心抽屉与表格接入行级重取入口
- 同步四语言文案、技术文档与实施计划
2026-10-13 15:04:40 +08:00
sophie 7e7bcbd388 fix: 解决merge conflict 2026-10-13 13:17:14 +08:00
HTEWJ\26070045 28b4a428ef fix(order-delivery-reply): 修改excel导出后命名中的时间显示为北京时间 2026-10-13 10:31:42 +08:00
HTEWJ\26070045 e181d4e9ec Merge branch 'dev' into change 2026-10-13 09:23:01 +08:00
HTEWJ\26070045 8c97d5ed21 style(order-delivery-reply): 新增导出excel,批次条可直接填写首批次回复 2026-10-13 09:16:16 +08:00
hugoandCursor e38e5a63fe chore(migrations): 合并 shipping 与设备验收并行 migration heads
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 21:39:11 +08:00
hugo d95c4dc086 Merge branch 'hugo-auto-transfer' into dev 2026-10-12 21:34:33 +08:00
hugo a8d721e793 feat(in-transit-transfer): 自动调拨支持收料日期范围并收归排程通用通知
- 自动调拨任务新增收料日期范围动态参数(receipt_date_from/to):缩小匹配面便于测试与排障,非法范围由匹配层校验拒绝
- 排程动态参数表单支持占位文案 key 与空值归 null,日期筛选直达任务配置
- 执行结果通知统一走排程「启用通知」通用企微通知,任务不再自建领域通知
- 门禁契约澄清 retry_inventory_matching 语义:复用已抓库存重匹配不重抓;STP 多候选无匹配时阶段能力禁用、不隐式触发 RPA
- 同步匹配/自动调拨/排程测试、四语言文案与文档
2026-10-12 21:25:35 +08:00
sophie 8cd8012632 build: 锁定sqlalchemy版本,避免新版本sqlalchemy取了错误的postgrsql驱动
(cherry picked from commit aed076046a)
(cherry picked from commit b3550247bf198b5909795a4458d924fa41ec329c)
2026-10-12 16:23:29 +08:00
sophie 91a4bcbb8b Merge branch 'feature/equipment-acceptance-sync' into dev 2026-10-12 14:06:36 +08:00
sophie 02af2c9599 fix: 恢复casdoor域名地址 2026-10-12 13:28:42 +08:00
sophie 86fc8a2c06 feat(equipment-acceptance): 设备验收预警 2026-10-12 11:53:40 +08:00
hugo 34c3bfb254 fix(freight-rpa): 收敛 DSV 登录双认证域判定并补自愈重登录
- 认证态判定统一 _on_dsv_auth_domain 双域:PingFederate resume 链迁至新域后单域硬编码漏判,升级提示不点「也许以后」卡死登录
- 「已记住标识」的 PingID 选择登录方法页(无用户名框)按强特征判定,跳过邮箱直进密码阶段
- 用户名步骤走不通时清空 Cookie 从 portal 重新发起登录,仍失败才抛错交由批内重试
- 登录流程抽独立 dsv_auth_login_flow 模块,补 worker 参数化测试,technical.md 记录加固决策
2026-10-12 11:47:22 +08:00
hugo 386f93108c feat(shipping-notice): 库存缺口料号兜底自动放行并新增料号可用量列
- 匹配器按料号二次汇总 part_available_qty 随行级匹配事实持久化(新列,迁移 0a575f3a)
- 缺口行料号总库存满足需求时系统自动放行,复用人工放行同一落库/审计/门禁链路,证据按预约优先→料号兜底自动带出
- 前端库存匹配表原「可用数量」列改为「预约数量」,其后新增「可用数量」(料号总库存)列
- DSV 连接器防误点「忘记密码」链接并参数化料号报表取数,库存 worker 按料号查询配套
- 收料就绪与来源状态联动调整;casdoor 未识别认证错误日志保留原始异常堆栈
- 同步门禁/投影/持久化测试、调拨卡片文案四语言与文档
2026-10-11 17:42:55 +08:00
hugo 4e97553f42 fix(shipping-notice): 收料回调路径契约改为 drop 根内文件名
- 修复跨机成功回调全程 400:Worker(Windows)与后端(Linux 挂载根)分属两机根路径不同,后端无法解析 Worker 本机绝对路径
- Worker 只上报文件名(output.name),后端按自身挂载的 drop 根拼接定位;历史载荷携带绝对路径亦按末段文件名兼容解析
- 同步收料 worker 路径契约注释与跨机路径回归测试
2026-10-08 13:14:47 +08:00
hugo 91a4bd538d fix(shipping-notice): 找回重构合并丢失的收料进度上报路由
- 恢复 receipt-unit-progress / receipt-batch-progress 两路由(Tool 蓝图):Worker 上报全程 404、活动锚失效、在飞批次被超时对账误杀
- 路由注释标注「勿再从旧路径文件删除」防回归;新增路由注册回归锁测试,路由缺失在部署前即红
- 单元领取 mark 落单元 started_at,接续收料超时对账的笔间静默判活链路
2026-10-08 11:31:09 +08:00
hugo ffbcb93b2e Merge branch 'hugo-auto-transfer' into dev 2026-10-08 11:07:47 +08:00
hugo e8d9dba8a3 fix(freight-rpa): 两域超时放宽至 1 小时并强制收料重试完整重导航
- 库存/收料超时 900s 放宽到 3600s:对账按笔间静默判活后,超时须覆盖最坏批次总时长,防健康在飞批次被误回收(RUN20261008003113B726 实测教训)
- 收料 worker 重试尝试(attempt>1)强制完整重导航:对齐库存 AWSRTM 兜底,报表导出菜单缺失属瞬态故障,须回入口页重选菜单,绝不在错误页直接重试
- 凭据校验类失败(invalid/verification)为确定性失败,不进入重试
- 同步 test 环境超时配置
2026-10-08 11:06:25 +08:00
sophie 239d373503 fix: 优化错误提示 2026-10-08 09:49:57 +08:00
sophie d57ecc62f9 fix: 合同付款预警优化 2026-10-07 18:28:33 +08:00
sophie c5b7cc662b Merge branch 'dev' of https://gitee.com/justop/hxops into dev 2026-10-07 17:43:37 +08:00
sophie abde3de71d fix: 解决本地分支不能登录 2026-10-07 17:42:58 +08:00
sophie f4edec6e07 !23 feat(order-delivery-reply): 单行回复弹窗取消快速统一交区,联合回复保留
Merge pull request !23 from 王瑞雪/fix-order-delivery-reply-
2026-10-07 09:25:40 +00:00
sophie fe5191b38a fix: 合同付款预警优化 2026-10-07 16:21:44 +08:00
HTEWJ\26070045 444a7482e3 feat(order-delivery-reply): 单行回复弹窗取消快速统一交区,联合回复保留 2026-10-07 11:51:35 +08:00
sophie 83e0bad22f Merge branch 'dev' of https://gitee.com/justop/hxops into dev 2026-10-07 10:21:33 +08:00
hugo 20122ce6d3 Merge branch 'hugo-auto-transfer' into test 2026-10-07 10:00:14 +08:00
hugo a3078a4415 Merge branch 'hugo-auto-transfer' into dev 2026-10-07 09:58:07 +08:00
hugo 9adb3ec077 fix(schedule): 收料 RPA 超时对账迁至每轮 tick 并按笔间静默判活
- 修复收料 run 卡「执行中」5 天:超时回收从 worker 启动一次性分支迁到每轮领取维护,长驻进程期间超时 run 不再永不终态
- 超时判据换为最后活动锚(笔间静默):补记单元 started_at,worker 每开始/完成一笔推进锚点,健康长批次不被误杀
- 心跳哨兵口径统一:库存与收料均要求共享哨兵
- 同步排程与心跳测试、worker 启动脚本、四份文档
2026-10-07 09:56:31 +08:00
sophie 64afe94924 fix(login): 网络差浏览器未收到响应时友好提示 2026-10-07 09:36:51 +08:00
sophie ebd27ccfa7 fix: 临时绕开证书过期问题 2026-10-06 15:48:57 +08:00
sophie ce4b69eb7c Merge branch 'training' into dev 2026-10-06 14:37:56 +08:00
sophie 3bfd881c4f Merge branch 'equipment-acceptance' into dev 2026-10-06 14:20:41 +08:00
sophie 5b7e0d5f87 feat(equipment-acceptance): 设备验收提醒需求文档 2026-10-06 14:02:35 +08:00
sophie aed076046a build: 锁定sqlalchemy版本,避免新版本sqlalchemy取了错误的postgrsql驱动 2026-10-06 10:25:01 +08:00
sophie d004a141f2 !22 fix(order-delivery-reply): 测试/生产企微事件白名单补齐交期回复通知
Merge pull request !22 from 王瑞雪/fix-test-order-delivery-reply
2026-09-30 09:00:52 +00:00
HTEWJ\26070045 6ad93e829c fix(env): 不同环境冗余变量收敛到 2026-09-30 16:43:25 +08:00
sophie 425ed43649 feat(invoice-check): 立账凭证优化 2026-09-30 16:12:27 +08:00
HTEWJ\26070045 5ede1cbcc4 fix(order-delivery-reply): 测试/生产企微事件白名单补齐交期回复通知 2026-09-30 14:24:13 +08:00
runny 22b05c91a2 fix(training): 精益催办按人按天合并去重,多期未完成仅发一条汇总提醒 2026-09-30 13:18:32 +08:00
runny d2e7eb678a Merge branch 'dev' into runny0914 2026-09-30 09:39:07 +08:00
sophie f723732eb5 !21 Merge branch 'dev' into order-delivery-reply
Merge pull request !21 from 王瑞雪/order-delivery-reply
2026-09-30 00:48:53 +00:00
runny 594d9c22b5 Merge branch 'dev' into runny0914 2026-09-30 08:20:15 +08:00
runny d635a2920c fix(training): 解决视频推送任务多的问题! 2026-09-30 08:18:19 +08:00
sophie 863e009b59 feat(training): 原型图 2026-09-29 09:19:33 +08:00
1034 changed files with 113248 additions and 36372 deletions

No files matched your search

-70
View File
@@ -1,70 +0,0 @@
---
description: 文件层与函数层注释强制规范(撰写与调整代码时均适用)
alwaysApply: true
---
# 代码注释(强制)
撰写或**修改**代码时,必须补齐或更新两层注释。完整说明见 `AGENTS.md` §5。
## 文件层(文件顶部)
块注释须包含:**用途**、**主要 import/依赖**、**与上下游文件的逻辑关系**。
```typescript
/**
* features/kb/composables/useKbWorkspace.ts
* 用途:知识库作业面编排入口,组合 state / computed / data 等子模块。
* 依赖:kb-workspace/* composables、kb.api、kb-display.utils。
* 逻辑:KbWorkspaceView 调用本 composable;本文件再分发至 useKbWorkspaceData 等子模块。
*/
```
```python
"""
services/kb_sync.py
用途:知识库文档与 Dify 之间的同步编排。
依赖:dify_service、models.KbDocument、minio_service。
逻辑:由 api/knowledge_base 路由调用;内部委托 chunking 与 job 状态机。
"""
```
## 函数层(每个函数定义上方)
须说明:**用途**、**核心逻辑与实现方式**、**参数**与**返回值**(及异常)。
```typescript
/**
* 加载当前分组下的文档列表,并在静默刷新时合并 stable 项避免闪烁。
* 核心逻辑:调用 getKbGroupFilesSafe,按 mergeStableItems 策略合并新旧列表。
* @param options.silent - 为 true 时不切换 loading,用于轮询刷新
* @returns 是否成功拉取到数据
*/
async function loadDocuments(options?: LoadListOptions): Promise<boolean> { ... }
```
```python
def sync_document_to_dify(document_id: int, *, force: bool = False) -> SyncResult:
"""
将指定文档切片同步至 Dify 知识库。
核心逻辑:读 MinIO 原文 → 切块 → 调 Dify API upsert;失败写入 KbJob 供重试。
Args:
document_id: 本地 KbDocument 主键。
force: 为 True 时忽略已完成状态强制重同步。
Returns:
SyncResult: 含 dify_document_id 与分段数。
Raises:
KbNotFoundError: 文档不存在或无权限。
"""
```
## 修改既有文件时
- 改函数逻辑/签名 → 同步改该函数注释。
- 改 import 或模块协作关系 → 同步改文件头注释。
- Vue SFC:`<script setup>` 内每个函数同样要求函数层注释。
+21
View File
@@ -0,0 +1,21 @@
---
description: 未启用。管理端改用 Element Plus 的写法。启用前不要自动套用。
alwaysApply: false
---
# 管理端 Element Plus(未启用)
本规则现在不自动生效:`alwaysApply` 为 false,且没有 `globs`。打开管理端文件时不会套用。
启用:在本文件顶部 frontmatter 加上下面的 `globs` 后保存。不要改 `alwaysApply`。
```yaml
globs: frontend/src/features/admin/**/*.vue,frontend/src/features/kb/components/KbAdminPanel.vue,frontend/src/features/kb/components/KbGroupDrawer.vue
```
启用之后,改这些 Vue 时遵守 `docs/ui/ELEMENT_MIGRATION.md` §4:
- 按钮、输入、下拉、表格、弹窗、分页用 Element Plus,不要新写 `<button>`、`<input>`、`<select>`、`<textarea>`。
- 不要新写 `btn-primary`、`btn-secondary`、`btn-ghost`、`btn-danger`、`input-field`、`select-field`。
- 图标用 `@element-plus/icons-vue`,不要新加 `lucide-vue-next`。
- 字号和颜色用 `element-trial.css` 里的 Element 变量,不要在单元格上写 `text-sm`、`text-xs`、`text-muted`。
-2
View File
@@ -1,2 +0,0 @@
DEBUG_SERVER_URL=http://127.0.0.1:7778/event
DEBUG_SESSION_ID=login-401
@@ -1,2 +0,0 @@
{"sessionId": "app-open-error", "runId": "pre-fix", "hypothesisId": "A", "location": "src/main.ts:8", "msg": "[DEBUG] Frontend bootstrap started", "data": {"href": "http://192.168.100.192:8910/config"}, "ts": 1788828493927}
{"sessionId": "app-open-error", "runId": "pre-fix", "hypothesisId": "C", "location": "src/main.ts:16", "msg": "[DEBUG] Vue app mounted", "data": {"appChildren": 1}, "ts": 1788828493938}
+22 -19
View File
@@ -1,4 +1,4 @@
# ============================================================================= # =============================================================================
# Development — docker compose / deploy_compose.sh dev # Development — docker compose / deploy_compose.sh dev
# Environment-specific variables stay in .env.dev/.env.test/.env.prod # Environment-specific variables stay in .env.dev/.env.test/.env.prod
# - .env.dev / .env.test / .env.prod for deployment environments # - .env.dev / .env.test / .env.prod for deployment environments
@@ -102,15 +102,13 @@ SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
# 复核工作台字段级 AI 建议;仅开发环境启用,建议仍须证据校验与人工裁决 # 复核工作台字段级 AI 建议;仅开发环境启用,建议仍须证据校验与人工裁决
SHIPPING_NOTICE_LLM_REVIEW_ENABLED=true SHIPPING_NOTICE_LLM_REVIEW_ENABLED=true
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4) # 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同) # Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
@@ -135,32 +133,37 @@ SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900 FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS=900
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3 FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30 FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
# RPA 目录(相对 backend/ 根目录,统一 freight_rpa/{inventory,receipt,common} 三层布局) # RPA 目录(相对 backend/ 根;freight_rpa/{onhand,inbound,outbound,upload,common},2026-10-16 批次 R)
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=data/freight_rpa/inventory/drop FREIGHT_RPA_SHARED_ONHAND_DROP_DIR=data/freight_rpa/onhand/drop
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory/triggers FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR=data/freight_rpa/onhand/triggers
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=data/freight_rpa/receipt/drop FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=data/freight_rpa/inbound/drop
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=data/freight_rpa/receipt/triggers FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=data/freight_rpa/inbound/triggers
FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=data/freight_rpa/receipt/archives FREIGHT_RPA_INBOUND_ARCHIVE_DIR=data/freight_rpa/inbound/archives
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=data/freight_rpa/inventory/upload_queue FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR=data/freight_rpa/outbound/drop
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/freight_rpa/inventory/upload_triggers FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR=data/freight_rpa/outbound/triggers
FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR=data/freight_rpa/outbound/archives
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=data/freight_rpa/upload/queue
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/freight_rpa/upload/triggers
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR=data/freight_rpa/common/browser_profile FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR=data/freight_rpa/common/browser_profile
# AWS 库存列映射(可选 JSON 字符串) # AWS 库存列映射(可选 JSON 字符串)
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"} # FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
# 本地 RPA(scripts/freight_rpa/inventory/inventory_rpa_worker.py) # 本地 RPA(scripts/freight_rpa/onhand/onhand_rpa_worker.py)
FREIGHT_RPA_WORKER_MOCK=false FREIGHT_RPA_WORKER_MOCK=false
# 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis # 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false
FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK=true FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK=true
# 企微心跳告警总开关(默认关闭;需要时改为 true)
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
# FREIGHT_RPA_WORKER_POLL_SECONDS=3 # FREIGHT_RPA_WORKER_POLL_SECONDS=3
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY= # FREIGHT_RPA_WORKER_SAMPLE_ONHAND=
# --- 10. 运维、告警与维护工具 --- # --- 10. 运维、告警与维护工具 ---
# 设备维保助手后端工具调用密钥 # 设备维保助手后端工具调用密钥
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
+18 -20
View File
@@ -1,4 +1,4 @@
# ============================================================================= # =============================================================================
# Production — docker compose env_file + deploy_compose.sh prod # Production — docker compose env_file + deploy_compose.sh prod
# Environment-specific variables stay in .env.dev/.env.test/.env.prod # Environment-specific variables stay in .env.dev/.env.test/.env.prod
# - .env.dev / .env.test / .env.prod for deployment environments # - .env.dev / .env.test / .env.prod for deployment environments
@@ -25,6 +25,7 @@ HXOPS_PUBLIC_BASE_URL=https://ai.well-trust.com
AUTH_LOGIN_MODE=casdoor AUTH_LOGIN_MODE=casdoor
# 如果需要用户密码登录,修改该值为password # 如果需要用户密码登录,修改该值为password
# AUTH_LOGIN_MODE=password # AUTH_LOGIN_MODE=password
# 是否启用 JWT 认证 # 是否启用 JWT 认证
AUTH_JWT_REQUIRED=true AUTH_JWT_REQUIRED=true
AUTH_JWT_ISSUER=https://auth.well-trust.com AUTH_JWT_ISSUER=https://auth.well-trust.com
@@ -72,7 +73,6 @@ GUNICORN_WORKERS=20
# 企业微信通知配置(如果不使用企业微信通知,留空即可) # 企业微信通知配置(如果不使用企业微信通知,留空即可)
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL # WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/ WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
# --- 5. 数据库与基础设施 --- # --- 5. 数据库与基础设施 ---
@@ -116,11 +116,10 @@ SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
# 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享) # 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享)
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true
# 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥) # 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥)
SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
@@ -138,34 +137,33 @@ SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=false SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=false
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=false SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=false
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
# RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。 # RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。
# 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。 # 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。
FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE= FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致) # 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致)
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900 FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS=900
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
# 企微心跳告警总开关(默认关闭;需要时改为 true)
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微 # 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
FREIGHT_RPA_WORKER_ALERT_USERNAMES= FREIGHT_RPA_WORKER_ALERT_USERNAMES=
FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120 FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600 FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
# RPA 目录(正式环境:Ubuntu 挂载 Windows RPA 正式共享,统一 freight_rpa/{inventory,receipt,common} 三层布局) # RPA 目录(正式:Ubuntu 挂载 Windows 共享;freight_rpa/{onhand,inbound,outbound,upload,common})
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/drop FREIGHT_RPA_SHARED_ONHAND_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/onhand/drop
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/triggers FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/onhand/triggers
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/drop FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inbound/drop
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/triggers FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inbound/triggers
FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/archives FREIGHT_RPA_INBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inbound/archives
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_queue FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/outbound/drop
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_triggers FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/outbound/triggers
FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/outbound/archives
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/upload/queue
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/upload/triggers
# 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问) # 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001 # 订单交期回复 Agent(2026-10-10 上线边界):只同步订单日期 ≥ 起始日的订单行,早于边界的历史行随 erp_missing 语义自动移出工作台;留空/删除 = 全量同步(dev/test 不配置)
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv ORDER_DELIVERY_SYNC_DATE_FROM=2026-10-10
# --- 10. 运维、告警与维护工具 --- # --- 10. 运维、告警与维护工具 ---
# 设备维保助手后端工具调用密钥 # 设备维保助手后端工具调用密钥
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
+1 -2
View File
@@ -150,7 +150,7 @@ WECOM_TRUSTED_DOMAIN=
WECOM_PUBLIC_BASE_URL= WECOM_PUBLIC_BASE_URL=
WECOM_NOTIFY_ENABLED=true WECOM_NOTIFY_ENABLED=true
WECOM_NOTIFY_BASE_URL= WECOM_NOTIFY_BASE_URL=
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,order_delivery_reply_notify,training_overseas_thailand_guidelines WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,equipment_acceptance_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,order_delivery_reply_notify,training_overseas_thailand_guidelines
WECOM_FEEDBACK_NOTIFY_ENABLED=true WECOM_FEEDBACK_NOTIFY_ENABLED=true
WECOM_FEEDBACK_NOTIFY_BASE_URL=http://ai.well-trust.com:8881 WECOM_FEEDBACK_NOTIFY_BASE_URL=http://ai.well-trust.com:8881
# 企业微信群机器人 webhook,按环境写入 .env.<env> 或部署平台变量;不要提交真实 URL。 # 企业微信群机器人 webhook,按环境写入 .env.<env> 或部署平台变量;不要提交真实 URL。
@@ -238,7 +238,6 @@ IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS=86400
IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS=3 IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS=3
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS=5 IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS=5
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS=7 IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS=7
IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS=2
# 归档 bucket(MinIO;凭据复用 MINIO_*) # 归档 bucket(MinIO;凭据复用 MINIO_*)
IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET=hxops-transfer IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET=hxops-transfer
+20 -25
View File
@@ -1,4 +1,4 @@
# ============================================================================= # =============================================================================
# Test — docker compose / deploy_compose.sh test # Test — docker compose / deploy_compose.sh test
# Environment-specific variables stay in .env.dev/.env.test/.env.prod # Environment-specific variables stay in .env.dev/.env.test/.env.prod
# - .env.dev / .env.test / .env.prod for deployment environments # - .env.dev / .env.test / .env.prod for deployment environments
@@ -24,8 +24,6 @@ HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
# 如果需要用户密码登录,修改该值为password # 如果需要用户密码登录,修改该值为password
#AUTH_LOGIN_MODE=casdoor #AUTH_LOGIN_MODE=casdoor
AUTH_LOGIN_MODE=casdoor AUTH_LOGIN_MODE=casdoor
# 是否启用 JWT 认证
AUTH_JWT_REQUIRED=true
# 必须与 CASDOOR_BASE_URL discovery 返回的 issuer 完全一致,不能填写 HXOPS 地址。 # 必须与 CASDOOR_BASE_URL discovery 返回的 issuer 完全一致,不能填写 HXOPS 地址。
AUTH_JWT_ISSUER=https://autht.well-trust.com AUTH_JWT_ISSUER=https://autht.well-trust.com
@@ -72,7 +70,6 @@ GUNICORN_WORKERS=6
# 企业微信通知配置(如果不使用企业微信通知,留空即可) # 企业微信通知配置(如果不使用企业微信通知,留空即可)
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL # WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/ WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines
WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com
HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
@@ -120,13 +117,11 @@ SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095 SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4) # 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
# 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥) # 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥)
@@ -151,16 +146,16 @@ SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐) # 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐)
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900 # 两域超时须覆盖最坏批次总时长(10 站串行 + 单站失败重试可达 30 分钟+),
# 否则每轮对账会把仍在飞的健康批次误回收(2026-10-08 RUN20261008003113B726 实测教训)
FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS=3600
FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS=3600
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3 FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30 FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
# 企微心跳告警总开关(默认关闭;需要时改为 true)
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微 # 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
# 两者皆无则告警只写日志、不会发企微 # 两者皆无则告警只写日志、不会发企微
FREIGHT_RPA_WORKER_ALERT_USERNAMES= FREIGHT_RPA_WORKER_ALERT_USERNAMES=
@@ -170,25 +165,25 @@ FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600 FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
FREIGHT_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns= FREIGHT_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns=
# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享,统一 freight_rpa/{inventory,receipt,common} 三层布局) # RPA 目录(测试:Ubuntu 挂载 Windows 共享;freight_rpa/{onhand,inbound,outbound,upload,common})
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/drop FREIGHT_RPA_SHARED_ONHAND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/onhand/drop
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/onhand/triggers
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/drop
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/triggers
FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/archives FREIGHT_RPA_INBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/archives
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_queue FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/drop
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_triggers FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/triggers
FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/archives
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/upload/queue
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/upload/triggers
# AWS 库存列映射(可选 JSON 字符串) # AWS 库存列映射(可选 JSON 字符串)
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"} # FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
# 本地 Mock RPA(scripts/freight_rpa/inventory/inventory_rpa_worker.py,可选) # 本地 Mock RPA(scripts/freight_rpa/onhand/onhand_rpa_worker.py,可选)
# FREIGHT_RPA_WORKER_MOCK=true # FREIGHT_RPA_WORKER_MOCK=true
# FREIGHT_RPA_WORKER_POLL_SECONDS=3 # FREIGHT_RPA_WORKER_POLL_SECONDS=3
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY= # FREIGHT_RPA_WORKER_SAMPLE_ONHAND=
# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问) # 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
# --- 10. 运维、告警与维护工具 --- # --- 10. 运维、告警与维护工具 ---
# 设备维保助手后端工具调用密钥 # 设备维保助手后端工具调用密钥
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
+23
View File
@@ -0,0 +1,23 @@
## 改动说明
<!-- 这次改了什么、为什么改。 -->
## 管理端界面
这次改动如果碰到管理控制台、知识库配置,或已经换成 Element Plus 的页面,按 `docs/ui/ELEMENT_MIGRATION.md` §6 核对。没改界面就删掉下面的清单。
- [ ] 只在该页入口引入 Element 样式和 `element-trial.css`,并用 `ElConfigProvider` 包住。
- [ ] 列表骨架符合规范 §3,左右 32px 对齐,只有一层卡片。
- [ ] 按钮符合规范 §4.1,没有 `size="small"` 和默认按钮混在一行。
- [ ] 表格状态是 `ElTag`,单元格没有 `text-xs` / `text-sm` / `text-muted`。
- [ ] 筛选框没有被拉成整行,空选项不是「请选择」。
- [ ] 弹窗宽度只有 480px 或 680px,短表单不是整屏抽屉。
- [ ] 加载遮罩只等列表请求,数据出来后遮罩消失。
- [ ] 删除确认与本页其他确认框是同一种。
- [ ] 四种语言下按钮、表头、空状态、分页都能读通。
- [ ] `html.dark` 下边框、表头、弹窗底色跟着变量变。
- [ ] `frontend` 下 `npx vue-tsc -b --pretty false` 通过。
## 测试
<!-- 怎么验证。 -->
+3
View File
@@ -59,6 +59,9 @@ frontend/package-lock.json
!.vscode/extensions.json !.vscode/extensions.json
.trae/* .trae/*
.cursor/* .cursor/*
!.cursor/rules/
!.cursor/rules/*.mdc
.cursor/rules/* copy.mdc
.idea/ .idea/
*.swp *.swp
*.swo *.swo
+4 -2
View File
@@ -150,6 +150,7 @@ docker compose logs -f hxops-backend
- 🧬 **修改数据库表结构必须配套迁移**:任何对 `models.py` / 数据表结构的新增、删除、字段或约束变更,都必须生成并提交对应的 Alembic 迁移脚本(`flask db migrate -m "..."` → `flask db upgrade`),禁止只改模型不出迁移。 - 🧬 **修改数据库表结构必须配套迁移**:任何对 `models.py` / 数据表结构的新增、删除、字段或约束变更,都必须生成并提交对应的 Alembic 迁移脚本(`flask db migrate -m "..."` → `flask db upgrade`),禁止只改模型不出迁移。
- 🌐 **环境变量分层**:`.env.shared` + `.env.<env>`(dev/test/prod),不要在代码里写死环境值。规则见 **[docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md)** 与 **[docs/convention/环境变量规则.md](docs/convention/环境变量规则.md)**。 - 🌐 **环境变量分层**:`.env.shared` + `.env.<env>`(dev/test/prod),不要在代码里写死环境值。规则见 **[docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md)** 与 **[docs/convention/环境变量规则.md](docs/convention/环境变量规则.md)**。
- 🌍 **i18n 四语言**:前端新增文案必须同时补齐 `zh-CN / zh-TW / en / th`,禁止硬编码中文。Agent 流程见项目 Skill `add-i18n-keys` 与 [docs/skills/add-i18n-keys-skill.md](docs/skills/add-i18n-keys-skill.md)。 - 🌍 **i18n 四语言**:前端新增文案必须同时补齐 `zh-CN / zh-TW / en / th`,禁止硬编码中文。Agent 流程见项目 Skill `add-i18n-keys` 与 [docs/skills/add-i18n-keys-skill.md](docs/skills/add-i18n-keys-skill.md)。
- 🎨 **前端界面统一 Element Plus**:`frontend/src` 的页面、弹窗、筛选、表格、按钮和输入使用 Element Plus,写法以 [docs/ui/ELEMENT_MIGRATION.md](docs/ui/ELEMENT_MIGRATION.md) 为准。新改的界面禁止再加 `btn-*`、`input-field`、`select-field`,以及手写 `<button>` / `<input>` / `<select>` / `<textarea>`。尚未替换的旧页面保持原样,轮到该页再整页替换,同一页不要混用两套控件。管理端列表骨架用 `AdminListPage`,页签用 `AdminListTabs`。
- 📡 **SSE 流式约束**:对话链路依赖 Gevent 异步 worker + Nginx `proxy_buffering off`;对话接口(`chat.py`)使用原生 Fetch/SSE 而非 Axios,改动需保持流式不被破坏。 - 📡 **SSE 流式约束**:对话链路依赖 Gevent 异步 worker + Nginx `proxy_buffering off`;对话接口(`chat.py`)使用原生 Fetch/SSE 而非 Axios,改动需保持流式不被破坏。
- 🔌 **外部集成依赖**:Oracle Instant Client 19.30 / `pyodbc` / `zeep`(OA、PLM、HR)等本地未必可运行,涉及这些 service 时谨慎并说明。 - 🔌 **外部集成依赖**:Oracle Instant Client 19.30 / `pyodbc` / `zeep`(OA、PLM、HR)等本地未必可运行,涉及这些 service 时谨慎并说明。
- ➕ **新增依赖需克制**:不擅自引入未经评审的第三方依赖;如需新增,在提交说明中给出理由。 - ➕ **新增依赖需克制**:不擅自引入未经评审的第三方依赖;如需新增,在提交说明中给出理由。
@@ -163,7 +164,7 @@ docker compose logs -f hxops-backend
- **文件内章节顺序**:① 环境与应用标识 → ② 应用运行与进程 → ③ 公共地址与网络入口 → ④ 安全、认证与身份源 → ⑤ 数据库与基础设施 → ⑥ AI 平台、模型与内部工具 → ⑦ 企业系统集成 → ⑧ 知识库与文件处理 → ⑨ 业务模块 → ⑩ 运维、告警与维护工具;文件没有某类变量时直接省略该章节。 - **文件内章节顺序**:① 环境与应用标识 → ② 应用运行与进程 → ③ 公共地址与网络入口 → ④ 安全、认证与身份源 → ⑤ 数据库与基础设施 → ⑥ AI 平台、模型与内部工具 → ⑦ 企业系统集成 → ⑧ 知识库与文件处理 → ⑨ 业务模块 → ⑩ 运维、告警与维护工具;文件没有某类变量时直接省略该章节。
- **章节内组织**:先按业务域及子域聚合(如 Casdoor、MinIO、WeCom、HR、PLM、SRM、FAQ、Shipping Notice、Fixed Asset),不得把同一域拆散后做全局字母排序;同一域内按“开关/模式 → 地址 → 标识 → 凭据 → 路径 → 业务参数 → 超时/重试/并发 → 兼容/Mock”排列,同级变量再按字母排序。 - **章节内组织**:先按业务域及子域聚合(如 Casdoor、MinIO、WeCom、HR、PLM、SRM、FAQ、Shipping Notice、Fixed Asset),不得把同一域拆散后做全局字母排序;同一域内按“开关/模式 → 地址 → 标识 → 凭据 → 路径 → 业务参数 → 超时/重试/并发 → 兼容/Mock”排列,同级变量再按字母排序。
- **数据库连接固定顺序**:`HOST → PORT → DATABASE/SID → USERNAME → PASSWORD → DRIVER → ENCRYPT/TRUST_CERT → TIMEOUT`;完整连接串(如 `DATABASE_URL`、`*_DSN`)置于该数据源首位。 - **数据库连接固定顺序**:`HOST → PORT → DATABASE/SID → USERNAME → PASSWORD → DRIVER → ENCRYPT/TRUST_CERT → TIMEOUT`;完整连接串(如 `DATABASE_URL`、`*_DSN`)置于该数据源首位。
- **RPA 命名空间(强制,2026-09-18 修订)**:货代 RPA(库存/收料/上传及后续新增 Worker)统一使用 `FREIGHT_RPA_*`。后端业务参数使用 `FREIGHT_RPA_<配置项>`,后端与 Windows Worker 的共享目录/标识使用 `FREIGHT_RPA_SHARED_*`,Windows Worker 自身运行参数使用 `FREIGHT_RPA_WORKER_*`,平台凭据主密钥使用 `FREIGHT_RPA_CREDENTIAL_KEY`。禁止新增 `SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`。历史名称 `SHIPPING_NOTICE_RPA_*` 于 2026-09-18 未上线期一刀切废弃,**不设兼容层**;RPA 运行期数据统一存放于独立 `freight_rpa/` 根下,按 `inventory/`、`receipt/`、`common/` 分域(common 仅放跨 Worker 共享物,如 browser_profile)。 - **RPA 命名空间(强制,2026-09-18 修订)**:货代 RPA(库存/收料/上传及后续新增 Worker)统一使用 `FREIGHT_RPA_*`。后端业务参数使用 `FREIGHT_RPA_<配置项>`,后端与 Windows Worker 的共享目录/标识使用 `FREIGHT_RPA_SHARED_*`,Windows Worker 自身运行参数使用 `FREIGHT_RPA_WORKER_*`,平台凭据主密钥使用 `FREIGHT_RPA_CREDENTIAL_KEY`。禁止新增 `SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`。历史名称 `SHIPPING_NOTICE_RPA_*` 于 2026-09-18 未上线期一刀切废弃,**不设兼容层**;RPA 运行期数据统一存放于独立 `freight_rpa/` 根下,按 `onhand/`、`inbound/`、`outbound/`(抓取域,叶目录同构 triggers/drop/logs/archives)、`upload/`(上传域,triggers/queue)、`common/`(跨 Worker 共享物,如 browser_profile)分域(2026-10-16 批次 R:原 inventory/receipt 已随迁)。
- **跨环境一致性**:`.env.dev`、`.env.test`、`.env.prod` 使用相同章节骨架;同名变量保持相同相对位置,便于审查差异;新增变量时同步检查所有适用环境文件和上述权威文档。 - **跨环境一致性**:`.env.dev`、`.env.test`、`.env.prod` 使用相同章节骨架;同名变量保持相同相对位置,便于审查差异;新增变量时同步检查所有适用环境文件和上述权威文档。
- **调整红线**:重排环境变量时只能移动“注释 + 完整赋值行”,禁止修改变量名或值,禁止删除变量、注释或示例;真实密码、密钥、Token、Webhook 与生产连接信息必须由系统环境变量、Jenkins/CI 或 Secret 管理机制注入。 - **调整红线**:重排环境变量时只能移动“注释 + 完整赋值行”,禁止修改变量名或值,禁止删除变量、注释或示例;真实密码、密钥、Token、Webhook 与生产连接信息必须由系统环境变量、Jenkins/CI 或 Secret 管理机制注入。
@@ -204,9 +205,10 @@ docker compose logs -f hxops-backend
| 环境变量 | [docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md) · [docs/convention/环境变量规则.md](docs/convention/环境变量规则.md) | | 环境变量 | [docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md) · [docs/convention/环境变量规则.md](docs/convention/环境变量规则.md) |
| 知识库部署 | [docs/knowledge_base_runtime_deploy.md](docs/knowledge_base_runtime_deploy.md) | | 知识库部署 | [docs/knowledge_base_runtime_deploy.md](docs/knowledge_base_runtime_deploy.md) |
| Excel/CSV 切块与 Dify 分段 | [docs/kb-excel-dify-chunking.md](docs/kb-excel-dify-chunking.md) | | Excel/CSV 切块与 Dify 分段 | [docs/kb-excel-dify-chunking.md](docs/kb-excel-dify-chunking.md) |
| FAQ 缓存 / 热点发现运维 | [docs/faq_cache_ops_manual.md](docs/faq_cache_ops_manual.md) | | FAQ 缓存 / 热点发现运维 | [docs/features/faq/faq_cache_ops_manual.md](docs/features/faq/faq_cache_ops_manual.md) |
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) | | 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) |
| 前端架构规范 | [docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md) | | 前端架构规范 | [docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md) |
| 前端 Element Plus | [docs/ui/ELEMENT_MIGRATION.md](docs/ui/ELEMENT_MIGRATION.md) |
| 错误处理规范 | [docs/convention/error_handling.md](docs/convention/error_handling.md) | | 错误处理规范 | [docs/convention/error_handling.md](docs/convention/error_handling.md) |
| Cursor Skills 索引 | [docs/skills/README.md](docs/skills/README.md) | | Cursor Skills 索引 | [docs/skills/README.md](docs/skills/README.md) |
| 前端四语言 i18n Skill | [docs/skills/add-i18n-keys-skill.md](docs/skills/add-i18n-keys-skill.md) | | 前端四语言 i18n Skill | [docs/skills/add-i18n-keys-skill.md](docs/skills/add-i18n-keys-skill.md) |
Vendored
+23
View File
@@ -353,6 +353,29 @@ pipeline {
} }
} }
stage('Frontend Lint') {
when {
expression { env.FRONTEND_CHANGED == 'true' }
}
steps {
echo '[Frontend Lint] FRONTEND_CHANGED=true,执行 npm run lint(Element 规则当前为 off)'
sh '''
set -eu
test -f "${WORKSPACE}/scripts/ci_frontend_lint.sh"
test -f "${WORKSPACE}/frontend/package.json"
# 不用 -v 挂载工作区:Jenkins 在容器里时,宿主机 Docker 看不到 /var/jenkins_home。
# 把前端源码和脚本打进容器再检查。node_modules 由容器内 npm ci 安装。
tar -C "${WORKSPACE}" \
--exclude=frontend/node_modules \
--exclude=frontend/dist \
-cf - \
frontend scripts/ci_frontend_lint.sh \
| docker run --rm -i node:22-alpine \
sh -c 'mkdir -p /repo && tar -xf - -C /repo && sh /repo/scripts/ci_frontend_lint.sh'
'''
}
}
// stage('Frontend Build (CI)') { // stage('Frontend Build (CI)') {
// when { // when {
// expression { env.FRONTEND_CHANGED == 'true' } // expression { env.FRONTEND_CHANGED == 'true' }
+20 -1
View File
@@ -79,6 +79,20 @@ def create_app(config_name='default'):
_transfer_capabilities.register_transfer_capabilities() _transfer_capabilities.register_transfer_capabilities()
# onhand/inbound/outbound RPA 回调 sink 注册(幂等):按消费域分组合根——
# onhand → shipping_notice.rpa_sinks;inbound/outbound → in_transit_transfer.rpa_sinks。
# 进度类经 callback_sinks.dispatch_sink;文件事实经 reports.dispatch;
# 未注册 kind 显式 404(FREIGHT_RPA.SINK_NOT_REGISTERED)。
from app.services.in_transit_transfer.rpa_sinks import (
register_inbound_sinks,
register_outbound_sinks,
)
from app.services.shipping_notice.rpa_sinks import register_onhand_sinks
register_onhand_sinks()
register_inbound_sinks()
register_outbound_sinks()
# 启动时强制加载一次,避免 worker 冷启动到首个请求之间仍用镜像默认值。 # 启动时强制加载一次,避免 worker 冷启动到首个请求之间仍用镜像默认值。
with app.app_context(): with app.app_context():
_apply_persisted_settings(app, force=True) _apply_persisted_settings(app, force=True)
@@ -122,6 +136,11 @@ def create_app(config_name='default'):
ensure_default_contract_payment_schedules() ensure_default_contract_payment_schedules()
except Exception as exc: # pragma: no cover - 表未就绪时容忍 except Exception as exc: # pragma: no cover - 表未就绪时容忍
logger.warning('Failed to ensure contract-payment schedules: %s', exc) logger.warning('Failed to ensure contract-payment schedules: %s', exc)
try:
from app.services.equipment_acceptance.schedule_seed import ensure_default_equipment_acceptance_schedules
ensure_default_equipment_acceptance_schedules()
except Exception as exc: # pragma: no cover - 表未就绪时容忍
logger.warning('Failed to ensure equipment-acceptance schedules: %s', exc)
try: try:
from app.services.order_delivery_reply.schedule_seed import ensure_default_order_delivery_schedules from app.services.order_delivery_reply.schedule_seed import ensure_default_order_delivery_schedules
ensure_default_order_delivery_schedules() ensure_default_order_delivery_schedules()
@@ -144,7 +163,7 @@ def create_app(config_name='default'):
# 负责(dev Wave 4),Web 进程不再兜底扫描。 # 负责(dev Wave 4),Web 进程不再兜底扫描。
# AUTO_UPLOAD 显式开启时启动级校验货代上传 RPA(仅告警,不阻断启动)。 # AUTO_UPLOAD 显式开启时启动级校验货代上传 RPA(仅告警,不阻断启动)。
try: try:
from app.services.shipping_notice.rpa_worker_heartbeat import ( from app.services.freight_rpa.common.worker_heartbeat import (
log_auto_upload_readiness_at_startup, log_auto_upload_readiness_at_startup,
) )
log_auto_upload_readiness_at_startup(app) log_auto_upload_readiness_at_startup(app)
+4
View File
@@ -47,8 +47,10 @@ def register_blueprints(app: Flask) -> None:
procurement_contract_bp, procurement_contract_bp,
shipping_notice_bp, shipping_notice_bp,
) )
from app.api.freight_rpa import freight_rpa_bp
from app.api.files import files_bp from app.api.files import files_bp
from app.api.contract_payment import contract_payment_bp from app.api.contract_payment import contract_payment_bp
from app.api.equipment_acceptance import equipment_acceptance_bp
from app.api.order_delivery_reply import order_delivery_reply_bp from app.api.order_delivery_reply import order_delivery_reply_bp
from app.api.in_transit_transfer import in_transit_transfer_bp from app.api.in_transit_transfer import in_transit_transfer_bp
from app.api.integration_connector import integration_connector_bp from app.api.integration_connector import integration_connector_bp
@@ -70,6 +72,7 @@ def register_blueprints(app: Flask) -> None:
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs') app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance') app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance')
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice') app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
app.register_blueprint(freight_rpa_bp, url_prefix='/api/freight-rpa')
app.register_blueprint(file_check_bp, url_prefix='/api/file-check') app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context') app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context')
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance') app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
@@ -81,6 +84,7 @@ def register_blueprints(app: Flask) -> None:
app.register_blueprint(files_bp, url_prefix='/api/files') app.register_blueprint(files_bp, url_prefix='/api/files')
app.register_blueprint(procurement_contract_bp, url_prefix='/api/procurement-contract') app.register_blueprint(procurement_contract_bp, url_prefix='/api/procurement-contract')
app.register_blueprint(contract_payment_bp, url_prefix='/api/contract-payment') app.register_blueprint(contract_payment_bp, url_prefix='/api/contract-payment')
app.register_blueprint(equipment_acceptance_bp, url_prefix='/api/equipment-acceptance')
app.register_blueprint(order_delivery_reply_bp, url_prefix='/api/order-delivery-reply') app.register_blueprint(order_delivery_reply_bp, url_prefix='/api/order-delivery-reply')
app.register_blueprint(in_transit_transfer_bp, url_prefix='/api/in-transit-transfer') app.register_blueprint(in_transit_transfer_bp, url_prefix='/api/in-transit-transfer')
app.register_blueprint(integration_connector_bp, url_prefix='/api/integration-connector') app.register_blueprint(integration_connector_bp, url_prefix='/api/integration-connector')
+3 -1
View File
@@ -23,7 +23,8 @@ import app.api.admin.shipping_order_extraction # noqa: F401
import app.api.admin.announcements # noqa: F401 import app.api.admin.announcements # noqa: F401
import app.api.admin.shipping_customers # noqa: F401 import app.api.admin.shipping_customers # noqa: F401
import app.api.admin.shipping_identity_rules # noqa: F401 import app.api.admin.shipping_identity_rules # noqa: F401
import app.api.admin.shipping_inventory # noqa: F401 import app.api.admin.shipping_notice_admin # noqa: F401
import app.api.admin_freight_rpa # noqa: F401
import app.api.admin.shipping_order_schema # noqa: F401 import app.api.admin.shipping_order_schema # noqa: F401
import app.api.admin.shipping_field_assets # noqa: F401 import app.api.admin.shipping_field_assets # noqa: F401
import app.api.admin.shipping_order_document_profiles # noqa: F401 import app.api.admin.shipping_order_document_profiles # noqa: F401
@@ -32,5 +33,6 @@ import app.api.admin.shipping_process_gate # noqa: F401
import app.api.admin.linked_services # noqa: F401 import app.api.admin.linked_services # noqa: F401
import app.api.admin.procurement_contract # noqa: F401 import app.api.admin.procurement_contract # noqa: F401
import app.api.admin.training_configs # noqa: F401 import app.api.admin.training_configs # noqa: F401
import app.api.admin.transfer_type # noqa: F401
__all__ = ['admin_bp'] __all__ = ['admin_bp']
-617
View File
@@ -1,617 +0,0 @@
"""
api/admin/shipping_inventory.py
用途:提供库存源、RPA Profile、路由规则及外部系统映射的管理 API。
依赖:admin blueprint、require_admin、shipping_inventory_service。
逻辑:路由只处理鉴权和 JSON 参数,业务校验、凭据加密及事务由服务层完成。
"""
from __future__ import annotations
import json
from flask import g, request, send_file
from app.api.admin.blueprint import admin_bp
from app.core.decorators import require_admin
from app.core.errors import ConflictError
from app.core.response import ok
from app.services.admin import shipping_inventory_service
from app.services.shipping_notice.order_schema import service as order_schema_service
from app.services.shipping_notice import inventory_parsing_profile
from app.services.shipping_notice import excel_template
from app.services.shipping_notice import inventory_field_catalog
from app.services.shipping_notice import inventory_structure_analysis
def _actor_id() -> int | None:
"""取得 require_admin 已写入请求上下文的管理员 ID。"""
return getattr(getattr(g, 'current_user', None), 'id', None)
def _ok(data, *, status: int = 200):
"""按平台统一 envelope 返回管理 API 成功结果。"""
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
@admin_bp.route('/shipping-notice/excel-templates', methods=['GET'])
@require_admin
def list_shipping_excel_templates():
"""列出版本化发货 Excel 模板。"""
return _ok(excel_template.list_templates())
@admin_bp.route('/shipping-notice/excel-templates', methods=['POST'])
@require_admin
def create_shipping_excel_template():
"""上传 xlsx 并创建模板草稿版本。"""
try:
definition = json.loads(request.form.get('definition') or '{}')
except json.JSONDecodeError as exc:
from app.core.errors import ValidationError
raise ValidationError('definition must be valid JSON', code='SHIPPING.EXCEL_TEMPLATE_INVALID') from exc
data = {
'template_code': request.form.get('template_code'),
'display_name': request.form.get('display_name'),
'definition': definition,
}
return _ok(excel_template.create_draft(request.files.get('file'), data, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>', methods=['PUT'])
@require_admin
def update_shipping_excel_template(template_id: int):
"""更新 Excel 模板草稿定义。"""
return _ok(excel_template.update_draft(template_id, request.get_json(silent=True) or {}))
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/layout', methods=['GET'])
@require_admin
def get_shipping_excel_template_layout(template_id: int):
"""读取已保存模板的工作表和栏位,编辑时无需重新上传 Excel。"""
return _ok(excel_template.get_layout(template_id))
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/new-version', methods=['POST'])
@require_admin
def create_shipping_excel_template_version(template_id: int):
"""复制现有模板文件和映射定义,创建新的草稿版本。"""
return _ok(excel_template.create_draft_from_existing(template_id, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/clone', methods=['POST'])
@require_admin
def clone_shipping_excel_template(template_id: int):
"""复制已有模板为使用新编码的独立 v1 草稿。"""
return _ok(excel_template.clone_as_new_template(
template_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
), status=201)
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/publish', methods=['POST'])
@require_admin
def publish_shipping_excel_template(template_id: int):
"""校验工作簿和字段映射后发布模板。"""
return _ok(excel_template.publish(template_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_excel_template(template_id: int):
"""退役没有启用库存源引用的模板。"""
return _ok(excel_template.retire(template_id))
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>', methods=['DELETE'])
@require_admin
def delete_shipping_excel_template(template_id: int):
"""删除从未发布且未使用的模板草稿。"""
excel_template.delete_draft(template_id)
return '', 204
@admin_bp.route('/shipping-notice/rpa-profiles', methods=['GET'])
@require_admin
def list_shipping_rpa_profiles():
"""列出脱敏后的 RPA Profile 配置。"""
return _ok(shipping_inventory_service.list_profiles())
@admin_bp.route('/shipping-notice/rpa-profiles', methods=['POST'])
@require_admin
def create_shipping_rpa_profile():
"""创建 RPA Profile;明文凭据仅在本次请求内用于加密。"""
return _ok(shipping_inventory_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/rpa-profiles/<int:profile_id>', methods=['PUT'])
@require_admin
def update_shipping_rpa_profile(profile_id: int):
"""更新 RPA Profile;未提交密码字段时保留既有密文。"""
return _ok(shipping_inventory_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id))
@admin_bp.route('/shipping-notice/rpa-profiles/<int:profile_id>', methods=['DELETE'])
@require_admin
def delete_shipping_rpa_profile(profile_id: int):
"""删除没有库存源引用的错误连接配置。"""
shipping_inventory_service.delete_profile(profile_id)
return '', 204
@admin_bp.route('/shipping-notice/sources', methods=['GET'])
@require_admin
def list_shipping_inventory_sources():
"""列出库存业务来源。"""
return _ok(shipping_inventory_service.list_sources())
@admin_bp.route('/shipping-notice/sources', methods=['POST'])
@require_admin
def create_shipping_inventory_source():
"""保存停用的库存站点基础配置;正式启用由独立接口控制。"""
return _ok(shipping_inventory_service.save_source(
request.get_json(silent=True) or {}, actor_id=_actor_id(), allow_enable_transition=False,
), status=201)
@admin_bp.route('/shipping-notice/sources/<int:source_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_source(source_id: int):
"""更新库存站点业务配置;不能借由普通保存绕过启用门禁。"""
return _ok(shipping_inventory_service.save_source(
request.get_json(silent=True) or {}, actor_id=_actor_id(), source_id=source_id,
allow_enable_transition=False,
))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/receipt-report-config', methods=['GET'])
@require_admin
def get_shipping_receipt_report_config(source_id: int):
"""读取站点独立收料报表配置;库存配置和收料配置永不混写。"""
return _ok(shipping_inventory_service.get_receipt_report_config(source_id))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/receipt-report-config', methods=['PUT'])
@require_admin
def save_shipping_receipt_report_config(source_id: int):
"""保存独立收料报表配置,并由服务记录可追溯的前后快照审计。"""
return _ok(shipping_inventory_service.save_receipt_report_config(
source_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/bind-parsing-profile', methods=['POST'])
@require_admin
def bind_shipping_inventory_source_parsing_profile(source_id: int):
"""直接为停用库存站点绑定已发布解析方案;审计说明由系统自动记录。"""
payload = request.get_json(silent=True) or {}
rows = shipping_inventory_service.bind_source_parsing_profile(
[source_id], payload.get('parsing_profile_id'), actor_id=_actor_id(),
reason=str(payload.get('reason') or ''), operation='direct',
)
return _ok(rows[0])
@admin_bp.route('/shipping-notice/sources/bulk-bind-parsing-profile', methods=['POST'])
@require_admin
def bulk_bind_shipping_inventory_source_parsing_profile():
"""原子批量绑定已发布解析方案;任一站点预检失败则整批不写入。"""
payload = request.get_json(silent=True) or {}
source_ids = payload.get('source_ids')
if not isinstance(source_ids, list):
source_ids = []
return _ok(shipping_inventory_service.bind_source_parsing_profile(
source_ids, payload.get('parsing_profile_id'), actor_id=_actor_id(),
reason=str(payload.get('reason') or ''), operation='bulk',
))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/parsing-binding-audits', methods=['GET'])
@require_admin
def list_shipping_inventory_source_parsing_binding_audits(source_id: int):
"""返回库存站点的解析方案绑定审计,不包含任何 RPA 凭据。"""
return _ok(shipping_inventory_service.get_source_parsing_binding_audits(source_id))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/activate', methods=['POST'])
@require_admin
def activate_shipping_inventory_source(source_id: int):
"""仅在库存站点完成测试与必需绑定后启用正式运行。"""
return _ok(shipping_inventory_service.activate_source(source_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/deactivate', methods=['POST'])
@require_admin
def deactivate_shipping_inventory_source(source_id: int):
"""停用库存站点而不删除已有配置和运行审计。"""
return _ok(shipping_inventory_service.deactivate_source(source_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/sources/<int:source_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_source(source_id: int):
"""删除无运行/路由引用的错误库存源。"""
shipping_inventory_service.delete_source(source_id)
return '', 204
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export', methods=['POST'])
@require_admin
def start_shipping_inventory_configuration_test(source_id: int):
"""为停用库存站点发起异步测试导出,不产生生产库存快照。"""
from app.services.shipping_notice import inventory_configuration_test
return _ok(inventory_configuration_test.start_test_export(source_id, actor_id=_actor_id()), status=202)
@admin_bp.route('/shipping-notice/source-validation-batches', methods=['POST'])
@require_admin
def start_shipping_inventory_validation_batch():
"""为多个停用且已绑定发布解析方案的站点发起批量测试验证。"""
from app.services.shipping_notice import inventory_configuration_test
payload = request.get_json(silent=True) or {}
return _ok(inventory_configuration_test.start_batch_test_export(
payload.get('source_ids') or [], actor_id=_actor_id(),
), status=202)
@admin_bp.route('/shipping-notice/source-validation-batches/latest-active', methods=['GET'])
@require_admin
def get_latest_active_shipping_inventory_validation_batch():
"""恢复最近未结束的批量验证,避免页面刷新后丢失进度。"""
from app.services.shipping_notice import inventory_configuration_test
return _ok(inventory_configuration_test.get_latest_active_validation_batch())
@admin_bp.route('/shipping-notice/source-validation-batches/<int:batch_id>', methods=['GET'])
@require_admin
def get_shipping_inventory_validation_batch(batch_id: int):
"""读取批量验证汇总进度及每个站点的独立测试结果。"""
from app.services.shipping_notice import inventory_configuration_test
return _ok(inventory_configuration_test.get_validation_batch(batch_id))
@admin_bp.route('/shipping-notice/source-validation-batches/<int:batch_id>/retry-failed', methods=['POST'])
@require_admin
def retry_failed_shipping_inventory_validation_batch(batch_id: int):
"""只重试批次中失败或配置已过期的站点,不重复导出成功项。"""
from app.services.shipping_notice import inventory_configuration_test
return _ok(inventory_configuration_test.retry_failed_validation_batch(batch_id, actor_id=_actor_id()), status=202)
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export/latest', methods=['GET'])
@require_admin
def get_latest_shipping_inventory_configuration_test(source_id: int):
"""读取当前库存站点配置对应的最近测试,使管理端可恢复异步执行状态。"""
from app.services.shipping_notice import inventory_configuration_test
return _ok(inventory_configuration_test.get_latest_test_run(source_id))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export/<string:run_no>', methods=['GET'])
@require_admin
def get_shipping_inventory_configuration_test(source_id: int, run_no: str):
"""读取库存站点测试导出的异步执行状态与结构识别结果。"""
from app.services.shipping_notice import inventory_configuration_test
return _ok(inventory_configuration_test.get_test_run(source_id, run_no))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export/<string:run_no>/confirm-profile', methods=['POST'])
@require_admin
def confirm_shipping_inventory_configuration_test_profile(source_id: int, run_no: str):
"""确认测试结果采用的解析方案,并更新仍停用的库存站点绑定。"""
from app.services.shipping_notice import inventory_configuration_test
payload = request.get_json(silent=True) or {}
return _ok(inventory_configuration_test.confirm_test_profile(
source_id, run_no, int(payload.get('profile_id') or 0), actor_id=_actor_id(),
))
@admin_bp.route('/shipping-notice/snapshots', methods=['GET'])
@require_admin
def list_shipping_inventory_snapshots():
"""列出库存快照的管理端只读记录。"""
return _ok(shipping_inventory_service.list_snapshots())
@admin_bp.route('/shipping-notice/snapshots/<int:snapshot_id>/download', methods=['GET'])
@require_admin
def download_shipping_inventory_snapshot(snapshot_id: int):
"""下载管理员选定的已托管库存快照,不向前端暴露服务器存储路径。"""
path, filename = shipping_inventory_service.get_snapshot_download(snapshot_id)
return send_file(path, as_attachment=True, download_name=filename)
@admin_bp.route('/shipping-notice/export-records', methods=['GET'])
@require_admin
def list_shipping_inventory_export_records():
"""列出 RPA 导出结果;失败后应修复配置并重新创建运行。"""
return _ok(shipping_inventory_service.list_export_records())
@admin_bp.route('/shipping-notice/routing-rules', methods=['GET'])
@require_admin
def list_shipping_inventory_rules():
"""列出库存源路由规则及条件。"""
return _ok(shipping_inventory_service.list_rules())
@admin_bp.route('/shipping-notice/routing-fields', methods=['GET'])
@require_admin
def list_shipping_inventory_routing_fields():
"""返回路由规则可引用的已发布订单字段;路由不再读取固定系统投影。"""
try:
contract = order_schema_service.get_published_contract()
order_fields = contract['fields']
published = True
except ConflictError as exc:
if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED':
raise
order_fields = []
published = False
return _ok({
'order_fields': order_fields,
'order_schema_published': published,
})
@admin_bp.route('/shipping-notice/inventory-fields', methods=['GET'])
@require_admin
def list_shipping_inventory_fields():
"""列出库存统一业务字段;管理工作区可查看已停用字段。"""
return _ok(inventory_field_catalog.list_fields(include_retired=request.args.get('include_retired') == 'true'))
@admin_bp.route('/shipping-notice/inventory-fields', methods=['POST'])
@require_admin
def create_shipping_inventory_field():
"""创建可由 DBS、Crane 等多个库存解析方案复用的扩展业务字段。"""
return _ok(inventory_field_catalog.create_field(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/inventory-fields/<int:field_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_field(field_id: int):
"""更新库存业务字段的名称、说明、格式和展示顺序。"""
return _ok(inventory_field_catalog.update_field(field_id, request.get_json(silent=True) or {}, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/inventory-fields/<int:field_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_inventory_field(field_id: int):
"""停用无引用的扩展库存字段,核心字段始终由服务层保护。"""
return _ok(inventory_field_catalog.retire_field(field_id))
@admin_bp.route('/shipping-notice/inventory-fields/<int:field_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_field(field_id: int):
"""删除未被配置引用的扩展库存字段。"""
inventory_field_catalog.delete_field(field_id)
return '', 204
@admin_bp.route('/shipping-notice/configuration-catalog', methods=['GET'])
@require_admin
def get_shipping_inventory_configuration_catalog():
"""返回 Profile、模板和路由编辑器共用的后端受控字段目录。"""
from app.services.shipping_notice.excel_template import (
ALLOWED_FORMATTERS,
ALLOWED_ROW_MODES,
ALLOWED_SOURCE_KINDS,
ALLOWED_SYSTEM_FACTS,
)
try:
contract = order_schema_service.get_published_contract()
order_fields = contract['fields']
published = True
except ConflictError as exc:
if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED':
raise
order_fields = []
published = False
return _ok({
'order_fields': order_fields,
'order_schema_published': published,
'inventory_fields': inventory_field_catalog.list_fields(),
'template_system_facts': sorted(ALLOWED_SYSTEM_FACTS),
'template_source_kinds': sorted(ALLOWED_SOURCE_KINDS),
'template_row_modes': sorted(ALLOWED_ROW_MODES),
'template_formatters': sorted(ALLOWED_FORMATTERS),
})
@admin_bp.route('/shipping-notice/movement-fields', methods=['GET'])
@require_admin
def list_movement_fields():
"""标准异动字段目录(只读领域契约,供收料异动解析规则映射表单;禁止增删)。"""
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
return _ok([
{
'code': field.code, 'value_type': str(field.value_type),
'required': bool(field.required), 'is_identity': bool(field.is_identity),
}
for field in MOVEMENT_FIELDS
])
@admin_bp.route('/shipping-notice/parsing-profiles', methods=['GET'])
@require_admin
def list_shipping_inventory_parsing_profiles():
"""列出可复用库存解析 Profile 版本。"""
return _ok(inventory_parsing_profile.list_profiles())
@admin_bp.route('/shipping-notice/parsing-profiles', methods=['POST'])
@require_admin
def create_shipping_inventory_parsing_profile():
"""创建库存解析 Profile 草稿。"""
return _ok(inventory_parsing_profile.save_draft(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_parsing_profile(profile_id: int):
"""更新库存解析 Profile 草稿。"""
return _ok(inventory_parsing_profile.save_draft(
request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id,
))
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>/sample-replacement-preview/<int:analysis_id>', methods=['POST'])
@require_admin
def preview_shipping_inventory_sample_replacement(profile_id: int, analysis_id: int):
"""比较库存映射草稿当前样本与候选样本,替换前必须由管理员确认差异。"""
return _ok(inventory_structure_analysis.preview_profile_sample_replacement(
profile_id, analysis_id, request.get_json(silent=True) or {},
))
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>/publish', methods=['POST'])
@require_admin
def publish_shipping_inventory_parsing_profile(profile_id: int):
"""发布库存解析 Profile。"""
return _ok(inventory_parsing_profile.publish(profile_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_inventory_parsing_profile(profile_id: int):
"""退役无库存源引用的已发布解析 Profile。"""
return _ok(inventory_parsing_profile.retire(profile_id))
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_parsing_profile(profile_id: int):
"""删除从未发布的解析 Profile 草稿。"""
inventory_parsing_profile.delete_draft(profile_id)
return '', 204
@admin_bp.route('/shipping-notice/inventory-structure-analyses', methods=['POST'])
@require_admin
def create_shipping_inventory_structure_analysis():
"""上传库存样本并返回后端分析出的工作表、表头、栏位和建议。"""
return _ok(inventory_structure_analysis.create_sample_upload(
request.files.get('file'), actor_id=_actor_id(),
), status=201)
@admin_bp.route('/shipping-notice/inventory-structure-analyses/<int:analysis_id>', methods=['GET'])
@require_admin
def get_shipping_inventory_structure_analysis(analysis_id: int):
"""读取库存样本结构分析结果,供管理端继续配置解析方案。"""
return _ok(inventory_structure_analysis.get_analysis(analysis_id))
@admin_bp.route('/shipping-notice/inventory-structure-analyses/<int:analysis_id>/create-profile-draft', methods=['POST'])
@require_admin
def create_shipping_inventory_parsing_draft_from_analysis(analysis_id: int):
"""使用确认后的真实表头和匹配键创建库存文件解析方案草稿。"""
return _ok(inventory_structure_analysis.create_profile_draft(
analysis_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
), status=201)
@admin_bp.route('/shipping-notice/inventory-structure-analyses/<int:analysis_id>/adopt-profile', methods=['POST'])
@require_admin
def adopt_shipping_inventory_parsing_profile(analysis_id: int):
"""确认复用推荐的已发布库存文件解析方案,不修改库存站点绑定。"""
payload = request.get_json(silent=True) or {}
return _ok(inventory_structure_analysis.adopt_published_profile(
analysis_id, int(payload.get('profile_id') or 0),
))
@admin_bp.route('/shipping-notice/temporary-inventory-sessions', methods=['GET'])
@require_admin
def list_confirmed_shipping_temporary_inventory_sessions():
"""列出已通过质量校验、可供管理员沉淀为解析方案草稿的对话临时库存会话。"""
from app.services.shipping_notice import inventory_temporary_session
return _ok(inventory_temporary_session.list_confirmed_temporary_inventory_sessions())
@admin_bp.route('/shipping-notice/temporary-inventory-sessions/<string:session_no>/create-profile-draft', methods=['POST'])
@require_admin
def create_shipping_parsing_draft_from_temporary_inventory_session(session_no: str):
"""管理员将已确认临时会话锁定映射复制为解析方案草稿;发布仍走既有门禁。"""
from app.services.shipping_notice import inventory_temporary_session
return _ok(inventory_temporary_session.create_parsing_profile_draft_from_temporary_session(
session_no, request.get_json(silent=True) or {}, actor_id=_actor_id(),
), status=201)
@admin_bp.route('/shipping-notice/routing-rules', methods=['POST'])
@require_admin
def create_shipping_inventory_rule():
"""创建草稿路由规则。"""
return _ok(shipping_inventory_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/routing-rules/<int:rule_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_rule(rule_id: int):
"""更新草稿规则;已发布规则由服务层拒绝原地修改。"""
return _ok(shipping_inventory_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id(), rule_id=rule_id))
@admin_bp.route('/shipping-notice/routing-rules/<int:rule_id>/publish', methods=['POST'])
@require_admin
def publish_shipping_inventory_rule(rule_id: int):
"""发布草稿规则并写入不可变定义快照。"""
return _ok(shipping_inventory_service.publish_rule(rule_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/routing-rules/<int:rule_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_inventory_rule(rule_id: int):
"""归档已发布规则,保留其审计版本但停止新路由使用。"""
return _ok(shipping_inventory_service.retire_rule(rule_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/routing-rules/<int:rule_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_rule(rule_id: int):
"""删除从未发布的草稿规则。"""
shipping_inventory_service.delete_draft_rule(rule_id)
return '', 204
@admin_bp.route('/shipping-notice/external-mappings', methods=['GET'])
@require_admin
def list_shipping_inventory_external_mappings():
"""列出库存源到外部系统仓库映射。"""
return _ok(shipping_inventory_service.list_external_mappings())
@admin_bp.route('/shipping-notice/external-mappings', methods=['POST'])
@require_admin
def create_shipping_inventory_external_mapping():
"""创建精确或 Source 默认外部系统映射。"""
return _ok(shipping_inventory_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/external-mappings/<int:mapping_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_external_mapping(mapping_id: int):
"""更新外部系统映射,不参与任何调拨动作。"""
return _ok(shipping_inventory_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id(), mapping_id=mapping_id))
@admin_bp.route('/shipping-notice/external-mappings/<int:mapping_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_external_mapping(mapping_id: int):
"""删除错误的外部系统仓库映射。"""
shipping_inventory_service.delete_external_mapping(mapping_id)
return '', 204
@@ -0,0 +1,126 @@
"""
api/admin/shipping_notice_admin.py
用途:发货通知仍留在本蓝图的管理面——Excel 模板、临时在手会话。
依赖:admin blueprint、require_admin、excel_template、临时会话服务。
逻辑:货代 RPA 管理路由(含 movement-fields / 报表规则)已迁至
api/admin_freight_rpa.py 的 /api/admin/freight-rpa/;本文件不再注册那些路径。
临时会话只改路径段 temporary-onhand-sessions,仍挂在 /shipping-notice/。
"""
from __future__ import annotations
import json
from flask import g, request
from app.api.admin.blueprint import admin_bp
from app.core.decorators import require_admin
from app.core.response import ok
from app.services.shipping_notice import excel_template
def _actor_id() -> int | None:
"""取得 require_admin 已写入请求上下文的管理员 ID。"""
return getattr(getattr(g, 'current_user', None), 'id', None)
def _ok(data, *, status: int = 200):
"""按平台统一 envelope 返回管理 API 成功结果。"""
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
@admin_bp.route('/shipping-notice/excel-templates', methods=['GET'])
@require_admin
def list_shipping_excel_templates():
"""列出版本化发货 Excel 模板。"""
return _ok(excel_template.list_templates())
@admin_bp.route('/shipping-notice/excel-templates', methods=['POST'])
@require_admin
def create_shipping_excel_template():
"""上传 xlsx 并创建模板草稿版本。"""
try:
definition = json.loads(request.form.get('definition') or '{}')
except json.JSONDecodeError as exc:
from app.core.errors import ValidationError
raise ValidationError('definition must be valid JSON', code='SHIPPING.EXCEL_TEMPLATE_INVALID') from exc
data = {
'template_code': request.form.get('template_code'),
'display_name': request.form.get('display_name'),
'definition': definition,
}
return _ok(excel_template.create_draft(request.files.get('file'), data, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>', methods=['PUT'])
@require_admin
def update_shipping_excel_template(template_id: int):
"""更新 Excel 模板草稿定义。"""
return _ok(excel_template.update_draft(template_id, request.get_json(silent=True) or {}))
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/layout', methods=['GET'])
@require_admin
def get_shipping_excel_template_layout(template_id: int):
"""读取已保存模板的工作表和栏位,编辑时无需重新上传 Excel。"""
return _ok(excel_template.get_layout(template_id))
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/new-version', methods=['POST'])
@require_admin
def create_shipping_excel_template_version(template_id: int):
"""复制现有模板文件和映射定义,创建新的草稿版本。"""
return _ok(excel_template.create_draft_from_existing(template_id, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/clone', methods=['POST'])
@require_admin
def clone_shipping_excel_template(template_id: int):
"""复制已有模板为使用新编码的独立 v1 草稿。"""
return _ok(excel_template.clone_as_new_template(
template_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
), status=201)
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/publish', methods=['POST'])
@require_admin
def publish_shipping_excel_template(template_id: int):
"""校验工作簿和字段映射后发布模板。"""
return _ok(excel_template.publish(template_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_excel_template(template_id: int):
"""退役没有启用库存源引用的模板。"""
return _ok(excel_template.retire(template_id))
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>', methods=['DELETE'])
@require_admin
def delete_shipping_excel_template(template_id: int):
"""删除从未发布且未使用的模板草稿。"""
excel_template.delete_draft(template_id)
return '', 204
@admin_bp.route('/shipping-notice/temporary-onhand-sessions', methods=['GET'])
@require_admin
def list_confirmed_shipping_temporary_inventory_sessions():
"""列出已通过质量校验、可供管理员沉淀为解析方案草稿的对话临时库存会话。"""
from app.services.shipping_notice import onhand_temporary_session
return _ok(onhand_temporary_session.list_confirmed_temporary_inventory_sessions())
@admin_bp.route('/shipping-notice/temporary-onhand-sessions/<string:session_no>/create-profile-draft', methods=['POST'])
@require_admin
def create_shipping_parsing_draft_from_temporary_inventory_session(session_no: str):
"""管理员将已确认临时会话锁定映射复制为解析方案草稿;发布仍走既有门禁。"""
from app.services.shipping_notice import onhand_temporary_session
return _ok(onhand_temporary_session.create_parsing_profile_draft_from_temporary_session(
session_no, request.get_json(silent=True) or {}, actor_id=_actor_id(),
), status=201)
+157
View File
@@ -0,0 +1,157 @@
"""
api/admin/transfer_type.py
用途:调拨类型配置的管理 API(列表/创建/更新,ADR 0002 类型配置化)。
依赖:admin blueprint、require_admin、transfer_type_config_service(Task 4)。
逻辑:路由只做鉴权、参数形态门禁与错误码→HTTP 状态映射;业务校验、配置
规范化与事务全在服务层。重复 code(服务层预检)与并发唯一键冲突
(IntegrityError 兜底)统一映射 422 TRANSFER.TRANSFER_TYPE_CODE_EXISTS;
code 不可变 422;更新目标不存在 404。本模块是稳定错误码 → 前端四语言
errors.json 文案的 API 侧登记点(TRANSFER_TYPE_*/SCOPE/WAREHOUSE/TRANSFORM)。
"""
from __future__ import annotations
from flask import g, request
from sqlalchemy.exc import IntegrityError
from app.api.admin.blueprint import admin_bp
from app.core.decorators import require_admin
from app.core.errors import AppError, ValidationError
from app.core.response import ok, utc_iso
from app.services.in_transit_transfer import transfer_type_config_service as service
# 稳定错误码统一转出(服务层常量 + 引擎码 + 匹配链码),避免 API 层散落字符串。
ERR_NOT_CONFIGURED = service.TRANSFER_TYPE_NOT_CONFIGURED
ERR_CODE_EXISTS = service.TRANSFER_TYPE_CODE_EXISTS
ERR_CODE_IMMUTABLE = service.TRANSFER_TYPE_CODE_IMMUTABLE
ERR_WAREHOUSE_INVALID = service.WAREHOUSE_CONFIG_INVALID
ERR_SCOPE_INVALID = "TRANSFER.SCOPE_RULE_INVALID"
ERR_TRANSFORM_INVALID = "TRANSFER.TRANSFORM_RULE_INVALID"
# 服务层业务码 → HTTP 状态映射:编码冲突/不可变是语义冲突(422)、更新目标
# 不存在(404);不在表内的码(含 VALIDATION.INVALID_PARAM 与三块配置引擎码)
# 保持 ValidationError 默认 400。
_HTTP_STATUS_BY_CODE = {
ERR_CODE_EXISTS: 422,
ERR_CODE_IMMUTABLE: 422,
ERR_NOT_CONFIGURED: 404,
}
def _actor_id() -> int | None:
"""取得 require_admin 已写入请求上下文的管理员 ID。"""
return getattr(getattr(g, 'current_user', None), 'id', None)
def _ok(data, *, status: int = 200):
"""按平台统一 envelope 返回管理 API 成功结果。"""
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
def _reraise_with_status(exc: ValidationError) -> None:
"""按稳定错误码改写 HTTP 状态后重抛;表外码原样透传(保持 400)。"""
status = _HTTP_STATUS_BY_CODE.get(exc.code)
if status is None:
raise exc
raise AppError(
code=exc.code, message=exc.message, http_status=status, details=exc.details,
) from exc
def _request_payload() -> dict:
"""读取 JSON body 并保证是 dict(非对象形态统一 400,防下游 AttributeError)。"""
payload = request.get_json(silent=True) or {}
if not isinstance(payload, dict):
raise ValidationError("request body must be a JSON object")
return payload
def _enforce_field_types(payload: dict) -> None:
"""API 层参数形态门禁:enabled 只接受布尔/整数、sort_order 只接受整数。
防御字符串形态(如 "false")绕过 API 直达服务层被 bool() 强转为真值;
业务校验(code 格式、names、三块配置)仍归服务层,此处只挡类型。
"""
if "enabled" in payload and not isinstance(payload["enabled"], (bool, int)):
raise ValidationError(
"enabled must be boolean or integer", details={"enabled": payload["enabled"]},
)
sort_order = payload.get("sort_order")
if "sort_order" in payload and (not isinstance(sort_order, int) or isinstance(sort_order, bool)):
raise ValidationError("sort_order must be integer", details={"sort_order": sort_order})
def _warehouse_role_json(role) -> dict:
"""WarehouseRole → 管理端 JSON 项(与入库规范化形态读写对称)。"""
return {
"mode": role.mode,
"warehouse_code": role.warehouse_code,
"external_org": role.external_org,
}
def _serialize_config(dto) -> dict:
"""TransferTypeConfigDTO → 管理 API 全量视图(三块配置全暴露,仅管理端可见)。"""
return {
"code": dto.code,
"names": dict(dto.names),
"enabled": dto.enabled,
"sort_order": dto.sort_order,
"scope_rules": [
{"field": rule.field, "match": rule.match, "values": list(rule.values)}
for rule in dto.scope_rules
],
"warehouse_config": {
"from": _warehouse_role_json(dto.warehouse_config.from_role),
"to": _warehouse_role_json(dto.warehouse_config.to_role),
},
"transform_rules": [
{"field": rule.field, "op": rule.op, "source": rule.source, "target": rule.target}
for rule in dto.transform_rules
],
"description": dto.description,
"updated_at": utc_iso(dto.updated_at),
}
@admin_bp.route('/in-transit-transfer/transfer-types', methods=['GET'])
@require_admin
def list_transfer_types():
"""全量类型配置(含停用),sort_order 升序——管理页列表。"""
return _ok([_serialize_config(dto) for dto in service.list_configs()])
@admin_bp.route('/in-transit-transfer/transfer-types', methods=['POST'])
@require_admin
def create_transfer_type():
"""创建类型配置;重复 code(预检或并发唯一键)统一 422。"""
payload = _request_payload()
_enforce_field_types(payload)
try:
dto = service.create_config(payload, operator_id=_actor_id())
except ValidationError as exc:
_reraise_with_status(exc)
except IntegrityError as exc:
# [防御] 服务层唯一性预检在事务之前,并发窗口漏出的唯一键冲突兜底映射
# 422,避免 500 漏给管理页(控制器裁定①)。
raise AppError(
code=ERR_CODE_EXISTS,
message="transfer type code already exists",
http_status=422,
details={},
) from exc
return _ok(_serialize_config(dto), status=201)
@admin_bp.route('/in-transit-transfer/transfer-types/<string:code>', methods=['PUT'])
@require_admin
def update_transfer_type(code: str):
"""更新类型配置(部分更新;改 code → 422,目标不存在 → 404)。"""
payload = _request_payload()
_enforce_field_types(payload)
try:
dto = service.update_config(code, payload, operator_id=_actor_id())
except ValidationError as exc:
_reraise_with_status(exc)
return _ok(_serialize_config(dto))
+543
View File
@@ -0,0 +1,543 @@
"""
api/admin_freight_rpa.py
用途:货代 RPA 管理 API,挂在 /api/admin/freight-rpa/(站点 sources、onhand 配置、
入站/出站报表配置、报表规则、异动字段目录、RPA Profile)。
依赖:admin blueprint、require_admin、freight_rpa_source_admin_service、
shipping_onhand_admin_service、freight_rpa_report_config_service、
freight_rpa.parsing_profile、
onhand 字段/结构分析服务、in_transit_transfer.movement_contract。
逻辑:路由只做鉴权与 JSON 参数;业务校验与事务留在服务层。
不保留 /shipping-notice/ 双路由。Excel 模板与 temporary-onhand-sessions
仍在 admin/shipping_notice_admin.py。
"""
from __future__ import annotations
from flask import g, request, send_file
from app.api.admin.blueprint import admin_bp
from app.core.decorators import require_admin
from app.core.errors import ConflictError
from app.core.response import ok
from app.services.admin import (
freight_rpa_report_config_service,
freight_rpa_source_admin_service,
shipping_onhand_admin_service,
)
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
from app.services.shipping_notice import onhand_field_catalog, onhand_structure_analysis
from app.services.shipping_notice.order_schema import service as order_schema_service
def _actor_id() -> int | None:
"""取得 require_admin 已写入请求上下文的管理员 ID。"""
return getattr(getattr(g, 'current_user', None), 'id', None)
def _ok(data, *, status: int = 200):
"""按平台统一 envelope 返回管理 API 成功结果。"""
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
@admin_bp.route('/freight-rpa/rpa-profiles', methods=['GET'])
@require_admin
def list_shipping_rpa_profiles():
"""列出 RPA Profile;响应含用户名明文,不含密码与密文。"""
return _ok(freight_rpa_source_admin_service.list_profiles())
@admin_bp.route('/freight-rpa/rpa-profiles', methods=['POST'])
@require_admin
def create_shipping_rpa_profile():
"""创建 RPA Profile;明文凭据仅在本次请求内用于加密。"""
return _ok(freight_rpa_source_admin_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/freight-rpa/rpa-profiles/<int:profile_id>', methods=['PUT'])
@require_admin
def update_shipping_rpa_profile(profile_id: int):
"""更新 RPA Profile;用户名与已存明文相同、或密码留空时不重写对应密文。"""
return _ok(freight_rpa_source_admin_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id))
@admin_bp.route('/freight-rpa/rpa-profiles/<int:profile_id>', methods=['DELETE'])
@require_admin
def delete_shipping_rpa_profile(profile_id: int):
"""删除没有库存源引用的错误连接配置。"""
freight_rpa_source_admin_service.delete_profile(profile_id)
return '', 204
@admin_bp.route('/freight-rpa/sources', methods=['GET'])
@require_admin
def list_shipping_inventory_sources():
"""列出库存业务来源。"""
return _ok(freight_rpa_source_admin_service.list_sources())
@admin_bp.route('/freight-rpa/sources', methods=['POST'])
@require_admin
def create_shipping_inventory_source():
"""保存停用的库存站点基础配置;正式启用由独立接口控制。"""
return _ok(freight_rpa_source_admin_service.save_source(
request.get_json(silent=True) or {}, actor_id=_actor_id(), allow_enable_transition=False,
), status=201)
@admin_bp.route('/freight-rpa/sources/<int:source_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_source(source_id: int):
"""更新库存站点业务配置;不能借由普通保存绕过启用门禁。"""
return _ok(freight_rpa_source_admin_service.save_source(
request.get_json(silent=True) or {}, actor_id=_actor_id(), source_id=source_id,
allow_enable_transition=False,
))
@admin_bp.route('/freight-rpa/sources/<int:source_id>/inbound-report-config', methods=['GET'])
@require_admin
def get_shipping_inbound_report_config(source_id: int):
"""读取站点独立入站报表配置;库存配置和入站配置永不混写。"""
return _ok(freight_rpa_report_config_service.get_inbound_report_config(source_id))
@admin_bp.route('/freight-rpa/sources/<int:source_id>/inbound-report-config', methods=['PUT'])
@require_admin
def save_shipping_inbound_report_config(source_id: int):
"""保存独立入站报表配置,并由服务记录可追溯的前后快照审计。"""
return _ok(freight_rpa_report_config_service.save_inbound_report_config(
source_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
))
@admin_bp.route('/freight-rpa/sources/<int:source_id>/outbound-report-config', methods=['GET'])
@require_admin
def get_shipping_outbound_report_config(source_id: int):
"""读取站点独立出站报表配置;库存/入站/出站配置永不混写。"""
return _ok(freight_rpa_report_config_service.get_outbound_report_config(source_id))
@admin_bp.route('/freight-rpa/sources/<int:source_id>/outbound-report-config', methods=['PUT'])
@require_admin
def save_shipping_outbound_report_config(source_id: int):
"""保存独立出站报表配置,并由服务记录可追溯的前后快照审计。"""
return _ok(freight_rpa_report_config_service.save_outbound_report_config(
source_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
))
@admin_bp.route('/freight-rpa/movement-fields', methods=['GET'])
@require_admin
def list_freight_rpa_movement_fields():
"""标准异动字段目录(只读领域契约,供入站/出站报表规则映射表单)。"""
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
return _ok([
{
'code': field.code, 'value_type': str(field.value_type),
'required': bool(field.required), 'is_identity': bool(field.is_identity),
}
for field in MOVEMENT_FIELDS
])
@admin_bp.route('/freight-rpa/sources/<int:source_id>/bind-parsing-profile', methods=['POST'])
@require_admin
def bind_shipping_inventory_source_parsing_profile(source_id: int):
"""直接为停用库存站点绑定已发布解析方案;审计说明由系统自动记录。"""
payload = request.get_json(silent=True) or {}
rows = freight_rpa_source_admin_service.bind_source_parsing_profile(
[source_id], payload.get('parsing_profile_id'), actor_id=_actor_id(),
reason=str(payload.get('reason') or ''), operation='direct',
)
return _ok(rows[0])
@admin_bp.route('/freight-rpa/sources/bulk-bind-parsing-profile', methods=['POST'])
@require_admin
def bulk_bind_shipping_inventory_source_parsing_profile():
"""原子批量绑定已发布解析方案;任一站点预检失败则整批不写入。"""
payload = request.get_json(silent=True) or {}
source_ids = payload.get('source_ids')
if not isinstance(source_ids, list):
source_ids = []
return _ok(freight_rpa_source_admin_service.bind_source_parsing_profile(
source_ids, payload.get('parsing_profile_id'), actor_id=_actor_id(),
reason=str(payload.get('reason') or ''), operation='bulk',
))
@admin_bp.route('/freight-rpa/sources/<int:source_id>/parsing-binding-audits', methods=['GET'])
@require_admin
def list_shipping_inventory_source_parsing_binding_audits(source_id: int):
"""返回库存站点的解析方案绑定审计,不包含任何 RPA 凭据。"""
return _ok(freight_rpa_source_admin_service.get_source_parsing_binding_audits(source_id))
@admin_bp.route('/freight-rpa/sources/<int:source_id>/activate', methods=['POST'])
@require_admin
def activate_shipping_inventory_source(source_id: int):
"""仅在库存站点完成测试与必需绑定后启用正式运行。"""
return _ok(freight_rpa_source_admin_service.activate_source(source_id, actor_id=_actor_id()))
@admin_bp.route('/freight-rpa/sources/<int:source_id>/deactivate', methods=['POST'])
@require_admin
def deactivate_shipping_inventory_source(source_id: int):
"""停用库存站点而不删除已有配置和运行审计。"""
return _ok(freight_rpa_source_admin_service.deactivate_source(source_id, actor_id=_actor_id()))
@admin_bp.route('/freight-rpa/sources/<int:source_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_source(source_id: int):
"""删除无运行/路由引用的错误库存源。"""
freight_rpa_source_admin_service.delete_source(source_id)
return '', 204
@admin_bp.route('/freight-rpa/sources/<int:source_id>/test-export', methods=['POST'])
@require_admin
def start_shipping_inventory_configuration_test(source_id: int):
"""为停用库存站点发起异步测试导出,不产生生产库存快照。"""
from app.services.shipping_notice import onhand_configuration_test
return _ok(onhand_configuration_test.start_test_export(source_id, actor_id=_actor_id()), status=202)
@admin_bp.route('/freight-rpa/onhand/validation-batches', methods=['POST'])
@require_admin
def start_shipping_inventory_validation_batch():
"""为多个停用且已绑定发布解析方案的站点发起批量测试验证。"""
from app.services.shipping_notice import onhand_configuration_test
payload = request.get_json(silent=True) or {}
return _ok(onhand_configuration_test.start_batch_test_export(
payload.get('source_ids') or [], actor_id=_actor_id(),
), status=202)
@admin_bp.route('/freight-rpa/onhand/validation-batches/latest-active', methods=['GET'])
@require_admin
def get_latest_active_shipping_inventory_validation_batch():
"""恢复最近未结束的批量验证,避免页面刷新后丢失进度。"""
from app.services.shipping_notice import onhand_configuration_test
return _ok(onhand_configuration_test.get_latest_active_validation_batch())
@admin_bp.route('/freight-rpa/onhand/validation-batches/<int:batch_id>', methods=['GET'])
@require_admin
def get_shipping_inventory_validation_batch(batch_id: int):
"""读取批量验证汇总进度及每个站点的独立测试结果。"""
from app.services.shipping_notice import onhand_configuration_test
return _ok(onhand_configuration_test.get_validation_batch(batch_id))
@admin_bp.route('/freight-rpa/onhand/validation-batches/<int:batch_id>/retry-failed', methods=['POST'])
@require_admin
def retry_failed_shipping_inventory_validation_batch(batch_id: int):
"""只重试批次中失败或配置已过期的站点,不重复导出成功项。"""
from app.services.shipping_notice import onhand_configuration_test
return _ok(onhand_configuration_test.retry_failed_validation_batch(batch_id, actor_id=_actor_id()), status=202)
@admin_bp.route('/freight-rpa/sources/<int:source_id>/test-export/latest', methods=['GET'])
@require_admin
def get_latest_shipping_inventory_configuration_test(source_id: int):
"""读取当前库存站点配置对应的最近测试,使管理端可恢复异步执行状态。"""
from app.services.shipping_notice import onhand_configuration_test
return _ok(onhand_configuration_test.get_latest_test_run(source_id))
@admin_bp.route('/freight-rpa/sources/<int:source_id>/test-export/<string:run_no>', methods=['GET'])
@require_admin
def get_shipping_inventory_configuration_test(source_id: int, run_no: str):
"""读取库存站点测试导出的异步执行状态与结构识别结果。"""
from app.services.shipping_notice import onhand_configuration_test
return _ok(onhand_configuration_test.get_test_run(source_id, run_no))
@admin_bp.route('/freight-rpa/sources/<int:source_id>/test-export/<string:run_no>/confirm-profile', methods=['POST'])
@require_admin
def confirm_shipping_inventory_configuration_test_profile(source_id: int, run_no: str):
"""确认测试结果采用的解析方案,并更新仍停用的库存站点绑定。"""
from app.services.shipping_notice import onhand_configuration_test
payload = request.get_json(silent=True) or {}
return _ok(onhand_configuration_test.confirm_test_profile(
source_id, run_no, int(payload.get('profile_id') or 0), actor_id=_actor_id(),
))
@admin_bp.route('/freight-rpa/onhand/snapshots', methods=['GET'])
@require_admin
def list_shipping_inventory_snapshots():
"""列出库存快照的管理端只读记录。"""
return _ok(shipping_onhand_admin_service.list_snapshots())
@admin_bp.route('/freight-rpa/onhand/snapshots/<int:snapshot_id>/download', methods=['GET'])
@require_admin
def download_shipping_inventory_snapshot(snapshot_id: int):
"""下载管理员选定的已托管库存快照,不向前端暴露服务器存储路径。"""
path, filename = shipping_onhand_admin_service.get_snapshot_download(snapshot_id)
return send_file(path, as_attachment=True, download_name=filename)
@admin_bp.route('/freight-rpa/onhand/export-records', methods=['GET'])
@require_admin
def list_shipping_inventory_export_records():
"""列出 RPA 导出结果;失败后应修复配置并重新创建运行。"""
return _ok(shipping_onhand_admin_service.list_export_records())
@admin_bp.route('/freight-rpa/onhand/routing-rules', methods=['GET'])
@require_admin
def list_shipping_inventory_rules():
"""列出库存源路由规则及条件。"""
return _ok(shipping_onhand_admin_service.list_rules())
@admin_bp.route('/freight-rpa/onhand/routing-fields', methods=['GET'])
@require_admin
def list_shipping_inventory_routing_fields():
"""返回路由规则可引用的已发布订单字段;路由不再读取固定系统投影。"""
try:
contract = order_schema_service.get_published_contract()
order_fields = contract['fields']
published = True
except ConflictError as exc:
if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED':
raise
order_fields = []
published = False
return _ok({
'order_fields': order_fields,
'order_schema_published': published,
})
@admin_bp.route('/freight-rpa/onhand/fields', methods=['GET'])
@require_admin
def list_shipping_inventory_fields():
"""列出库存统一业务字段;管理工作区可查看已停用字段。"""
return _ok(onhand_field_catalog.list_fields(include_retired=request.args.get('include_retired') == 'true'))
@admin_bp.route('/freight-rpa/onhand/fields', methods=['POST'])
@require_admin
def create_shipping_inventory_field():
"""创建可由 DBS、Crane 等多个库存解析方案复用的扩展业务字段。"""
return _ok(onhand_field_catalog.create_field(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/freight-rpa/onhand/fields/<int:field_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_field(field_id: int):
"""更新库存业务字段的名称、说明、格式和展示顺序。"""
return _ok(onhand_field_catalog.update_field(field_id, request.get_json(silent=True) or {}, actor_id=_actor_id()))
@admin_bp.route('/freight-rpa/onhand/fields/<int:field_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_inventory_field(field_id: int):
"""停用无引用的扩展库存字段,核心字段始终由服务层保护。"""
return _ok(onhand_field_catalog.retire_field(field_id))
@admin_bp.route('/freight-rpa/onhand/fields/<int:field_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_field(field_id: int):
"""删除未被配置引用的扩展库存字段。"""
onhand_field_catalog.delete_field(field_id)
return '', 204
@admin_bp.route('/freight-rpa/onhand/configuration-catalog', methods=['GET'])
@require_admin
def get_shipping_inventory_configuration_catalog():
"""返回 Profile、模板和路由编辑器共用的后端受控字段目录。"""
from app.services.shipping_notice.excel_template import (
ALLOWED_FORMATTERS,
ALLOWED_ROW_MODES,
ALLOWED_SOURCE_KINDS,
ALLOWED_SYSTEM_FACTS,
)
try:
contract = order_schema_service.get_published_contract()
order_fields = contract['fields']
published = True
except ConflictError as exc:
if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED':
raise
order_fields = []
published = False
return _ok({
'order_fields': order_fields,
'order_schema_published': published,
'inventory_fields': onhand_field_catalog.list_fields(),
'template_system_facts': sorted(ALLOWED_SYSTEM_FACTS),
'template_source_kinds': sorted(ALLOWED_SOURCE_KINDS),
'template_row_modes': sorted(ALLOWED_ROW_MODES),
'template_formatters': sorted(ALLOWED_FORMATTERS),
})
@admin_bp.route('/freight-rpa/onhand/parsing-profiles', methods=['GET'])
@require_admin
def list_shipping_inventory_parsing_profiles():
"""列出可复用库存解析 Profile 版本。"""
return _ok(onhand_parsing_profile.list_profiles())
@admin_bp.route('/freight-rpa/onhand/parsing-profiles', methods=['POST'])
@require_admin
def create_shipping_inventory_parsing_profile():
"""创建库存解析 Profile 草稿。"""
return _ok(onhand_parsing_profile.save_draft(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/freight-rpa/onhand/parsing-profiles/<int:profile_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_parsing_profile(profile_id: int):
"""更新库存解析 Profile 草稿。"""
return _ok(onhand_parsing_profile.save_draft(
request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id,
))
@admin_bp.route('/freight-rpa/onhand/parsing-profiles/<int:profile_id>/sample-replacement-preview/<int:analysis_id>', methods=['POST'])
@require_admin
def preview_shipping_inventory_sample_replacement(profile_id: int, analysis_id: int):
"""比较库存映射草稿当前样本与候选样本,替换前必须由管理员确认差异。"""
return _ok(onhand_structure_analysis.preview_profile_sample_replacement(
profile_id, analysis_id, request.get_json(silent=True) or {},
))
@admin_bp.route('/freight-rpa/onhand/parsing-profiles/<int:profile_id>/publish', methods=['POST'])
@require_admin
def publish_shipping_inventory_parsing_profile(profile_id: int):
"""发布库存解析 Profile。"""
return _ok(onhand_parsing_profile.publish(profile_id, actor_id=_actor_id()))
@admin_bp.route('/freight-rpa/onhand/parsing-profiles/<int:profile_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_inventory_parsing_profile(profile_id: int):
"""退役无库存源引用的已发布解析 Profile。"""
return _ok(onhand_parsing_profile.retire(profile_id))
@admin_bp.route('/freight-rpa/onhand/parsing-profiles/<int:profile_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_parsing_profile(profile_id: int):
"""删除从未发布的解析 Profile 草稿。"""
onhand_parsing_profile.delete_draft(profile_id)
return '', 204
@admin_bp.route('/freight-rpa/onhand/structure-analyses', methods=['POST'])
@require_admin
def create_shipping_inventory_structure_analysis():
"""上传库存样本并返回后端分析出的工作表、表头、栏位和建议。"""
return _ok(onhand_structure_analysis.create_sample_upload(
request.files.get('file'), actor_id=_actor_id(),
), status=201)
@admin_bp.route('/freight-rpa/onhand/structure-analyses/<int:analysis_id>', methods=['GET'])
@require_admin
def get_shipping_inventory_structure_analysis(analysis_id: int):
"""读取库存样本结构分析结果,供管理端继续配置解析方案。"""
return _ok(onhand_structure_analysis.get_analysis(analysis_id))
@admin_bp.route('/freight-rpa/onhand/structure-analyses/<int:analysis_id>/create-profile-draft', methods=['POST'])
@require_admin
def create_shipping_inventory_parsing_draft_from_analysis(analysis_id: int):
"""使用确认后的真实表头和匹配键创建库存文件解析方案草稿。"""
return _ok(onhand_structure_analysis.create_profile_draft(
analysis_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
), status=201)
@admin_bp.route('/freight-rpa/onhand/structure-analyses/<int:analysis_id>/adopt-profile', methods=['POST'])
@require_admin
def adopt_shipping_inventory_parsing_profile(analysis_id: int):
"""确认复用推荐的已发布库存文件解析方案,不修改库存站点绑定。"""
payload = request.get_json(silent=True) or {}
return _ok(onhand_structure_analysis.adopt_published_profile(
analysis_id, int(payload.get('profile_id') or 0),
))
@admin_bp.route('/freight-rpa/onhand/routing-rules', methods=['POST'])
@require_admin
def create_shipping_inventory_rule():
"""创建草稿路由规则。"""
return _ok(shipping_onhand_admin_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/freight-rpa/onhand/routing-rules/<int:rule_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_rule(rule_id: int):
"""更新草稿规则;已发布规则由服务层拒绝原地修改。"""
return _ok(shipping_onhand_admin_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id(), rule_id=rule_id))
@admin_bp.route('/freight-rpa/onhand/routing-rules/<int:rule_id>/publish', methods=['POST'])
@require_admin
def publish_shipping_inventory_rule(rule_id: int):
"""发布草稿规则并写入不可变定义快照。"""
return _ok(shipping_onhand_admin_service.publish_rule(rule_id, actor_id=_actor_id()))
@admin_bp.route('/freight-rpa/onhand/routing-rules/<int:rule_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_inventory_rule(rule_id: int):
"""归档已发布规则,保留其审计版本但停止新路由使用。"""
return _ok(shipping_onhand_admin_service.retire_rule(rule_id, actor_id=_actor_id()))
@admin_bp.route('/freight-rpa/onhand/routing-rules/<int:rule_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_rule(rule_id: int):
"""删除从未发布的草稿规则。"""
shipping_onhand_admin_service.delete_draft_rule(rule_id)
return '', 204
@admin_bp.route('/freight-rpa/onhand/external-mappings', methods=['GET'])
@require_admin
def list_shipping_inventory_external_mappings():
"""列出库存源到外部系统仓库映射。"""
return _ok(shipping_onhand_admin_service.list_external_mappings())
@admin_bp.route('/freight-rpa/onhand/external-mappings', methods=['POST'])
@require_admin
def create_shipping_inventory_external_mapping():
"""创建精确或 Source 默认外部系统映射。"""
return _ok(shipping_onhand_admin_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/freight-rpa/onhand/external-mappings/<int:mapping_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_external_mapping(mapping_id: int):
"""更新外部系统映射,不参与任何调拨动作。"""
return _ok(shipping_onhand_admin_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id(), mapping_id=mapping_id))
@admin_bp.route('/freight-rpa/onhand/external-mappings/<int:mapping_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_external_mapping(mapping_id: int):
"""删除错误的外部系统仓库映射。"""
shipping_onhand_admin_service.delete_external_mapping(mapping_id)
return '', 204
@@ -0,0 +1,205 @@
"""
backend/app/api/equipment_acceptance/__init__.py
用途:设备验收预警的 Chat 作业面接口。
依赖:JWT 当前用户、Agent 授权、sync_service、统一成功响应。
逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录、已归档 Excel 和配置;同步、扫描、发送和保存配置仅平台管理员。
"""
from __future__ import annotations
from io import BytesIO
from flask import Blueprint, g, request, send_file
from app.core.auth.jwt import get_current_user
from app.core.errors import ForbiddenError, UnauthorizedError
from app.core.response import ok
from app.models import Agent
from app.services.equipment_acceptance.config_service import (
get_acceptance_config,
save_acceptance_config,
)
from app.services.equipment_acceptance.alert_service import generate_alerts, send_pending_alerts
from app.services.equipment_acceptance.send_record_service import get_send_file, list_send_files, list_send_records
from app.services.equipment_acceptance.sync_service import (
get_acceptance_order,
list_acceptance_orders,
sync_acceptance_snapshots,
)
equipment_acceptance_bp = Blueprint("equipment_acceptance", __name__)
EQUIPMENT_ACCEPTANCE_AGENT_CODE = "equipment_acceptance"
def _require_user():
"""
读取当前登录用户。
Returns:
已认证用户。
Raises:
UnauthorizedError: 没有有效登录身份。
"""
user = get_current_user()
if not user:
raise UnauthorizedError()
return user
def _user_has_equipment_acceptance_agent(user) -> bool:
"""
判断用户是否持有启用中的设备验收预警 Agent。
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions。
"""
agent = Agent.query.filter_by(agent_code=EQUIPMENT_ACCEPTANCE_AGENT_CODE, is_active=True).first()
return bool(agent is not None and agent in user.agents)
def _require_equipment_acceptance_access():
"""
确保当前用户可以打开设备验收预警作业面。
核心逻辑:平台管理员放行;普通用户必须被授予启用中的 equipment_acceptance Agent。
Returns:
已认证且有权查看的用户。
Raises:
UnauthorizedError: 没有有效登录身份。
ForbiddenError: 已登录但没有该 Agent。
"""
user = _require_user()
if user.is_platform_admin() or _user_has_equipment_acceptance_agent(user):
return user
raise ForbiddenError(
"Equipment acceptance agent permission required",
code="EQUIPMENT_ACCEPTANCE.FORBIDDEN",
)
def _require_equipment_acceptance_admin():
"""
确保当前用户可以触发 E10 同步。
核心逻辑:先确认能看作业面,再要求平台管理员。同步会读取外部库并改写本地快照。
Returns:
已认证的管理员。
Raises:
ForbiddenError: 不是平台管理员。
"""
user = _require_equipment_acceptance_access()
if not user.is_platform_admin():
raise ForbiddenError(
"Admin privilege required for equipment acceptance sync",
code="EQUIPMENT_ACCEPTANCE.ADMIN_REQUIRED",
)
return user
@equipment_acceptance_bp.route("/sync", methods=["POST"])
def sync_equipment_acceptance():
"""从 E10 拉取验收单并写入本地快照。仅平台管理员。"""
_require_equipment_acceptance_admin()
return ok(sync_acceptance_snapshots(), request_id=getattr(g, "request_id", None))
@equipment_acceptance_bp.route("/orders", methods=["GET"])
def list_equipment_acceptance_orders():
"""分页查看已同步的验收单。focus 按原型分组过滤,summary 始终统计全部单据。"""
_require_equipment_acceptance_access()
page = _int_arg("page", 1)
page_size = _int_arg("page_size", 20)
payload = list_acceptance_orders(
monitor_status=request.args.get("monitor_status"),
focus=request.args.get("focus"),
page=page,
page_size=page_size,
)
return ok(payload, request_id=getattr(g, "request_id", None))
@equipment_acceptance_bp.route("/config", methods=["GET"])
def get_equipment_acceptance_config():
"""读取四档天数和三个固定岗位。候选人名单只给平台管理员。"""
user = _require_equipment_acceptance_access()
payload = get_acceptance_config(include_candidates=user.is_platform_admin())
return ok(payload, request_id=getattr(g, "request_id", None))
@equipment_acceptance_bp.route("/config", methods=["PUT"])
def save_equipment_acceptance_config():
"""保存四档天数和三个固定岗位。仅平台管理员。发送时刻不在本接口。"""
user = _require_equipment_acceptance_access()
if not user.is_platform_admin():
raise ForbiddenError(
"Admin privilege required for equipment acceptance settings",
code="EQUIPMENT_ACCEPTANCE.SETTINGS_ADMIN_REQUIRED",
)
payload = request.get_json(silent=True) or {}
saved = save_acceptance_config(payload, updated_by=user.id)
return ok(saved, request_id=getattr(g, "request_id", None))
@equipment_acceptance_bp.route("/alerts/scan", methods=["POST"])
def scan_equipment_acceptance_alerts():
"""管理员立即同步 E10 并生成待发送记录。不发企业微信。"""
_require_equipment_acceptance_admin()
return ok(generate_alerts(), request_id=getattr(g, "request_id", None))
@equipment_acceptance_bp.route("/alerts/send", methods=["POST"])
def send_equipment_acceptance_alerts():
"""管理员立即把待发送记录按收件人发到企业微信。"""
_require_equipment_acceptance_admin()
return ok(send_pending_alerts(), request_id=getattr(g, "request_id", None))
@equipment_acceptance_bp.route("/send-files", methods=["GET"])
def list_equipment_acceptance_send_files():
"""列出最近按收件人归档的 Excel。不含文件字节。"""
_require_equipment_acceptance_access()
return ok({"items": list_send_files()}, request_id=getattr(g, "request_id", None))
@equipment_acceptance_bp.route("/send-files/<int:file_id>/excel", methods=["GET"])
def download_equipment_acceptance_send_file(file_id: int):
"""下载一份当时发给收件人的设备验收预警 Excel。"""
_require_equipment_acceptance_access()
row = get_send_file(file_id)
return send_file(
BytesIO(row.excel_file_data),
as_attachment=True,
download_name=row.excel_file_name or f"equipment-acceptance-alert-{file_id}.xlsx",
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
@equipment_acceptance_bp.route("/sends", methods=["GET"])
def list_equipment_acceptance_sends():
"""分页查看发送记录。扫描写入后这里才有行。"""
_require_equipment_acceptance_access()
payload = list_send_records(page=_int_arg("page", 1), page_size=_int_arg("page_size", 20))
return ok(payload, request_id=getattr(g, "request_id", None))
@equipment_acceptance_bp.route("/orders/<int:order_id>", methods=["GET"])
def get_equipment_acceptance_order(order_id: int):
"""查看一张验收单的节点和操作人原值。"""
_require_equipment_acceptance_access()
return ok(get_acceptance_order(order_id), request_id=getattr(g, "request_id", None))
def _int_arg(name: str, default: int) -> int:
"""读取正整数查询参数,非法时用默认值。"""
raw = request.args.get(name)
if raw is None or str(raw).strip() == "":
return default
try:
return int(raw)
except (TypeError, ValueError):
return default
+261
View File
@@ -0,0 +1,261 @@
"""
backend/app/api/freight_rpa.py
用途:货代 RPA 回调蓝图(/api/freight-rpa/*)——Windows Worker 向后端上报心跳、
库存(onhand)/入站(inbound)/出站(outbound)导出结果与货代上传结果的唯一回调入口。
批次 R 解耦后取代旧 shipping-notice rpa 回调前缀(无双路由、无兼容层)。
依赖:app.core.tool_auth(集成密钥鉴权)、freight_rpa.common.callback_sinks(sink 分发)、
freight_rpa.common.worker_heartbeat(心跳)、shipping_tools。
逻辑:before_request 统一 Bearer / X-Integration-Key 鉴权(与 Tool 蓝图同一把 key)。
分发策略按「处理函数当前住在哪个包」决定:
- /heartbeat 直连 freight_rpa.common.worker_heartbeat;
- /upload-complete 直连现有业务处理器(shipping_notice.tools);
- onhand-* / inbound-* / outbound-* 全部经 callback_sinks.dispatch_sink 分发,
真实业务 sink 由组合根注册(onhand→shipping_notice.rpa_sinks;
inbound/outbound→in_transit_transfer.rpa_sinks);
未注册的 kind 显式 404(FREIGHT_RPA.SINK_NOT_REGISTERED)。
"""
from __future__ import annotations
from flask import Blueprint, current_app, jsonify, request
from app.core.errors import ValidationError
from app.core.tool_auth import require_tool_auth
from app.services.freight_rpa.common.callback_sinks import dispatch_sink
from app.services.freight_rpa.common.worker_heartbeat import record_rpa_worker_heartbeat
freight_rpa_bp = Blueprint('freight_rpa', __name__)
def _payload() -> dict:
"""
读取回调 JSON 请求体,并剥离不可信的操作人身份字段。
核心逻辑:与 shipping_notice Tool 蓝图同口径——集成密钥调用方不得通过 body
伪造 `_trusted_user_id` / `operator_id` / `actor_id`。
"""
raw = request.get_json(silent=True) or {}
if not isinstance(raw, dict):
return {}
payload = dict(raw)
for key in ('_trusted_user_id', 'operator_id', 'actor_id'):
payload.pop(key, None)
return payload
@freight_rpa_bp.before_request
def _verify_worker_access():
"""RPA Worker 回调统一 Header 鉴权;与 Tool API 共用同一集成密钥配置。"""
require_tool_auth()
return None
@freight_rpa_bp.route('/heartbeat', methods=['POST'])
def heartbeat():
"""
RPA Worker 心跳上报。
【AI 触发时机】:非 Agent 入口;Windows Worker(库存/入站)由独立守护线程周期调用。
核心逻辑:校验 payload 后写入 Redis/内存;后端在写各类 trigger 前以此做在线就绪检查。
"""
payload = _payload()
try:
worker = record_rpa_worker_heartbeat(payload)
except ValueError as exc:
raise ValidationError(str(exc))
# 心跳存储不可用(ServiceUnavailableError)原样上抛,由全局 AppError handler 出标准错误 envelope。
# 到期的 Crane 定时回查跟着心跳落成 trigger;写失败不让心跳本身失败。
try:
from app.services.freight_rpa.upload.crane_recheck import materialize_due_crane_rechecks
materialize_due_crane_rechecks()
except Exception:
current_app.logger.exception('crane recheck materialize failed')
return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker})
@freight_rpa_bp.route('/onhand-ready', methods=['POST'])
def onhand_ready():
"""
onhand 单任务导出回调(旧 inventory-ready 端点随批次 R 迁入本蓝图)。
【AI 触发时机】:非 Agent 入口;库存 Worker 完成单任务导出后调用。
核心逻辑:dispatch_sink('onhand-ready') 分发到组合根注册的业务 sink
(onhand_rpa_workflow.rpa_report_inventory:快照落盘 + 任务状态回写),
envelope = 裸业务 tool_response dict(与旧 /rpa/inventory-ready 逐字一致)。
"""
return jsonify(dispatch_sink('onhand-ready', **_payload()))
@freight_rpa_bp.route('/onhand-batch-ready', methods=['POST'])
def onhand_batch_ready():
"""
onhand 批量导出终态回调(旧 /rpa/inventory-batch-ready)。
【AI 触发时机】:非 Agent 入口;库存 Worker 按排程批次完成全部站点导出后调用。
核心逻辑:dispatch_sink('onhand-batch-ready') 分发;按 Warehouse 写入库存快照并
finalize 排程 run(rpa_report_inventory_batch),envelope = 裸业务 dict。
"""
return jsonify(dispatch_sink('onhand-batch-ready', **_payload()))
@freight_rpa_bp.route('/onhand-batch-claimed', methods=['POST'])
def onhand_batch_claimed():
"""
onhand 批量领取回调(旧 /rpa/inventory-batch-claimed)。
【AI 触发时机】:非 Agent 入口;v2 Worker 领取批次 trigger 后立即调用。
核心逻辑:dispatch_sink('onhand-batch-claimed') 分发;仅记录 Attempt 执行阶段
(per_source_rpa_service.claim_inventory_batch),envelope = {'success':True,'data':...}。
"""
return jsonify(dispatch_sink('onhand-batch-claimed', **_payload()))
@freight_rpa_bp.route('/onhand-batch-progress', methods=['POST'])
def onhand_batch_progress():
"""
onhand 批量导出进度回调(旧 /rpa/inventory-batch-progress)。
【AI 触发时机】:非 Agent 入口;Worker 每完成一个站点导出后调用(非终态,以 batch-ready 为准)。
核心逻辑:dispatch_sink('onhand-batch-progress') 分发;实时回写排程 run 计数
(onhand_rpa_workflow.report_inventory_batch_progress),envelope = 裸业务 dict。
"""
return jsonify(dispatch_sink('onhand-batch-progress', **_payload()))
@freight_rpa_bp.route('/onhand-configuration-test-start', methods=['POST'])
def onhand_configuration_test_start():
"""
onhand 配置测试开始回调(旧 /rpa/inventory-configuration-test-batch-progress)。
【AI 触发时机】:非 Agent 入口;Worker 领取批量验证中的单个站点后立即调用。
核心逻辑:dispatch_sink('onhand-configuration-test-start') 分发;把该站点测试运行写为
processing / rpa_exporting,envelope = {'status':'ok','data':...}(旧 batch-progress 同款)。
"""
return jsonify(dispatch_sink('onhand-configuration-test-start', **_payload()))
@freight_rpa_bp.route('/onhand-configuration-test-analyze', methods=['POST'])
def onhand_configuration_test_analyze():
"""
onhand 配置测试结构分析回调(旧 /rpa/inventory-configuration-test-ready)。
【AI 触发时机】:非 Agent 入口;Worker 完成单站点配置测试导出后调用。
核心逻辑:dispatch_sink('onhand-configuration-test-analyze') 分发;仅分析文件结构,
不创建生产库存快照或任务关联,envelope = {'status':'ok','data':...}(旧 ready 同款)。
"""
return jsonify(dispatch_sink('onhand-configuration-test-analyze', **_payload()))
@freight_rpa_bp.route('/onhand-configuration-test-complete', methods=['POST'])
def onhand_configuration_test_complete():
"""
onhand 配置测试批次终态回调(旧 /rpa/inventory-configuration-test-batch-ready)。
【AI 触发时机】:非 Agent 入口;Worker 完成批量配置测试后按 validation_run_no 回传 results。
核心逻辑:dispatch_sink('onhand-configuration-test-complete') 分发;独立回写每个库存站点
的测试结果,envelope = {'status':'ok','data':...}(旧 batch-ready 同款)。
"""
return jsonify(dispatch_sink('onhand-configuration-test-complete', **_payload()))
@freight_rpa_bp.route('/onhand-repair', methods=['POST'])
def onhand_repair():
"""
onhand 受控库存回调修复(旧 /rpa/inventory-repair)。
【AI 触发时机】:非 Agent 入口;人工/运维补偿链路调用,复用正式 v2 ingest 流程。
核心逻辑:dispatch_sink('onhand-repair') 分发;repair 语义由 kind 承载——sink 等价于
旧实现 `payload['repair'] = True` 后走 batch-ready ingest,envelope = 裸业务 dict。
"""
return jsonify(dispatch_sink('onhand-repair', **_payload()))
@freight_rpa_bp.route('/inbound-batch-ready', methods=['POST'])
def inbound_batch_ready():
"""
inbound(收料)批量导出终态回调(旧 /rpa/receipt-batch-ready)。
【AI 触发时机】:非 Agent 入口;入站 Worker 完成报表导出并落 drop 目录后调用。
核心逻辑:dispatch_sink('inbound-batch-ready') 分发到组合根
(in_transit_transfer.rpa_sinks)注册的业务 sink——直挂
freight_rpa.inbound.report_archive.ingest_inbound_callback 原样归档,终态 commit
后经 ReportFact → handle_inbound_report 推进调拨并归集排程;绝不进入库存匹配链路;
envelope = {'success': True, 'data': ...}(旧端点逐字一致)。
"""
return jsonify(dispatch_sink('inbound-batch-ready', **_payload()))
@freight_rpa_bp.route('/inbound-unit-progress', methods=['POST'])
def inbound_unit_progress():
"""
inbound 单元领取/导出中回调(旧 /rpa/receipt-unit-progress)。
【AI 触发时机】:非 Agent 入口;入站 Worker 领取单元后调用(awaiting_rpa → processing)。
核心逻辑:dispatch_sink('inbound-unit-progress') 分发到 mark_inbound_unit_processing
(Task 11 已随排程壳平移改名,现住 schedule.freight_rpa_inbound_finalize);本路由同时是收料
超时对账的活动锚数据源(mark 落单元 started_at)。曾因重构分叉合并丢失(2026-10-08),
Worker 上报全程 404,勿再从任何路由文件删除。
"""
return jsonify(dispatch_sink('inbound-unit-progress', **_payload()))
@freight_rpa_bp.route('/inbound-batch-progress', methods=['POST'])
def inbound_batch_progress():
"""
inbound 批量导出累计进度回调(旧 /rpa/receipt-batch-progress)。
【AI 触发时机】:非 Agent 入口;入站 Worker 每完成一笔导出后调用(非终态)。
核心逻辑:dispatch_sink('inbound-batch-progress') 分发到 report_inbound_batch_progress
(Task 11 已随排程壳平移改名,现住 schedule.freight_rpa_inbound_finalize),回写排程 run 计数
(对齐 onhand-batch-progress 语义)。
"""
return jsonify(dispatch_sink('inbound-batch-progress', **_payload()))
@freight_rpa_bp.route('/outbound-batch-ready', methods=['POST'])
def outbound_batch_ready():
"""
outbound(出站)批量导出终态回调。
【AI 触发时机】:非 Agent 入口;出站 Worker 完成报表导出并落 drop 目录后调用。
核心逻辑:dispatch_sink('outbound-batch-ready') 分发到组合根或测内注册的 sink
(ingest_outbound_callback:原样归档,终态 commit 后 dispatch_report_fact
report_kind='outbound');鉴权与入站同 ToolApiKey。
"""
return jsonify(dispatch_sink('outbound-batch-ready', **_payload()))
@freight_rpa_bp.route('/outbound-unit-progress', methods=['POST'])
def outbound_unit_progress():
"""
outbound 单元领取/导出中回调。
【AI 触发时机】:非 Agent 入口;出站 Worker 领取单元后调用(awaiting_rpa → processing)。
核心逻辑:dispatch_sink('outbound-unit-progress') 分发;鉴权与入站同 ToolApiKey。
"""
return jsonify(dispatch_sink('outbound-unit-progress', **_payload()))
@freight_rpa_bp.route('/outbound-batch-progress', methods=['POST'])
def outbound_batch_progress():
"""
outbound 批量导出累计进度回调。
【AI 触发时机】:非 Agent 入口;出站 Worker 每完成一笔导出后调用(非终态)。
核心逻辑:dispatch_sink('outbound-batch-progress') 分发;鉴权与入站同 ToolApiKey。
"""
return jsonify(dispatch_sink('outbound-batch-progress', **_payload()))
@freight_rpa_bp.route('/upload-complete', methods=['POST'])
def upload_complete():
"""
货代上传结果回调(旧 /rpa/upload-complete,URL 词根不变)。
【AI 触发时机】:非 Agent 入口;Worker 完成出货 Excel 上传(成功或失败)后调用。
核心逻辑:直连 shipping_notice.tools.rpa_report_upload 回写任务状态。
"""
from app.services.shipping_notice import tools as shipping_tools
return jsonify(shipping_tools.rpa_report_upload(_payload()))
File diff suppressed because it is too large. Load diff
+30 -10
View File
@@ -2,7 +2,8 @@
backend/app/api/internal/jobs.py backend/app/api/internal/jobs.py
用途:平台内置 Job 内部 API(POST /api/internal/jobs/<job_key>)。 用途:平台内置 Job 内部 API(POST /api/internal/jobs/<job_key>)。
依赖:job_registry、schedule_contract、scheduler_service。 依赖:job_registry、schedule_contract、scheduler_service、
freight_rpa_onhand_finalize / inbound_finalize / outbound_finalize(awaiting 延后终态)。
逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。 逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
""" """
from __future__ import annotations from __future__ import annotations
@@ -19,15 +20,20 @@ from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
from app.services.schedule.job_registry import get_platform_job, run_platform_job from app.services.schedule.job_registry import get_platform_job, run_platform_job
from app.services.schedule.schedule_contract import normalize_job_key from app.services.schedule.schedule_contract import normalize_job_key
from app.services.schedule.scheduler_service import _generate_run_no from app.services.schedule.scheduler_service import _generate_run_no
from app.services.schedule.shipping_inventory_rpa_finalize import ( from app.services.schedule.freight_rpa_onhand_finalize import (
apply_deferred_schedule_run_state, apply_deferred_schedule_run_state,
recover_stale_awaiting_rpa_schedule_runs, recover_stale_awaiting_rpa_schedule_runs,
should_defer_schedule_run_finalization, should_defer_schedule_run_finalization,
) )
from app.services.schedule.freight_receipt_rpa_finalize import ( from app.services.schedule.freight_rpa_inbound_finalize import (
apply_deferred_receipt_schedule_run_state, apply_deferred_inbound_schedule_run_state,
recover_stale_receipt_rpa_schedule_runs, recover_stale_inbound_rpa_schedule_runs,
should_defer_receipt_schedule_run, should_defer_inbound_schedule_run,
)
from app.services.schedule.freight_rpa_outbound_finalize import (
apply_deferred_outbound_schedule_run_state,
recover_stale_outbound_rpa_schedule_runs,
should_defer_outbound_schedule_run,
) )
internal_jobs_bp = Blueprint('internal_jobs', __name__) internal_jobs_bp = Blueprint('internal_jobs', __name__)
@@ -139,7 +145,8 @@ def run_internal_job(name: str):
task, run = _resolve_schedule_task_and_run(key, data) task, run = _resolve_schedule_task_and_run(key, data)
recover_stale_awaiting_rpa_schedule_runs(task) recover_stale_awaiting_rpa_schedule_runs(task)
recover_stale_receipt_rpa_schedule_runs(task) recover_stale_inbound_rpa_schedule_runs(task)
recover_stale_outbound_rpa_schedule_runs(task)
try: try:
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = run_platform_job( total_count, success_count, failed_count, skipped_count, details, errors, step_logs = run_platform_job(
key, task, run, data, key, task, run, data,
@@ -189,8 +196,8 @@ def run_internal_job(name: str):
'awaiting_rpa_callback': True, 'awaiting_rpa_callback': True,
}) })
if should_defer_receipt_schedule_run(task, step_logs): if should_defer_inbound_schedule_run(task, step_logs):
apply_deferred_receipt_schedule_run_state( apply_deferred_inbound_schedule_run_state(
run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs, run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs,
) )
return jsonify({ return jsonify({
@@ -199,7 +206,20 @@ def run_internal_job(name: str):
'failed_count': failed_count, 'skipped_count': skipped_count, 'failed_count': failed_count, 'skipped_count': skipped_count,
}, },
'details': details, 'errors': errors, 'step_logs': step_logs, 'details': details, 'errors': errors, 'step_logs': step_logs,
'awaiting_receipt_rpa_callback': True, 'awaiting_inbound_rpa_callback': True,
})
if should_defer_outbound_schedule_run(task, step_logs):
apply_deferred_outbound_schedule_run_state(
run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs,
)
return jsonify({
'summary': {
'total_count': total_count, 'success_count': success_count,
'failed_count': failed_count, 'skipped_count': skipped_count,
},
'details': details, 'errors': errors, 'step_logs': step_logs,
'awaiting_outbound_rpa_callback': True,
}) })
_finalize_run( _finalize_run(
+29 -1
View File
@@ -16,7 +16,11 @@ backend/app/api/order_delivery_reply.py
from __future__ import annotations from __future__ import annotations
from flask import Blueprint, g, request from datetime import datetime
from io import BytesIO
from zoneinfo import ZoneInfo
from flask import Blueprint, g, request, send_file
from app.core.auth.jwt import get_current_user from app.core.auth.jwt import get_current_user
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError
@@ -28,6 +32,8 @@ from app.services.order_delivery_reply.sync_service import OrderDeliverySyncServ
order_delivery_reply_bp = Blueprint("order_delivery_reply", __name__) order_delivery_reply_bp = Blueprint("order_delivery_reply", __name__)
XLSX_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
def _utc_to_shanghai(value) -> str | None: def _utc_to_shanghai(value) -> str | None:
""" """
@@ -121,6 +127,28 @@ def list_lines():
return ok(data, request_id=getattr(g, "request_id", None)) return ok(data, request_id=getattr(g, "request_id", None))
@order_delivery_reply_bp.get("/lines/export")
def export_lines():
"""
导出当前筛选下的全部订单行 Excel(不分页)。
用途与触发时机:工作台工具栏「导出 Excel」按钮;查询参数与列表一致
(keyword/order_date/status),导出全部命中行(服务层 EXPORT_MAX_ROWS 兜底)。
参数与输出约束:要求 order_delivery_reply.access 及以上;返回 xlsx 文件流(attachment,
文件名带北京时间日期)。
"""
_require_access()
content = query_service.export_lines(request.args.to_dict(flat=True))
filename = f"订单交期回复_{datetime.now(ZoneInfo('Asia/Shanghai')):%Y%m%d}.xlsx"
return send_file(
BytesIO(content),
as_attachment=True,
download_name=filename,
mimetype=XLSX_MIME_TYPE,
)
@order_delivery_reply_bp.get("/lines/<order_no>/<int:line_no>") @order_delivery_reply_bp.get("/lines/<order_no>/<int:line_no>")
def get_line(order_no: str, line_no: int): def get_line(order_no: str, line_no: int):
""" """
+1 -1
View File
@@ -67,7 +67,7 @@ def update_schedule_task_config(task_id: int):
config_data = data.get('config', data) config_data = data.get('config', data)
if isinstance(config_data, dict) and config_data: if isinstance(config_data, dict) and config_data:
# platform_job 仅白名单且 enabled 的任务(如 shipping-inventory-rpa)允许写 ScheduleTaskConfig # platform_job 仅白名单且 enabled 的任务(如 freight-rpa-onhand)允许写 ScheduleTaskConfig
if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE and not platform_job_allows_config(task.platform_api_path): if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE and not platform_job_allows_config(task.platform_api_path):
raise ValidationError( raise ValidationError(
f"platform_job '{task.platform_api_path}' does not accept ScheduleTaskConfig" f"platform_job '{task.platform_api_path}' does not accept ScheduleTaskConfig"
+6 -6
View File
@@ -1,9 +1,9 @@
""" """
backend/app/api/schedule/rpa_workers.py backend/app/api/schedule/rpa_workers.py
用途:管理端查询货代库存/收料 RPA Worker 在线状态与就绪摘要。 用途:管理端查询货代库存/入站/出站 RPA Worker 在线状态与就绪摘要。
依赖:schedule.blueprint、rpa_worker_heartbeat.serialize_rpa_worker_status。 依赖:schedule.blueprint、freight_rpa.common.worker_heartbeat.serialize_rpa_worker_status。
逻辑:ScheduleWorkbenchPanel 在库存或收料 RPA 排程工作台展示对应 worker 心跳状态。 逻辑:ScheduleWorkbenchPanel 在库存、入站或出站 RPA 排程工作台展示对应 worker 心跳状态。
""" """
from __future__ import annotations from __future__ import annotations
@@ -13,7 +13,7 @@ from flask import request
from app.api.schedule.blueprint import schedule_admin_bp from app.api.schedule.blueprint import schedule_admin_bp
from app.core.decorators import require_admin from app.core.decorators import require_admin
from app.core.response import ok from app.core.response import ok
from app.services.shipping_notice.rpa_worker_heartbeat import serialize_rpa_worker_status from app.services.freight_rpa.common.worker_heartbeat import serialize_rpa_worker_status
@schedule_admin_bp.route('/rpa-workers/status', methods=['GET']) @schedule_admin_bp.route('/rpa-workers/status', methods=['GET'])
@@ -23,7 +23,7 @@ def get_rpa_workers_status():
返回 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。 返回 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。
Query: Query:
scope: inventory(默认)或 receipt。 scope: onhand(默认)、inbound 或 outbound。
""" """
scope = str(request.args.get('scope') or 'inventory').strip().lower() or 'inventory' scope = str(request.args.get('scope') or 'onhand').strip().lower() or 'onhand'
return ok(serialize_rpa_worker_status(scope=scope)) return ok(serialize_rpa_worker_status(scope=scope))
+177 -58
View File
@@ -2,8 +2,10 @@
backend/app/api/schedule/runs.py backend/app/api/schedule/runs.py
用途:排程运行触发与运行记录查询 API。 用途:排程运行触发与运行记录查询 API。
依赖:schedule.blueprint、services/schedule/query_service、queue_service。 依赖:schedule.blueprint、services/schedule/query_service、queue_service、
freight_rpa inbound/outbound archive 与 trigger_io。
逻辑:手动执行仅创建 queued run/job;独立 schedule worker 承担实际运行。 逻辑:手动执行仅创建 queued run/job;独立 schedule worker 承担实际运行。
入站/出站 raw-zip 下载与失败单元 list/retry 对照同构。
""" """
from __future__ import annotations from __future__ import annotations
@@ -18,14 +20,15 @@ from app.api.schedule.blueprint import schedule_admin_bp
from app.core.auth.jwt import get_current_user from app.core.auth.jwt import get_current_user
from app.core.decorators import require_admin from app.core.decorators import require_admin
from app.core.errors import ConflictError, NotFoundError from app.core.errors import ConflictError, NotFoundError
from app.models import ScheduleRun, ScheduleTask, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun from app.models import ScheduleRun, ScheduleTask, FreightRpaInboundUnitRun, FreightRpaOutboundUnitRun
from app.services.schedule.query_service import get_run, list_runs, serialize_run from app.services.schedule.query_service import get_run, list_runs, serialize_run
from app.services.schedule.queue_service import enqueue_manual_schedule_run from app.services.schedule.queue_service import enqueue_manual_schedule_run
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download from app.services.schedule.freight_rpa_onhand_archive import resolve_inventory_raw_zip_download
from app.services.schedule.shipping_receipt_rpa_archive import resolve_receipt_raw_zip_download from app.services.schedule.freight_rpa_inbound_archive import resolve_inbound_raw_zip_download
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file from app.services.schedule.freight_rpa_outbound_archive import resolve_outbound_raw_zip_download
from app.services.shipping_notice.audit_service import append_shipping_audit_event from app.services.shipping_notice.audit_service import append_shipping_audit_event
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger from app.services.freight_rpa.inbound.trigger_io import SCHEMA, write_inbound_export_batch_trigger
from app.services.freight_rpa.outbound.trigger_io import SCHEMA as OUTBOUND_SCHEMA, write_outbound_export_batch_trigger
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST']) @schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
@@ -44,7 +47,11 @@ def run_schedule(task_id: int):
triggered_by_user_id=getattr(user, 'id', None), triggered_by_user_id=getattr(user, 'id', None),
) )
if not created: if not created:
raise ConflictError('该排程正在等待或执行中,请等待完成后再试', details={'run_id': run.id}) raise ConflictError(
'该排程正在等待或执行中,请等待完成后再试',
code='SCHEDULE.RUN_ALREADY_ACTIVE',
details={'run_id': run.id},
)
fresh = db.session.get(ScheduleRun, run.id) fresh = db.session.get(ScheduleRun, run.id)
return jsonify(serialize_run(fresh)) return jsonify(serialize_run(fresh))
@@ -124,18 +131,18 @@ def get_schedule_run_inventory_raw_zip(run_id: int):
) )
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/receipt-raw-zip', methods=['GET']) @schedule_admin_bp.route('/schedule-runs/<int:run_id>/inbound-raw-zip', methods=['GET'])
@require_admin @require_admin
def get_schedule_run_receipt_raw_zip(run_id: int): def get_schedule_run_inbound_raw_zip(run_id: int):
""" """
下载收料 RPA 排程 run 的原始收料 Excel 打包(ZIP + manifest)。 下载入站 RPA 排程 run 的原始入站 Excel 打包(ZIP + manifest)。
核心逻辑:对齐 inventory-raw-zip;展示名为 收料RPA-{日期}-{时刻}-收料.zip。 核心逻辑:对齐 inventory-raw-zip;展示名为 入站RPA-{日期}-{时刻}-入站.zip。
""" """
run = get_run(run_id) run = get_run(run_id)
if not run: if not run:
raise NotFoundError('Not found') raise NotFoundError('Not found')
zip_path, file_name = resolve_receipt_raw_zip_download(run) zip_path, file_name = resolve_inbound_raw_zip_download(run)
return send_file( return send_file(
zip_path, zip_path,
as_attachment=True, as_attachment=True,
@@ -144,31 +151,10 @@ def get_schedule_run_receipt_raw_zip(run_id: int):
) )
@schedule_admin_bp.route('/receipt-report-files/<int:file_id>/resend', methods=['POST']) @schedule_admin_bp.route('/inbound-rpa-units', methods=['GET'])
@require_admin @require_admin
def resend_receipt_report_file(file_id: int): def list_inbound_rpa_units():
"""管理员重发已归档的收料文件;禁止借重发重新触发 RPA 导出。""" """管理员查看入站单元运行事实,供失败单元填写原因后人工重试。"""
report_file = db.session.get(ShippingReceiptReportFile, file_id)
if report_file is None or report_file.archive_deleted_at is not None:
raise NotFoundError('Receipt report file not found')
user = get_current_user()
outcome = deliver_receipt_file(report_file.id, force=True)
append_shipping_audit_event(
event_type='shipping_receipt_report_notification_resent', aggregate_type='shipping_receipt_file',
aggregate_id=str(report_file.id), actor_type='admin', actor_id=getattr(user, 'id', None),
owner_user_id=getattr(user, 'id', None), unit_id=report_file.unit_run_id, result='success',
after={'status': 'resent', 'owner_user_id': getattr(user, 'id', None)},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
metadata={'success_count': int(outcome.get('success_count', 0)), 'failed_count': int(outcome.get('failed_count', 0))},
)
db.session.commit()
return jsonify({'success': True, 'data': outcome})
@schedule_admin_bp.route('/receipt-rpa-units', methods=['GET'])
@require_admin
def list_receipt_rpa_units():
"""管理员查看收料单元运行事实,供失败单元填写原因后人工重试。"""
status = str(request.args.get('status') or '').strip().lower() status = str(request.args.get('status') or '').strip().lower()
if status and status not in {'queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled'}: if status and status not in {'queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled'}:
from app.core.errors import ValidationError from app.core.errors import ValidationError
@@ -178,19 +164,19 @@ def list_receipt_rpa_units():
except (TypeError, ValueError): except (TypeError, ValueError):
from app.core.errors import ValidationError from app.core.errors import ValidationError
raise ValidationError('limit is invalid') raise ValidationError('limit is invalid')
query = ShippingReceiptRpaUnitRun.query.order_by( query = FreightRpaInboundUnitRun.query.order_by(
ShippingReceiptRpaUnitRun.created_at.desc(), ShippingReceiptRpaUnitRun.id.desc(), FreightRpaInboundUnitRun.created_at.desc(), FreightRpaInboundUnitRun.id.desc(),
) )
if status: if status:
query = query.filter(ShippingReceiptRpaUnitRun.status == status) query = query.filter(FreightRpaInboundUnitRun.status == status)
units = query.limit(limit).all() units = query.limit(limit).all()
user = get_current_user() user = get_current_user()
append_shipping_audit_event( append_shipping_audit_event(
event_type='shipping_receipt_rpa_units_listed', aggregate_type='shipping_receipt_unit_collection', event_type='shipping_inbound_rpa_units_listed', aggregate_type='shipping_inbound_unit_collection',
aggregate_id=str(getattr(user, 'id', 'admin')), actor_type='admin', actor_id=getattr(user, 'id', None), aggregate_id=str(getattr(user, 'id', 'admin')), actor_type='admin', actor_id=getattr(user, 'id', None),
owner_user_id=getattr(user, 'id', None), result='success', owner_user_id=getattr(user, 'id', None), result='success',
after={'visible_count': len(units), 'status': status or None, 'limit': limit}, after={'visible_count': len(units), 'status': status or None, 'limit': limit},
metadata={'surface': 'workspace_receipt_report_files'}, metadata={'surface': 'admin_inbound_rpa_units'},
) )
db.session.commit() db.session.commit()
return jsonify({'success': True, 'data': {'items': [{ return jsonify({'success': True, 'data': {'items': [{
@@ -207,34 +193,34 @@ def list_receipt_rpa_units():
} for unit in units]}}) } for unit in units]}})
@schedule_admin_bp.route('/receipt-rpa-units/<int:unit_id>/retry', methods=['POST']) @schedule_admin_bp.route('/inbound-rpa-units/<int:unit_id>/retry', methods=['POST'])
@require_admin @require_admin
def retry_receipt_rpa_unit(unit_id: int): def retry_inbound_rpa_unit(unit_id: int):
"""管理员为失败收料单元创建独立重试事实;旧单元永不覆盖。""" """管理员为失败入站单元创建独立重试事实;旧单元永不覆盖。"""
failed = db.session.get(ShippingReceiptRpaUnitRun, unit_id) failed = db.session.get(FreightRpaInboundUnitRun, unit_id)
if failed is None: if failed is None:
raise NotFoundError('Receipt RPA unit not found') raise NotFoundError('Inbound RPA unit not found')
if failed.status not in {'failed', 'cancelled'}: if failed.status not in {'failed', 'cancelled'}:
raise ConflictError('Only failed receipt RPA units can be retried') raise ConflictError('Only failed inbound RPA units can be retried')
data = request.get_json(silent=True) or {} data = request.get_json(silent=True) or {}
reason = str(data.get('reason') or '').strip() reason = str(data.get('reason') or '').strip()
if not reason: if not reason:
from app.core.errors import ValidationError from app.core.errors import ValidationError
raise ValidationError('reason is required', code='SHIPPING.RECEIPT_RETRY_REASON_REQUIRED') raise ValidationError('reason is required', code='SHIPPING.INBOUND_RETRY_REASON_REQUIRED')
user = get_current_user() user = get_current_user()
retry = ShippingReceiptRpaUnitRun( retry = FreightRpaInboundUnitRun(
schedule_run_id=failed.schedule_run_id, inventory_source_id=failed.inventory_source_id, schedule_run_id=failed.schedule_run_id, source_id=failed.source_id,
retry_of_id=failed.id, source_code=failed.source_code, connector_type=failed.connector_type, retry_of_id=failed.id, source_code=failed.source_code, connector_type=failed.connector_type,
warehouse_id=failed.warehouse_id, callback_id=f'receipt:{uuid.uuid4().hex}', status='awaiting_rpa', warehouse_id=failed.warehouse_id, callback_id=f'inbound:{uuid.uuid4().hex}', status='awaiting_rpa',
config_snapshot_json=dict(failed.config_snapshot_json or {}), config_snapshot_json=dict(failed.config_snapshot_json or {}),
) )
db.session.add(retry) db.session.add(retry)
db.session.flush() db.session.flush()
source = retry.inventory_source source = retry.source
profile = source.rpa_profile if source is not None else None profile = source.rpa_profile if source is not None else None
if source is None or profile is None or not profile.enabled: if source is None or profile is None or not profile.enabled:
db.session.rollback() db.session.rollback()
raise ConflictError('Receipt RPA profile is unavailable') raise ConflictError('Inbound RPA profile is unavailable')
snapshot = dict(retry.config_snapshot_json or {}) snapshot = dict(retry.config_snapshot_json or {})
trigger_unit = { trigger_unit = {
'unit_run_id': retry.id, 'callback_id': retry.callback_id, 'source_code': retry.source_code, 'unit_run_id': retry.id, 'callback_id': retry.callback_id, 'source_code': retry.source_code,
@@ -247,20 +233,153 @@ def retry_receipt_rpa_unit(unit_id: int):
} }
retry.trigger_snapshot_json = trigger_unit retry.trigger_snapshot_json = trigger_unit
run = retry.schedule_run run = retry.schedule_run
trigger_path = write_receipt_export_batch_trigger( trigger_path = write_inbound_export_batch_trigger(
f'{run.run_no}-retry-{retry.id}', [trigger_unit], f'{run.run_no}-retry-{retry.id}', [trigger_unit],
{'schedule_run_id': run.id, 'schedule_task_id': run.schedule_task_id, 'schema_version': 'shipping_receipt_rpa.v1', 'retry_of_unit_id': failed.id}, {'schedule_run_id': run.id, 'schedule_task_id': run.schedule_task_id, 'schema_version': SCHEMA, 'retry_of_unit_id': failed.id},
) )
if not trigger_path: if not trigger_path:
db.session.rollback() db.session.rollback()
raise ConflictError('Receipt RPA trigger directory is unavailable') raise ConflictError('Inbound RPA trigger directory is unavailable')
run.status = 'running' run.status = 'running'
run.finished_at = None run.finished_at = None
summary = dict(run.response_summary_json or {}) summary = dict(run.response_summary_json or {})
summary['awaiting_receipt_rpa'] = True summary['awaiting_inbound_rpa'] = True
run.response_summary_json = summary run.response_summary_json = summary
append_shipping_audit_event( append_shipping_audit_event(
event_type='shipping_receipt_rpa_unit_retried', aggregate_type='shipping_receipt_unit', event_type='shipping_inbound_rpa_unit_retried', aggregate_type='shipping_inbound_unit',
aggregate_id=str(retry.id), actor_type='admin', actor_id=getattr(user, 'id', None),
owner_user_id=getattr(user, 'id', None), unit_id=retry.id, result='success', reason=reason,
before={'status': failed.status, 'error_code': failed.error_code},
after={'status': retry.status, 'source_run_no': retry.callback_id, 'owner_user_id': getattr(user, 'id', None)},
metadata={'retry_of_id': failed.id},
)
db.session.commit()
return jsonify({'success': True, 'data': {'unit_id': retry.id, 'retry_of_id': failed.id, 'callback_id': retry.callback_id, 'trigger_path': trigger_path}})
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/outbound-raw-zip', methods=['GET'])
@require_admin
def get_schedule_run_outbound_raw_zip(run_id: int):
"""
下载出站 RPA 排程 run 的原始出站 Excel 打包(ZIP + manifest)。
核心逻辑:对齐 inbound-raw-zip;展示名为 出站RPA-{日期}-{时刻}-出站.zip。
"""
run = get_run(run_id)
if not run:
raise NotFoundError('Not found')
zip_path, file_name = resolve_outbound_raw_zip_download(run)
return send_file(
zip_path,
as_attachment=True,
download_name=file_name,
mimetype='application/zip',
)
@schedule_admin_bp.route('/outbound-rpa-units', methods=['GET'])
@require_admin
def list_outbound_rpa_units():
"""管理员查出站单元运行事实,供失败单元填写原因后人工重试。"""
status = str(request.args.get('status') or '').strip().lower()
if status and status not in {'queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled'}:
from app.core.errors import ValidationError
raise ValidationError('status is invalid')
try:
limit = max(1, min(int(request.args.get('limit') or 100), 200))
except (TypeError, ValueError):
from app.core.errors import ValidationError
raise ValidationError('limit is invalid')
query = FreightRpaOutboundUnitRun.query.order_by(
FreightRpaOutboundUnitRun.created_at.desc(), FreightRpaOutboundUnitRun.id.desc(),
)
if status:
query = query.filter(FreightRpaOutboundUnitRun.status == status)
units = query.limit(limit).all()
user = get_current_user()
append_shipping_audit_event(
event_type='shipping_outbound_rpa_units_listed', aggregate_type='shipping_outbound_unit_collection',
aggregate_id=str(getattr(user, 'id', 'admin')), actor_type='admin', actor_id=getattr(user, 'id', None),
owner_user_id=getattr(user, 'id', None), result='success',
after={'visible_count': len(units), 'status': status or None, 'limit': limit},
metadata={'surface': 'admin_outbound_rpa_units'},
)
db.session.commit()
return jsonify({'success': True, 'data': {'items': [{
'id': unit.id,
'source_code': unit.source_code,
'warehouse_id': unit.warehouse_id,
'status': unit.status,
'error_code': unit.error_code,
'error_message': unit.error_message,
'retry_of_id': unit.retry_of_id,
'schedule_run_id': unit.schedule_run_id,
'created_at': unit.created_at.isoformat() if unit.created_at else None,
'finished_at': unit.finished_at.isoformat() if unit.finished_at else None,
} for unit in units]}})
@schedule_admin_bp.route('/outbound-rpa-units/<int:unit_id>/retry', methods=['POST'])
@require_admin
def retry_outbound_rpa_unit(unit_id: int):
"""管理员为失败出站单元创建独立重试事实;旧单元永不覆盖。调拨按需单元无排程 run 时仍可重试。"""
failed = db.session.get(FreightRpaOutboundUnitRun, unit_id)
if failed is None:
raise NotFoundError('Outbound RPA unit not found')
if failed.status not in {'failed', 'cancelled'}:
raise ConflictError('Only failed outbound RPA units can be retried')
data = request.get_json(silent=True) or {}
reason = str(data.get('reason') or '').strip()
if not reason:
from app.core.errors import ValidationError
raise ValidationError('reason is required', code='SHIPPING.OUTBOUND_RETRY_REASON_REQUIRED')
user = get_current_user()
retry = FreightRpaOutboundUnitRun(
schedule_run_id=failed.schedule_run_id, source_id=failed.source_id,
retry_of_id=failed.id, source_code=failed.source_code, connector_type=failed.connector_type,
warehouse_id=failed.warehouse_id, callback_id=f'outbound:{uuid.uuid4().hex}', status='awaiting_rpa',
config_snapshot_json=dict(failed.config_snapshot_json or {}),
)
db.session.add(retry)
db.session.flush()
source = retry.source
profile = source.rpa_profile if source is not None else None
if source is None or profile is None or not profile.enabled:
db.session.rollback()
raise ConflictError('Outbound RPA profile is unavailable')
snapshot = dict(retry.config_snapshot_json or {})
trigger_unit = {
'unit_run_id': retry.id, 'callback_id': retry.callback_id, 'source_code': retry.source_code,
'connector_type': retry.connector_type, 'warehouse_id': retry.warehouse_id,
'rpa_profile_id': profile.id, 'rpa_profile_code': profile.profile_code, 'login_url': profile.login_url,
'login_config': dict(profile.login_config_json or {}),
'credential_envelope': {'username_ciphertext': profile.username_ciphertext, 'password_ciphertext': profile.password_ciphertext},
'report_path_json': dict(snapshot.get('report_path_json') or {}),
'query_parameters_json': list(snapshot.get('query_parameters_json') or []), 'config_snapshot': snapshot,
}
retry.trigger_snapshot_json = trigger_unit
run = retry.schedule_run
run_no = run.run_no if run is not None else f'outbound-retry-{retry.id}'
trigger_meta = {
'schema_version': OUTBOUND_SCHEMA, 'retry_of_unit_id': failed.id,
}
if run is not None:
trigger_meta['schedule_run_id'] = run.id
trigger_meta['schedule_task_id'] = run.schedule_task_id
trigger_path = write_outbound_export_batch_trigger(
f'{run_no}-retry-{retry.id}', [trigger_unit], trigger_meta,
)
if not trigger_path:
db.session.rollback()
raise ConflictError('Outbound RPA trigger directory is unavailable')
if run is not None:
run.status = 'running'
run.finished_at = None
summary = dict(run.response_summary_json or {})
summary['awaiting_outbound_rpa'] = True
run.response_summary_json = summary
append_shipping_audit_event(
event_type='shipping_outbound_rpa_unit_retried', aggregate_type='shipping_outbound_unit',
aggregate_id=str(retry.id), actor_type='admin', actor_id=getattr(user, 'id', None), aggregate_id=str(retry.id), actor_type='admin', actor_id=getattr(user, 'id', None),
owner_user_id=getattr(user, 'id', None), unit_id=retry.id, result='success', reason=reason, owner_user_id=getattr(user, 'id', None), unit_id=retry.id, result='success', reason=reason,
before={'status': failed.status, 'error_code': failed.error_code}, before={'status': failed.status, 'error_code': failed.error_code},
+10 -125
View File
@@ -1,10 +1,11 @@
""" """
backend/app/api/tools/shipping_notice.py backend/app/api/tools/shipping_notice.py
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。 用途:暴露发货通知 Tool API,供 Dify Chatflow Agent 与导出下载入口调用。
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url。 依赖:app.core.errors、app.core.tool_auth、shipping_notice.tools、query_service、openapi_spec、tool_api_url。
逻辑:register_blueprints 从 api.tools 挂载;Tool 成功响应仍用 status: ok/failed 业务 envelope; 逻辑:register_blueprints 从 api.tools 挂载;Tool 成功响应仍用 status: ok/failed 业务 envelope;
HTTP 级参数/资源错误统一 raise AppError;`_payload()` 剥离 body 中的操作人伪造字段; HTTP 级参数/资源错误统一 raise AppError;`_payload()` 剥离 body 中的操作人伪造字段;
RPA 回调已整体迁出至 api/freight_rpa.py(/api/freight-rpa/*,无双路由);
历史批次 Tool 已删除,订单抽取统一走 order-extraction-submissions。 历史批次 Tool 已删除,订单抽取统一走 order-extraction-submissions。
""" """
from __future__ import annotations from __future__ import annotations
@@ -15,10 +16,8 @@ from app import db
from app.core.errors import ( from app.core.errors import (
AppError, AppError,
NotFoundError, NotFoundError,
ServiceUnavailableError,
UnauthorizedError,
ValidationError,
) )
from app.core.tool_auth import require_tool_auth
from app.services.shipping_notice import tools as shipping_tools from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
from app.services.shipping_notice.query_service import ( from app.services.shipping_notice.query_service import (
@@ -28,40 +27,10 @@ from app.services.shipping_notice.query_service import (
serialize_task_summary, serialize_task_summary,
task_export_error_message, task_export_error_message,
) )
from app.services.shipping_notice.rpa_worker_heartbeat import record_rpa_worker_heartbeat
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
shipping_notice_bp = Blueprint("shipping_notice", __name__) shipping_notice_bp = Blueprint("shipping_notice", __name__)
def _require_tool_auth() -> None:
"""
校验货代 Tool API 鉴权 Header。
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA 或外部系统请求本蓝图时由 before_request 自动触发。
核心逻辑:只接受 `Authorization: Bearer <token>` 或 `X-Integration-Key`。
货代专用 `SHIPPING_NOTICE_TOOL_API_KEY` 优先,未配置时回退 `INTEGRATION_API_KEY`;
未配置任何可用 key 时报服务不可用,缺失或错误时报未授权。
"""
configured = str(
current_app.config.get('SHIPPING_NOTICE_TOOL_API_KEY')
or current_app.config.get('INTEGRATION_API_KEY')
or ''
).strip()
if not configured:
raise ServiceUnavailableError(
'SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured',
code='missing_auth',
)
bearer = str(request.headers.get('Authorization') or '').strip()
token = bearer[7:].strip() if bearer.lower().startswith('bearer ') else ''
integration_key = str(request.headers.get('X-Integration-Key') or '').strip()
if configured in {token, integration_key}:
return
if not token and (not integration_key):
raise UnauthorizedError('missing_auth')
raise UnauthorizedError('invalid_auth')
def _tool_error_code(exc: AppError) -> str: def _tool_error_code(exc: AppError) -> str:
"""统一归一化 Tool API 的错误码,保持与文件检核 Tool 返回风格一致。""" """统一归一化 Tool API 的错误码,保持与文件检核 Tool 返回风格一致。"""
message = str(exc.message or '').strip() message = str(exc.message or '').strip()
@@ -84,12 +53,13 @@ def _handle_tool_app_error(exc: AppError):
@shipping_notice_bp.before_request @shipping_notice_bp.before_request
def _verify_tool_access(): def _verify_tool_access():
""" """
对货代 Tool / RPA / 导出接口做统一 Header 鉴权。 对货代 Tool / 导出接口做统一 Header 鉴权。
核心逻辑:仅放行 OpenAPI 导入文档,其他请求都必须携带有效 Tool Key。 核心逻辑:仅放行 OpenAPI 导入文档,其他请求都必须携带有效 Tool Key
(鉴权实现见 app.core.tool_auth.require_tool_auth,与 freight-rpa 回调蓝图共用)。
""" """
if request.path.endswith('/openapi.json') or request.path.endswith('/openapi.dify.yaml'): if request.path.endswith('/openapi.json') or request.path.endswith('/openapi.dify.yaml'):
return None return None
_require_tool_auth() require_tool_auth()
return None return None
def _tool_api_base_url() -> str: def _tool_api_base_url() -> str:
@@ -229,7 +199,7 @@ def tool_ensure_inventory():
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(), task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
trigger='legacy_tool_ensure_inventory', trigger='legacy_tool_ensure_inventory',
operator_id=payload.get('operator_id'), operator_id=payload.get('operator_id'),
resume_gate_code='inventory_preparation', resume_gate_code='onhand_preparation',
)) ))
@shipping_notice_bp.route('/tools/auto_progress', methods=['POST']) @shipping_notice_bp.route('/tools/auto_progress', methods=['POST'])
@@ -252,7 +222,7 @@ def tool_match_inventory():
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(), task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
trigger='legacy_tool_match_inventory', trigger='legacy_tool_match_inventory',
operator_id=payload.get('operator_id'), operator_id=payload.get('operator_id'),
resume_gate_code='inventory_matching', resume_gate_code='onhand_matching',
)) ))
@shipping_notice_bp.route('/tools/confirm_customer', methods=['POST']) @shipping_notice_bp.route('/tools/confirm_customer', methods=['POST'])
@@ -299,78 +269,6 @@ def tool_get_task_status():
_require_read_capability(payload, scope='get_shipping_status', task_no=task_no or None) _require_read_capability(payload, scope='get_shipping_status', task_no=task_no or None)
return jsonify(shipping_tools.get_task_status(payload)) return jsonify(shipping_tools.get_task_status(payload))
@shipping_notice_bp.route('/rpa/heartbeat', methods=['POST'])
def rpa_worker_heartbeat():
"""
RPA Worker 心跳上报。
核心逻辑:校验 payload 后写入 Redis/内存;供触发库存 RPA 前就绪检查使用。
"""
payload = _payload()
try:
worker = record_rpa_worker_heartbeat(payload)
except ValueError as exc:
raise ValidationError(str(exc))
except ServiceUnavailableError:
raise
return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker})
@shipping_notice_bp.route('/rpa/inventory-ready', methods=['POST'])
def rpa_inventory_ready():
"""RPA 回调入口:上报库存导出结果并回写任务状态。"""
return jsonify(shipping_tools.rpa_report_inventory(_payload()))
@shipping_notice_bp.route('/rpa/inventory-batch-ready', methods=['POST'])
def rpa_inventory_batch_ready():
"""RPA 批量库存导出回调:按 Warehouse 写入库存快照。"""
return jsonify(shipping_tools.rpa_report_inventory_batch(_payload()))
@shipping_notice_bp.route('/rpa/receipt-batch-ready', methods=['POST'])
def rpa_receipt_batch_ready():
"""收料 RPA 回调:独立归档文件,绝不进入库存回调或库存匹配链路。"""
from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback
return jsonify({'success': True, 'data': ingest_receipt_callback(_payload())})
@shipping_notice_bp.route('/rpa/inventory-batch-claimed', methods=['POST'])
def rpa_inventory_batch_claimed():
"""v2 Worker 领取回调:仅记录 Attempt 执行阶段。"""
from app.services.shipping_notice.per_source_rpa_service import claim_inventory_batch
return jsonify({'success': True, 'data': claim_inventory_batch(_payload())})
@shipping_notice_bp.route('/rpa/inventory-batch-progress', methods=['POST'])
def rpa_inventory_batch_progress():
"""RPA 批量库存导出进度回调:实时回写排程 run 计数(非终态,最终以 batch-ready 为准)。"""
from app.services.shipping_notice.inventory_rpa_workflow import report_inventory_batch_progress
return jsonify(report_inventory_batch_progress(_payload()))
@shipping_notice_bp.route('/rpa/inventory-configuration-test-ready', methods=['POST'])
def rpa_inventory_configuration_test_ready():
"""RPA 配置测试回调:仅分析文件结构,不创建生产库存快照或任务关联。"""
from app.services.shipping_notice import inventory_configuration_test
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_test_export(_payload())})
@shipping_notice_bp.route('/rpa/inventory-configuration-test-batch-ready', methods=['POST'])
def rpa_inventory_configuration_test_batch_ready():
"""RPA 批量配置测试回调:按 validation_run_no 独立回写每个库存站点。"""
from app.services.shipping_notice import inventory_configuration_test
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_batch_test_exports(_payload())})
@shipping_notice_bp.route('/rpa/inventory-configuration-test-batch-progress', methods=['POST'])
def rpa_inventory_configuration_test_batch_progress():
"""RPA 批量配置测试进度:Worker 领取单个站点后立即回写执行阶段。"""
from app.services.shipping_notice import inventory_configuration_test
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_batch_test_progress(_payload())})
@shipping_notice_bp.route('/tasks/<task_no>/repair-inventory-attachment', methods=['POST']) @shipping_notice_bp.route('/tasks/<task_no>/repair-inventory-attachment', methods=['POST'])
def repair_task_inventory_attachment(task_no: str): def repair_task_inventory_attachment(task_no: str):
""" """
@@ -382,19 +280,6 @@ def repair_task_inventory_attachment(task_no: str):
payload.setdefault("task_id", task_no) payload.setdefault("task_id", task_no)
return jsonify(shipping_tools.repair_task_inventory_attachment(payload)) return jsonify(shipping_tools.repair_task_inventory_attachment(payload))
@shipping_notice_bp.route('/rpa/inventory-repair', methods=['POST'])
def rpa_inventory_repair():
"""受控库存回调修复:复用正式 v2 ingest 链路。"""
payload = _payload()
payload['repair'] = True
return jsonify(shipping_tools.rpa_report_inventory_batch(payload))
@shipping_notice_bp.route('/rpa/upload-complete', methods=['POST'])
def rpa_upload_complete():
"""RPA 回调入口:上报货代上传结果并回写任务状态。"""
return jsonify(shipping_tools.rpa_report_upload(_payload()))
@shipping_notice_bp.route('/tasks/<task_no>/export', methods=['GET']) @shipping_notice_bp.route('/tasks/<task_no>/export', methods=['GET'])
def download_task_export(task_no: str): def download_task_export(task_no: str):
"""下载任务已生成的出货 Excel。""" """下载任务已生成的出货 Excel。"""
+1 -1
View File
@@ -12,7 +12,7 @@ from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
from app.api.workspace.voucher_check import workspace_voucher_check_bp from app.api.workspace.voucher_check import workspace_voucher_check_bp
import app.api.workspace.shipping_process_gate # noqa: F401 import app.api.workspace.shipping_process_gate # noqa: F401
import app.api.workspace.shipping_inventory_candidates # noqa: F401 import app.api.workspace.shipping_onhand_candidates # noqa: F401
__all__ = [ __all__ = [
'workspace_announcements_bp', 'workspace_announcements_bp',
+245 -54
View File
@@ -20,7 +20,7 @@ from flask import Blueprint, Response, current_app, g, request, send_file
from app import db from app import db
from app.core.auth.jwt import get_current_user from app.core.auth.jwt import get_current_user
from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError from app.core.errors import AppError, ConflictError, NotFoundError, UnauthorizedError, ValidationError
from app.core.response import ok from app.core.response import ok
from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice, ShippingOrderTask from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice, ShippingOrderTask
from app.services.shipping_notice.chat_actions import build_chat_actions_payload from app.services.shipping_notice.chat_actions import build_chat_actions_payload
@@ -87,34 +87,6 @@ def _ok(payload: Any, *, status: int = 200):
return ok(payload, request_id=getattr(g, 'request_id', None), status=status) return ok(payload, request_id=getattr(g, 'request_id', None), status=status)
@workspace_shipping_notice_bp.route('/receipt-report-files/<int:file_id>/download', methods=['GET'])
def workspace_download_receipt_report_file(file_id: int):
"""下载当前接收人或管理员有权读取的原样收料报表。"""
user = _require_user()
from app.services.shipping_notice.receipt_report_access import resolve_receipt_report_download
stream, filename, content_type = resolve_receipt_report_download(file_id, user)
response = send_file(
stream, as_attachment=True, download_name=filename,
mimetype=content_type or 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
)
response.call_on_close(stream.close)
return response
@workspace_shipping_notice_bp.route('/receipt-report-files', methods=['GET'])
def workspace_list_receipt_report_files():
"""列出当前接收人或管理员可下载的收料归档文件,不返回对象存储定位。"""
user = _require_user()
try:
limit = int(request.args.get('limit') or 100)
except (TypeError, ValueError) as exc:
raise ValidationError('limit must be an integer') from exc
from app.services.shipping_notice.receipt_report_access import list_receipt_report_files
return _ok({'items': list_receipt_report_files(user, limit=limit)})
def _assert_fulfillment_task_ownership(task: ShippingNotice, user_id: int) -> None: def _assert_fulfillment_task_ownership(task: ShippingNotice, user_id: int) -> None:
""" """
履约写接口:若请求携带期望 OT/Case/Run,校验与正式 Notice 归属一致。 履约写接口:若请求携带期望 OT/Case/Run,校验与正式 Notice 归属一致。
@@ -186,6 +158,7 @@ def workspace_shipping_tasks():
lifecycle_status=lifecycle_status, lifecycle_status=lifecycle_status,
page=page, page=page,
page_size=page_size, page_size=page_size,
is_admin=bool(user.is_platform_admin()),
)) ))
@@ -394,14 +367,38 @@ def workspace_batch_restore_shipping_tasks():
@workspace_shipping_notice_bp.route('/shipping-exports/archive', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-exports/archive', methods=['POST'])
def workspace_shipping_export_archive(): def workspace_shipping_export_archive():
"""按显式任务号下载当前用户可访问的 ready 发货 Excel ZIP。""" """按显式任务号下载当前用户可下载(创建者或管理员)的 ready 发货 Excel ZIP。"""
user = _require_user() user = _require_user()
data = request.get_json(silent=True) or {} data = request.get_json(silent=True) or {}
task_nos = data.get('task_nos') task_nos = data.get('task_nos')
if task_nos is not None and not isinstance(task_nos, list): if task_nos is not None and not isinstance(task_nos, list):
raise ValidationError('task_nos must be a list', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID') raise ValidationError('task_nos must be a list', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
from app.services.shipping_notice.export_archive import build_export_archive from app.services.shipping_notice.export_archive import build_export_archive
stream, filename, _manifest = build_export_archive(user_id=user.id, task_nos=task_nos or []) from app.services.shipping_notice.fulfillment_audit import record_access_audit
stream, filename, manifest = build_export_archive(
user_id=user.id,
task_nos=task_nos or [],
is_admin=bool(user.is_platform_admin()),
)
# 与 business_no 批量导出同一审计口径:按票落 record_access_audit(自行提交)。
for entry in manifest.get('entries') or []:
aggregate_no = str(entry.get('business_no') or '').strip()
task_no = str(entry.get('task_no') or '').strip()
if not aggregate_no and not task_no:
continue
record_access_audit(
action='download_task_excel',
aggregate_type='shipping_task',
aggregate_id=task_no or aggregate_no,
actor_id=user.id,
task_no=task_no or None,
reason_code='excel_downloaded',
metadata={
'export': 'batch_zip',
'batch_status': str(entry.get('status') or ''),
},
)
response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip') response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
response.call_on_close(stream.close) response.call_on_close(stream.close)
return response return response
@@ -455,7 +452,11 @@ def workspace_confirm_shipping_customer(task_no: str):
details={'field': 'customer_id'}, details={'field': 'customer_id'},
) from exc ) from exc
updated = confirm_task_customer(task, customer_id=customer_id, actor_id=user.id) updated = confirm_task_customer(task, customer_id=customer_id, actor_id=user.id)
return _ok(serialize_task_detail(updated)) return _ok(serialize_task_detail(
updated,
viewer_user_id=user.id,
is_admin=bool(user.is_platform_admin()),
))
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
@@ -499,7 +500,7 @@ def workspace_create_shipping_task_from_notice():
db.session.commit() db.session.commit()
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
orchestrator_started = start_task_orchestrator(task_id) orchestrator_started = start_task_orchestrator(task_id)
return _ok({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}}) return _ok({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task, viewer_user_id=user.id) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST'])
def workspace_replace_shipping_task_notice(task_no: str): def workspace_replace_shipping_task_notice(task_no: str):
@@ -657,7 +658,12 @@ def workspace_shipping_task_ui_state(task_no: str):
task = get_task_for_user(task_no, user.id) task = get_task_for_user(task_no, user.id)
if not task: if not task:
raise NotFoundError('Not found') raise NotFoundError('Not found')
return _ok(build_task_ui_state(task, include_stage_context=True)) return _ok(build_task_ui_state(
task,
include_stage_context=True,
viewer_user_id=user.id,
viewer_is_admin=bool(user.is_platform_admin()),
))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
def workspace_shipping_task_chat_actions(task_no: str): def workspace_shipping_task_chat_actions(task_no: str):
@@ -1032,6 +1038,38 @@ def _load_business_notice_for_user(*, business_no: str, user_id: int) -> Shippin
return task return task
def _load_business_notice_readable_for_user(
*,
business_no: str,
user_id: int,
is_admin: bool,
) -> ShippingNotice:
"""
按精确发货通知单号加载当前用户可下载的 Notice(创建者或管理员)。
核心逻辑:下载是只读动作,授权走 can_download_task_export 统一谓词口径
(可下载=可见),不经过写路径的履约归属断言;管理员可下载其可见的正式
Notice,且每次下载均由端点写入 record_access_audit。
Args:
business_no: 对外发货通知单号。
user_id: 当前服务端会话用户主键。
is_admin: 是否平台管理员。
Returns:
可下载的 ShippingNotice。
Raises:
NotFoundError: 编号不存在、非正式 Notice 或用户不可见。
"""
normalized = str(business_no or '').strip().upper()
from app.services.shipping_notice.query_service import get_task_visible_to_user
task = get_task_visible_to_user(normalized, user_id, is_admin=is_admin)
if not isinstance(task, ShippingNotice) or str(task.business_no or '').strip().upper() != normalized:
raise NotFoundError('Shipping notice not found')
return task
def _start_notice_rpa_upload(*, business_no: str, user_id: int, artifact_id: int | None = None) -> dict[str, Any]: def _start_notice_rpa_upload(*, business_no: str, user_id: int, artifact_id: int | None = None) -> dict[str, Any]:
"""按 business_no 发起单张通知的货代 RPA 上传或重试。""" """按 business_no 发起单张通知的货代 RPA 上传或重试。"""
task = _load_business_notice_for_user(business_no=business_no, user_id=user_id) task = _load_business_notice_for_user(business_no=business_no, user_id=user_id)
@@ -1064,6 +1102,47 @@ def workspace_confirm_shipping_notice_uploaded(business_no: str):
)) ))
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/refresh-crane-upload', methods=['POST'])
def workspace_refresh_crane_upload_status(business_no: str):
"""手动刷新一张仍在分配中的 Crane 发货单。
核心逻辑:校验当前用户可见的通知单,读取最近一次上传尝试,写入一条只查状态的 trigger。
不改 10 分钟定时回查的到期时间,也不重新上传 Excel。
Args:
business_no: 对外发货通知单号,同时是 Crane 的 Pull Request #。
Returns:
JSON: business_no 与 trigger_queued。
Raises:
ValidationError: 没有可刷新的上传尝试或来源连接。
ConflictError: 当前不是分配中,或上一次手动刷新还在排队。
"""
user = _require_user()
task = _load_business_notice_for_user(business_no=business_no, user_id=int(user.id))
from app.services.freight_rpa.upload.crane_recheck import request_manual_crane_refresh
from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source
from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source
from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt
attempt = latest_upload_attempt(task)
from app.models import ShippingExportArtifact
artifact = db.session.get(ShippingExportArtifact, attempt.artifact_id) if attempt is not None else None
snapshot = task_rpa_inventory_source(task) or {}
upload_source = get_rpa_trigger_inventory_source(str(snapshot.get('source_code') or '')) if snapshot.get('source_code') else None
if attempt is None or artifact is None or not isinstance(upload_source, dict):
raise ValidationError('Crane upload status cannot be refreshed', code='SHIPPING.UPLOAD_CRANE_ALLOCATING')
trigger_path = request_manual_crane_refresh(
attempt,
upload_source,
task_no=str(task.task_no),
export_file_path=str(artifact.file_path or ''),
)
db.session.commit()
return _ok({'business_no': str(task.business_no), 'trigger_queued': bool(trigger_path)})
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/rpa-upload', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/rpa-upload', methods=['POST'])
def workspace_start_shipping_notice_rpa_upload(business_no: str): def workspace_start_shipping_notice_rpa_upload(business_no: str):
"""按发货通知单号发起 RPA 上传;RPA 成功事实仍由受信回调裁决。""" """按发货通知单号发起 RPA 上传;RPA 成功事实仍由受信回调裁决。"""
@@ -1138,9 +1217,13 @@ def workspace_batch_start_shipping_notice_rpa_upload():
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/export', methods=['GET']) @workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/export', methods=['GET'])
def workspace_shipping_notice_export(business_no: str): def workspace_shipping_notice_export(business_no: str):
"""按发货通知单号下载该通知唯一的正式 Excel,并保留下载审计。""" """按发货通知单号下载该通知唯一的正式 Excel(创建者或管理员),并保留下载审计。"""
user = _require_user() user = _require_user()
task = _load_business_notice_for_user(business_no=business_no, user_id=int(user.id)) task = _load_business_notice_readable_for_user(
business_no=business_no,
user_id=int(user.id),
is_admin=bool(user.is_platform_admin()),
)
err_msg = task_export_error_message(task) err_msg = task_export_error_message(task)
if err_msg: if err_msg:
raise NotFoundError(err_msg) raise NotFoundError(err_msg)
@@ -1162,7 +1245,7 @@ def workspace_shipping_notice_export(business_no: str):
@workspace_shipping_notice_bp.route('/shipping-notices/batch/export', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-notices/batch/export', methods=['POST'])
def workspace_shipping_notice_export_archive(): def workspace_shipping_notice_export_archive():
"""按多个 business_no 下载各自唯一 Excel 的 ZIP;任一越权或缺文件均整体拒绝。""" """按多个 business_no 下载各自唯一 Excel 的 ZIP(创建者或管理员);任一越权或缺文件均整体拒绝。"""
user = _require_user() user = _require_user()
data = request.get_json(silent=True) or {} data = request.get_json(silent=True) or {}
raw_values = data.get('business_nos') raw_values = data.get('business_nos')
@@ -1174,8 +1257,32 @@ def workspace_shipping_notice_export_archive():
if not business_nos or len(business_nos) > 100: if not business_nos or len(business_nos) > 100:
raise ValidationError('business_nos must contain 1 to 100 business numbers') raise ValidationError('business_nos must contain 1 to 100 business numbers')
from app.services.shipping_notice.export_archive import build_export_archive from app.services.shipping_notice.export_archive import build_export_archive
from app.services.shipping_notice.fulfillment_audit import record_access_audit
stream, filename, _manifest = build_export_archive(user_id=int(user.id), business_nos=business_nos) stream, filename, manifest = build_export_archive(
user_id=int(user.id),
business_nos=business_nos,
is_admin=bool(user.is_platform_admin()),
)
# 批量导出与单票下载同一审计口径:按票落 record_access_audit(自行提交),
# manifest.business_no 是 aggregate 事实源;missing/checksum 票据也留痕。
for entry in manifest.get('entries') or []:
aggregate_no = str(entry.get('business_no') or '').strip()
task_no = str(entry.get('task_no') or '').strip()
if not aggregate_no and not task_no:
continue
record_access_audit(
action='download_notice_excel',
aggregate_type='shipping_notice',
aggregate_id=aggregate_no or task_no,
actor_id=user.id,
task_no=task_no or None,
reason_code='excel_downloaded',
metadata={
'export': 'batch_zip',
'batch_status': str(entry.get('status') or ''),
},
)
response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip') response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
response.call_on_close(stream.close) response.call_on_close(stream.close)
return response return response
@@ -1183,9 +1290,10 @@ def workspace_shipping_notice_export_archive():
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
def workspace_shipping_task_export(task_no: str): def workspace_shipping_task_export(task_no: str):
"""下载当前用户可访问任务的出货 Excel;写入统一访问审计。""" """下载当前用户可下载任务的出货 Excel(创建者或管理员);写入统一访问审计。"""
user = _require_user() user = _require_user()
task = get_task_for_user(task_no, user.id) from app.services.shipping_notice.query_service import get_task_visible_to_user
task = get_task_visible_to_user(task_no, user.id, is_admin=bool(user.is_platform_admin()))
task = _require_formal_notice(task) task = _require_formal_notice(task)
err_msg = task_export_error_message(task) err_msg = task_export_error_message(task)
if err_msg: if err_msg:
@@ -1213,11 +1321,11 @@ def workspace_shipping_task_inventory_file(task_no: str):
task = get_task_for_user(task_no, user.id) task = get_task_for_user(task_no, user.id)
if not task: if not task:
raise NotFoundError('Not found') raise NotFoundError('Not found')
from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download from app.services.shipping_notice.onhand_file_store import resolve_task_inventory_download
resolved = resolve_task_inventory_download(task) resolved = resolve_task_inventory_download(task)
if resolved is None: if resolved is None:
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND') raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_ONHAND_FILE_NOT_FOUND')
path, download_name = resolved path, download_name = resolved
from app.services.shipping_notice.fulfillment_audit import record_access_audit from app.services.shipping_notice.fulfillment_audit import record_access_audit
record_access_audit( record_access_audit(
@@ -1243,30 +1351,31 @@ def workspace_shipping_task_line_inventory_file(task_no: str, inventory_file_no:
raise NotFoundError('Not found') raise NotFoundError('Not found')
from pathlib import Path from pathlib import Path
from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch from app.models import FreightRpaOnhandReportFile, ShippingNoticeLineOnhandMatch
requested_file_no = str(inventory_file_no or '').strip() requested_file_no = str(inventory_file_no or '').strip()
inventory_file = ( inventory_file = (
ShippingInventoryFile.query FreightRpaOnhandReportFile.query
.join( .join(
ShippingNoticeLineInventoryMatch, ShippingNoticeLineOnhandMatch,
ShippingNoticeLineInventoryMatch.inventory_snapshot_id == ShippingInventoryFile.id, ShippingNoticeLineOnhandMatch.onhand_snapshot_id == FreightRpaOnhandReportFile.id,
) )
.filter( .filter(
ShippingNoticeLineInventoryMatch.task_id == int(task.id), ShippingNoticeLineOnhandMatch.task_id == int(task.id),
ShippingNoticeLineInventoryMatch.is_current.is_(True), ShippingNoticeLineOnhandMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.matched_file_no == requested_file_no, ShippingNoticeLineOnhandMatch.matched_file_no == requested_file_no,
ShippingInventoryFile.inventory_file_no == requested_file_no, FreightRpaOnhandReportFile.onhand_file_no == requested_file_no,
) )
.first() .first()
) )
storage_path = str(getattr(inventory_file, 'storage_path', '') or '').strip() storage_path = str(getattr(inventory_file, 'storage_path', '') or '').strip()
path = Path(storage_path).resolve() if storage_path else None path = Path(storage_path).resolve() if storage_path else None
if inventory_file is None or not storage_path or storage_path.startswith('failed://') or not path.is_file(): if inventory_file is None or not storage_path or storage_path.startswith('failed://') or not path.is_file():
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND') raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_ONHAND_FILE_NOT_FOUND')
download_name = str( from app.services.shipping_notice.onhand_file_store import build_inventory_download_name
inventory_file.source_file_name or f'{inventory_file.inventory_file_no}{path.suffix or ".xlsx"}', download_name = build_inventory_download_name(
).strip() inventory_file, source_file_name=inventory_file.source_file_name, path=path,
)
from app.services.shipping_notice.fulfillment_audit import record_access_audit from app.services.shipping_notice.fulfillment_audit import record_access_audit
record_access_audit( record_access_audit(
action='download_task_line_inventory_file', action='download_task_line_inventory_file',
@@ -2103,6 +2212,88 @@ def workspace_confirm_shipping_order_review_customer(case_no: str):
)) ))
@workspace_shipping_notice_bp.route(
'/shipping-notice/order-review-cases/<case_no>/customer/rebind',
methods=['POST'],
)
def workspace_rebind_shipping_order_review_customer(case_no: str):
"""
确认客户改绑:直接修改已确认的客户识别结果并刷新订单快照客户。
Body: customer_id, expected_order_data_version, reason?
仅当订单编辑窗 header 可编辑(任一通知无 Export Artifact 且无活动 Gate Attempt,
即发货通知/Excel 未产生)时允许;版本乐观锁与状态守卫在服务层 fail-closed。
"""
user = _require_user()
data = request.get_json(silent=True) or {}
try:
customer_id = int(data.get('customer_id'))
except (TypeError, ValueError) as exc:
raise ValidationError(
'Customer id is required',
code='SHIPPING.CUSTOMER_REBIND_CUSTOMER_REQUIRED',
details={'field': 'customer_id'},
) from exc
try:
expected_order_data_version = int(data.get('expected_order_data_version'))
except (TypeError, ValueError) as exc:
raise ValidationError(
'Expected order data version is required',
code='SHIPPING.CUSTOMER_REBIND_VERSION_REQUIRED',
details={'field': 'expected_order_data_version'},
) from exc
from app.services.shipping_notice.customer_resolution_service import rebind_confirmed_customer
from app.services.shipping_notice.order_review_customer_service import (
project_review_case_customer_resolution,
)
from app.services.shipping_notice.order_review_draft_service import soft_load_review_case_for_audit
from app.services.shipping_notice.order_review_projection import serialize_review_case
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or ''))
if case is None:
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
formal = resolve_formal_ot(case)
if not formal.get('has_formal_ot') or formal.get('task') is None:
raise ConflictError(
'A formal order task is required before rebinding customer',
code='SHIPPING.FORMAL_OT_REQUIRED',
details={'task_missing': bool(formal.get('task_missing'))},
)
result = rebind_confirmed_customer(
task=formal['task'],
new_customer_id=customer_id,
actor_id=int(user.id),
expected_order_data_version=expected_order_data_version,
reason=str(data.get('reason') or '').strip() or None,
)
db.session.commit()
resolution = result['resolution']
rebind_record = next(
(
item.get('rebind') for item in (resolution.evidence_json or [])
if isinstance(item, dict) and item.get('rebind')
),
None,
) or {}
refreshed_case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or ''))
return _ok({
'case': serialize_review_case(refreshed_case) if refreshed_case is not None else None,
'customer_resolution': (
project_review_case_customer_resolution(refreshed_case)
if refreshed_case is not None else None
),
'rebind': {
'previous_customer_id': rebind_record.get('previous_customer_id'),
'customer_id': int(resolution.confirmed_customer_id),
'snapshot_id': int(result['snapshot'].id),
},
})
@workspace_shipping_notice_bp.route( @workspace_shipping_notice_bp.route(
'/shipping-notice/order-review-cases/<case_no>/reservation/revalidate', '/shipping-notice/order-review-cases/<case_no>/reservation/revalidate',
methods=['POST'], methods=['POST'],
@@ -1,8 +1,8 @@
""" """
backend/app/api/workspace/shipping_inventory_candidates.py backend/app/api/workspace/shipping_onhand_candidates.py
用途:正式 Task 库存候选只读详情 API。 用途:正式 Task 库存候选只读详情 API。
依赖:workspace_shipping_notice_bp、query_service.get_task_for_user、inventory_candidate_projection。 依赖:workspace_shipping_notice_bp、query_service.get_task_for_user、onhand_candidate_projection。
逻辑:路由层仅做鉴权与查询参数校验;当前版本缺失返回 200 + current_set=null + blocking_reason, 逻辑:路由层仅做鉴权与查询参数校验;当前版本缺失返回 200 + current_set=null + blocking_reason,
不把可恢复业务阻断误报成 404。 不把可恢复业务阻断误报成 404。
""" """
@@ -13,7 +13,7 @@ from flask import request
from app.api.workspace.shipping_notice import _ok, _require_user, workspace_shipping_notice_bp from app.api.workspace.shipping_notice import _ok, _require_user, workspace_shipping_notice_bp
from app.core.errors import ValidationError from app.core.errors import ValidationError
from app.services.shipping_notice.inventory_candidate_projection import ( from app.services.shipping_notice.onhand_candidate_projection import (
project_inventory_candidate_detail, project_inventory_candidate_detail,
) )
from app.services.shipping_notice.query_service import get_task_for_user from app.services.shipping_notice.query_service import get_task_for_user
+41 -27
View File
@@ -299,9 +299,6 @@ class Config:
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS', '5') or '5') IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS', '5') or '5')
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS', '7') or '7') IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS', '7') or '7')
IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET = os.getenv('IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET', 'hxops-transfer').strip() IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET = os.getenv('IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET', 'hxops-transfer').strip()
IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS = int(
os.getenv('IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS', '2') or '2'
)
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float( SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float(
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '420') os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '420')
) )
@@ -373,14 +370,18 @@ class Config:
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY = float( SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY = float(
os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY') or '0.98' os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY') or '0.98'
) )
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = ( SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED = (
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true' os.getenv('SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED', 'true').lower() == 'true'
) )
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS = int( FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS = int(
os.getenv('FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS') or '900' os.getenv('FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS') or '900'
) )
FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS = int( FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS = int(
os.getenv('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS') or '900' os.getenv('FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS') or '900'
)
# 出站抓取本期无 Worker;超时键与 inbound 同形预留,避免后续批次再改 env 骨架。
FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS = int(
os.getenv('FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS') or '900'
) )
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int( FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int(
os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90' os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90'
@@ -442,38 +443,51 @@ class Config:
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS = int( SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS = int(
os.getenv('SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS') or '24' os.getenv('SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS') or '24'
) )
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED = ( SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED = (
os.getenv('SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED', 'true').lower() == 'true' os.getenv('SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED', 'true').lower() == 'true'
) )
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS') SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP') FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
# RPA 运行期数据目录统一为 `freight_rpa/{inventory,receipt,common}` 三层布局(与 env/ps1 三侧一致)。 # RPA 运行期数据目录分域(2026-10-16 批次 R):
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR = _rpa_data_path( # onhand/ inbound/ outbound/ — 抓取域,叶目录同构 triggers|drop|logs|archives
'FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR', 'freight_rpa', 'inventory', 'drop' # upload/ — 上传域,叶目录 triggers|queue(与抓取域并列,勿挂 outbound 下)
# common/ — 跨 Worker 共享(browser_profile)
# outbound 本期无 Worker,仍落盘同构目录 + env,避免切换日再改骨架。
FREIGHT_RPA_SHARED_ONHAND_DROP_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_ONHAND_DROP_DIR', 'freight_rpa', 'onhand', 'drop'
) )
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR = _rpa_data_path( FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR', 'freight_rpa', 'inventory', 'triggers' 'FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR', 'freight_rpa', 'onhand', 'triggers'
) )
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR = _rpa_data_path( FREIGHT_RPA_SHARED_INBOUND_DROP_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR', 'freight_rpa', 'receipt', 'drop' 'FREIGHT_RPA_SHARED_INBOUND_DROP_DIR', 'freight_rpa', 'inbound', 'drop'
) )
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR = _rpa_data_path( FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', 'freight_rpa', 'receipt', 'triggers' 'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR', 'freight_rpa', 'inbound', 'triggers'
)
FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR', 'freight_rpa', 'outbound', 'drop'
)
FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR', 'freight_rpa', 'outbound', 'triggers'
) )
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = _rpa_data_path( FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR', 'freight_rpa', 'inventory', 'upload_queue' 'FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR', 'freight_rpa', 'upload', 'queue'
) )
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = _rpa_data_path( FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR', 'freight_rpa', 'inventory', 'upload_triggers' 'FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR', 'freight_rpa', 'upload', 'triggers'
) )
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = _rpa_data_path( FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = _rpa_data_path(
'FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR', 'freight_rpa', 'common', 'browser_profile' 'FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR', 'freight_rpa', 'common', 'browser_profile'
) )
FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path( FREIGHT_RPA_ONHAND_ARCHIVE_DIR = _rpa_data_path(
'FREIGHT_RPA_INVENTORY_ARCHIVE_DIR', 'freight_rpa', 'inventory', 'archives' 'FREIGHT_RPA_ONHAND_ARCHIVE_DIR', 'freight_rpa', 'onhand', 'archives'
) )
FREIGHT_RPA_RECEIPT_ARCHIVE_DIR = _rpa_data_path( FREIGHT_RPA_INBOUND_ARCHIVE_DIR = _rpa_data_path(
'FREIGHT_RPA_RECEIPT_ARCHIVE_DIR', 'freight_rpa', 'receipt', 'archives' 'FREIGHT_RPA_INBOUND_ARCHIVE_DIR', 'freight_rpa', 'inbound', 'archives'
)
FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR = _rpa_data_path(
'FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR', 'freight_rpa', 'outbound', 'archives'
) )
FREIGHT_RPA_WORKER_MOCK = os.getenv('FREIGHT_RPA_WORKER_MOCK', 'false') FREIGHT_RPA_WORKER_MOCK = os.getenv('FREIGHT_RPA_WORKER_MOCK', 'false')
@@ -499,7 +513,7 @@ class Config:
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL') WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true' WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL') WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,order_delivery_reply_notify,training_lean_video_push,training_overseas_thailand_guidelines') WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,equipment_acceptance_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,order_delivery_reply_notify,training_lean_video_push,training_overseas_thailand_guidelines')
# 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/<id>)。 # 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/<id>)。
# 缺省 0 = 不显式指定,由后端按 handler_config.content_profile='training' 动态解析各环境的培训 Agent # 缺省 0 = 不显式指定,由后端按 handler_config.content_profile='training' 动态解析各环境的培训 Agent
# (测试/正式环境 Agent ID 不同,动态解析保证卡片均可定位「员工培训-精益管理」); # (测试/正式环境 Agent ID 不同,动态解析保证卡片均可定位「员工培训-精益管理」);
+4 -1
View File
@@ -28,11 +28,14 @@ class ValidationError(AppError):
*, *,
code: str = "VALIDATION.INVALID_PARAM", code: str = "VALIDATION.INVALID_PARAM",
details: dict[str, Any] | None = None, details: dict[str, Any] | None = None,
http_status: int = 400,
): ):
super().__init__( super().__init__(
code=code, code=code,
message=message, message=message,
http_status=400, # 默认 400(参数形态类校验);业务契约指定状态码时显式传入
# (如调拨类型门禁 REQUIRED/NOT_CONFIGURED/DISABLED = 422,规格 §11)。
http_status=http_status,
details=details or {}, details=details or {},
retryable=False, retryable=False,
) )
+45
View File
@@ -0,0 +1,45 @@
"""
backend/app/core/tool_auth.py
用途:集成密钥鉴权的公共实现,供所有以 Bearer / X-Integration-Key 方式接入的
Tool / 回调蓝图共用(当前:shipping_notice Tool 蓝图、freight-rpa 回调蓝图)。
依赖:flask.current_app/request、app.core.errors(ServiceUnavailableError / UnauthorizedError)。
逻辑:由各蓝图 before_request 调用 require_tool_auth();本模块只做 Header 校验,
不感知任何具体蓝图的错误 envelope(由蓝图自身 errorhandler 决定响应格式)。
"""
from __future__ import annotations
from flask import current_app, request
from app.core.errors import ServiceUnavailableError, UnauthorizedError
def require_tool_auth() -> None:
"""
校验集成方 Tool / RPA 回调 API 鉴权 Header。
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA Worker 或
外部系统请求挂接本鉴权的蓝图时,由该蓝图的 before_request 自动触发。
核心逻辑:只接受 `Authorization: Bearer <token>` 或 `X-Integration-Key`。
货代专用 `SHIPPING_NOTICE_TOOL_API_KEY` 优先,未配置时回退 `INTEGRATION_API_KEY`;
未配置任何可用 key 时报服务不可用,缺失或错误时报未授权。
"""
configured = str(
current_app.config.get('SHIPPING_NOTICE_TOOL_API_KEY')
or current_app.config.get('INTEGRATION_API_KEY')
or ''
).strip()
if not configured:
raise ServiceUnavailableError(
'SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured',
code='missing_auth',
)
bearer = str(request.headers.get('Authorization') or '').strip()
token = bearer[7:].strip() if bearer.lower().startswith('bearer ') else ''
integration_key = str(request.headers.get('X-Integration-Key') or '').strip()
if configured in {token, integration_key}:
return
if not token and (not integration_key):
raise UnauthorizedError('missing_auth')
raise UnauthorizedError('invalid_auth')
+1 -1
View File
@@ -16,7 +16,7 @@ from app.jobs.handlers import ( # noqa: F401
procurement_contract_review, procurement_contract_review,
schedule_run, schedule_run,
shipping_document_layout, shipping_document_layout,
shipping_inventory_callback_process, freight_rpa_onhand_callback_process,
shipping_notice_parse, shipping_notice_parse,
shipping_notice_run, shipping_notice_run,
shipping_order_extraction, shipping_order_extraction,
@@ -1,9 +1,13 @@
""" """
backend/app/jobs/handlers/shipping_inventory_callback_process.py backend/app/jobs/handlers/freight_rpa_onhand_callback_process.py
用途:异步处理已收件的库存 RPA batch 回调,避免 Worker HTTP 回调被 Excel 处理阻塞。 用途:异步处理已收件的库存 RPA batch 回调,避免 Worker HTTP 回调被 Excel 处理阻塞。
依赖:Job 队列、inventory_rpa_workflow 的正式批量处理函数。 依赖:Job 队列、onhand_rpa_workflow 的正式批量处理函数。
逻辑:HTTP 回调只写本 Job;shipping worker 领取后执行结构校验、库存解析、任务关联与后续推进。 逻辑:HTTP 回调只写本 Job;shipping worker 领取后执行结构校验、库存解析、任务关联与后续推进。
业务失败(transport/result_status=failed)收口为不可重试;意外异常(含批量 commit 后
onhand 事实处理函数失败的重抛)收口为可重试(Task 7 修复轮 2——文件行已提交不回滚,
重放按幂等契约补齐候选/门禁收口);修复轮 3:投递失败重抛携带的未成功文件清单写回
payload(retry_dispatch_files),重试经批量入口的「只重投失败文件」通道补齐。
""" """
from __future__ import annotations from __future__ import annotations
@@ -16,7 +20,7 @@ from app.jobs.types import JobType
from app.models import Job from app.models import Job
@register_handler(JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS) @register_handler(JobType.FREIGHT_RPA_ONHAND_CALLBACK_PROCESS)
def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> None: def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> None:
"""处理一个已收件的库存 RPA 回调。 """处理一个已收件的库存 RPA 回调。
@@ -31,7 +35,7 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N
owned_attempt = int(job.attempts or 0) owned_attempt = int(job.attempts or 0)
try: try:
from app.services.shipping_notice.inventory_rpa_workflow import process_rpa_report_inventory_batch from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
result = process_rpa_report_inventory_batch(dict(job.payload_json or {})) result = process_rpa_report_inventory_batch(dict(job.payload_json or {}))
result_data = result.get('data') if isinstance(result, dict) else None result_data = result.get('data') if isinstance(result, dict) else None
@@ -44,7 +48,7 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N
if transport_status == 'failed' or result_status in {'failed', 'partial_failed'}: if transport_status == 'failed' or result_status in {'failed', 'partial_failed'}:
failed_items = result_data.get('failed') if isinstance(result_data, dict) else [] failed_items = result_data.get('failed') if isinstance(result_data, dict) else []
first_error = failed_items[0].get('error') if isinstance(failed_items, list) and failed_items and isinstance(failed_items[0], dict) else None first_error = failed_items[0].get('error') if isinstance(failed_items, list) and failed_items and isinstance(failed_items[0], dict) else None
from app.services.shipping_notice.inventory_rpa_workflow import settle_failed_inventory_callback from app.services.shipping_notice.onhand_rpa_workflow import settle_failed_inventory_callback
settle_failed_inventory_callback( settle_failed_inventory_callback(
dict(job.payload_json or {}), dict(job.payload_json or {}),
@@ -64,12 +68,32 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N
message='库存 RPA 回调已异步处理', message='库存 RPA 回调已异步处理',
owned_attempt=owned_attempt, owned_attempt=owned_attempt,
) )
except Exception as exc: # noqa: BLE001 - queue must retain retryable receipt evidence except Exception as exc: # noqa: BLE001 - 队列收口保留可重试证据
db.session.rollback() db.session.rollback()
# 【Task 7 修复轮 3】批量 commit 后投递失败的重抛携带「未成功文件清单」——
# 写回 Job payload(retry_dispatch_files),重试经批量入口的「只重投失败
# 文件」通道补齐(整批重放会被 callback_id 已消费的 replay 检查跳过、
# 已收口的排程 run 校验拦下);清单随重试结果逐轮收敛,直至全部成功或
# attempts 耗尽。普通意外异常(无清单)仍整批自然重放。
from app.services.shipping_notice.onhand_rpa_workflow import (
OnhandReportDispatchAfterCommitError,
)
if isinstance(exc, OnhandReportDispatchAfterCommitError) and exc.failed_files:
job.payload_json = {
**(dict(job.payload_json or {})),
'retry_dispatch_files': list(exc.failed_files),
}
db.session.commit()
fail_job( fail_job(
job.id, job.id,
error=str(exc), error=str(exc),
result={'status': 'processing_failed', 'error': str(exc)[:1000]}, result={'status': 'processing_failed', 'error': str(exc)[:1000]},
retryable=False, # 【Task 7 修复轮 2】意外异常(含批量 commit 后 onhand 事实处理函数失败
# ——process_rpa_report_inventory_batch 已尽力完成其余投递、排程收口与
# drop 文件清理入队后原样重抛)必须可重试:文件行已提交不回滚,重放按
# 幂等契约补齐收口;业务失败(transport/result_status=failed)仍走上方
# retryable=False 分支。
retryable=True,
owned_attempt=owned_attempt, owned_attempt=owned_attempt,
) )
@@ -5,6 +5,13 @@
逻辑:领取后按 payload.matching_id 加载匹配,运行 run_matching 并回写 逻辑:领取后按 payload.matching_id 加载匹配,运行 run_matching 并回写
状态/计数/Hash;匹配不存在时 fail-closed 抛 RuntimeError。业务收尾后 状态/计数/Hash;匹配不存在时 fail-closed 抛 RuntimeError。业务收尾后
handler 自行 finish_job(runner 仅兜底异常路径,正常完成不代收口)。 handler 自行 finish_job(runner 仅兜底异常路径,正常完成不代收口)。
【2026-10-14 出生翻转/快照自足确认】异步重跑的全部口径从 scope_json
快照回读——transfer_type 编码 + scope_rules/transform_rules 覆盖传入
(不读现行配置规则,在途匹配口径不被中途改配置扰动);类型门禁按
require_enabled=False(「停用后存量不受影响」,规格 §4.1),仅要求配置
仍存在(类型只有停用没有删除)。run_matching 传 matching_id:重跑圈档
仅补建「未被有效 items 占用」的新档记录(D17:自有 items 不重复圈定/
不重复评估他匹配行),并刷新本匹配自有 items。
""" """
from __future__ import annotations from __future__ import annotations
@@ -36,6 +43,8 @@ def run_in_transit_transfer_match(_ctx, payload: dict) -> None:
owned_attempt = int(job_row.attempts) if job_row is not None else None owned_attempt = int(job_row.attempts) if job_row is not None else None
deps = transfer_deps.get_transfer_dependencies() deps = transfer_deps.get_transfer_dependencies()
# [快照自足] 类型/范围/转换规则全部回读 scope_json(无枚举依赖、不查现行
# 配置规则);warehouse 路由的 fixed 定义随类型配置现行值(未入快照契约)。
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {} scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
source_codes = list(scope.get("source_codes") or []) source_codes = list(scope.get("source_codes") or [])
result = run_matching( result = run_matching(
@@ -43,14 +52,18 @@ def run_in_transit_transfer_match(_ctx, payload: dict) -> None:
business_date=matching.business_date, business_date=matching.business_date,
deps=deps, deps=deps,
run_no=matching.run.run_no if matching.run else "RUN-PENDING", run_no=matching.run.run_no if matching.run else "RUN-PENDING",
# 类型范围随匹配落库回读:异步重跑与创建时口径一致(缺省回落类型1)。
transfer_type=str(scope.get("transfer_type")) if scope.get("transfer_type") else None, transfer_type=str(scope.get("transfer_type")) if scope.get("transfer_type") else None,
matching_id=matching.id,
scope_rules_override=scope.get("scope_rules") if isinstance(scope.get("scope_rules"), list) else None,
transform_rules_override=(
scope.get("transform_rules") if isinstance(scope.get("transform_rules"), list) else None
),
require_enabled=False, # 存量重跑:停用类型不受影响(仅要求配置仍存在)
) )
summary = result.summary summary = result.summary
matching.status = summary.status matching.status = summary.status
matching.counts_json = { matching.counts_json = {
"file_invoice_count": summary.counts.file_invoice_count, "file_invoice_count": summary.counts.file_invoice_count,
"not_matured_count": summary.counts.not_matured_count,
"matched_count": summary.counts.matched_count, "matched_count": summary.counts.matched_count,
"executable_count": summary.counts.executable_count, "executable_count": summary.counts.executable_count,
"blocked_count": summary.counts.blocked_count, "blocked_count": summary.counts.blocked_count,
@@ -724,6 +724,58 @@ def _handoff_continue_order_extraction(
return True return True
def _emit_reservation_heuristic_audit(
*,
run: Any,
merged_by_unit_id: dict[int, list[dict[str, Any]]],
) -> None:
"""
合并末段「裸数字预约单号兜底」落地后补审计事件,供上线后观察误判率。
【AI 触发时机】:EML 补充合并(merge_email_supplements)完成后调用。
只读订单上的 _hxops_reservation_heuristic 标记,不修改订单;命中与多候选
各发一条事件,metadata 携带 unit/候选值/正文文档定位,便于按 Case 回溯证据。
Args:
run: 当前订单抽取 Run(审计聚合根)。
merged_by_unit_id: 本趟合并产物 {unit_id: [order]}。
"""
applied_entries: list[dict[str, Any]] = []
ambiguous_entries: list[dict[str, Any]] = []
for unit_id, orders in (merged_by_unit_id or {}).items():
for order in orders or []:
marker = order.get('_hxops_reservation_heuristic') if isinstance(order, dict) else None
if not isinstance(marker, dict):
continue
entry = {
'unit_id': int(unit_id),
'values': marker.get('values') or [],
'document_id': marker.get('document_id'),
}
if marker.get('status') == 'applied':
applied_entries.append({**entry, 'value': marker.get('value')})
else:
ambiguous_entries.append(entry)
for event_type, entries in (
('reservation_heuristic_applied', applied_entries),
('reservation_heuristic_ambiguous', ambiguous_entries),
):
if not entries:
continue
append_shipping_audit_event(
event_type=event_type,
aggregate_type='order_extraction_run',
aggregate_id=str(run.id),
run_no=run.run_no,
actor_type='system',
source='shipping_order_extraction',
metadata={
'entries': entries,
'decision_rule_version': 'bare-numeric-reservation-v1',
},
)
def _is_transient_lock_error(exc: BaseException) -> bool: def _is_transient_lock_error(exc: BaseException) -> bool:
""" """
判断异常是否为瞬时锁冲突(PostgreSQL 死锁 40P01 / 锁等待超时 55P03)。 判断异常是否为瞬时锁冲突(PostgreSQL 死锁 40P01 / 锁等待超时 55P03)。
@@ -1139,6 +1191,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
}, },
) )
_merge_group_orders(eml_units, apply_email_supplements=True) _merge_group_orders(eml_units, apply_email_supplements=True)
_emit_reservation_heuristic_audit(run=run, merged_by_unit_id=merged_by_unit_id)
append_shipping_audit_event( append_shipping_audit_event(
event_type='ORDER_EMAIL_ADJUDICATION_COMPLETED', event_type='ORDER_EMAIL_ADJUDICATION_COMPLETED',
aggregate_type='order_extraction_run', aggregate_type='order_extraction_run',
+7 -4
View File
@@ -3,7 +3,9 @@ backend/app/jobs/types.py
用途:Job 类型与状态枚举;KbJob.job_type 与 handler JobType 的双向映射。 用途:Job 类型与状态枚举;KbJob.job_type 与 handler JobType 的双向映射。
逻辑:handlers 与 queue 通过 JobType 注册;store 持久化仍走 KbJob 表(Wave 2 双轨); 逻辑:handlers 与 queue 通过 JobType 注册;store 持久化仍走 KbJob 表(Wave 2 双轨);
shipping_process_gate 由 shipping worker 与发货通知任务同队列领取。 shipping_process_gate 由 shipping worker 与发货通知任务同队列领取;
在手回调成员 FREIGHT_RPA_ONHAND_CALLBACK_PROCESS 的持久化值为
freight_rpa_onhand_callback_process。
""" """
from __future__ import annotations from __future__ import annotations
@@ -20,8 +22,9 @@ class JobType(StrEnum):
SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction' SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction'
SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout' SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout'
SHIPPING_PROCESS_GATE = 'shipping_process_gate' SHIPPING_PROCESS_GATE = 'shipping_process_gate'
# RPA 回调 HTTP 只收件;Excel 校验、解析、任务关联由 shipping worker 异步完成。 # 在手 RPA 回调 HTTP 只收件;Excel 校验、解析、任务关联由 shipping worker 异步完成。
SHIPPING_INVENTORY_CALLBACK_PROCESS = 'shipping_inventory_callback_process' # 持久化 jobs.job_type 为 freight_rpa_onhand_callback_process。
FREIGHT_RPA_ONHAND_CALLBACK_PROCESS = 'freight_rpa_onhand_callback_process'
# 统一 PDF 自动标记:按实际证据能力执行坐标重建或 XFA 多源视觉融合。 # 统一 PDF 自动标记:按实际证据能力执行坐标重建或 XFA 多源视觉融合。
SHIPPING_PDF_AUTOMARK = 'shipping_pdf_automark' SHIPPING_PDF_AUTOMARK = 'shipping_pdf_automark'
# 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm) # 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm)
@@ -76,7 +79,7 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
'shipping': frozenset({ 'shipping': frozenset({
'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction', 'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction',
'shipping_document_layout', 'shipping_process_gate', 'shipping_pdf_automark', 'shipping_document_layout', 'shipping_process_gate', 'shipping_pdf_automark',
'shipping_inventory_callback_process', 'freight_rpa_onhand_callback_process',
'shipping_stp_auto_create', 'shipping_line_auto_fulfill', 'shipping_stp_auto_create', 'shipping_line_auto_fulfill',
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress', 'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
}), }),
+87 -60
View File
@@ -2,8 +2,9 @@
backend/app/models/__init__.py backend/app/models/__init__.py
用途:按业务域拆分的 ORM 模型包入口;聚合导出以保持 `from app.models import User` 兼容。 用途:按业务域拆分的 ORM 模型包入口;聚合导出以保持 `from app.models import User` 兼容。
依赖:models/* 子模块(含 voucher_check)、app.extensions.db(经 base.Base)。 依赖:models/* 子模块(含 voucher_check、equipment_acceptance、freight_rpa_*)、app.extensions.db(经 base.Base)。
逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。 逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。
在手/入站/出站模型导出 FreightRpa*。
""" """
from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest
@@ -31,15 +32,15 @@ from app.models.contract_payment import (
ContractPaymentVendorRequest, ContractPaymentVendorRequest,
) )
from app.models.shipping import ( from app.models.shipping import (
ShippingInventoryFile,
ShippingNotice, ShippingNotice,
ShippingOrderCandidate, ShippingOrderCandidate,
ShippingOrderDocument, ShippingOrderDocument,
ShippingOrderIntake, ShippingOrderIntake,
ShippingTaskEvent, ShippingTaskEvent,
ShippingTaskPurgeAudit, ShippingTaskPurgeAudit,
ShippingTaskInventoryLink, ShippingTaskOnhandLink,
) )
from app.models.freight_rpa_onhand_report_file import FreightRpaOnhandReportFile
from app.models.shipping_order_submission import ShippingOrderSubmission from app.models.shipping_order_submission import ShippingOrderSubmission
from app.models.shipping_order_task import ShippingOrderTask from app.models.shipping_order_task import ShippingOrderTask
from app.models.shipping_order_candidate_evidence import ShippingOrderCandidateEvidence from app.models.shipping_order_candidate_evidence import ShippingOrderCandidateEvidence
@@ -52,8 +53,8 @@ from app.models.shipping_context_provider import ShippingContextProvider, Shippi
from app.models.shipping_excel_template import ShippingExcelTemplate, ShippingExportArtifact from app.models.shipping_excel_template import ShippingExcelTemplate, ShippingExportArtifact
from app.models.shipping_fulfillment import ( from app.models.shipping_fulfillment import (
ShippingExportArtifactLine, ShippingExportArtifactLine,
ShippingInventoryVerification, ShippingOnhandVerification,
ShippingInventoryVerificationLine, ShippingOnhandVerificationLine,
ShippingReservation, ShippingReservation,
ShippingUploadAttempt, ShippingUploadAttempt,
) )
@@ -95,7 +96,7 @@ from app.models.shipping_order_review import (
from app.models.shipping_order_review_line_decision import ShippingOrderReviewLineDecision from app.models.shipping_order_review_line_decision import ShippingOrderReviewLineDecision
from app.models.shipping_order_review_wave_line import ShippingOrderReviewWaveLine from app.models.shipping_order_review_wave_line import ShippingOrderReviewWaveLine
from app.models.shipping_order_review_wave_idempotency import ShippingOrderReviewWaveIdempotency from app.models.shipping_order_review_wave_idempotency import ShippingOrderReviewWaveIdempotency
from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch from app.models.shipping_notice_line_onhand_match import ShippingNoticeLineOnhandMatch
from app.models.shipping_order_review_suggestion import ShippingOrderReviewSuggestion from app.models.shipping_order_review_suggestion import ShippingOrderReviewSuggestion
from app.models.shipping_order_extraction_run import ( from app.models.shipping_order_extraction_run import (
ShippingOrderExtractionDiagnosticAudit, ShippingOrderExtractionDiagnosticAudit,
@@ -137,27 +138,32 @@ from app.models.shipping_document_layout import ShippingDocumentLayoutVersion
from app.models.shipping_eml_preview_snapshot import ShippingEmlPreviewSnapshot from app.models.shipping_eml_preview_snapshot import ShippingEmlPreviewSnapshot
from app.models.shipping_xfa_structure_analysis import ShippingXfaStructureAnalysis from app.models.shipping_xfa_structure_analysis import ShippingXfaStructureAnalysis
from app.models.shipping_xfa_audit_snapshot import ShippingXfaAuditSnapshot from app.models.shipping_xfa_audit_snapshot import ShippingXfaAuditSnapshot
from app.models.shipping_inventory_config import ( from app.models.freight_rpa_config import (
ShippingInventoryField, FreightRpaOnhandField,
ShippingInventoryExternalMapping, FreightRpaOnhandExternalMapping,
ShippingInventoryConfigurationTestRun, FreightRpaOnhandConfigurationTestRun,
ShippingInventoryValidationBatch, FreightRpaOnhandValidationBatch,
ShippingInventorySourceParsingBindingAudit, FreightRpaSourceParsingBindingAudit,
ShippingInventoryParsingProfile, FreightRpaParsingProfile,
ShippingInventoryRoutingRule, FreightRpaOnhandRoutingRule,
ShippingInventoryRoutingRuleCondition, FreightRpaOnhandRoutingRuleCondition,
ShippingInventoryRoutingRuleVersion, FreightRpaOnhandRoutingRuleVersion,
ShippingInventorySource, FreightRpaSource,
ShippingInventoryStructureAnalysis, FreightRpaOnhandReportConfig,
ShippingRpaProfile, FreightRpaOnhandStructureAnalysis,
FreightRpaProfile,
) )
from app.models.shipping_receipt_report import ( from app.models.freight_rpa_inbound_report import (
ShippingReceiptNotificationDelivery, FreightRpaInboundReportConfig,
ShippingReceiptReportConfig, FreightRpaInboundReportFile,
ShippingReceiptReportFile, FreightRpaInboundUnitRun,
ShippingReceiptRpaUnitRun,
) )
from app.models.shipping_temporary_inventory import ShippingTemporaryInventorySession from app.models.freight_rpa_outbound_report import (
FreightRpaOutboundReportConfig,
FreightRpaOutboundReportFile,
FreightRpaOutboundUnitRun,
)
from app.models.shipping_temporary_onhand import ShippingTemporaryOnhandSession
from app.models.shipping_customer import ( from app.models.shipping_customer import (
ShippingBusinessSequence, ShippingBusinessSequence,
ShippingCustomer, ShippingCustomer,
@@ -180,18 +186,18 @@ from app.models.shipping_identity_rule import (
ShippingIdentityRuleAuditEvent, ShippingIdentityRuleAuditEvent,
ShippingIdentityRuleSet, ShippingIdentityRuleSet,
) )
from app.models.shipping_inventory_candidates import ( from app.models.shipping_onhand_candidates import (
ShippingInventoryCandidateLine, ShippingOnhandCandidateLine,
ShippingInventoryCandidateSet, ShippingOnhandCandidateSet,
ShippingInventoryCandidateSource, ShippingOnhandCandidateSource,
) )
from app.models.shipping_task_inventory_rpa_attempts import ShippingTaskInventoryRpaAttempt from app.models.freight_rpa_onhand_task_attempts import FreightRpaOnhandTaskAttempt
from app.models.shipping_process_recovery_plan import ShippingProcessRecoveryPlan from app.models.shipping_process_recovery_plan import ShippingProcessRecoveryPlan
from app.models.shipping_inventory_preparation import ( from app.models.shipping_onhand_preparation import (
ShippingInventoryPreparationAttempt, ShippingOnhandPreparationAttempt,
ShippingInventoryPreparationSourceAttempt, ShippingOnhandPreparationSourceAttempt,
) )
from app.models.shipping_inventory_mapping import ShippingInventoryMapping from app.models.freight_rpa_onhand_mapping import FreightRpaOnhandMapping
from app.models.training import ( from app.models.training import (
LeanTrainingCompletion, LeanTrainingCompletion,
LeanTrainingReminder, LeanTrainingReminder,
@@ -208,8 +214,10 @@ from app.models.in_transit_transfer import (
TransferDocument, TransferDocument,
TransferInvoiceItem, TransferInvoiceItem,
TransferMatching, TransferMatching,
TransferMovementLedger,
TransferRun, TransferRun,
TransferSourceJob, TransferSourceJob,
TransferTypeConfig,
) )
from app.models.integration_connector import ( from app.models.integration_connector import (
IntegrationBinding, IntegrationBinding,
@@ -238,6 +246,14 @@ from app.models.contract_payment import (
ContractPaymentSyncState, ContractPaymentSyncState,
ContractPaymentVendorRequest, ContractPaymentVendorRequest,
) )
from app.models.equipment_acceptance import (
EquipmentAcceptanceNode,
EquipmentAcceptanceOperator,
EquipmentAcceptanceOrder,
EquipmentAcceptanceSendFile,
EquipmentAcceptanceSendRecord,
EquipmentAcceptanceSetting,
)
from app.models.order_delivery_reply import ( from app.models.order_delivery_reply import (
OrderDeliveryAuditEvent, OrderDeliveryAuditEvent,
OrderDeliveryBatch, OrderDeliveryBatch,
@@ -309,7 +325,7 @@ __all__ = [
'ShippingOrderReviewLineDecision', 'ShippingOrderReviewLineDecision',
'ShippingOrderReviewWaveLine', 'ShippingOrderReviewWaveLine',
'ShippingOrderReviewWaveIdempotency', 'ShippingOrderReviewWaveIdempotency',
'ShippingNoticeLineInventoryMatch', 'ShippingNoticeLineOnhandMatch',
'ShippingOrderReviewSuggestion', 'ShippingOrderReviewSuggestion',
'ShippingOrderProcessingRun', 'ShippingOrderProcessingRun',
'ShippingOrderProcessingRunIntake', 'ShippingOrderProcessingRunIntake',
@@ -358,30 +374,33 @@ __all__ = [
'ShippingIdentityRuleAuditEvent', 'ShippingIdentityRuleAuditEvent',
'ShippingTaskEvent', 'ShippingTaskEvent',
'ShippingTaskPurgeAudit', 'ShippingTaskPurgeAudit',
'ShippingInventoryFile', 'FreightRpaOnhandReportFile',
'ShippingTaskInventoryLink', 'ShippingTaskOnhandLink',
'ShippingRpaProfile', 'FreightRpaProfile',
'ShippingInventorySource', 'FreightRpaSource',
'ShippingReceiptReportConfig', 'FreightRpaOnhandReportConfig',
'ShippingReceiptRpaUnitRun', 'FreightRpaInboundReportConfig',
'ShippingReceiptReportFile', 'FreightRpaInboundUnitRun',
'ShippingReceiptNotificationDelivery', 'FreightRpaInboundReportFile',
'ShippingInventoryField', 'FreightRpaOutboundReportConfig',
'ShippingInventoryStructureAnalysis', 'FreightRpaOutboundUnitRun',
'ShippingInventoryRoutingRule', 'FreightRpaOutboundReportFile',
'ShippingInventoryRoutingRuleCondition', 'FreightRpaOnhandField',
'ShippingInventoryRoutingRuleVersion', 'FreightRpaOnhandStructureAnalysis',
'ShippingInventoryExternalMapping', 'FreightRpaOnhandRoutingRule',
'ShippingInventoryConfigurationTestRun', 'FreightRpaOnhandRoutingRuleCondition',
'ShippingInventoryValidationBatch', 'FreightRpaOnhandRoutingRuleVersion',
'ShippingInventorySourceParsingBindingAudit', 'FreightRpaOnhandExternalMapping',
'ShippingInventoryParsingProfile', 'FreightRpaOnhandConfigurationTestRun',
'ShippingTemporaryInventorySession', 'FreightRpaOnhandValidationBatch',
'FreightRpaSourceParsingBindingAudit',
'FreightRpaParsingProfile',
'ShippingTemporaryOnhandSession',
'ShippingExcelTemplate', 'ShippingExcelTemplate',
'ShippingExportArtifact', 'ShippingExportArtifact',
'ShippingReservation', 'ShippingReservation',
'ShippingInventoryVerification', 'ShippingOnhandVerification',
'ShippingInventoryVerificationLine', 'ShippingOnhandVerificationLine',
'ShippingExportArtifactLine', 'ShippingExportArtifactLine',
'ShippingUploadAttempt', 'ShippingUploadAttempt',
'ShippingProcessExecution', 'ShippingProcessExecution',
@@ -416,10 +435,10 @@ __all__ = [
'MaintenanceDevice', 'MaintenanceDevice',
'MaintenanceRecord', 'MaintenanceRecord',
'MaintenanceAuditLog', 'MaintenanceAuditLog',
'ShippingInventoryCandidateSet', 'ShippingOnhandCandidateSet',
'ShippingInventoryCandidateSource', 'ShippingOnhandCandidateSource',
'ShippingInventoryCandidateLine', 'ShippingOnhandCandidateLine',
'ShippingTaskInventoryRpaAttempt', 'FreightRpaOnhandTaskAttempt',
'VoucherCheckProfile', 'VoucherCheckProfile',
'VoucherCheckRun', 'VoucherCheckRun',
'VoucherCheckSubject', 'VoucherCheckSubject',
@@ -434,6 +453,12 @@ __all__ = [
'ContractPaymentAlert', 'ContractPaymentAlert',
'ContractPaymentAlertBatch', 'ContractPaymentAlertBatch',
'ContractPaymentSyncState', 'ContractPaymentSyncState',
'EquipmentAcceptanceOrder',
'EquipmentAcceptanceNode',
'EquipmentAcceptanceOperator',
'EquipmentAcceptanceSetting',
'EquipmentAcceptanceSendFile',
'EquipmentAcceptanceSendRecord',
'TransferRun', 'TransferRun',
'TransferSourceJob', 'TransferSourceJob',
'TransferMatching', 'TransferMatching',
@@ -442,6 +467,8 @@ __all__ = [
'TransferAttempt', 'TransferAttempt',
'TransferAuditEvent', 'TransferAuditEvent',
'TransferArchive', 'TransferArchive',
'TransferTypeConfig',
'TransferMovementLedger',
'IntegrationCredentialReference', 'IntegrationCredentialReference',
'IntegrationClientInstance', 'IntegrationClientInstance',
'IntegrationInterfaceDefinition', 'IntegrationInterfaceDefinition',
+3
View File
@@ -35,6 +35,7 @@ class QuickQuestion(Base):
常用问题表 常用问题表
用途:存储全局/用户常用问题;全局条目(user_id 为空)可配置标准答案并启用 FAQ 缓存命中。 用途:存储全局/用户常用问题;全局条目(user_id 为空)可配置标准答案并启用 FAQ 缓存命中。
is_enabled 控制工作台首页快捷入口;cache_enabled 控制聊天是否跳过 Dify 直答,二者独立。 is_enabled 控制工作台首页快捷入口;cache_enabled 控制聊天是否跳过 Dify 直答,二者独立。
fuzzy_enabled / fuzzy_threshold 控制精确未命中后的模糊兜底直答(逐条目独立,阈值钳制在 0.5~1.0)。
""" """
__tablename__ = 'quick_questions' __tablename__ = 'quick_questions'
@@ -48,6 +49,8 @@ class QuickQuestion(Base):
aliases: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) aliases: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
cache_enabled: Mapped[bool] = mapped_column(default=False) cache_enabled: Mapped[bool] = mapped_column(default=False)
is_enabled: Mapped[bool] = mapped_column(default=True) is_enabled: Mapped[bool] = mapped_column(default=True)
fuzzy_enabled: Mapped[bool] = mapped_column(default=False)
fuzzy_threshold: Mapped[float] = mapped_column(default=0.80)
hit_count: Mapped[int] = mapped_column(default=0) hit_count: Mapped[int] = mapped_column(default=0)
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) retriever_resources: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
source_kb_document_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) source_kb_document_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
+181
View File
@@ -0,0 +1,181 @@
"""
backend/app/models/equipment_acceptance.py
用途:设备验收预警的本地同步快照和可改配置。
依赖:models.base.Base、users。
逻辑:同步服务按流程实例 request_id upsert 主表,并整批替换当前节点和操作人子表。
配置表存四档天数、第 4 轮是否启用,以及三个固定岗位的系统用户。发送时刻不在这张表。
发送记录按验收单和档位留一行。已发送和已取消的姓名不回写;待发送每次扫描重算。
发给每位收件人的 Excel 另存一行,并用 send_record_ids 挂回发送记录,供表格列下载。
不保存流程编号、第二合同编号、验收日期和 isremark。
"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import JSON, BigInteger, Boolean, DateTime, ForeignKey, Index, LargeBinary, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class EquipmentAcceptanceOrder(Base):
"""一张验收单的最近一次同步结果。流程实例 request_id 唯一。"""
__tablename__ = "equipment_acceptance_orders"
__table_args__ = (
UniqueConstraint("request_id", name="uq_equipment_acceptance_orders_request_id"),
Index("ix_equipment_acceptance_orders_status", "monitor_status"),
)
id: Mapped[int] = mapped_column(primary_key=True)
acceptance_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
purchase_order_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
contract_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
timer_started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
dwell_days: Mapped[Optional[int]] = mapped_column(nullable=True)
can_accept: Mapped[Optional[int]] = mapped_column(
nullable=True,
comment="是否可以正常验收。0 否,1 是。空表示未标明。由 OA sfkyzcys 翻转,OA 为 0 是、1 否。",
)
cannot_accept_note: Mapped[Optional[str]] = mapped_column(
Text,
nullable=True,
comment="无法验收说明正文,来自 OA ft_gdzcysdv2.ycsm。只留痕,不单独触发停表。",
)
is_returned: Mapped[Optional[int]] = mapped_column(
nullable=True,
comment="是否退回。0 否,1 是。由 OA sfzfth 翻转,OA 为 0 是、1 否;OA 空值收成 0。",
)
flow_status_raw: Mapped[Optional[int]] = mapped_column(nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
request_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
request_match_count: Mapped[int] = mapped_column(nullable=False, default=0)
owner_oa_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
owner_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
owner_job_num: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
equip_oa_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
equip_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
equip_job_num: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
applicant_oa_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
applicant_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
applicant_job_num: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
monitor_status: Mapped[str] = mapped_column(String(40), nullable=False)
present_in_source: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
synced_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
)
class EquipmentAcceptanceNode(Base):
"""同步时看到的当前节点。一条流程可以有多行。"""
__tablename__ = "equipment_acceptance_nodes"
__table_args__ = (
UniqueConstraint("order_id", "node_id", name="uq_equipment_acceptance_nodes_order_node"),
Index("ix_equipment_acceptance_nodes_order", "order_id"),
)
id: Mapped[int] = mapped_column(primary_key=True)
order_id: Mapped[int] = mapped_column(
ForeignKey("equipment_acceptance_orders.id", ondelete="CASCADE"), nullable=False
)
node_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
node_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
node_type: Mapped[Optional[int]] = mapped_column(nullable=True)
class EquipmentAcceptanceOperator(Base):
"""当前节点上的操作人。同一节点同一人只留一行。不保存 isremark。"""
__tablename__ = "equipment_acceptance_operators"
__table_args__ = (
Index("ix_equipment_acceptance_operators_order", "order_id"),
)
id: Mapped[int] = mapped_column(primary_key=True)
order_id: Mapped[int] = mapped_column(
ForeignKey("equipment_acceptance_orders.id", ondelete="CASCADE"), nullable=False
)
node_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
user_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
handler_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
handler_job_num: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
class EquipmentAcceptanceSetting(Base):
"""预警配置。全表只使用 id=1 这一行。岗位存系统用户主键,姓名不入库。"""
__tablename__ = "equipment_acceptance_settings"
id: Mapped[int] = mapped_column(primary_key=True)
day_1: Mapped[int] = mapped_column(nullable=False, default=30)
day_2: Mapped[int] = mapped_column(nullable=False, default=37)
day_3: Mapped[int] = mapped_column(nullable=False, default=44)
day_4: Mapped[int] = mapped_column(nullable=False, default=51)
round_4_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
buyer_manager_user_id: Mapped[Optional[int]] = mapped_column(
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
)
coo_user_id: Mapped[Optional[int]] = mapped_column(
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
)
executive_user_id: Mapped[Optional[int]] = mapped_column(
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
)
updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
updated_by: Mapped[Optional[int]] = mapped_column(nullable=True)
class EquipmentAcceptanceSendRecord(Base):
"""一张验收单某一档的发送记录。同一张单同一档只留一行。已发送后不改收件人。"""
__tablename__ = "equipment_acceptance_send_records"
__table_args__ = (
UniqueConstraint("order_id", "tier", name="uq_equipment_acceptance_send_records_order_tier"),
Index("ix_equipment_acceptance_send_records_created", "created_at"),
Index("ix_equipment_acceptance_send_records_status", "status"),
)
id: Mapped[int] = mapped_column(primary_key=True)
order_id: Mapped[Optional[int]] = mapped_column(
ForeignKey("equipment_acceptance_orders.id", ondelete="SET NULL"), nullable=True
)
acceptance_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
purchase_order_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
tier: Mapped[int] = mapped_column(nullable=False)
threshold_days: Mapped[int] = mapped_column(nullable=False)
to_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
cc_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
recipients_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default="pending")
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
class EquipmentAcceptanceSendFile(Base):
"""一位收件人一次发送留下的 Excel。字节与当时发给企业微信的文件相同。"""
__tablename__ = "equipment_acceptance_send_files"
__table_args__ = (
Index("ix_equipment_acceptance_send_files_created", "created_at"),
)
id: Mapped[int] = mapped_column(primary_key=True)
recipient_user_id: Mapped[Optional[int]] = mapped_column(
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
)
recipient_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
excel_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary, nullable=True)
excel_file_size: Mapped[Optional[int]] = mapped_column(nullable=True)
send_record_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default="sent")
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
@@ -1,9 +1,11 @@
""" """
models/shipping_inventory_config.py backend/app/models/freight_rpa_config.py
用途:定义货代库存源、RPA Profile、通用路由规则及外部系统仓库映射主数据。 用途:定义货代库存源、RPA Profile、在手/入站/出站报表配置、通用路由规则及外部系统仓库映射主数据。
依赖:models.base.Base、SQLAlchemy ORM;凭据密文由 shipping_notice.credential_crypto 读写。 依赖:models.base.Base、SQLAlchemy ORM;凭据密文由 freight_rpa.common.credential_crypto 读写。
逻辑:库存运行链路以 ShippingInventorySource.source_code 为业务主键;RPA Profile 仅提供登录连接配置, 逻辑:库存运行链路以 FreightRpaSource.source_code 为业务主键;RPA Profile 仅提供登录连接配置;
在手报表路径/查询条件/解析方案绑定自 s18 起归 FreightRpaOnhandReportConfig(站点行不再存这三列),
入站/出站配置分别挂 inbound_report_config / outbound_report_config 一对一关系;
外部系统映射仅供后端内部复用,不承载调拨决策。 外部系统映射仅供后端内部复用,不承载调拨决策。
""" """
@@ -18,18 +20,18 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base from app.models.base import Base
class ShippingInventoryField(Base): class FreightRpaOnhandField(Base):
"""用户维护的库存业务字段目录;程序仅依据字段 ID 和业务用途运行。""" """用户维护的库存业务字段目录;程序仅依据字段 ID 和业务用途运行。"""
__tablename__ = 'shipping_inventory_fields' __tablename__ = 'freight_rpa_onhand_fields'
__table_args__ = ( __table_args__ = (
UniqueConstraint('field_code', name='uq_shipping_inventory_fields_code'), UniqueConstraint('field_code', name='uq_freight_rpa_onhand_fields_code'),
UniqueConstraint('display_name', name='uq_shipping_inventory_fields_display_name'), UniqueConstraint('display_name', name='uq_freight_rpa_onhand_fields_display_name'),
CheckConstraint("status IN ('active', 'retired')", name='ck_shipping_inventory_fields_status'), CheckConstraint("status IN ('active', 'retired')", name='ck_freight_rpa_onhand_fields_status'),
CheckConstraint("value_type IN ('text', 'integer', 'decimal', 'date')", name='ck_shipping_inventory_fields_value_type'), CheckConstraint("value_type IN ('text', 'integer', 'decimal', 'date')", name='ck_freight_rpa_onhand_fields_value_type'),
CheckConstraint( CheckConstraint(
"usage_type IN ('match_identity', 'inventory_quantity', 'warehouse_identity', 'general')", "usage_type IN ('match_identity', 'inventory_quantity', 'warehouse_identity', 'general')",
name='ck_shipping_inventory_fields_usage_type', name='ck_freight_rpa_onhand_fields_usage_type',
), ),
) )
@@ -48,13 +50,13 @@ class ShippingInventoryField(Base):
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
class ShippingRpaProfile(Base): class FreightRpaProfile(Base):
"""货代库存登录连接配置;凭据字段始终保存密文。""" """货代库存登录连接配置;凭据字段始终保存密文。"""
__tablename__ = 'shipping_rpa_profiles' __tablename__ = 'freight_rpa_profiles'
__table_args__ = ( __table_args__ = (
UniqueConstraint('profile_code', name='uq_shipping_rpa_profiles_profile_code'), UniqueConstraint('profile_code', name='uq_freight_rpa_profiles_profile_code'),
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_rpa_profiles_connector_type'), CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_freight_rpa_profiles_connector_type'),
) )
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
@@ -67,11 +69,9 @@ class ShippingRpaProfile(Base):
login_config_json: Mapped[dict[str, Any]] = mapped_column( login_config_json: Mapped[dict[str, Any]] = mapped_column(
JSON, default=lambda: {'auth_mode': 'password'}, nullable=False, JSON, default=lambda: {'auth_mode': 'password'}, nullable=False,
) )
# 连接级“发货 Excel 自动上传”配置。先使用 login_url 登录,再访问 upload_config_json.entry_url 进入上传页; # 连接级“发货 Excel 自动上传”开关。只保存 {enabled}。
# 上传配置由管理端表单编辑,后端白名单校验后保存为受限 JSON。白名单字段仅 # 上传页、文件控件、提交和成功判断在连接器代码里,由 login_url 的主机拼出入口。
# enabled / entry_url / file_input_selector / submit_mode / submit_selector / # 该配置变更不递增 config_version(见 admin 服务)。
# result_mode / result_selector / success_texts / timeout_seconds。
# 一条连接只保存一份上传配置;该配置变更不递增 config_version(见 admin 服务)。
upload_config_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) upload_config_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False) enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False) config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
@@ -81,24 +81,24 @@ class ShippingRpaProfile(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='rpa_profile') sources: Mapped[list['FreightRpaSource']] = relationship(back_populates='rpa_profile')
class ShippingInventorySource(Base): class FreightRpaSource(Base):
"""库存业务来源;固定仓或库存行动态解析 Warehouse。""" """库存业务来源;固定仓或库存行动态解析 Warehouse。"""
__tablename__ = 'shipping_inventory_sources' __tablename__ = 'freight_rpa_sources'
__table_args__ = ( __table_args__ = (
UniqueConstraint('source_code', name='uq_shipping_inventory_sources_source_code'), UniqueConstraint('source_code', name='uq_freight_rpa_sources_source_code'),
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_inventory_sources_connector_type'), CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_freight_rpa_sources_connector_type'),
CheckConstraint( CheckConstraint(
"(warehouse_resolution_mode = 'fixed' AND fixed_warehouse_id IS NOT NULL) " "(warehouse_resolution_mode = 'fixed' AND fixed_warehouse_id IS NOT NULL) "
"OR (warehouse_resolution_mode = 'inventory_match' AND fixed_warehouse_id IS NULL)", "OR (warehouse_resolution_mode = 'inventory_match' AND fixed_warehouse_id IS NULL)",
name='ck_shipping_inventory_sources_warehouse_mode', name='ck_freight_rpa_sources_warehouse_mode',
), ),
CheckConstraint( CheckConstraint(
"enabled = false OR (parsing_profile_id IS NOT NULL AND excel_template_id IS NOT NULL)", "enabled = false OR excel_template_id IS NOT NULL",
name='ck_shipping_inventory_sources_enabled_bindings', name='ck_freight_rpa_sources_enabled_template',
), ),
) )
@@ -106,14 +106,12 @@ class ShippingInventorySource(Base):
source_code: Mapped[str] = mapped_column(String(64), nullable=False) source_code: Mapped[str] = mapped_column(String(64), nullable=False)
display_name: Mapped[str] = mapped_column(String(128), nullable=False) display_name: Mapped[str] = mapped_column(String(128), nullable=False)
connector_type: Mapped[str] = mapped_column(String(32), nullable=False) connector_type: Mapped[str] = mapped_column(String(32), nullable=False)
rpa_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_rpa_profiles.id'), nullable=False, index=True) rpa_profile_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_profiles.id'), nullable=False, index=True)
parsing_profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True)
excel_template_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=True, index=True) excel_template_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=True, index=True)
warehouse_resolution_mode: Mapped[str] = mapped_column(String(32), nullable=False) warehouse_resolution_mode: Mapped[str] = mapped_column(String(32), nullable=False)
fixed_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) fixed_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# 业务报表定义属于 Source;Driver 的 selector、等待与下载实现不进入数据库配置。 # 业务报表定义自 s18 起搬到 FreightRpaOnhandReportConfig(路径、查询条件、解析方案绑定);
report_path_json: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict, server_default=text("'{}'"), nullable=False) # CHECK 不能跨表,模板绑定仍留在站点行的启用约束上,解析方案存在性由保存站点的服务校验。
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, default=list, server_default=text("'[]'"), nullable=False)
snapshot_ttl_seconds: Mapped[int] = mapped_column(Integer, default=86400, server_default=text('86400'), nullable=False) snapshot_ttl_seconds: Mapped[int] = mapped_column(Integer, default=86400, server_default=text('86400'), nullable=False)
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False) enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False) config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
@@ -122,31 +120,75 @@ class ShippingInventorySource(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
rpa_profile: Mapped[ShippingRpaProfile] = relationship(back_populates='sources') rpa_profile: Mapped[FreightRpaProfile] = relationship(back_populates='sources')
parsing_profile: Mapped[Optional['ShippingInventoryParsingProfile']] = relationship(back_populates='sources')
excel_template: Mapped[Optional['ShippingExcelTemplate']] = relationship(back_populates='sources') excel_template: Mapped[Optional['ShippingExcelTemplate']] = relationship(back_populates='sources')
external_mappings: Mapped[list['ShippingInventoryExternalMapping']] = relationship( onhand_report_config: Mapped[Optional['FreightRpaOnhandReportConfig']] = relationship(
back_populates='inventory_source', cascade='all, delete-orphan' back_populates='source', uselist=False, cascade='all, delete-orphan',
) )
receipt_report_config: Mapped[Optional['ShippingReceiptReportConfig']] = relationship( external_mappings: Mapped[list['FreightRpaOnhandExternalMapping']] = relationship(
back_populates='inventory_source', uselist=False, cascade='all, delete-orphan', back_populates='source', cascade='all, delete-orphan'
)
inbound_report_config: Mapped[Optional['FreightRpaInboundReportConfig']] = relationship(
back_populates='source', uselist=False, cascade='all, delete-orphan',
)
outbound_report_config: Mapped[Optional['FreightRpaOutboundReportConfig']] = relationship(
back_populates='source', uselist=False, cascade='all, delete-orphan',
) )
class ShippingInventorySourceParsingBindingAudit(Base): class FreightRpaOnhandReportConfig(Base):
"""库存站点解析方案绑定的只追加审计;保存绑定前后快照以支持上线追溯。""" """库存站点的一对一在手报表配置;报表路径与查询条件归 RPA 域。
__tablename__ = 'shipping_inventory_source_parsing_binding_audits' 解析方案绑定随本表保存(purpose='onhand')。站点启用要求「本配置存在且
parsing_profile_id 非空」,PostgreSQL CHECK 不能跨表,该校验由保存站点的服务执行。
"""
__tablename__ = 'freight_rpa_onhand_report_configs'
__table_args__ = ( __table_args__ = (
Index('ix_inventory_source_parsing_binding_audit_source_created', 'inventory_source_id', 'created_at'), UniqueConstraint('source_id', name='uq_freight_rpa_onhand_report_configs_source'),
) )
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False) # 站点删除时配置行级联删除(与迁移端 fk_freight_rpa_onhand_report_configs_source 的 ondelete 一致)。
previous_parsing_profile_id: Mapped[Optional[int]] = mapped_column( source_id: Mapped[int] = mapped_column(
ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, ForeignKey('freight_rpa_sources.id', ondelete='CASCADE'), nullable=False, index=True,
) )
parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=False) # 在手报表文件解析规则(purpose='onhand');空则站点不得启用(服务层校验)。
parsing_profile_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True, index=True,
)
# 业务报表定义属于配置行;Driver 的 selector、等待与下载实现不进入数据库配置。
report_path_json: Mapped[dict[str, Any]] = mapped_column(
JSON, default=dict, server_default=text("'{}'"), nullable=False,
)
# 与入站同构:查询条件原样下发 Worker;空条件表示页面默认。
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(
JSON, default=list, server_default=text("'[]'"), nullable=False,
)
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
source: Mapped['FreightRpaSource'] = relationship(back_populates='onhand_report_config')
parsing_profile: Mapped[Optional['FreightRpaParsingProfile']] = relationship(back_populates='sources')
class FreightRpaSourceParsingBindingAudit(Base):
"""库存站点解析方案绑定的只追加审计;保存绑定前后快照以支持上线追溯。"""
__tablename__ = 'freight_rpa_onhand_source_parsing_binding_audits'
__table_args__ = (
Index('ix_inventory_source_parsing_binding_audit_source_created', 'source_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False)
previous_parsing_profile_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True,
)
parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_parsing_profiles.id'), nullable=False)
operation: Mapped[str] = mapped_column(String(32), nullable=False) operation: Mapped[str] = mapped_column(String(32), nullable=False)
reason: Mapped[str] = mapped_column(String(500), nullable=False) reason: Mapped[str] = mapped_column(String(500), nullable=False)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
@@ -157,31 +199,32 @@ class ShippingInventorySourceParsingBindingAudit(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingInventoryParsingProfile(Base): class FreightRpaParsingProfile(Base):
"""可跨源复用的通用文件解析规则(库存/异动按 purpose 区分)。 """可跨源复用的通用文件解析规则(在手/入站/出站按 purpose 区分)。
注意:表名中的 inventory 是历史命名——本表实为"通用文件解析规则表", 表 freight_rpa_parsing_profiles 按 purpose 服务在手/入站/出站。
用途以 purpose 字段为准,勿按表名推断只服务库存。 purpose='onhand':在手库存文件,端点用 FreightRpaOnhandField 库存字段目录;
purpose='inventory':端点用 ShippingInventoryField 库存字段目录(既有语义); purpose='inbound':入站文件,端点用定死领域字段
purpose='movement':端点用定死领域字段(MOVEMENT_FIELDS,doc_no/line_no/.../movement_date), (MOVEMENT_FIELDS,doc_no/line_no/.../movement_date),
供收料/异动文件映射,不依赖库存字段目录。校验逻辑按 purpose 分支。 不依赖库存字段目录。校验逻辑按 purpose 分支。
绑定入口:库存站点 ShippingInventorySource.parsing_profile_id / 绑定入口:在手配置 FreightRpaOnhandReportConfig.parsing_profile_id /
收料配置 ShippingReceiptReportConfig.parsing_profile_id(后者必须 purpose='movement')。 入站配置 FreightRpaInboundReportConfig.parsing_profile_id(后者必须 purpose='inbound');
purpose='outbound':出站文件,结构就位(白名单放行,暂无运行时消费方)。
""" """
__tablename__ = 'shipping_inventory_parsing_profiles' __tablename__ = 'freight_rpa_parsing_profiles'
__table_args__ = ( __table_args__ = (
UniqueConstraint('profile_code', 'version', name='uq_inventory_parsing_profiles_code_version'), UniqueConstraint('profile_code', 'version', name='uq_inventory_parsing_profiles_code_version'),
Index('ix_inv_parse_profile_exact_fp', 'exact_structure_fingerprint'), Index('ix_inv_parse_profile_exact_fp', 'exact_structure_fingerprint'),
Index('ix_inv_parse_profile_compat_fp', 'compatibility_fingerprint'), Index('ix_inv_parse_profile_compat_fp', 'compatibility_fingerprint'),
CheckConstraint( CheckConstraint(
"purpose IN ('inventory', 'movement')", "purpose IN ('onhand', 'inbound', 'outbound')",
name='ck_shipping_inventory_parsing_profiles_purpose', name='ck_freight_rpa_parsing_profiles_purpose',
), ),
) )
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
purpose: Mapped[str] = mapped_column(String(16), nullable=False, default='inventory', server_default='inventory') purpose: Mapped[str] = mapped_column(String(16), nullable=False, default='onhand', server_default='onhand')
profile_code: Mapped[str] = mapped_column(String(64), nullable=False) profile_code: Mapped[str] = mapped_column(String(64), nullable=False)
display_name: Mapped[str] = mapped_column(String(128), nullable=False) display_name: Mapped[str] = mapped_column(String(128), nullable=False)
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1')) version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
@@ -195,7 +238,7 @@ class ShippingInventoryParsingProfile(Base):
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
# Draft and published definitions keep their analysed sample evidence without retaining the full uploaded workbook. # Draft and published definitions keep their analysed sample evidence without retaining the full uploaded workbook.
sample_analysis_id: Mapped[Optional[int]] = mapped_column( sample_analysis_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True, index=True, ForeignKey('freight_rpa_onhand_structure_analyses.id'), nullable=True, index=True,
) )
# Preserve every confirmed evidence switch so a draft remains explainable after samples change. # Preserve every confirmed evidence switch so a draft remains explainable after samples change.
sample_evidence_history_json: Mapped[list[dict[str, Any]]] = mapped_column( sample_evidence_history_json: Mapped[list[dict[str, Any]]] = mapped_column(
@@ -206,16 +249,17 @@ class ShippingInventoryParsingProfile(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='parsing_profile') # s18 起站点行不再绑定解析方案;在手配置行(FreightRpaOnhandReportConfig)是 onhand 侧的唯一挂点。
sample_analysis: Mapped[Optional['ShippingInventoryStructureAnalysis']] = relationship( sources: Mapped[list['FreightRpaOnhandReportConfig']] = relationship(back_populates='parsing_profile')
sample_analysis: Mapped[Optional['FreightRpaOnhandStructureAnalysis']] = relationship(
foreign_keys=[sample_analysis_id], foreign_keys=[sample_analysis_id],
) )
class ShippingInventoryStructureAnalysis(Base): class FreightRpaOnhandStructureAnalysis(Base):
"""库存文件结构分析记录;保存脱敏结构证据,不承载正式库存快照。""" """库存文件结构分析记录;保存脱敏结构证据,不承载正式库存快照。"""
__tablename__ = 'shipping_inventory_structure_analyses' __tablename__ = 'freight_rpa_onhand_structure_analyses'
__table_args__ = ( __table_args__ = (
Index('ix_inv_structure_analysis_file_hash', 'file_checksum'), Index('ix_inv_structure_analysis_file_hash', 'file_checksum'),
Index('ix_inv_structure_analysis_created', 'created_at'), Index('ix_inv_structure_analysis_created', 'created_at'),
@@ -243,24 +287,28 @@ class ShippingInventoryStructureAnalysis(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingInventoryConfigurationTestRun(Base): class FreightRpaOnhandConfigurationTestRun(Base):
"""库存站点配置测试的异步 RPA 运行;锁定站点和连接配置版本且不进入生产库存池。""" """库存站点配置测试的异步 RPA 运行;锁定站点和连接配置版本且不进入生产库存池。"""
__tablename__ = 'shipping_inventory_configuration_test_runs' __tablename__ = 'freight_rpa_onhand_configuration_test_runs'
__table_args__ = (UniqueConstraint('run_no', name='uq_inventory_configuration_test_runs_run_no'),) __table_args__ = (
UniqueConstraint('run_no', name='uq_inventory_configuration_test_runs_run_no'),
# PostgreSQL 标识符上限 63。index=True 会生成 65 字节的自动名,故用显式短名。
Index('ix_fr_onhand_cfg_test_runs_validation_batch_id', 'validation_batch_id'),
)
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
run_no: Mapped[str] = mapped_column(String(64), nullable=False) run_no: Mapped[str] = mapped_column(String(64), nullable=False)
validation_batch_id: Mapped[Optional[int]] = mapped_column( validation_batch_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_validation_batches.id'), nullable=True, index=True, ForeignKey('freight_rpa_onhand_validation_batches.id'), nullable=True,
) )
rpa_batch_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) rpa_batch_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True) source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True)
source_config_version: Mapped[int] = mapped_column(Integer, nullable=False) source_config_version: Mapped[int] = mapped_column(Integer, nullable=False)
rpa_profile_config_version: Mapped[int] = mapped_column(Integer, nullable=False) rpa_profile_config_version: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='awaiting_rpa', server_default='awaiting_rpa') status: Mapped[str] = mapped_column(String(32), nullable=False, default='awaiting_rpa', server_default='awaiting_rpa')
stage: Mapped[str] = mapped_column(String(32), nullable=False, default='waiting_worker', server_default='waiting_worker') stage: Mapped[str] = mapped_column(String(32), nullable=False, default='waiting_worker', server_default='waiting_worker')
analysis_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True) analysis_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_structure_analyses.id'), nullable=True)
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
@@ -268,10 +316,10 @@ class ShippingInventoryConfigurationTestRun(Base):
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
class ShippingInventoryValidationBatch(Base): class FreightRpaOnhandValidationBatch(Base):
"""库存站点批量验证的聚合运行;逐站点结果仍由 ConfigurationTestRun 保存。""" """库存站点批量验证的聚合运行;逐站点结果仍由 ConfigurationTestRun 保存。"""
__tablename__ = 'shipping_inventory_validation_batches' __tablename__ = 'freight_rpa_onhand_validation_batches'
__table_args__ = (UniqueConstraint('batch_no', name='uq_inventory_validation_batches_batch_no'),) __table_args__ = (UniqueConstraint('batch_no', name='uq_inventory_validation_batches_batch_no'),)
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
@@ -284,21 +332,21 @@ class ShippingInventoryValidationBatch(Base):
stale_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0')) stale_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
retry_of_batch_id: Mapped[Optional[int]] = mapped_column( retry_of_batch_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_validation_batches.id'), nullable=True, ForeignKey('freight_rpa_onhand_validation_batches.id'), nullable=True,
) )
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
class ShippingInventoryRoutingRule(Base): class FreightRpaOnhandRoutingRule(Base):
"""可版本化的库存源路由决策表;仅产出受控 Source 候选。""" """可版本化的库存源路由决策表;仅产出受控 Source 候选。"""
__tablename__ = 'shipping_inventory_routing_rules' __tablename__ = 'freight_rpa_onhand_routing_rules'
__table_args__ = ( __table_args__ = (
UniqueConstraint('rule_code', 'version', name='uq_shipping_inventory_routing_rules_code_version'), UniqueConstraint('rule_code', 'version', name='uq_freight_rpa_onhand_routing_rules_code_version'),
CheckConstraint("scope IN ('task', 'line')", name='ck_shipping_inventory_routing_rules_scope'), CheckConstraint("scope IN ('task', 'line')", name='ck_freight_rpa_onhand_routing_rules_scope'),
CheckConstraint("match_mode IN ('all', 'any')", name='ck_shipping_inventory_routing_rules_match_mode'), CheckConstraint("match_mode IN ('all', 'any')", name='ck_freight_rpa_onhand_routing_rules_match_mode'),
CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_inventory_routing_rules_status'), CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_freight_rpa_onhand_routing_rules_status'),
) )
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
@@ -318,17 +366,17 @@ class ShippingInventoryRoutingRule(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
conditions: Mapped[list['ShippingInventoryRoutingRuleCondition']] = relationship( conditions: Mapped[list['FreightRpaOnhandRoutingRuleCondition']] = relationship(
back_populates='rule', cascade='all, delete-orphan', order_by='ShippingInventoryRoutingRuleCondition.sequence' back_populates='rule', cascade='all, delete-orphan', order_by='FreightRpaOnhandRoutingRuleCondition.sequence'
) )
class ShippingInventoryRoutingRuleCondition(Base): class FreightRpaOnhandRoutingRuleCondition(Base):
"""库存源路由条件;仅引用已发布订单 Schema 的稳定 field_id。""" """库存源路由条件;仅引用已发布订单 Schema 的稳定 field_id。"""
__tablename__ = 'shipping_inventory_routing_rule_conditions' __tablename__ = 'freight_rpa_onhand_routing_rule_conditions'
__table_args__ = ( __table_args__ = (
UniqueConstraint('rule_id', 'sequence', name='uq_shipping_inventory_routing_rule_conditions_sequence'), UniqueConstraint('rule_id', 'sequence', name='uq_freight_rpa_onhand_routing_rule_conditions_sequence'),
CheckConstraint( CheckConstraint(
"source_kind = 'order_field' AND order_field_id IS NOT NULL", "source_kind = 'order_field' AND order_field_id IS NOT NULL",
name='ck_inventory_routing_condition_source', name='ck_inventory_routing_condition_source',
@@ -336,7 +384,7 @@ class ShippingInventoryRoutingRuleCondition(Base):
) )
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
rule_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_routing_rules.id'), nullable=False, index=True) rule_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_routing_rules.id'), nullable=False, index=True)
condition_group: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False) condition_group: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
source_kind: Mapped[str] = mapped_column(String(16), nullable=False, default='order_field') source_kind: Mapped[str] = mapped_column(String(16), nullable=False, default='order_field')
order_field_id: Mapped[Optional[str]] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=True) order_field_id: Mapped[Optional[str]] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=True)
@@ -344,24 +392,24 @@ class ShippingInventoryRoutingRuleCondition(Base):
expected_value_json: Mapped[Any] = mapped_column(JSON, nullable=True) expected_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
sequence: Mapped[int] = mapped_column(Integer, nullable=False) sequence: Mapped[int] = mapped_column(Integer, nullable=False)
rule: Mapped[ShippingInventoryRoutingRule] = relationship(back_populates='conditions') rule: Mapped[FreightRpaOnhandRoutingRule] = relationship(back_populates='conditions')
class ShippingInventoryRoutingRuleVersion(Base): class FreightRpaOnhandRoutingRuleVersion(Base):
"""已发布路由规则的不可变定义快照,供任务审计回放使用。""" """已发布路由规则的不可变定义快照,供任务审计回放使用。"""
__tablename__ = 'shipping_inventory_routing_rule_versions' __tablename__ = 'freight_rpa_onhand_routing_rule_versions'
__table_args__ = (UniqueConstraint('rule_id', 'version', name='uq_shipping_inventory_routing_rule_versions_rule_version'),) __table_args__ = (UniqueConstraint('rule_id', 'version', name='uq_freight_rpa_onhand_routing_rule_versions_rule_version'),)
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
rule_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_routing_rules.id'), nullable=False, index=True) rule_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_routing_rules.id'), nullable=False, index=True)
version: Mapped[int] = mapped_column(Integer, nullable=False) version: Mapped[int] = mapped_column(Integer, nullable=False)
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False) definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False)
published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
published_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) published_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingInventoryExternalMapping(Base): class FreightRpaOnhandExternalMapping(Base):
"""库存源到外部系统仓库的映射。 """库存源到外部系统仓库的映射。
freight_warehouse_id(货代仓库)为可选维度:inventory_match 源用它匹配收料文件 freight_warehouse_id(货代仓库)为可选维度:inventory_match 源用它匹配收料文件
@@ -371,18 +419,18 @@ class ShippingInventoryExternalMapping(Base):
(in_transit_transfer DefaultRouteResolver),保存端必填,库内空串仅为存量行兼容。 (in_transit_transfer DefaultRouteResolver),保存端必填,库内空串仅为存量行兼容。
""" """
__tablename__ = 'shipping_inventory_external_mappings' __tablename__ = 'freight_rpa_onhand_external_mappings'
__table_args__ = ( __table_args__ = (
Index( Index(
'uq_shipping_inv_ext_map_src_default_enabled', 'uq_shipping_inv_ext_map_src_default_enabled',
'inventory_source_id', 'source_id',
unique=True, unique=True,
postgresql_where=text('freight_warehouse_id IS NULL AND enabled = true'), postgresql_where=text('freight_warehouse_id IS NULL AND enabled = true'),
sqlite_where=text('freight_warehouse_id IS NULL AND enabled = 1'), sqlite_where=text('freight_warehouse_id IS NULL AND enabled = 1'),
), ),
Index( Index(
'uq_shipping_inv_ext_map_src_wh_enabled', 'uq_shipping_inv_ext_map_src_wh_enabled',
'inventory_source_id', 'source_id',
'freight_warehouse_id', 'freight_warehouse_id',
unique=True, unique=True,
postgresql_where=text('freight_warehouse_id IS NOT NULL AND enabled = true'), postgresql_where=text('freight_warehouse_id IS NOT NULL AND enabled = true'),
@@ -391,7 +439,7 @@ class ShippingInventoryExternalMapping(Base):
) )
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True) source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True)
freight_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) freight_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
external_system_code: Mapped[str] = mapped_column(String(32), nullable=False) external_system_code: Mapped[str] = mapped_column(String(32), nullable=False)
external_organization_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) external_organization_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
@@ -407,4 +455,4 @@ class ShippingInventoryExternalMapping(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
inventory_source: Mapped[ShippingInventorySource] = relationship(back_populates='external_mappings') source: Mapped[FreightRpaSource] = relationship(back_populates='external_mappings')
@@ -0,0 +1,128 @@
"""
backend/app/models/freight_rpa_inbound_report.py
用途:入站报表 RPA 的配置、运行与归档持久化模型(per-file 企微投递表已拆除,见 Task 4 迁移)。
依赖:freight_rpa_sources、排程运行、freight_rpa_parsing_profiles、SQLAlchemy Base;完整操作追溯统一写入 ShippingAuditEvent。
逻辑:模型只复用站点连接资料,通过独立外键与唯一约束隔离在手快照、匹配和旧 RPA Worker 链路。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class FreightRpaInboundReportConfig(Base):
"""库存站点的一对一收料报表配置;路径和条件始终独立于库存配置。"""
__tablename__ = 'freight_rpa_inbound_report_configs'
__table_args__ = (
UniqueConstraint('source_id', name='uq_freight_rpa_inbound_report_configs_source'),
)
id: Mapped[int] = mapped_column(primary_key=True)
source_id: Mapped[int] = mapped_column(
ForeignKey('freight_rpa_sources.id'), nullable=False, index=True,
)
# 收料不设独立启停:是否运行统一由库存站点 enabled 与本配置是否存在决定。
# 收料文件解析规则(purpose='inbound');定死领域字段端点。空则无法解析收料文件。
parsing_profile_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True, index=True,
)
report_path_json: Mapped[dict[str, Any]] = mapped_column(
JSON, default=dict, server_default=text("'{}'"), nullable=False,
)
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(
JSON, default=list, server_default=text("'[]'"), nullable=False,
)
# 与库存同构:查询条件原样下发 Worker;空条件表示页面默认。排程一源一单元,不按仓拆分。
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
source: Mapped['FreightRpaSource'] = relationship(back_populates='inbound_report_config')
parsing_profile: Mapped[Optional['FreightRpaParsingProfile']] = relationship()
class FreightRpaInboundUnitRun(Base):
"""一次收料执行的站点或站点-Warehouse 不可重复执行单元。
schedule_run_id 指向排程 run;调拨按需触发(重试/预检补抓)无排程,保持 NULL。
"""
__tablename__ = 'freight_rpa_inbound_rpa_unit_runs'
__table_args__ = (
UniqueConstraint('callback_id', name='uq_freight_rpa_inbound_rpa_unit_runs_callback'),
CheckConstraint(
"status IN ('queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled')",
name='ck_freight_rpa_inbound_rpa_unit_runs_status',
),
Index('ix_shipping_receipt_unit_run_schedule_status', 'schedule_run_id', 'status'),
Index('ix_shipping_receipt_unit_run_source_created', 'source_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
schedule_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), nullable=True, index=True)
source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True)
retry_of_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('freight_rpa_inbound_rpa_unit_runs.id'), nullable=True, index=True,
)
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
connector_type: Mapped[str] = mapped_column(String(32), nullable=False)
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
callback_id: Mapped[str] = mapped_column(String(128), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
config_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
trigger_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
schedule_run: Mapped[Optional['ScheduleRun']] = relationship(foreign_keys=[schedule_run_id])
source: Mapped['FreightRpaSource'] = relationship()
retry_of: Mapped[Optional['FreightRpaInboundUnitRun']] = relationship(remote_side=[id])
files: Mapped[list['FreightRpaInboundReportFile']] = relationship(
back_populates='unit_run', cascade='all, delete-orphan',
)
class FreightRpaInboundReportFile(Base):
"""收料原样归档文件;保留文件身份和对象清理事实,不关联库存快照。"""
__tablename__ = 'freight_rpa_inbound_report_files'
__table_args__ = (
UniqueConstraint('unit_run_id', 'sha256', name='uq_freight_rpa_inbound_report_files_unit_sha256'),
CheckConstraint("file_size >= 0", name='ck_freight_rpa_inbound_report_files_size'),
Index('ix_freight_rpa_inbound_report_files_unit', 'unit_run_id'),
Index('ix_freight_rpa_inbound_report_files_expires', 'archive_expires_at', 'archive_deleted_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
unit_run_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_inbound_rpa_unit_runs.id'), nullable=False, index=True)
storage_provider: Mapped[str] = mapped_column(String(32), nullable=False)
storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False)
storage_key: Mapped[str] = mapped_column(String(1024), nullable=False)
original_filename: Mapped[str] = mapped_column(String(255), nullable=False)
content_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
file_size: Mapped[int] = mapped_column(Integer, nullable=False)
sha256: Mapped[str] = mapped_column(String(64), nullable=False)
# 解析失败分层标记:归档文件解析失败时写入;三者全空=未失败/已清除。
parse_failed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
parse_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
parse_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
archive_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
archive_deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
archive_delete_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
unit_run: Mapped[FreightRpaInboundUnitRun] = relationship(back_populates='files')
@@ -1,8 +1,8 @@
""" """
models/shipping_inventory_mapping.py backend/app/models/freight_rpa_onhand_mapping.py
用途:保存不可变库存字段映射版本。 用途:保存不可变库存字段映射版本。
依赖:ShippingInventoryFile、ShippingInventoryParsingProfile、Base。 依赖:FreightRpaOnhandReportFile、FreightRpaParsingProfile、Base。
逻辑:每次确认/重跑创建新版本,匹配 Attempt 通过 mapping_id 精确引用。 逻辑:每次确认/重跑创建新版本,匹配 Attempt 通过 mapping_id 精确引用。
""" """
@@ -17,24 +17,24 @@ from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base from app.models.base import Base
class ShippingInventoryMapping(Base): class FreightRpaOnhandMapping(Base):
"""库存文件的不可变字段映射版本。""" """库存文件的不可变字段映射版本。"""
__tablename__ = 'shipping_inventory_mappings' __tablename__ = 'freight_rpa_onhand_mappings'
__table_args__ = ( __table_args__ = (
UniqueConstraint('inventory_file_id', 'version', name='uq_shipping_inventory_mapping_file_version'), UniqueConstraint('onhand_file_id', 'version', name='uq_shipping_inventory_mapping_file_version'),
CheckConstraint("status IN ('active','superseded','invalidated')", name='ck_shipping_inventory_mapping_status'), CheckConstraint("status IN ('active','superseded','invalidated')", name='ck_shipping_inventory_mapping_status'),
Index('ix_shipping_inventory_mapping_file_status', 'inventory_file_id', 'status'), Index('ix_shipping_inventory_mapping_file_status', 'onhand_file_id', 'status'),
) )
id: Mapped[int] = mapped_column(Integer, primary_key=True) id: Mapped[int] = mapped_column(Integer, primary_key=True)
inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id', ondelete='CASCADE'), nullable=False) onhand_file_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id', ondelete='CASCADE'), nullable=False)
version: Mapped[int] = mapped_column(Integer, nullable=False) version: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active') status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active')
profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id', ondelete='SET NULL'), nullable=True) profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_parsing_profiles.id', ondelete='SET NULL'), nullable=True)
mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_mappings.id'), nullable=True) superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_mappings.id'), nullable=True)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -0,0 +1,123 @@
"""
backend/app/models/freight_rpa_onhand_report_file.py
用途:货代 RPA 抓回的在手报表文件。
依赖:models.base.Base、shipping.py 里的 ShippingTaskOnhandLink。
逻辑:表名 freight_rpa_onhand_report_files 不变;发货任务通过 ShippingTaskOnhandLink 引用本行。
"""
from __future__ import annotations
from datetime import datetime
from typing import List, Optional
from sqlalchemy import (
Boolean,
DateTime,
ForeignKey,
Index,
Integer,
JSON,
String,
text,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class FreightRpaOnhandReportFile(Base):
"""货代发货批次库存快照文件,承载一次上传后可被多票任务共用的库存数据。
在手文件表归货代 RPA(s18 由 shipping_onhand_files 改名而来);列不改,
仍含解析行、字段映射与快照状态,本阶段只改表名与指向它的外键。
"""
__tablename__ = 'freight_rpa_onhand_report_files'
__table_args__ = (
Index('ix_freight_rpa_onhand_report_files_user_created', 'user_id', 'created_at'),
Index(
'ix_freight_rpa_onhand_report_files_source_snapshot',
'source_code',
'warehouse_id',
'snapshot_status',
'exported_at',
),
Index(
'ix_freight_rpa_onhand_report_files_source_warehouse',
'source_code',
'warehouse_id',
),
Index(
'uq_freight_rpa_onhand_report_files_rpa_identity_ready',
'rpa_run_no',
'source_code',
'warehouse_id',
unique=True,
postgresql_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND warehouse_id IS NOT NULL"
),
sqlite_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND warehouse_id IS NOT NULL"
),
),
# 动态多仓文件没有单一 Warehouse;按 RPA run + Source 保证回调重放幂等。
Index(
'uq_freight_rpa_onhand_report_files_rpa_dynamic_source_ready',
'rpa_run_no',
'source_code',
unique=True,
postgresql_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND warehouse_id IS NULL"
),
sqlite_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND warehouse_id IS NULL"
),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
onhand_file_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
storage_path: Mapped[str] = mapped_column(String(500), nullable=False)
schema_preview_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
field_mapping_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
mapping_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
mapping_confirmed: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
onhand_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
line_count: Mapped[int] = mapped_column(Integer, default=0)
share_mode: Mapped[str] = mapped_column(String(32), default='task_only')
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
identity_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
snapshot_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
exported_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
rpa_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
schedule_run_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True)
source_query_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), nullable=True)
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
links: Mapped[List['ShippingTaskOnhandLink']] = relationship(
'ShippingTaskOnhandLink',
back_populates='inventory_file',
cascade='all, delete-orphan',
)
@@ -1,5 +1,5 @@
""" """
models/shipping_task_inventory_rpa_attempts.py backend/app/models/freight_rpa_onhand_task_attempts.py
用途:逐库存源的 RPA 导出 Attempt 结构化记录(决策 D1/D2 三元组幂等)。 用途:逐库存源的 RPA 导出 Attempt 结构化记录(决策 D1/D2 三元组幂等)。
依赖:Base、ShippingNotice(task_no FK 可选直连 id 先保留 task_no 字符串关联)、users。 依赖:Base、ShippingNotice(task_no FK 可选直连 id 先保留 task_no 字符串关联)、users。
@@ -47,10 +47,10 @@ PER_SOURCE_RPA_ATTEMPT_STATUSES = (
) )
class ShippingTaskInventoryRpaAttempt(Base): class FreightRpaOnhandTaskAttempt(Base):
"""逐 (task_no, source_code) 的库存 RPA 导出 Attempt 记录。""" """逐 (task_no, source_code) 的库存 RPA 导出 Attempt 记录。"""
__tablename__ = 'shipping_task_inventory_rpa_attempts' __tablename__ = 'freight_rpa_onhand_task_rpa_attempts'
__table_args__ = ( __table_args__ = (
# 三元组唯一:同一运行号同一源只允许一条记录 # 三元组唯一:同一运行号同一源只允许一条记录
UniqueConstraint('task_no', 'source_code', 'source_run_no', name='uq_shipping_task_inv_rpa_triplet'), UniqueConstraint('task_no', 'source_code', 'source_run_no', name='uq_shipping_task_inv_rpa_triplet'),
@@ -87,7 +87,7 @@ class ShippingTaskInventoryRpaAttempt(Base):
trigger_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True) trigger_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
callback_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True) callback_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
inventory_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) onhand_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
@@ -0,0 +1,129 @@
"""
backend/app/models/freight_rpa_outbound_report.py
用途:出站报表 RPA 的配置、运行与归档持久化模型(不建 per-file 企微投递表)。
依赖:freight_rpa_sources、排程运行、freight_rpa_parsing_profiles、SQLAlchemy Base;完整操作追溯统一写入 ShippingAuditEvent。
逻辑:模型只复用站点连接资料,通过独立外键与唯一约束隔离在手快照、匹配和旧 RPA Worker 链路。
FreightRpaSource.outbound_report_config 一对一回指本配置行。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class FreightRpaOutboundReportConfig(Base):
"""库存站点的一对一出站报表配置;路径和条件始终独立于库存 / 入站配置。"""
__tablename__ = 'freight_rpa_outbound_report_configs'
__table_args__ = (
UniqueConstraint('source_id', name='uq_freight_rpa_outbound_report_configs_source'),
)
id: Mapped[int] = mapped_column(primary_key=True)
source_id: Mapped[int] = mapped_column(
ForeignKey('freight_rpa_sources.id'), nullable=False, index=True,
)
# 出站不设独立启停:是否运行统一由库存站点 enabled 与本配置是否存在决定。
# 出站文件解析规则(purpose='outbound');定死领域字段端点。空则无法解析出站文件。
parsing_profile_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True, index=True,
)
report_path_json: Mapped[dict[str, Any]] = mapped_column(
JSON, default=dict, server_default=text("'{}'"), nullable=False,
)
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(
JSON, default=list, server_default=text("'[]'"), nullable=False,
)
# 与库存同构:查询条件原样下发 Worker;空条件表示页面默认。排程一源一单元,不按仓拆分。
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
source: Mapped['FreightRpaSource'] = relationship(back_populates='outbound_report_config')
parsing_profile: Mapped[Optional['FreightRpaParsingProfile']] = relationship()
class FreightRpaOutboundUnitRun(Base):
"""一次出站执行的站点或站点-Warehouse 不可重复执行单元。
schedule_run_id 指向排程 run;调拨按需触发(重试/预检补抓)无排程,保持 NULL。
"""
__tablename__ = 'freight_rpa_outbound_rpa_unit_runs'
__table_args__ = (
UniqueConstraint('callback_id', name='uq_freight_rpa_outbound_rpa_unit_runs_callback'),
CheckConstraint(
"status IN ('queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled')",
name='ck_freight_rpa_outbound_rpa_unit_runs_status',
),
Index('ix_freight_rpa_outbound_unit_run_schedule_status', 'schedule_run_id', 'status'),
Index('ix_freight_rpa_outbound_unit_run_source_created', 'source_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
schedule_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), nullable=True, index=True)
source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True)
retry_of_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('freight_rpa_outbound_rpa_unit_runs.id'), nullable=True, index=True,
)
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
connector_type: Mapped[str] = mapped_column(String(32), nullable=False)
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
callback_id: Mapped[str] = mapped_column(String(128), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
config_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
trigger_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
schedule_run: Mapped[Optional['ScheduleRun']] = relationship(foreign_keys=[schedule_run_id])
source: Mapped['FreightRpaSource'] = relationship()
retry_of: Mapped[Optional['FreightRpaOutboundUnitRun']] = relationship(remote_side=[id])
files: Mapped[list['FreightRpaOutboundReportFile']] = relationship(
back_populates='unit_run', cascade='all, delete-orphan',
)
class FreightRpaOutboundReportFile(Base):
"""出站原样归档文件;保留文件身份和对象清理事实,不关联库存快照。"""
__tablename__ = 'freight_rpa_outbound_report_files'
__table_args__ = (
UniqueConstraint('unit_run_id', 'sha256', name='uq_freight_rpa_outbound_report_files_unit_sha256'),
CheckConstraint("file_size >= 0", name='ck_freight_rpa_outbound_report_files_size'),
Index('ix_freight_rpa_outbound_report_files_unit', 'unit_run_id'),
Index('ix_freight_rpa_outbound_report_files_expires', 'archive_expires_at', 'archive_deleted_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
unit_run_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_outbound_rpa_unit_runs.id'), nullable=False, index=True)
storage_provider: Mapped[str] = mapped_column(String(32), nullable=False)
storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False)
storage_key: Mapped[str] = mapped_column(String(1024), nullable=False)
original_filename: Mapped[str] = mapped_column(String(255), nullable=False)
content_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
file_size: Mapped[int] = mapped_column(Integer, nullable=False)
sha256: Mapped[str] = mapped_column(String(64), nullable=False)
# 解析失败分层标记:归档文件解析失败时写入;三者全空=未失败/已清除。
parse_failed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
parse_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
parse_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
archive_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
archive_deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
archive_delete_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
unit_run: Mapped[FreightRpaOutboundUnitRun] = relationship(back_populates='files')
+187 -27
View File
@@ -1,13 +1,22 @@
"""models/in_transit_transfer.py """models/in_transit_transfer.py
用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Matching、InvoiceItem、 用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Matching、InvoiceItem、
Document(ERP 调拨单)、Attempt、AuditEvent 与 Archive。 Document(ERP 调拨单)、Attempt、AuditEvent 与 Archive;另含调拨类型
依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁)。 配置表 TransferTypeConfig(类型配置化,ADR 0002)与库存异动档
TransferMovementLedger(外部系统入站/出站记录镜像,ADR 0001)。
依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁);
source_file_id 外键指向 freight_rpa_inbound_report_files(FreightRpaInboundReportFile 原样归档,入站证据)。
逻辑:Run 是异步真相源;InvoiceItem 按(matching_id, invoice_no)唯一防止重复建单; 逻辑:Run 是异步真相源;InvoiceItem 按(matching_id, invoice_no)唯一防止重复建单;
Document(单)实现「五元组一组一单」,同组未完结单唯一由部分唯一索引在 Document(单)实现「五元组一组一单」,同组未完结单唯一由部分唯一索引在
DB 层强制(D15 防双单兜底);单:Attempt=1:N,外键在 Attempt 侧(D14); DB 层强制(D15 防双单兜底);单:Attempt=1:N,外键在 Attempt 侧(D14);
Attempt 保留每次恢复/重查/执行事实,旧 Attempt 永不覆盖; Attempt 保留每次恢复/重查/执行事实,旧 Attempt 永不覆盖;
AuditEvent 保存脱敏快照与事件 Hash,禁止更新/删除。 AuditEvent 保存脱敏快照与事件 Hash,禁止更新/删除;
transfer_runs.transfer_type 合法值由 TransferTypeConfig 配置承接
(原枚举 CHECK 约束已移除);
TransferMovementLedger 以自然键 (source_code, record_kind, doc_no,
line_no, line_seq, in_out_flag, carton_id, lot_no) 幂等增量落地外部记录,
已执行记录经 transfer_executed 封存(防二次调拨),来源文件删除后档事实留存
(ON DELETE SET NULL,链接仅溯源)。
""" """
from __future__ import annotations from __future__ import annotations
@@ -34,20 +43,16 @@ from app.core.errors import ValidationError
from app.models.base import Base from app.models.base import Base
# 与 services/in_transit_transfer/status.py 保持一致的冻结枚举(数据库级兜底)。 # 与 services/in_transit_transfer/status.py 保持一致的冻结枚举(数据库级兜底)。
# 【not_matured 已退役 2026-10-16】成熟概念删除,存量行经 tt16 重映射 cancelled。
TRANSFER_ITEM_STATUSES = ( TRANSFER_ITEM_STATUSES = (
'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing', 'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing',
'success', 'duplicate_success', 'blocked_recoverable', 'not_matured', 'success', 'duplicate_success', 'blocked_recoverable',
'result_unknown', 'manually_closed', 'cancelled', 'notification_failed', 'result_unknown', 'manually_closed', 'cancelled', 'notification_failed',
) )
TRANSFER_RUN_STATUSES = ( TRANSFER_RUN_STATUSES = (
'queued', 'preparing_files', 'matching', 'ready_to_execute', 'executing', 'queued', 'preparing_files', 'matching', 'ready_to_execute', 'executing',
'success', 'partial_failed', 'failed', 'cancelled', 'success', 'partial_failed', 'failed', 'cancelled',
) )
# 与 services/in_transit_transfer/transfer_type.py TransferType 保持一致的冻结枚举
# (数据库级兜底);一期仅 in_transit_to_hub 进入处理链路,其余为占位值。
TRANSFER_RUN_TYPES = (
'in_transit_to_hub', 'hub_repair_out', 'hub_to_hub',
)
TRANSFER_SOURCE_JOB_STATUSES = ( TRANSFER_SOURCE_JOB_STATUSES = (
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing', 'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
'matching', 'executing', 'success', 'partial_failed', 'failed', 'cancelled', 'matching', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
@@ -98,10 +103,6 @@ class TransferRun(Base):
"trigger_type IN ('manual', 'schedule')", "trigger_type IN ('manual', 'schedule')",
name='ck_transfer_runs_trigger_type', name='ck_transfer_runs_trigger_type',
), ),
CheckConstraint(
f"transfer_type IN ({', '.join(repr(t) for t in TRANSFER_RUN_TYPES)})",
name='ck_transfer_runs_transfer_type',
),
Index('ix_transfer_runs_status_created', 'status', 'created_at'), Index('ix_transfer_runs_status_created', 'status', 'created_at'),
Index('ix_transfer_runs_business_date', 'business_date'), Index('ix_transfer_runs_business_date', 'business_date'),
) )
@@ -109,9 +110,11 @@ class TransferRun(Base):
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
run_no: Mapped[str] = mapped_column(String(64), nullable=False) run_no: Mapped[str] = mapped_column(String(64), nullable=False)
trigger_type: Mapped[str] = mapped_column(String(16), nullable=False, default='manual', server_default='manual') trigger_type: Mapped[str] = mapped_column(String(16), nullable=False, default='manual', server_default='manual')
# 调拨业务类型(在途仓至HUB仓/HUB仓维修出/HUB仓间调拨);决定匹配收料数据范围。 # 调拨业务类型(合法值由 TransferTypeConfig 配置承接,合法 code 正则
# ^[a-z][a-z0-9_]{1,63}$ 上限 64);决定匹配入站数据范围。列宽 64 与配置表
# code 上限对齐(终审 I2:33~64 字符 code 建匹配时写 32 宽列会 DB 500)。
transfer_type: Mapped[str] = mapped_column( transfer_type: Mapped[str] = mapped_column(
String(32), nullable=False, default='in_transit_to_hub', server_default='in_transit_to_hub', String(64), nullable=False, default='in_transit_to_hub', server_default='in_transit_to_hub',
) )
business_date: Mapped[str] = mapped_column(String(16), nullable=False) business_date: Mapped[str] = mapped_column(String(16), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued') status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
@@ -215,15 +218,18 @@ class TransferMatching(Base):
class TransferInvoiceItem(Base): class TransferInvoiceItem(Base):
"""匹配明细项;同一匹配内 (来源,Invoice,料号,收料日期) 唯一,保留原始行追溯。 """匹配明细项;同一匹配内 (来源,Invoice,料号,异动日期) 唯一,保留原始行追溯。
Invoice 锚定批号(2026-09-21 业务口径):同一批号跨料号/跨日期拆分为多行。 Invoice 锚定批号(2026-09-21 业务口径):同一批号跨料号/跨日期拆分为多行。
【2026-10-14 出生翻转(ADR 0001/D4)】行不再由文件落地写入,而是匹配创建时
从库存异动档圈定生成:ledger_record_id 指向档记录(业务字段=档原值),
matching_id 创建即绑定(D17:一条档记录一生只生成一次 items 绑定)。
""" """
__tablename__ = 'transfer_invoice_items' __tablename__ = 'transfer_invoice_items'
__table_args__ = ( __table_args__ = (
UniqueConstraint( UniqueConstraint(
'matching_id', 'source_code', 'invoice_no', 'material_no', 'receipt_date', 'matching_id', 'source_code', 'invoice_no', 'material_no', 'movement_date',
name='uq_transfer_invoice_items_matching_grain', name='uq_transfer_invoice_items_matching_grain',
), ),
CheckConstraint( CheckConstraint(
@@ -236,32 +242,40 @@ class TransferInvoiceItem(Base):
# 单据级执行(T10)高频「按单查行」:document_id 单列索引(控制器裁决, # 单据级执行(T10)高频「按单查行」:document_id 单列索引(控制器裁决,
# 并入 tt0d1e2f3a4b 避免额外迁移节点)。 # 并入 tt0d1e2f3a4b 避免额外迁移节点)。
Index('ix_transfer_invoice_items_document_id', 'document_id'), Index('ix_transfer_invoice_items_document_id', 'document_id'),
# 匹配创建圈档的占用互斥检查(D17)高频「按档记录查行」:单列索引
# (并入 tt12c3d4e5f6a7 避免额外迁移节点)。
Index('ix_transfer_invoice_items_ledger_record_id', 'ledger_record_id'),
) )
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
# 行归属解耦后 matching_id 仅留痕(首次创建值);落地证据同步行尚无匹配归属 # 【2026-10-14 出生翻转】matching_id 回归「创建即绑定」:行由匹配创建时从档
# (2026-09-25),放开非空。uq_transfer_invoice_items_matching_grain 含本列, # 圈定生成(落地不再写 items,见 evidence_sync/ADR 0001),新行恒非空
# NULL 行不受该唯一约束保护——同步的幂等去重由 evidence_sync 应用层按 # (模型层不强制 NOT NULL,存量兼容,服务层保证);D17 圈档互斥的占用判定
# (source, invoice, material, receipt_date) 四元组负责(见 evidence_sync)。 # 以本列 + 所属匹配状态为准(取消匹配即释放占用)。
matching_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_matchings.id'), nullable=True, index=True) matching_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_matchings.id'), nullable=True, index=True)
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True) run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True)
# 【2026-10-14 出生翻转】行来源档记录外键(可空:隔离的历史行允许 NULL);
# 行上业务字段=档原值,批号等转换只在系统边界按匹配快照规则派生(不落库)。
ledger_record_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('transfer_movement_ledger.id'), nullable=True,
)
source_code: Mapped[str] = mapped_column(String(64), nullable=False) source_code: Mapped[str] = mapped_column(String(64), nullable=False)
invoice_no: Mapped[str] = mapped_column(String(64), nullable=False) invoice_no: Mapped[str] = mapped_column(String(64), nullable=False)
# 批号(External ASN 等)原值;「拨入批号」展示由 WTP→HOW 转换派生,不落库。 # 批号(External ASN 等)原值;「拨入批号」展示由 WTP→HOW 转换派生,不落库。
lot_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) lot_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(拨出库位解析审计)。 # 入站文件「仓库」列原值:inventory_match 源映射行匹配键(拨出库位解析审计)。
receipt_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='') movement_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
# 交易单位原值(movement 契约第 11 字段 unit,计划 D4):解析原样保留(仅 trim, # 交易单位原值(movement 契约第 11 字段 unit,计划 D4):解析原样保留(仅 trim,
# 不换算);空值行在匹配阶段落 blocked_missing_unit。unit 不参与匹配 Hash(口径冻结)。 # 不换算);空值行在匹配阶段落 blocked_missing_unit。unit 不参与匹配 Hash(口径冻结)。
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, default='', server_default='') unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, default='', server_default='')
material_no: Mapped[str] = mapped_column(String(64), nullable=False) material_no: Mapped[str] = mapped_column(String(64), nullable=False)
material_name: Mapped[str] = mapped_column(String(200), nullable=False, default='') material_name: Mapped[str] = mapped_column(String(200), nullable=False, default='')
specification: Mapped[str] = mapped_column(String(200), nullable=False, default='') specification: Mapped[str] = mapped_column(String(200), nullable=False, default='')
receipt_date: Mapped[Optional[str]] = mapped_column(String(16), nullable=True) movement_date: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False) from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False) to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
# 数量以 Decimal 文本保存,杜绝浮点误差;比较在服务层完成。 # 数量以 Decimal 文本保存,杜绝浮点误差;比较在服务层完成。
receipt_quantity: Mapped[str] = mapped_column(String(40), nullable=False) movement_quantity: Mapped[str] = mapped_column(String(40), nullable=False)
external_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True) external_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
# [库存查得时刻] 当前 external_quantity 的 ERP 取数时间戳(stale 徽标判定时钟, # [库存查得时刻] 当前 external_quantity 的 ERP 取数时间戳(stale 徽标判定时钟,
# 2026-09-29 起与行新鲜度 updated_at 分离:证据同步换戳/存续不续期本字段, # 2026-09-29 起与行新鲜度 updated_at 分离:证据同步换戳/存续不续期本字段,
@@ -289,6 +303,12 @@ class TransferInvoiceItem(Base):
# (document_id 置 NULL)回到 ready_to_execute,可被重新勾选组建新单。 # (document_id 置 NULL)回到 ready_to_execute,可被重新勾选组建新单。
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_documents.id'), nullable=True) document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_documents.id'), nullable=True)
document: Mapped[Optional['TransferDocument']] = relationship(back_populates='items') document: Mapped[Optional['TransferDocument']] = relationship(back_populates='items')
# 【2026-10-14 改锚(规格 §10)】行 → 档记录只读导航:file_current 门禁与行装饰
# 的版本戳取档记录 file_sha256(档记录是证据权威)。纯 ORM relationship——
# 不新增列/索引/约束(ledger_record_id 列与索引既有),无配套迁移。
ledger_record: Mapped[Optional['TransferMovementLedger']] = relationship(
foreign_keys=[ledger_record_id],
)
class TransferDocument(Base): class TransferDocument(Base):
@@ -320,7 +340,7 @@ class TransferDocument(Base):
# 建表同语义(部分唯一,非全组唯一)。 # 建表同语义(部分唯一,非全组唯一)。
Index( Index(
'uq_transfer_documents_group_live', 'uq_transfer_documents_group_live',
'source_code', 'external_org', 'receipt_date', 'from_warehouse', 'to_warehouse', 'source_code', 'external_org', 'movement_date', 'from_warehouse', 'to_warehouse',
unique=True, unique=True,
postgresql_where=text(UNRESOLVED_DOC_STATUS_WHERE), postgresql_where=text(UNRESOLVED_DOC_STATUS_WHERE),
sqlite_where=text(UNRESOLVED_DOC_STATUS_WHERE), sqlite_where=text(UNRESOLVED_DOC_STATUS_WHERE),
@@ -333,7 +353,7 @@ class TransferDocument(Base):
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True) run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True)
source_code: Mapped[str] = mapped_column(String(64), nullable=False) source_code: Mapped[str] = mapped_column(String(64), nullable=False)
external_org: Mapped[str] = mapped_column(String(64), nullable=False) external_org: Mapped[str] = mapped_column(String(64), nullable=False)
receipt_date: Mapped[str] = mapped_column(String(16), nullable=False) movement_date: Mapped[str] = mapped_column(String(16), nullable=False)
from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False) from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False) to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
# 提交标识(D3 终身复用):同组复用单时保持首建值不变;唯一性由 # 提交标识(D3 终身复用):同组复用单时保持首建值不变;唯一性由
@@ -476,6 +496,146 @@ class TransferArchive(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class TransferTypeConfig(Base):
"""调拨类型配置(ADR 0002):编码/四语言名称/启停/排序 + 范围规则/仓库定义/转换规则。
code 创建后不可变(transfer_runs.transfer_type 引用);只有停用没有删除;
配置为空时匹配链路 fail-closed(TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED)。
"""
__tablename__ = 'transfer_type_configs'
__table_args__ = (
UniqueConstraint('code', name='uq_transfer_type_configs_code'),
)
id: Mapped[int] = mapped_column(primary_key=True)
code: Mapped[str] = mapped_column(String(64), nullable=False)
names_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
enabled: Mapped[bool] = mapped_column(default=False, server_default=text('false'), nullable=False)
sort_order: Mapped[int] = mapped_column(Integer, default=0, server_default=text('0'), nullable=False)
scope_rules_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
warehouse_config_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
transform_rules_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
class TransferMovementLedger(Base):
"""库存异动档(ADR 0001):外部系统入站/出站记录的平台镜像(参照 ERP inaj_t 形态)。
用途:外部系统入站(一期)/出站(结构就位,record_kind='outbound')记录统一落档;
匹配明细(items)由匹配创建时从档圈定生成(落地不再写 items,出生翻转)。
幂等增量落地:自然键 (source_code, record_kind, doc_no, line_no, line_seq,
in_out_flag, carton_id, lot_no, external_doc_no, external_line_no) 唯一约束
去重——不存在则插入、证据变化则原行更新、文件缺席不删(tt14 扩维:真实 WMS
行身份=单据+行+箱/批,carton_id/lot_no 加入键防同箱/批塌缩丢行;R7 终审:
两列同步 NOT NULL + default '',nullable 成分的 NULL 不参与 PG/SQLite 唯一
比对会逃逸约束,空值成分一律以空串入库保证唯一约束可比;2026-10-21 再扩维:
外部单号/外部项次=WMS Order #/Line # 入键,外部单据身份作为档幂等主键管控);
已执行记录 transfer_executed=true 封存(executed_doc_no 回写),永不更新、
永不复活、永不再次被圈定(防二次调拨,档级封存兜底)。
刻意双字段:record_kind(文件种类声明,权威)与 in_out_flag(数据列原值),
两者矛盾即解析错位,由落档链路打审计事件,记录照常落档。
可空语义:自然键 8 成分一律 NOT NULL(line_seq/in_out_flag/carton_id/lot_no
default '' 保证唯一约束可比、防 PG NULL 逃逸唯一比对),业务/证据列一律
nullable(外部列宽松落地);movement_date 可空——空值记录照常落档但不进
异动日期圈定(日期条件恒排除 NULL)。
source_file_id ON DELETE SET NULL:来源文件被清理(文件资产保留策略)后
档记录必须留存(事实不随文件消失,链接仅溯源)。
D 组 ⭐5 列(order_type/odm_id/odm_name/carton_id/pallet_id)为本期新增强
业务字段(进解析 Profile 可映射);🔖预留列(doc_nature/movement_type/
reason_code/source_ref_no/partner_code/remark)出货报告确认后直接映射,
免后续迁移。
"""
__tablename__ = 'transfer_movement_ledger'
__table_args__ = (
# 自然键唯一(幂等增量落地兜底;应用层按自然键查档先行)。tt14 扩维 8 成分:
# carton_id/lot_no 进键(真实 WMS 行身份=单据+行+箱/批),R7 终审同步
# NOT NULL + default ''(可空成分以空串入库,防 PG NULL 逃逸唯一比对)。
# 2026-10-21 扩维 10 成分:external_doc_no/external_line_no(外部单号/
# 外部项次,WMS Order #/Line #)进键——外部单据身份作为档幂等主键管控,
# 同一外部单号+项次的重复落档/证据更新收敛到同一档行(存量行以空串参与
# 键;配置外部映射后重放同文件即按新键收敛,必要时走清空并重解析重建)。
UniqueConstraint(
'source_code', 'record_kind', 'doc_no', 'line_no', 'line_seq', 'in_out_flag',
'carton_id', 'lot_no', 'external_doc_no', 'external_line_no',
name='uq_transfer_movement_ledger_natural_key',
),
# 匹配创建圈档主路径:来源 + 记录种类 + 异动日期范围扫描。
Index('ix_transfer_movement_ledger_source_kind_date', 'source_code', 'record_kind', 'movement_date'),
# 档级封存/待匹配桶扫描:按记录种类过滤已执行位。
Index('ix_transfer_movement_ledger_kind_executed', 'record_kind', 'transfer_executed'),
)
id: Mapped[int] = mapped_column(primary_key=True)
# --- A 单据标识(自然键成分,NOT NULL;line_seq/in_out_flag 可空成分 default '')---
doc_no: Mapped[str] = mapped_column(String(64), nullable=False)
line_no: Mapped[str] = mapped_column(String(32), nullable=False)
line_seq: Mapped[str] = mapped_column(String(32), nullable=False, default='', server_default='')
# 数据列原值(入站=收发标记),与 record_kind 交叉校验用,不参与权威判定。
in_out_flag: Mapped[str] = mapped_column(String(8), nullable=False, default='', server_default='')
# --- A+ 外部单据身份(2026-10-21 起入自然键:外部单号/外部项次 = WMS Order #/
# --- 行号;NOT NULL + default '' 与 line_seq 同口径,防 NULL 逃逸唯一比对)---
external_doc_no: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
external_line_no: Mapped[str] = mapped_column(String(32), nullable=False, default='', server_default='')
# --- B 物料与数量(数量 Decimal 文本,与 items.movement_quantity 同约定)---
material_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
material_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
specification: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
# 批号原值(tt14 起入自然键:NOT NULL + default '' 防 PG NULL 逃逸唯一比对;
# 空值成分以空串入库保证唯一约束可比,与 line_seq/in_out_flag 同口径)。
lot_no: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
# --- C 仓储与日期(movement_date 可空:空值不进异动日期圈定)---
warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
storage_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
movement_date: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
# --- D 业务属性(⭐本期新增强业务字段;carton_id tt14 起入自然键 NOT NULL
# --- default '';🔖预留列 nullable,出货侧直接映射)---
order_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
odm_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
odm_name: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
# 箱号(tt14 起入自然键:NOT NULL + default '',与 lot_no 同口径,防 NULL 逃逸唯一比对)。
carton_id: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
pallet_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
doc_nature: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
movement_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
reason_code: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
source_ref_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
partner_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
# --- E 平台溯源(证据字段:evidence_sync 原行更新时整体换新)---
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
# 文件种类声明(tt14 值迁移后 'inbound'/'outbound',权威);与 in_out_flag 矛盾打审计事件。
record_kind: Mapped[str] = mapped_column(String(16), nullable=False)
# 来源文件溯源:ON DELETE SET NULL(文件清理后档事实留存)。
source_file_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('freight_rpa_inbound_report_files.id', ondelete='SET NULL'), nullable=True,
)
file_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
sheet_name: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
row_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
# --- F 平台回写(档级封存:票据执行成功落单号时回写,永不解除)---
transfer_executed: Mapped[bool] = mapped_column(
default=False, server_default=text('false'), nullable=False,
)
executed_doc_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# 溯源关系:档案行 → FreightRpaInboundReportFile 原样归档文件(单向,不回挂;FreightRpaInboundReportFile
# 不感知调拨域,避免跨域 back_populates 环)。
source_file: Mapped[Optional['FreightRpaInboundReportFile']] = relationship()
@event.listens_for(TransferAuditEvent, 'before_update') @event.listens_for(TransferAuditEvent, 'before_update')
def _reject_transfer_audit_update(_mapper, _connection, _target) -> None: def _reject_transfer_audit_update(_mapper, _connection, _target) -> None:
"""拒绝 ORM 更新,确保审计事件不可改写。""" """拒绝 ORM 更新,确保审计事件不可改写。"""
+2 -2
View File
@@ -2,7 +2,7 @@
backend/app/models/job.py backend/app/models/job.py
用途:通用后台任务模型,承载跨业务域的异步任务执行状态。 用途:通用后台任务模型,承载跨业务域的异步任务执行状态。
依赖:models.base.Base。 依赖:models.base.Base;候选集外键指向 shipping_onhand_candidate_sets。
逻辑:由 app.jobs.queue 写入和领取,由 worker 分发到具体业务 handler;业务模型保存业务状态,本表保存执行状态、锁、重试与结果。 逻辑:由 app.jobs.queue 写入和领取,由 worker 分发到具体业务 handler;业务模型保存业务状态,本表保存执行状态、锁、重试与结果。
""" """
@@ -149,7 +149,7 @@ class Job(Base):
ForeignKey('shipping_process_gates.id'), nullable=True, index=True, ForeignKey('shipping_process_gates.id'), nullable=True, index=True,
) )
candidate_set_id: Mapped[Optional[int]] = mapped_column( candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id'), nullable=True, index=True, ForeignKey('shipping_onhand_candidate_sets.id'), nullable=True, index=True,
) )
fencing_token: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) fencing_token: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id')) created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
+12 -105
View File
@@ -1,7 +1,7 @@
""" """
backend/app/models/shipping.py backend/app/models/shipping.py
用途:货代发货通知正式 Notice(shipping_notices)、事件、库存文件、接入记录、文档/候选与库存映射模型。 用途:货代发货通知正式 Notice(shipping_notices)、事件、在手报表文件(freight_rpa_onhand_report_files,s18 起归 RPA,列仍含解析行与快照状态)、任务关联(shipping_task_onhand_links)、接入记录与文档/候选模型。
依赖:models.base.Base;规范订单行见 shipping_task_line;建单前 OT 见 shipping_order_task。 依赖:models.base.Base;规范订单行见 shipping_task_line;建单前 OT 见 shipping_order_task。
逻辑:co8e9f0a1b2c 已物理 DROP shipping_batches 及全表 batch_id / consumed_batch_id 列; 逻辑:co8e9f0a1b2c 已物理 DROP shipping_batches 及全表 batch_id / consumed_batch_id 列;
Intake 消费绑定仅保留 consumed_task_id / consumed_at;upload_batch_id 为上传边界批次(非 shipping_batches); Intake 消费绑定仅保留 consumed_task_id / consumed_at;upload_batch_id 为上传边界批次(非 shipping_batches);
@@ -164,108 +164,15 @@ class ShippingTaskPurgeAudit(Base):
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
class ShippingInventoryFile(Base): class ShippingTaskOnhandLink(Base):
"""货代发货批次库存快照文件,承载一次上传后可被多票任务共用的库存数据。"""
__tablename__ = 'shipping_inventory_files'
__table_args__ = (
Index('ix_shipping_inventory_files_user_created', 'user_id', 'created_at'),
Index(
'ix_shipping_inventory_files_source_snapshot',
'source_code',
'warehouse_id',
'snapshot_status',
'exported_at',
),
Index(
'ix_shipping_inventory_files_source_warehouse',
'source_code',
'warehouse_id',
),
Index(
'uq_shipping_inventory_files_rpa_identity_ready',
'rpa_run_no',
'source_code',
'warehouse_id',
unique=True,
postgresql_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND warehouse_id IS NOT NULL"
),
sqlite_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND warehouse_id IS NOT NULL"
),
),
# 动态多仓文件没有单一 Warehouse;按 RPA run + Source 保证回调重放幂等。
Index(
'uq_shipping_inventory_files_rpa_dynamic_source_ready',
'rpa_run_no',
'source_code',
unique=True,
postgresql_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND warehouse_id IS NULL"
),
sqlite_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND warehouse_id IS NULL"
),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
inventory_file_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
storage_path: Mapped[str] = mapped_column(String(500), nullable=False)
schema_preview_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
field_mapping_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
mapping_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
mapping_confirmed: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
line_count: Mapped[int] = mapped_column(Integer, default=0)
share_mode: Mapped[str] = mapped_column(String(32), default='task_only')
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
identity_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
snapshot_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
exported_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
rpa_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
schedule_run_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True)
source_query_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
links: Mapped[List['ShippingTaskInventoryLink']] = relationship(
'ShippingTaskInventoryLink',
back_populates='inventory_file',
cascade='all, delete-orphan',
)
class ShippingTaskInventoryLink(Base):
"""发货任务与库存快照的关联记录,一期每个任务只保留一条 active link。""" """发货任务与库存快照的关联记录,一期每个任务只保留一条 active link。"""
__tablename__ = 'shipping_task_inventory_links' __tablename__ = 'shipping_task_onhand_links'
__table_args__ = ( __table_args__ = (
Index('ix_shipping_task_inventory_links_task_active', 'task_id', 'is_active'), Index('ix_shipping_task_onhand_links_task_active', 'task_id', 'is_active'),
Index('ix_shipping_task_inventory_links_file_active', 'inventory_file_id', 'is_active'), Index('ix_shipping_task_onhand_links_file_active', 'onhand_file_id', 'is_active'),
Index( Index(
'ix_shipping_task_inventory_links_task_source', 'ix_shipping_task_onhand_links_task_source',
'task_id', 'task_id',
'matched_source_code', 'matched_source_code',
), ),
@@ -273,7 +180,7 @@ class ShippingTaskInventoryLink(Base):
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), index=True) task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), index=True)
inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id'), index=True) onhand_file_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), index=True)
link_role: Mapped[str] = mapped_column(String(32), default='member') link_role: Mapped[str] = mapped_column(String(32), default='member')
access_mode: Mapped[str] = mapped_column(String(32), default='readonly') access_mode: Mapped[str] = mapped_column(String(32), default='readonly')
is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), index=True) is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), index=True)
@@ -283,8 +190,8 @@ class ShippingTaskInventoryLink(Base):
identity_check_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) identity_check_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
identity_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) identity_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
snapshot_age_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) snapshot_age_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', use_alter=True), nullable=True, index=True) preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_preparation_attempts.id', use_alter=True), nullable=True, index=True)
source_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_source_attempts.id', use_alter=True), nullable=True, index=True) source_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_preparation_source_attempts.id', use_alter=True), nullable=True, index=True)
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True) invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True) invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
@@ -294,10 +201,10 @@ class ShippingTaskInventoryLink(Base):
linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', foreign_keys=[task_id]) task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', foreign_keys=[task_id])
inventory_file: Mapped['ShippingInventoryFile'] = relationship( inventory_file: Mapped['FreightRpaOnhandReportFile'] = relationship(
'ShippingInventoryFile', 'FreightRpaOnhandReportFile',
back_populates='links', back_populates='links',
foreign_keys=[inventory_file_id], foreign_keys=[onhand_file_id],
) )
@@ -30,8 +30,9 @@ class ShippingDocumentProfileAutoFreezeQualification(Base):
"status IN ('manual_confirmation', 'auto_freeze_approved', 'auto_freeze_suspended')", "status IN ('manual_confirmation', 'auto_freeze_approved', 'auto_freeze_suspended')",
name='ck_shipping_document_profile_auto_freeze_qualification_status', name='ck_shipping_document_profile_auto_freeze_qualification_status',
), ),
# 索引名沿用迁移 0aa34b5c6d7e 的短名;PostgreSQL 标识符上限 63 字符,超长名会导致建库失败。
Index( Index(
'ix_shipping_document_profile_auto_freeze_qualification_profile_status', 'ix_ship_doc_prof_auto_freeze_profile_status',
'profile_id', 'status', 'profile_id', 'status',
), ),
) )
@@ -2,7 +2,7 @@
models/shipping_excel_template.py models/shipping_excel_template.py
用途:定义版本化发货 Excel 模板及不可变 Notice 导出产物。 用途:定义版本化发货 Excel 模板及不可变 Notice 导出产物。
依赖:models.base.Base、库存源、订单 Schema、ShippingNotice 与库存快照模型。 依赖:models.base.Base、FreightRpaSource、订单 Schema、ShippingNotice、freight_rpa_parsing_profiles 与 freight_rpa_onhand_report_files。
逻辑:库存源只绑定已发布模板版本;每次生成均新增 Artifact 并锁定输入版本与校验和; 逻辑:库存源只绑定已发布模板版本;每次生成均新增 Artifact 并锁定输入版本与校验和;
co8e9f0a1b2c 已删除 export artifact 的 batch_id 列;Artifact 直接属于一张 Notice。 co8e9f0a1b2c 已删除 export artifact 的 batch_id 列;Artifact 直接属于一张 Notice。
""" """
@@ -44,7 +44,7 @@ class ShippingExcelTemplate(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='excel_template') sources: Mapped[list['FreightRpaSource']] = relationship(back_populates='excel_template')
class ShippingExportArtifact(Base): class ShippingExportArtifact(Base):
@@ -62,8 +62,8 @@ class ShippingExportArtifact(Base):
template_id: Mapped[int] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=False) template_id: Mapped[int] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=False)
order_schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False) order_schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
order_extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False) order_extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False)
inventory_parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=False) inventory_parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_parsing_profiles.id'), nullable=False)
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True) inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), nullable=True)
input_checksum: Mapped[str] = mapped_column(String(64), nullable=False) input_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
file_path: Mapped[str] = mapped_column(String(500), nullable=False) file_path: Mapped[str] = mapped_column(String(500), nullable=False)
file_name: Mapped[str] = mapped_column(String(255), nullable=False) file_name: Mapped[str] = mapped_column(String(255), nullable=False)
+17 -17
View File
@@ -2,7 +2,7 @@
backend/app/models/shipping_fulfillment.py backend/app/models/shipping_fulfillment.py
用途:保存预约单全局注册、每轮库存核验和 Excel 对预约单的不可重叠归属。 用途:保存预约单全局注册、每轮库存核验和 Excel 对预约单的不可重叠归属。
依赖:冻结订单 Snapshot、库存文件、导出 Artifact 与 SQLAlchemy Base;Notice 主表 shipping_notices。 依赖:冻结订单 Snapshot、freight_rpa_onhand_report_files、导出 Artifact 与 SQLAlchemy Base;核验表 shipping_notice_onhand_verifications / shipping_notice_onhand_verification_lines;Notice 主表 shipping_notices。
逻辑:Snapshot 行可保留历史预约号;全局 Reservation 决定当前有效行和履约状态,核验与 Artifact 行均追加保存。 逻辑:Snapshot 行可保留历史预约号;全局 Reservation 决定当前有效行和履约状态,核验与 Artifact 行均追加保存。
""" """
@@ -46,53 +46,53 @@ class ShippingReservation(Base):
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
class ShippingInventoryVerification(Base): class ShippingOnhandVerification(Base):
"""一次任务库存核验的不可变轮次,绑定当时有效库存快照。""" """一次任务库存核验的不可变轮次,绑定当时有效库存快照。"""
__tablename__ = 'shipping_notice_inventory_verifications' __tablename__ = 'shipping_notice_onhand_verifications'
__table_args__ = ( __table_args__ = (
CheckConstraint( CheckConstraint(
"status IN ('completed', 'expired', 'superseded')", "status IN ('completed', 'expired', 'superseded')",
name='ck_shipping_notice_inventory_verifications_status', name='ck_shipping_notice_onhand_verifications_status',
), ),
Index('ix_shipping_notice_inventory_verifications_task_created', 'task_id', 'created_at'), Index('ix_shipping_notice_onhand_verifications_task_created', 'task_id', 'created_at'),
) )
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False) task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False)
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True) onhand_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), nullable=True)
source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', ondelete='SET NULL'), nullable=True, index=True) preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_preparation_attempts.id', ondelete='SET NULL'), nullable=True, index=True)
matching_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True, index=True) matching_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True, index=True)
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_inventory_verifications.id'), nullable=True) superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_onhand_verifications.id'), nullable=True)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='completed', server_default='completed') status: Mapped[str] = mapped_column(String(16), nullable=False, default='completed', server_default='completed')
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
lines: Mapped[list['ShippingInventoryVerificationLine']] = relationship( lines: Mapped[list['ShippingOnhandVerificationLine']] = relationship(
back_populates='verification', cascade='all, delete-orphan', order_by='ShippingInventoryVerificationLine.id', back_populates='verification', cascade='all, delete-orphan', order_by='ShippingOnhandVerificationLine.id',
) )
class ShippingInventoryVerificationLine(Base): class ShippingOnhandVerificationLine(Base):
"""一个预约单在一轮库存中的需求、可用数量和确定性结果。""" """一个预约单在一轮库存中的需求、可用数量和确定性结果。"""
__tablename__ = 'shipping_notice_inventory_verification_lines' __tablename__ = 'shipping_notice_onhand_verification_lines'
__table_args__ = ( __table_args__ = (
UniqueConstraint( UniqueConstraint(
'verification_id', 'reservation_id', 'verification_id', 'reservation_id',
name='uq_shipping_notice_inventory_verification_lines_reservation', name='uq_shipping_notice_onhand_verification_lines_reservation',
), ),
CheckConstraint( CheckConstraint(
"status IN ('available', 'shortage', 'invalid')", "status IN ('available', 'shortage', 'invalid')",
name='ck_shipping_notice_inventory_verification_lines_status', name='ck_shipping_notice_onhand_verification_lines_status',
), ),
) )
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
verification_id: Mapped[int] = mapped_column( verification_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_inventory_verifications.id', ondelete='CASCADE'), nullable=False, ForeignKey('shipping_notice_onhand_verifications.id', ondelete='CASCADE'), nullable=False,
) )
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False) reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False)
required_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False) required_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False)
@@ -100,7 +100,7 @@ class ShippingInventoryVerificationLine(Base):
status: Mapped[str] = mapped_column(String(16), nullable=False) status: Mapped[str] = mapped_column(String(16), nullable=False)
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
verification: Mapped['ShippingInventoryVerification'] = relationship(back_populates='lines') verification: Mapped['ShippingOnhandVerification'] = relationship(back_populates='lines')
class ShippingExportArtifactLine(Base): class ShippingExportArtifactLine(Base):
@@ -120,7 +120,7 @@ class ShippingExportArtifactLine(Base):
) )
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False) reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False)
verification_line_id: Mapped[int] = mapped_column( verification_line_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_inventory_verification_lines.id'), nullable=False, ForeignKey('shipping_notice_onhand_verification_lines.id'), nullable=False,
) )
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
+2 -2
View File
@@ -2,7 +2,7 @@
backend/app/models/shipping_notice_line.py backend/app/models/shipping_notice_line.py
用途:正式发货通知行(shipping_notice_lines),对齐蓝图建单后命名空间。 用途:正式发货通知行(shipping_notice_lines),对齐蓝图建单后命名空间。
依赖:shipping_notices、shipping_order_snapshot_lines、SQLAlchemy Base。 依赖:shipping_notices、shipping_order_snapshot_lines、freight_rpa_onhand_report_files、SQLAlchemy Base。
逻辑:冻结 Snapshot 时双写;履约仍以 Snapshot 为权威,本表供 Notice 域查询与 1:N 扩展。 逻辑:冻结 Snapshot 时双写;履约仍以 Snapshot 为权威,本表供 Notice 域查询与 1:N 扩展。
""" """
@@ -47,7 +47,7 @@ class ShippingNoticeLine(Base):
# 正式履约事实按通知行固化;Notice 单头不得承载仓库或库存快照。 # 正式履约事实按通知行固化;Notice 单头不得承载仓库或库存快照。
inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
inventory_file_id: Mapped[Optional[int]] = mapped_column( inventory_file_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), nullable=True, index=True, ForeignKey('freight_rpa_onhand_report_files.id', ondelete='SET NULL'), nullable=True, index=True,
) )
inventory_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) inventory_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
field_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) field_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
@@ -1,9 +1,9 @@
""" """
models/shipping_notice_line_inventory_match.py models/shipping_notice_line_onhand_match.py
用途:正式 OT(ShippingNotice)行级库存匹配事实持久化——可用数量/短缺/match_result 的真相源。 用途:正式 OT(ShippingNotice)行级库存匹配事实持久化——可用数量/短缺/match_result 的真相源。
依赖:shipping_notices、shipping_inventory_files、shipping_order_review_cases(可选关联)。 依赖:shipping_notices、freight_rpa_onhand_report_files、shipping_order_review_cases(可选关联)。
逻辑:由 inventory_matching 完成后写入;同一 OT+行+快照唯一;新快照新增行不覆盖历史; 逻辑:由 onhand_matching 完成后写入;同一 OT+行+快照唯一;新快照新增行不覆盖历史;
is_current 标记投影用的当前事实;禁止用 Job payload / line_projections 充当正式真相。 is_current 标记投影用的当前事实;禁止用 Job payload / line_projections 充当正式真相。
""" """
@@ -30,15 +30,15 @@ from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base from app.models.base import Base
class ShippingNoticeLineInventoryMatch(Base): class ShippingNoticeLineOnhandMatch(Base):
"""一条 OT 明细在某库存快照下的匹配事实(不可原地覆盖历史快照结果)。""" """一条 OT 明细在某库存快照下的匹配事实(不可原地覆盖历史快照结果)。"""
__tablename__ = 'shipping_notice_line_inventory_matches' __tablename__ = 'shipping_notice_line_onhand_matches'
__table_args__ = ( __table_args__ = (
UniqueConstraint( UniqueConstraint(
'task_id', 'task_id',
'snapshot_line_id', 'snapshot_line_id',
'inventory_snapshot_id', 'onhand_snapshot_id',
name='uq_shipping_notice_line_inv_match_task_line_snap', name='uq_shipping_notice_line_inv_match_task_line_snap',
), ),
# 同一 OT 行同一时刻仅一条当前事实(PostgreSQL partial unique)。 # 同一 OT 行同一时刻仅一条当前事实(PostgreSQL partial unique)。
@@ -51,7 +51,7 @@ class ShippingNoticeLineInventoryMatch(Base):
), ),
Index('ix_shipping_notice_line_inv_match_task', 'task_id'), Index('ix_shipping_notice_line_inv_match_task', 'task_id'),
Index('ix_shipping_notice_line_inv_match_case', 'review_case_id'), Index('ix_shipping_notice_line_inv_match_case', 'review_case_id'),
Index('ix_shipping_notice_line_inv_match_snapshot', 'inventory_snapshot_id'), Index('ix_shipping_notice_line_inv_match_snapshot', 'onhand_snapshot_id'),
CheckConstraint( CheckConstraint(
"match_result IN (" "match_result IN ("
"'matched', 'not_found', 'result_missing', 'preparing', " "'matched', 'not_found', 'result_missing', 'preparing', "
@@ -60,7 +60,7 @@ class ShippingNoticeLineInventoryMatch(Base):
name='ck_shipping_notice_line_inv_match_result', name='ck_shipping_notice_line_inv_match_result',
), ),
CheckConstraint( CheckConstraint(
"inventory_status IN (" "onhand_status IN ("
"'ready', 'preparing', 'mapping_failed', 'source_conflict', " "'ready', 'preparing', 'mapping_failed', 'source_conflict', "
"'unavailable', 'invalid_key', 'invalid'" "'unavailable', 'invalid_key', 'invalid'"
")", ")",
@@ -85,30 +85,33 @@ class ShippingNoticeLineInventoryMatch(Base):
line_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1') line_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
candidate_set_id: Mapped[Optional[int]] = mapped_column( candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), ForeignKey('shipping_onhand_candidate_sets.id', ondelete='SET NULL'),
nullable=True, nullable=True,
index=True, index=True,
) )
candidate_set_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) candidate_set_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
candidate_line_id: Mapped[Optional[int]] = mapped_column( candidate_line_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_lines.id', ondelete='SET NULL'), ForeignKey('shipping_onhand_candidate_lines.id', ondelete='SET NULL'),
nullable=True, nullable=True,
index=True, index=True,
) )
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column( onhand_snapshot_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), ForeignKey('freight_rpa_onhand_report_files.id', ondelete='SET NULL'),
nullable=True, nullable=True,
) )
match_result: Mapped[str] = mapped_column(String(32), nullable=False) match_result: Mapped[str] = mapped_column(String(32), nullable=False)
inventory_status: Mapped[str] = mapped_column(String(32), nullable=False) onhand_status: Mapped[str] = mapped_column(String(32), nullable=False)
required_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) required_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
shortage_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) shortage_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
# 料号维度总可用量(忽略预约号、行允许源内汇总);预约号不匹配行的放行兜底依据。
# 历史行与无快照行为 NULL,前端显示占位符;重新匹配后回填。
part_available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
matching_rule_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) matching_rule_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
is_current: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default='true') is_current: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default='true')
matched_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow) matched_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
@@ -143,7 +146,7 @@ class ShippingNoticeLineInventoryMatch(Base):
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True) invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True) invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
superseded_by_match_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_line_inventory_matches.id'), nullable=True) superseded_by_match_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_line_onhand_matches.id'), nullable=True)
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
mapping_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_mappings.id', ondelete='SET NULL'), nullable=True, index=True) mapping_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_mappings.id', ondelete='SET NULL'), nullable=True, index=True)
verification_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_inventory_verifications.id', ondelete='SET NULL'), nullable=True, index=True) verification_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_onhand_verifications.id', ondelete='SET NULL'), nullable=True, index=True)
@@ -1,12 +1,12 @@
""" """
models/shipping_inventory_candidates.py models/shipping_onhand_candidates.py
用途:库存候选冻结的结构化持久化——决策 C1 的正式业务真相。 用途:库存候选冻结的结构化持久化——决策 C1 的正式业务真相。
InventoryCandidateSet(候选集合)→ Source(任务级候选源)→ Line(行级候选源), ShippingOnhandCandidateSet(候选集合)→ Source(任务级候选源)→ Line(行级候选源),
同时 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze'] 保存 同时 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze'] 保存
同一时刻的完整不可变副本,用于审计与回滚。 同一时刻的完整不可变副本,用于审计与回滚。
依赖:Base、ShippingOrderTask、ShippingProcessExecution、ShippingOrderReviewCase、users、 依赖:Base、ShippingOrderTask、ShippingProcessExecution、ShippingOrderReviewCase、users、
ShippingInventoryRoutingRule(可选外键,路由规则版本)。 FreightRpaOnhandRoutingRule(可选外键,路由规则版本)。
逻辑:建单前复核阶段(review_case 绑定)或建单后正式推进阶段(task 绑定)都可冻结; 逻辑:建单前复核阶段(review_case 绑定)或建单后正式推进阶段(task 绑定)都可冻结;
input_fingerprint 相同的重复 freeze 直接返回旧 set_id(幂等); input_fingerprint 相同的重复 freeze 直接返回旧 set_id(幂等);
source_codes_json 为有序列表(路由优先级信息不能丢),禁止用 SET 类型。 source_codes_json 为有序列表(路由优先级信息不能丢),禁止用 SET 类型。
@@ -39,7 +39,7 @@ def _utc_now() -> datetime:
return datetime.utcnow() return datetime.utcnow()
class ShippingInventoryCandidateSet(Base): class ShippingOnhandCandidateSet(Base):
""" """
库存候选集合(冻结真相根)。 库存候选集合(冻结真相根)。
@@ -48,7 +48,7 @@ class ShippingInventoryCandidateSet(Base):
二者至少一个非空(CheckConstraint 强制)。 二者至少一个非空(CheckConstraint 强制)。
""" """
__tablename__ = 'shipping_inventory_candidate_sets' __tablename__ = 'shipping_onhand_candidate_sets'
__table_args__ = ( __table_args__ = (
CheckConstraint( CheckConstraint(
'task_id IS NOT NULL OR review_case_id IS NOT NULL', 'task_id IS NOT NULL OR review_case_id IS NOT NULL',
@@ -98,7 +98,7 @@ class ShippingInventoryCandidateSet(Base):
) )
superseded_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) superseded_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
superseded_by_set_id: Mapped[Optional[int]] = mapped_column( superseded_by_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), nullable=True, ForeignKey('shipping_onhand_candidate_sets.id', ondelete='SET NULL'), nullable=True,
) )
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
invalidated_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) invalidated_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
@@ -111,19 +111,19 @@ class ShippingInventoryCandidateSet(Base):
) )
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True) remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
sources: Mapped[list['ShippingInventoryCandidateSource']] = relationship( sources: Mapped[list['ShippingOnhandCandidateSource']] = relationship(
back_populates='candidate_set', back_populates='candidate_set',
cascade='all, delete-orphan', cascade='all, delete-orphan',
order_by='ShippingInventoryCandidateSource.candidate_order', order_by='ShippingOnhandCandidateSource.candidate_order',
) )
lines: Mapped[list['ShippingInventoryCandidateLine']] = relationship( lines: Mapped[list['ShippingOnhandCandidateLine']] = relationship(
back_populates='candidate_set', back_populates='candidate_set',
cascade='all, delete-orphan', cascade='all, delete-orphan',
order_by='ShippingInventoryCandidateLine.line_no', order_by='ShippingOnhandCandidateLine.line_no',
) )
class ShippingInventoryCandidateSource(Base): class ShippingOnhandCandidateSource(Base):
""" """
任务级候选库存源(Set 的子级)。 任务级候选库存源(Set 的子级)。
@@ -132,7 +132,7 @@ class ShippingInventoryCandidateSource(Base):
candidate_origin ∈ {rule, manual_override},区分是规则算出来还是人工强制指定。 candidate_origin ∈ {rule, manual_override},区分是规则算出来还是人工强制指定。
""" """
__tablename__ = 'shipping_inventory_candidate_sources' __tablename__ = 'shipping_onhand_candidate_sources'
__table_args__ = ( __table_args__ = (
UniqueConstraint( UniqueConstraint(
'candidate_set_id', 'source_code', 'candidate_set_id', 'source_code',
@@ -151,13 +151,13 @@ class ShippingInventoryCandidateSource(Base):
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
candidate_set_id: Mapped[int] = mapped_column( candidate_set_id: Mapped[int] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='CASCADE'), nullable=False, ForeignKey('shipping_onhand_candidate_sets.id', ondelete='CASCADE'), nullable=False,
) )
source_code: Mapped[str] = mapped_column(String(64), nullable=False) source_code: Mapped[str] = mapped_column(String(64), nullable=False)
candidate_order: Mapped[int] = mapped_column(Integer, nullable=False) candidate_order: Mapped[int] = mapped_column(Integer, nullable=False)
candidate_origin: Mapped[str] = mapped_column(String(32), nullable=False, default='rule') candidate_origin: Mapped[str] = mapped_column(String(32), nullable=False, default='rule')
routing_rule_id: Mapped[Optional[int]] = mapped_column( routing_rule_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_routing_rules.id', ondelete='SET NULL'), nullable=True, ForeignKey('freight_rpa_onhand_routing_rules.id', ondelete='SET NULL'), nullable=True,
) )
routing_rule_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) routing_rule_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
@@ -170,12 +170,12 @@ class ShippingInventoryCandidateSource(Base):
DateTime, default=_utc_now, onupdate=_utc_now, nullable=False, DateTime, default=_utc_now, onupdate=_utc_now, nullable=False,
) )
candidate_set: Mapped['ShippingInventoryCandidateSet'] = relationship( candidate_set: Mapped['ShippingOnhandCandidateSet'] = relationship(
back_populates='sources', back_populates='sources',
) )
class ShippingInventoryCandidateLine(Base): class ShippingOnhandCandidateLine(Base):
""" """
行级候选库存源(Set 的子级,按稳定 line_no 对齐订单行)。 行级候选库存源(Set 的子级,按稳定 line_no 对齐订单行)。
@@ -185,7 +185,7 @@ class ShippingInventoryCandidateLine(Base):
part_number + reservation_id,不能只依赖 Snapshot JSON 做高频查询。 part_number + reservation_id,不能只依赖 Snapshot JSON 做高频查询。
""" """
__tablename__ = 'shipping_inventory_candidate_lines' __tablename__ = 'shipping_onhand_candidate_lines'
__table_args__ = ( __table_args__ = (
UniqueConstraint( UniqueConstraint(
'candidate_set_id', 'line_no', 'candidate_set_id', 'line_no',
@@ -199,7 +199,7 @@ class ShippingInventoryCandidateLine(Base):
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
candidate_set_id: Mapped[int] = mapped_column( candidate_set_id: Mapped[int] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='CASCADE'), nullable=False, ForeignKey('shipping_onhand_candidate_sets.id', ondelete='CASCADE'), nullable=False,
) )
line_no: Mapped[int] = mapped_column(Integer, nullable=False) line_no: Mapped[int] = mapped_column(Integer, nullable=False)
source_line_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) source_line_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
@@ -215,6 +215,6 @@ class ShippingInventoryCandidateLine(Base):
DateTime, default=_utc_now, onupdate=_utc_now, nullable=False, DateTime, default=_utc_now, onupdate=_utc_now, nullable=False,
) )
candidate_set: Mapped['ShippingInventoryCandidateSet'] = relationship( candidate_set: Mapped['ShippingOnhandCandidateSet'] = relationship(
back_populates='lines', back_populates='lines',
) )
@@ -1,8 +1,8 @@
""" """
models/shipping_inventory_preparation.py models/shipping_onhand_preparation.py
用途:表达一次任务级库存准备轮次及逐库存源状态。 用途:表达一次任务级库存准备轮次及逐库存源状态。
依赖:ShippingOrderTask、RecoveryPlan、RPA Attempt、InventoryFile、TaskInventoryLink、Base。 依赖:ShippingOrderTask、RecoveryPlan、FreightRpaOnhandTaskAttempt、FreightRpaOnhandReportFile、ShippingTaskOnhandLink、Base。
逻辑:PreparationAttempt 聚合多个 SourceAttempt,支持有效源复用和问题源单独重拉。 逻辑:PreparationAttempt 聚合多个 SourceAttempt,支持有效源复用和问题源单独重拉。
""" """
@@ -17,10 +17,10 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base from app.models.base import Base
class ShippingInventoryPreparationAttempt(Base): class ShippingOnhandPreparationAttempt(Base):
"""一次任务级库存准备恢复轮次。""" """一次任务级库存准备恢复轮次。"""
__tablename__ = 'shipping_inventory_preparation_attempts' __tablename__ = 'shipping_onhand_preparation_attempts'
__table_args__ = ( __table_args__ = (
UniqueConstraint('task_id', 'attempt_no', name='uq_shipping_inventory_preparation_task_attempt'), UniqueConstraint('task_id', 'attempt_no', name='uq_shipping_inventory_preparation_task_attempt'),
CheckConstraint( CheckConstraint(
@@ -38,7 +38,7 @@ class ShippingInventoryPreparationAttempt(Base):
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False) attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued') status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
combination_input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) combination_input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
candidate_set_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), nullable=True) candidate_set_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_candidate_sets.id', ondelete='SET NULL'), nullable=True)
input_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) input_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
output_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) output_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
@@ -46,13 +46,13 @@ class ShippingInventoryPreparationAttempt(Base):
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
source_attempts = relationship('ShippingInventoryPreparationSourceAttempt', back_populates='preparation_attempt', cascade='all, delete-orphan') source_attempts = relationship('ShippingOnhandPreparationSourceAttempt', back_populates='preparation_attempt', cascade='all, delete-orphan')
class ShippingInventoryPreparationSourceAttempt(Base): class ShippingOnhandPreparationSourceAttempt(Base):
"""准备轮次中某个库存源的业务状态。""" """准备轮次中某个库存源的业务状态。"""
__tablename__ = 'shipping_inventory_preparation_source_attempts' __tablename__ = 'shipping_onhand_preparation_source_attempts'
__table_args__ = ( __table_args__ = (
UniqueConstraint('preparation_attempt_id', 'source_code', name='uq_shipping_inventory_preparation_source_attempt'), UniqueConstraint('preparation_attempt_id', 'source_code', name='uq_shipping_inventory_preparation_source_attempt'),
CheckConstraint( CheckConstraint(
@@ -63,17 +63,17 @@ class ShippingInventoryPreparationSourceAttempt(Base):
) )
id: Mapped[int] = mapped_column(Integer, primary_key=True) id: Mapped[int] = mapped_column(Integer, primary_key=True)
preparation_attempt_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', ondelete='CASCADE'), nullable=False) preparation_attempt_id: Mapped[int] = mapped_column(ForeignKey('shipping_onhand_preparation_attempts.id', ondelete='CASCADE'), nullable=False)
source_code: Mapped[str] = mapped_column(String(64), nullable=False) source_code: Mapped[str] = mapped_column(String(64), nullable=False)
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued') status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
skip_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True) skip_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
rpa_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_inventory_rpa_attempts.id', ondelete='SET NULL'), nullable=True) rpa_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_task_rpa_attempts.id', ondelete='SET NULL'), nullable=True)
inventory_file_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), nullable=True) onhand_file_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id', ondelete='SET NULL'), nullable=True)
task_inventory_link_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_inventory_links.id', ondelete='SET NULL'), nullable=True) task_onhand_link_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_onhand_links.id', ondelete='SET NULL'), nullable=True)
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
preparation_attempt = relationship('ShippingInventoryPreparationAttempt', back_populates='source_attempts') preparation_attempt = relationship('ShippingOnhandPreparationAttempt', back_populates='source_attempts')
@@ -204,9 +204,10 @@ class ShippingOrderDocumentProfileSuggestionDecision(Base):
__tablename__ = 'shipping_order_document_profile_suggestion_decisions' __tablename__ = 'shipping_order_document_profile_suggestion_decisions'
__table_args__ = ( __table_args__ = (
CheckConstraint("decision IN ('accepted', 'accepted_adjusted', 'rejected')", name='ck_shipping_order_document_profile_suggestion_decisions_decision'), # 约束/索引名沿用迁移的短名;PostgreSQL 标识符上限 63 字符,超长名会导致建库失败。
UniqueConstraint('profile_id', 'suggestion_id', name='uq_shipping_order_document_profile_suggestion_decisions_suggestion'), CheckConstraint("decision IN ('accepted', 'accepted_adjusted', 'rejected')", name='ck_order_profile_suggestion_decision'),
Index('ix_shipping_order_document_profile_suggestion_decisions_profile_revision', 'profile_id', 'revision_no'), UniqueConstraint('profile_id', 'suggestion_id', name='uq_order_profile_suggestion'),
Index('ix_order_profile_suggestion_revision', 'profile_id', 'revision_no'),
) )
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
@@ -238,8 +239,8 @@ class ShippingOrderDocumentProfileValidationRun(Base):
name='ck_shipping_order_document_profile_validation_runs_type', name='ck_shipping_order_document_profile_validation_runs_type',
), ),
CheckConstraint("status IN ('pending', 'running', 'passed', 'failed')", name='ck_shipping_order_document_profile_validation_runs_status'), CheckConstraint("status IN ('pending', 'running', 'passed', 'failed')", name='ck_shipping_order_document_profile_validation_runs_status'),
Index('ix_shipping_order_document_profile_validation_runs_profile_created', 'profile_id', 'created_at'), Index('ix_order_profile_validation_created', 'profile_id', 'created_at'),
Index('ix_shipping_order_document_profile_validation_runs_checksum', 'profile_id', 'definition_checksum'), Index('ix_order_profile_validation_checksum', 'profile_id', 'definition_checksum'),
) )
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
@@ -268,10 +269,10 @@ class ShippingOrderDocumentProfilePublishCheckReport(Base):
__tablename__ = 'shipping_order_document_profile_publish_check_reports' __tablename__ = 'shipping_order_document_profile_publish_check_reports'
__table_args__ = ( __table_args__ = (
CheckConstraint("status IN ('valid', 'invalidated', 'consumed')", name='ck_shipping_order_document_profile_publish_check_reports_status'), CheckConstraint("status IN ('valid', 'invalidated', 'consumed')", name='ck_sodppcr_status'),
UniqueConstraint('profile_id', 'operation_id', name='uq_shipping_order_document_profile_publish_check_reports_operation'), UniqueConstraint('profile_id', 'operation_id', name='uq_sodppcr_profile_operation'),
Index('ix_shipping_order_document_profile_publish_check_reports_profile_created', 'profile_id', 'created_at'), Index('ix_sodppcr_profile_created', 'profile_id', 'created_at'),
Index('ix_shipping_order_document_profile_publish_check_reports_report_no', 'report_no', unique=True), Index('ix_sodppcr_report_no', 'report_no', unique=True),
) )
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
@@ -32,8 +32,8 @@ class ShippingOrderReviewLineDecision(Base):
), ),
CheckConstraint( CheckConstraint(
"decision_code IN (" "decision_code IN ("
"'wait_inventory', 'use_new_inventory_file', 'change_inventory_source', " "'wait_onhand', 'use_new_inventory_file', 'change_inventory_source', "
"'fulfill_complete_line_now', 'close_unfulfillable', 'reopen', 'release_inventory_shortage'" "'fulfill_complete_line_now', 'close_unfulfillable', 'reopen', 'release_onhand_shortage'"
")", ")",
name='ck_shipping_review_line_decisions_code', name='ck_shipping_review_line_decisions_code',
), ),
+2 -2
View File
@@ -2,7 +2,7 @@
backend/app/models/shipping_order_task.py backend/app/models/shipping_order_task.py
用途:正式发货通知创建前的 OT(shipping_order_tasks)聚合根,对齐多 EML/PDF 蓝图。 用途:正式发货通知创建前的 OT(shipping_order_tasks)聚合根,对齐多 EML/PDF 蓝图。
依赖:users、agents、shipping_order_submissions/intakes/candidates、extraction_runs。 依赖:users、agents、shipping_order_submissions/intakes/candidates、extraction_runs、shipping_onhand_candidate_sets。
逻辑:由 Extraction Run 的 user_task_no 双写/回填;正式 ShippingNotice 通过 order_task_id 反向关联,本表不保存通知单指针。 逻辑:由 Extraction Run 的 user_task_no 双写/回填;正式 ShippingNotice 通过 order_task_id 反向关联,本表不保存通知单指针。
页面链路以 task_no(OT-…)为根身份;1 OT 可对应 0..N Notice。 页面链路以 task_no(OT-…)为根身份;1 OT 可对应 0..N Notice。
""" """
@@ -104,7 +104,7 @@ class ShippingOrderTask(Base):
ForeignKey('shipping_order_snapshots.id', name='fk_shipping_order_tasks_order_snapshot', use_alter=True), nullable=True, index=True, ForeignKey('shipping_order_snapshots.id', name='fk_shipping_order_tasks_order_snapshot', use_alter=True), nullable=True, index=True,
) )
active_inventory_candidate_set_id: Mapped[Optional[int]] = mapped_column( active_inventory_candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', use_alter=True), nullable=True, index=True, ForeignKey('shipping_onhand_candidate_sets.id', use_alter=True), nullable=True, index=True,
) )
step_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) step_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
active_process_execution_id: Mapped[Optional[int]] = mapped_column( active_process_execution_id: Mapped[Optional[int]] = mapped_column(
+2 -2
View File
@@ -2,7 +2,7 @@
models/shipping_process_gate.py models/shipping_process_gate.py
用途:门禁级中断恢复的持久化模型——Execution / Gate / Attempt。 用途:门禁级中断恢复的持久化模型——Execution / Gate / Attempt。
依赖:SQLAlchemy Base、ReviewCase、ShippingOrderTask、Job;状态枚举与 process_gate_contract 对齐。 依赖:SQLAlchemy Base、ReviewCase、ShippingOrderTask、Job、shipping_onhand_candidate_sets;状态枚举与 process_gate_contract 对齐。
逻辑:Execution 为业务恢复真相;Gate 保存当前门禁状态;Attempt 不可变执行尝试并承载租约。 逻辑:Execution 为业务恢复真相;Gate 保存当前门禁状态;Attempt 不可变执行尝试并承载租约。
由领域服务独占写入;Job 仅调度。 由领域服务独占写入;Job 仅调度。
co8e9f0a1b2c:已移除对 shipping_notice_workflow_* 的硬外键(无历史兼容)。 co8e9f0a1b2c:已移除对 shipping_notice_workflow_* 的硬外键(无历史兼容)。
@@ -78,7 +78,7 @@ class ShippingProcessExecution(Base):
) )
# 绑定候选版本,防止旧 callback/job 写入新候选链。 # 绑定候选版本,防止旧 callback/job 写入新候选链。
candidate_set_id: Mapped[Optional[int]] = mapped_column( candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id'), nullable=True, ForeignKey('shipping_onhand_candidate_sets.id'), nullable=True,
) )
execution_revision: Mapped[int] = mapped_column( execution_revision: Mapped[int] = mapped_column(
Integer, nullable=False, default=1, server_default='1', Integer, nullable=False, default=1, server_default='1',
@@ -1,168 +0,0 @@
"""
收料报表 RPA 的配置、运行、归档与通知投递持久化模型。
用途:为独立收料排程保存站点级配置、每站点/仓库执行单元、原样归档文件及企微投递事实。
依赖:库存站点、排程运行、SQLAlchemy Base;完整操作追溯统一写入 ShippingAuditEvent。
逻辑:模型只复用库存站点的连接资料,通过独立外键与唯一约束隔离库存快照、匹配和旧 RPA Worker 链路。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingReceiptReportConfig(Base):
"""库存站点的一对一收料报表配置;路径和条件始终独立于库存配置。"""
__tablename__ = 'shipping_receipt_report_configs'
__table_args__ = (
UniqueConstraint('inventory_source_id', name='uq_shipping_receipt_report_configs_source'),
)
id: Mapped[int] = mapped_column(primary_key=True)
inventory_source_id: Mapped[int] = mapped_column(
ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True,
)
# 收料不设独立启停:是否运行统一由库存站点 enabled 与本配置是否存在决定。
# 收料文件解析规则(purpose='movement');定死领域字段端点。空则无法解析收料文件。
parsing_profile_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True,
)
report_path_json: Mapped[dict[str, Any]] = mapped_column(
JSON, default=dict, server_default=text("'{}'"), nullable=False,
)
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(
JSON, default=list, server_default=text("'[]'"), nullable=False,
)
# 与库存同构:查询条件原样下发 Worker;空条件表示页面默认。排程一源一单元,不按仓拆分。
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
inventory_source: Mapped['ShippingInventorySource'] = relationship(back_populates='receipt_report_config')
parsing_profile: Mapped[Optional['ShippingInventoryParsingProfile']] = relationship()
class ShippingReceiptRpaUnitRun(Base):
"""一次收料执行的站点或站点-Warehouse 不可重复执行单元。
schedule_run_id 指向排程 run;调拨按需触发(重试/预检补抓)无排程,保持 NULL。
"""
__tablename__ = 'shipping_receipt_rpa_unit_runs'
__table_args__ = (
UniqueConstraint('callback_id', name='uq_shipping_receipt_rpa_unit_runs_callback'),
CheckConstraint(
"status IN ('queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled')",
name='ck_shipping_receipt_rpa_unit_runs_status',
),
Index('ix_shipping_receipt_unit_run_schedule_status', 'schedule_run_id', 'status'),
Index('ix_shipping_receipt_unit_run_source_created', 'inventory_source_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
schedule_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), nullable=True, index=True)
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
retry_of_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=True, index=True,
)
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
connector_type: Mapped[str] = mapped_column(String(32), nullable=False)
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
callback_id: Mapped[str] = mapped_column(String(128), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
config_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
trigger_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
schedule_run: Mapped[Optional['ScheduleRun']] = relationship(foreign_keys=[schedule_run_id])
inventory_source: Mapped['ShippingInventorySource'] = relationship()
retry_of: Mapped[Optional['ShippingReceiptRpaUnitRun']] = relationship(remote_side=[id])
files: Mapped[list['ShippingReceiptReportFile']] = relationship(
back_populates='unit_run', cascade='all, delete-orphan',
)
class ShippingReceiptReportFile(Base):
"""收料原样归档文件;保留文件身份和对象清理事实,不关联库存快照。"""
__tablename__ = 'shipping_receipt_report_files'
__table_args__ = (
UniqueConstraint('unit_run_id', 'sha256', name='uq_shipping_receipt_report_files_unit_sha256'),
CheckConstraint("file_size >= 0", name='ck_shipping_receipt_report_files_size'),
Index('ix_shipping_receipt_report_files_unit', 'unit_run_id'),
Index('ix_shipping_receipt_report_files_expires', 'archive_expires_at', 'archive_deleted_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
unit_run_id: Mapped[int] = mapped_column(ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=False, index=True)
storage_provider: Mapped[str] = mapped_column(String(32), nullable=False)
storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False)
storage_key: Mapped[str] = mapped_column(String(1024), nullable=False)
original_filename: Mapped[str] = mapped_column(String(255), nullable=False)
content_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
file_size: Mapped[int] = mapped_column(Integer, nullable=False)
sha256: Mapped[str] = mapped_column(String(64), nullable=False)
# 解析失败分层标记:归档文件解析失败时写入;三者全空=未失败/已清除。
parse_failed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
parse_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
parse_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
archive_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
archive_deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
archive_delete_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
unit_run: Mapped[ShippingReceiptRpaUnitRun] = relationship(back_populates='files')
deliveries: Mapped[list['ShippingReceiptNotificationDelivery']] = relationship(
back_populates='report_file', cascade='all, delete-orphan',
)
class ShippingReceiptNotificationDelivery(Base):
"""收料文件或汇总企微消息的幂等投递事实,响应仅保存脱敏摘要。"""
__tablename__ = 'shipping_receipt_notification_deliveries'
__table_args__ = (
UniqueConstraint('idempotency_key', name='uq_shipping_receipt_notification_deliveries_idempotency'),
CheckConstraint("message_type IN ('file', 'summary')", name='ck_shipping_receipt_notification_deliveries_type'),
CheckConstraint(
"status IN ('pending', 'sending', 'success', 'failed')",
name='ck_shipping_receipt_notification_deliveries_status',
),
Index('ix_shipping_receipt_delivery_file_recipient', 'report_file_id', 'recipient_user_id'),
Index('ix_shipping_receipt_delivery_unit_created', 'unit_run_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
unit_run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=True, index=True,
)
report_file_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_receipt_report_files.id'), nullable=True, index=True,
)
recipient_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
message_type: Mapped[str] = mapped_column(String(16), nullable=False)
idempotency_key: Mapped[str] = mapped_column(String(255), nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='pending', server_default='pending')
response_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
unit_run: Mapped[Optional[ShippingReceiptRpaUnitRun]] = relationship(foreign_keys=[unit_run_id])
report_file: Mapped[Optional[ShippingReceiptReportFile]] = relationship(back_populates='deliveries')
@@ -1,8 +1,8 @@
""" """
models/shipping_temporary_inventory.py models/shipping_temporary_onhand.py
用途:定义对话上传库存文件的临时会话,隔离其分析、确认与后续任务挂接过程。 用途:定义对话上传库存文件的临时会话,隔离其分析、确认与后续任务挂接过程。
依赖:Base、FileAsset、ChatSession、ShippingNotice(shipping_notices)、库存结构分析记录。 依赖:Base、FileAsset、ChatSession、ShippingNotice(shipping_notices)、freight_rpa_onhand_structure_analyses。
逻辑:Dify Tool 与工作台均先创建本会话,再由后端对受控文件资产进行结构初检; 逻辑:Dify Tool 与工作台均先创建本会话,再由后端对受控文件资产进行结构初检;
co8e9f0a1b2c 已删除 batch_id;会话仅可关联 task_id; co8e9f0a1b2c 已删除 batch_id;会话仅可关联 task_id;
本表不代表库存站点配置,也不代表生产库存快照。 本表不代表库存站点配置,也不代表生产库存快照。
@@ -19,12 +19,12 @@ from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base from app.models.base import Base
class ShippingTemporaryInventorySession(Base): class ShippingTemporaryOnhandSession(Base):
"""对话上传库存候选文件的短生命周期会话;禁止直接成为生产库存来源。""" """对话上传库存候选文件的短生命周期会话;禁止直接成为生产库存来源。"""
__tablename__ = 'shipping_temporary_inventory_sessions' __tablename__ = 'shipping_temporary_onhand_sessions'
__table_args__ = ( __table_args__ = (
UniqueConstraint('session_no', name='uq_shipping_temporary_inventory_sessions_no'), UniqueConstraint('session_no', name='uq_shipping_temporary_onhand_sessions_no'),
Index('ix_shipping_temp_inventory_user_created', 'user_id', 'created_at'), Index('ix_shipping_temp_inventory_user_created', 'user_id', 'created_at'),
Index('ix_shipping_temp_inventory_conversation_created', 'conversation_id', 'created_at'), Index('ix_shipping_temp_inventory_conversation_created', 'conversation_id', 'created_at'),
Index('ix_shipping_temp_inventory_asset', 'asset_id'), Index('ix_shipping_temp_inventory_asset', 'asset_id'),
@@ -37,7 +37,7 @@ class ShippingTemporaryInventorySession(Base):
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True) conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), nullable=False, index=True) asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), nullable=False, index=True)
analysis_id: Mapped[Optional[int]] = mapped_column( analysis_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True, index=True, ForeignKey('freight_rpa_onhand_structure_analyses.id'), nullable=True, index=True,
) )
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True, index=True) task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True, index=True)
declared_intent: Mapped[str] = mapped_column(String(32), nullable=False, default='inventory_candidate') declared_intent: Mapped[str] = mapped_column(String(32), nullable=False, default='inventory_candidate')
+12 -1
View File
@@ -2,7 +2,7 @@
backend/app/services/admin/faq_service.py backend/app/services/admin/faq_service.py
用途:全局常用问题(QuickQuestion)与热点 FAQ 候选管理。 用途:全局常用问题(QuickQuestion)与热点 FAQ 候选管理。
依赖:models、faq_kb_invalidation、hot_faq_* services。 依赖:models、faq_kb_invalidation、hot_faq_* services、faq_text_utils(模糊阈值钳制)。
逻辑:由 api/admin/quick_questions.py、faq_candidates.py 调用。 逻辑:由 api/admin/quick_questions.py、faq_candidates.py 调用。
""" """
from __future__ import annotations from __future__ import annotations
@@ -13,6 +13,7 @@ from typing import Any
from app import db from app import db
from app.core.errors import NotFoundError, ValidationError from app.core.errors import NotFoundError, ValidationError
from app.models import Agent, KbDocument, QuickQuestion from app.models import Agent, KbDocument, QuickQuestion
from app.services.faq_text_utils import clamp_fuzzy_threshold
def parse_aliases(raw_aliases) -> list[str]: def parse_aliases(raw_aliases) -> list[str]:
@@ -61,6 +62,8 @@ def serialize_quick_question(
'aliases': q.aliases if isinstance(q.aliases, list) else [], 'aliases': q.aliases if isinstance(q.aliases, list) else [],
'cache_enabled': bool(q.cache_enabled), 'cache_enabled': bool(q.cache_enabled),
'is_enabled': bool(q.is_enabled), 'is_enabled': bool(q.is_enabled),
'fuzzy_enabled': bool(getattr(q, 'fuzzy_enabled', False)),
'fuzzy_threshold': clamp_fuzzy_threshold(getattr(q, 'fuzzy_threshold', None)),
'hit_count': q.hit_count or 0, 'hit_count': q.hit_count or 0,
'agent_id': q.agent_id, 'agent_id': q.agent_id,
'agent_name': agent_name, 'agent_name': agent_name,
@@ -93,6 +96,12 @@ def apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answe
qq.cache_enabled = bool(data['cache_enabled']) qq.cache_enabled = bool(data['cache_enabled'])
if 'is_enabled' in data: if 'is_enabled' in data:
qq.is_enabled = bool(data['is_enabled']) qq.is_enabled = bool(data['is_enabled'])
if 'fuzzy_enabled' in data:
qq.fuzzy_enabled = bool(data['fuzzy_enabled'])
if 'fuzzy_threshold' in data:
qq.fuzzy_threshold = clamp_fuzzy_threshold(data['fuzzy_threshold'])
else:
qq.fuzzy_threshold = clamp_fuzzy_threshold(qq.fuzzy_threshold)
if 'expires_at' in data: if 'expires_at' in data:
qq.expires_at = parse_expires_at(data['expires_at']) qq.expires_at = parse_expires_at(data['expires_at'])
if 'retriever_resources' in data and isinstance(data.get('retriever_resources'), list): if 'retriever_resources' in data and isinstance(data.get('retriever_resources'), list):
@@ -106,6 +115,8 @@ def apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answe
if qq.cache_enabled and not str(qq.answer or '').strip(): if qq.cache_enabled and not str(qq.answer or '').strip():
raise ValidationError('启用 FAQ 缓存时必须填写标准答案') raise ValidationError('启用 FAQ 缓存时必须填写标准答案')
if qq.fuzzy_enabled and not qq.cache_enabled:
raise ValidationError('启用模糊匹配前需先启用 FAQ 缓存')
if require_answer and (not qq.title or not qq.question or not qq.agent_id): if require_answer and (not qq.title or not qq.question or not qq.agent_id):
raise ValidationError('Missing required fields') raise ValidationError('Missing required fields')
@@ -0,0 +1,105 @@
"""
services/admin/freight_rpa_form_utils.py
用途:货代 RPA 管理端表单校验共用件(JSON 对象、报表路径、查询条件、时间序列化)。
依赖:app.core.errors.ValidationError。
逻辑:freight_rpa_source_admin_service(站点/连接)与 freight_rpa_report_config_service
(入站/出站报表配置)共用;错误码沿用历史 SHIPPING.ONHAND_SOURCE_CONFIG_INVALID,
调用方可按域 remap。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app.core.errors import ValidationError
def json_object(data: dict[str, Any], field: str) -> dict[str, Any]:
"""读取并复制对象型 JSON 配置。
Args:
data: 管理 API 的请求载荷。
field: 只允许 JSON object 的字段名。
Returns:
空值规范化为空对象后的可写入配置。
Raises:
ValidationError: 字段不是 JSON object。
"""
value = data.get(field, {})
if not isinstance(value, dict):
raise ValidationError(f'{field} must be an object', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
return dict(value)
def validate_report_path(connector_type: str, report_path: dict[str, Any]) -> dict[str, str]:
"""校验 DBS 四级报表路径,防止技术选择器混入业务配置。"""
allowed = {'program_group', 'program_label', 'report_group', 'report_name'}
if set(report_path) - allowed:
raise ValidationError('report_path_json contains unsupported fields', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
normalized = {key: str(value or '').strip() for key, value in report_path.items()}
if connector_type == 'dbs':
missing = [key for key in allowed if not normalized.get(key)]
if missing:
raise ValidationError(
'DBS inventory source requires a complete report path',
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', details={'missing': sorted(missing)},
)
elif normalized:
raise ValidationError(
'Only DBS inventory sources can define report_path_json',
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID',
)
return {key: normalized[key] for key in allowed if normalized.get(key)}
def validate_query_parameters(data: dict[str, Any]) -> list[dict[str, Any]]:
"""校验 Source 的可视化查询参数列表,禁止保存 selector 等 Driver 实现细节。"""
raw = data.get('query_parameters_json', [])
if not isinstance(raw, list):
raise ValidationError('query_parameters_json must be a list', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
result: list[dict[str, Any]] = []
seen_names: set[str] = set()
allowed = {'name', 'mode', 'values', 'required', 'select_all', 'joiner'}
for index, item in enumerate(raw):
if not isinstance(item, dict) or set(item) - allowed:
raise ValidationError(
'query parameter contains unsupported fields',
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', details={'index': index},
)
name = str(item.get('name') or '').strip()
mode = str(item.get('mode') or 'single').strip().lower()
values = item.get('values', [])
required = item.get('required', False)
select_all = item.get('select_all', False)
if not name or name.lower() in seen_names or mode not in {'single', 'multi_text', 'multi_select'}:
raise ValidationError('query parameter name or mode is invalid', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
if not isinstance(values, list) or any(not isinstance(value, str) for value in values):
raise ValidationError('query parameter values must be a string list', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
if not isinstance(required, bool) or not isinstance(select_all, bool):
raise ValidationError('query parameter flags must be boolean', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
normalized_values = [value.strip() for value in values if value.strip()]
if required and not normalized_values and not select_all:
raise ValidationError('required query parameter needs values or select_all', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
if select_all and mode != 'multi_select':
raise ValidationError('select_all only applies to multi_select', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
parameter: dict[str, Any] = {
'name': name, 'mode': mode, 'values': normalized_values,
'required': required, 'select_all': select_all,
}
if mode == 'multi_text':
joiner = str(item.get('joiner') or ',').strip()
if not joiner:
raise ValidationError('multi_text query parameter needs joiner', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
parameter['joiner'] = joiner
seen_names.add(name.lower())
result.append(parameter)
return result
def iso(value: datetime | None) -> str | None:
"""datetime → ISO 字符串;None 保持 None。"""
return value.isoformat() if value else None
@@ -0,0 +1,224 @@
"""
services/admin/freight_rpa_report_config_service.py
用途:货代 RPA 入站 / 出站报表配置管理(GET/PUT),与在手配置解耦。
依赖:db、FreightRpaSource / FreightRpaInboundReportConfig / FreightRpaOutboundReportConfig /
FreightRpaParsingProfile、freight_rpa_form_utils、shipping_notice.audit_service。
逻辑:admin_freight_rpa 蓝图委托本服务;不进入来源站点启用硬门槛;
解析绑定须 published 且 purpose 匹配 inbound/outbound。
"""
from __future__ import annotations
from typing import Any
from app.core.errors import NotFoundError, ValidationError
from app.extensions import db
from app.models import (
FreightRpaInboundReportConfig,
FreightRpaOutboundReportConfig,
FreightRpaParsingProfile,
FreightRpaSource,
)
from app.services.admin.freight_rpa_form_utils import iso, json_object, validate_query_parameters, validate_report_path
from app.services.shipping_notice.audit_service import append_shipping_audit_event
def _inbound_report_config_payload(config: FreightRpaInboundReportConfig) -> dict[str, Any]:
"""序列化独立入站配置,禁止把库存路径或凭据透传至管理端。"""
profile = config.parsing_profile
return {
'id': config.id, 'source_id': config.source_id,
'report_path_json': config.report_path_json or {},
'query_parameters_json': config.query_parameters_json or [],
'parsing_profile_id': config.parsing_profile_id,
'parsing_profile': ({
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
'version': profile.version, 'status': profile.status,
} if profile else None),
'config_version': config.config_version,
'created_at': iso(config.created_at), 'updated_at': iso(config.updated_at),
}
def _outbound_report_config_payload(config: FreightRpaOutboundReportConfig) -> dict[str, Any]:
"""序列化独立出站配置,禁止把库存/入站路径或凭据透传至管理端。"""
profile = config.parsing_profile
return {
'id': config.id, 'source_id': config.source_id,
'report_path_json': config.report_path_json or {},
'query_parameters_json': config.query_parameters_json or [],
'parsing_profile_id': config.parsing_profile_id,
'parsing_profile': ({
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
'version': profile.version, 'status': profile.status,
} if profile else None),
'config_version': config.config_version,
'created_at': iso(config.created_at), 'updated_at': iso(config.updated_at),
}
def _validate_inbound_profile_binding(profile_id: Any) -> int | None:
"""校验入站配置绑定的解析规则:必须已发布且 purpose='inbound';空值表示解绑。"""
if profile_id is None or str(profile_id).strip() == '':
return None
profile = db.session.get(FreightRpaParsingProfile, int(profile_id))
if profile is None or profile.status != 'published' or profile.purpose != 'inbound':
raise ValidationError(
'Inbound parsing profile must be published with purpose inbound',
code='SHIPPING.INBOUND_PROFILE_INVALID',
)
return profile.id
def _validate_outbound_profile_binding(profile_id: Any) -> int | None:
"""校验出站配置绑定的解析规则:必须已发布且 purpose='outbound';空值表示解绑。"""
if profile_id is None or str(profile_id).strip() == '':
return None
profile = db.session.get(FreightRpaParsingProfile, int(profile_id))
if profile is None or profile.status != 'published' or profile.purpose != 'outbound':
raise ValidationError(
'Outbound parsing profile must be published with purpose outbound',
code='SHIPPING.OUTBOUND_PROFILE_INVALID',
)
return profile.id
def _validate_inbound_report_config(
source: FreightRpaSource, data: dict[str, Any],
) -> tuple[dict[str, str], list[dict[str, Any]]]:
"""规范入站配置:路径+查询条件;日期禁填。"""
try:
parameters = validate_query_parameters(data)
except ValidationError as exc:
raise ValidationError(str(exc), code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID') from exc
if any('date' in str(item.get('name') or '').strip().lower() for item in parameters):
raise ValidationError('Inbound report date filtering is not supported', code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID')
raw_path = json_object(data, 'report_path_json')
if source.connector_type == 'dbs':
try:
path = validate_report_path('dbs', raw_path)
except ValidationError as exc:
raise ValidationError(str(exc), code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID') from exc
return path, parameters
if source.connector_type == 'crane':
if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Inbound Details'):
raise ValidationError('Crane inbound report is fixed to Inbound Details', code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID')
if parameters:
raise ValidationError(
'Crane inbound report does not support query parameters',
code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID',
)
return {'report_name': 'Inbound Details'}, []
raise ValidationError('Unsupported inbound connector type', code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID')
def _validate_outbound_report_config(
source: FreightRpaSource, data: dict[str, Any],
) -> tuple[dict[str, str], list[dict[str, Any]]]:
"""规范出站配置:路径+查询条件;日期禁填;Crane 固定 Outbound Details。"""
try:
parameters = validate_query_parameters(data)
except ValidationError as exc:
raise ValidationError(str(exc), code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID') from exc
if any('date' in str(item.get('name') or '').strip().lower() for item in parameters):
raise ValidationError('Outbound report date filtering is not supported', code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID')
raw_path = json_object(data, 'report_path_json')
if source.connector_type == 'dbs':
try:
path = validate_report_path('dbs', raw_path)
except ValidationError as exc:
raise ValidationError(str(exc), code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID') from exc
return path, parameters
if source.connector_type == 'crane':
if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Outbound Details'):
raise ValidationError('Crane outbound report is fixed to Outbound Details', code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID')
if parameters:
raise ValidationError(
'Crane outbound report does not support query parameters',
code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID',
)
return {'report_name': 'Outbound Details'}, []
raise ValidationError('Unsupported outbound connector type', code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID')
def get_inbound_report_config(source_id: int) -> dict[str, Any] | None:
"""读取站点的入站配置;不存在时返回空。"""
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
config = FreightRpaInboundReportConfig.query.filter_by(source_id=source.id).one_or_none()
return _inbound_report_config_payload(config) if config else None
def save_inbound_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""保存站点内独立入站配置并追加配置前后快照审计。"""
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
path, parameters = _validate_inbound_report_config(source, data)
config = FreightRpaInboundReportConfig.query.filter_by(source_id=source.id).one_or_none()
before = _inbound_report_config_payload(config) if config else None
is_new = config is None
if config is None:
config = FreightRpaInboundReportConfig(source_id=source.id)
config.created_by = actor_id
db.session.add(config)
else:
config.config_version += 1
config.report_path_json = path
config.query_parameters_json = parameters
config.parsing_profile_id = _validate_inbound_profile_binding(data.get('parsing_profile_id'))
config.updated_by = actor_id
db.session.flush()
after = _inbound_report_config_payload(config)
append_shipping_audit_event(
event_type='shipping_inbound_report_config_saved', aggregate_type='shipping_inbound_report_config',
aggregate_id=str(source.id), actor_type='admin', actor_id=actor_id, action='create' if is_new else 'update',
result='success', before=before, after=after,
metadata={'source_id': source.id, 'connector_type': source.connector_type,
'parsing_profile_id': config.parsing_profile_id},
)
db.session.commit()
return after
def get_outbound_report_config(source_id: int) -> dict[str, Any] | None:
"""读取站点的出站配置;不存在时返回空。"""
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
config = FreightRpaOutboundReportConfig.query.filter_by(source_id=source.id).one_or_none()
return _outbound_report_config_payload(config) if config else None
def save_outbound_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""保存站点内独立出站配置并追加配置前后快照审计。"""
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
path, parameters = _validate_outbound_report_config(source, data)
config = FreightRpaOutboundReportConfig.query.filter_by(source_id=source.id).one_or_none()
before = _outbound_report_config_payload(config) if config else None
is_new = config is None
if config is None:
config = FreightRpaOutboundReportConfig(source_id=source.id)
config.created_by = actor_id
db.session.add(config)
else:
config.config_version += 1
config.report_path_json = path
config.query_parameters_json = parameters
config.parsing_profile_id = _validate_outbound_profile_binding(data.get('parsing_profile_id'))
config.updated_by = actor_id
db.session.flush()
after = _outbound_report_config_payload(config)
append_shipping_audit_event(
event_type='shipping_outbound_report_config_saved', aggregate_type='shipping_outbound_report_config',
aggregate_id=str(source.id), actor_type='admin', actor_id=actor_id, action='create' if is_new else 'update',
result='success', before=before, after=after,
metadata={'source_id': source.id, 'connector_type': source.connector_type,
'parsing_profile_id': config.parsing_profile_id},
)
db.session.commit()
return after
@@ -0,0 +1,733 @@
"""
services/admin/freight_rpa_source_admin_service.py
用途:货代 RPA 共用主数据管理——登录连接(FreightRpaProfile)与来源站点(FreightRpaSource),
含站点启用门禁、在手配置行写入、解析绑定审计。
依赖:db、FreightRpaProfile / FreightRpaSource / FreightRpaOnhandReportConfig、
freight_rpa_form_utils、credential_crypto、parsing_profile、upload_config_validation、
onhand_source_repository.validate_source_profile、audit_service。
逻辑:admin_freight_rpa 蓝图的 rpa-profiles / sources / bind-parsing / activate 委托本服务;
Profile 列表与保存回执返回用户名明文,密码与密文不返回;
在手快照/路由规则/外部映射仍见 shipping_onhand_admin_service。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app.core.errors import ConflictError, NotFoundError, ServiceUnavailableError, ValidationError
from app.extensions import db
from app.models import (
FreightRpaOnhandExternalMapping,
FreightRpaOnhandReportConfig,
FreightRpaOnhandReportFile,
FreightRpaOnhandRoutingRule,
FreightRpaParsingProfile,
FreightRpaProfile,
FreightRpaSource,
FreightRpaSourceParsingBindingAudit,
ScheduleRun,
ShippingExcelTemplate,
ShippingNoticeLine,
ShippingNoticeLineOnhandMatch,
)
from app.services.admin.freight_rpa_form_utils import (
iso as _iso,
json_object as _json_object,
validate_query_parameters as _validate_query_parameters,
validate_report_path as _validate_report_path,
)
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
from app.services.freight_rpa.common.credential_crypto import decrypt_credential, encrypt_credential
from app.services.shipping_notice.audit_service import append_shipping_audit_event
from app.services.shipping_notice.onhand_source_repository import validate_source_profile
from app.services.shipping_notice.upload_config_validation import validate_upload_config
def _text(data: dict[str, Any], field: str, *, required: bool = False) -> str | None:
"""读取并清洗字符串表单字段。"""
value = str(data.get(field) or '').strip()
if required and not value:
raise ValidationError(f'{field} is required', code='VALIDATION.INVALID_PARAM', details={'field': field})
return value or None
def _bool(data: dict[str, Any], field: str, default: bool = True) -> bool:
"""读取布尔表单字段。"""
value = data.get(field, default)
if not isinstance(value, bool):
raise ValidationError(f'{field} must be a boolean', details={'field': field})
return value
def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]:
"""校验连接级登录配置,不接收页面选择器或报表操作字段。"""
value = data.get('login_config_json', {})
if not isinstance(value, dict) or set(value) - {'auth_mode'}:
raise ValidationError('login_config_json is invalid', code='SHIPPING.RPA_PROFILE_CONFIG_INVALID')
auth_mode = str(value.get('auth_mode') or 'password').strip().lower()
if auth_mode != 'password':
raise ValidationError(
'Only password authentication is currently supported',
code='SHIPPING.RPA_PROFILE_CONFIG_INVALID',
)
return {'auth_mode': auth_mode}
def _stored_username(profile: FreightRpaProfile) -> str | None:
"""解密已保存的用户名,供管理端辨认账号。
核心逻辑:用户名是账号标识,库内仍只存密文;解密失败时返回 None,避免坏密文拖垮连接列表。
密码不走本函数。
Args:
profile: 已持久化的货代登录连接。
Returns:
str | None: 用户名明文;未配置或无法解密时为 None。
"""
if not profile.username_ciphertext:
return None
try:
return decrypt_credential(profile.username_ciphertext)
except (ServiceUnavailableError, ValidationError):
return None
def _profile_payload(profile: FreightRpaProfile) -> dict[str, Any]:
"""序列化系统连接。用户名明文回传,密码与密文不出现在响应中。"""
return {
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
'connector_type': profile.connector_type, 'login_url': profile.login_url,
'login_config_json': profile.login_config_json or {'auth_mode': 'password'}, 'enabled': bool(profile.enabled),
'upload_config_json': profile.upload_config_json,
'config_version': profile.config_version,
'username': _stored_username(profile),
'username_masked': _mask(profile.username_ciphertext),
'password_configured': bool(profile.password_ciphertext), 'credential_updated_at': _iso(profile.credential_updated_at),
'created_at': _iso(profile.created_at), 'updated_at': _iso(profile.updated_at),
}
def _mask(ciphertext: str | None) -> str | None:
"""密码等不可回显凭据只报告是否已配置。"""
return 'configured' if ciphertext else None
def list_profiles() -> list[dict[str, Any]]:
"""列出 Profile。响应含用户名明文,不含密码与密文。"""
return [_profile_payload(item) for item in FreightRpaProfile.query.order_by(FreightRpaProfile.profile_code).all()]
def delete_profile(profile_id: int) -> None:
"""删除未绑定库存源的错误连接配置,保留已使用连接的可追溯性。"""
profile = db.session.get(FreightRpaProfile, profile_id)
if profile is None:
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
if FreightRpaSource.query.filter_by(rpa_profile_id=profile.id).count():
raise ConflictError('RPA Profile is referenced by inventory sources', code='SHIPPING.RPA_PROFILE_DELETE_BLOCKED')
db.session.delete(profile)
db.session.commit()
def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
"""创建或更新货代登录连接。
核心逻辑:用户名留空,或与已存明文相同,不重写用户名密文;密码留空则保留既有密码密文。
只有用户名实际变更或提交了新密码时才刷新 credential_updated_at。
"""
profile = db.session.get(FreightRpaProfile, profile_id) if profile_id else None
if profile_id and profile is None:
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
profile = profile or FreightRpaProfile(profile_code='', display_name='', connector_type='', login_url='', login_config_json={})
# 记录“非 upload_config”的既有运行时配置快照:仅当这些字段变化才递增 config_version,
# upload_config_json 属于连接上传配置,变更不得误判库存 RPA 配置测试过期。
prev_non_upload = (
profile.profile_code, profile.display_name, profile.connector_type, profile.login_url,
dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled),
bool(profile.username_ciphertext), bool(profile.password_ciphertext),
) if profile_id else None
profile.profile_code = str(_text(data, 'profile_code', required=True)).upper()
profile.display_name = str(_text(data, 'display_name', required=True))
profile.connector_type = str(_text(data, 'connector_type', required=True)).lower()
profile.login_url = str(_text(data, 'login_url', required=True))
profile.login_config_json = _validate_profile_login_config(data)
profile.enabled = _bool(data, 'enabled', bool(profile.enabled) if profile_id else True)
if not profile.enabled and any(source.enabled for source in profile.sources):
raise ConflictError(
'Disable inventory sources before disabling their RPA Profile',
code='SHIPPING.RPA_PROFILE_DISABLE_BLOCKED',
)
username = _text(data, 'username')
password = _text(data, 'password')
# [STEP] 管理端回显的用户名会随保存再次提交;与库内明文相同则不轮换 Fernet 密文。
username_changed = False
if username is not None and _stored_username(profile) != username:
profile.username_ciphertext = encrypt_credential(username)
username_changed = True
if password is not None:
profile.password_ciphertext = encrypt_credential(password)
if username_changed or password is not None:
profile.credential_updated_at = datetime.utcnow()
# 连接级受控上传配置(受限 JSON);与库存 RPA 运行期配置隔离,不参与 config_version。
if 'upload_config_json' in data:
profile.upload_config_json = validate_upload_config(profile.connector_type, data.get('upload_config_json'))
profile.updated_by = actor_id
if profile_id:
now_non_upload = (
profile.profile_code, profile.display_name, profile.connector_type, profile.login_url,
dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled),
bool(profile.username_ciphertext), bool(profile.password_ciphertext),
)
if now_non_upload != prev_non_upload:
profile.config_version += 1
if not profile_id:
profile.created_by = actor_id
db.session.add(profile)
try:
db.session.commit()
except Exception as exc:
db.session.rollback()
raise ConflictError('RPA Profile code already exists', code='SHIPPING.RPA_PROFILE_CONFLICT') from exc
return _profile_payload(profile)
def _onhand_report_config_payload(config: FreightRpaOnhandReportConfig) -> dict[str, Any]:
"""序列化站点一对一在手报表配置行,不透传解析方案定义。"""
return {
'id': config.id,
'report_path_json': config.report_path_json or {},
'query_parameters_json': config.query_parameters_json or [],
'parsing_profile_id': config.parsing_profile_id,
}
def _source_payload(source: FreightRpaSource) -> dict[str, Any]:
"""序列化库存站点及其是否满足正式启用前置条件。
s18 起报表路径/查询条件/解析方案绑定不再随站点 DTO 平铺,
改挂在 ``onhand_report_config`` 嵌套对象(配置行不存在时为 null)。
"""
return {
'id': source.id, 'source_code': source.source_code, 'display_name': source.display_name,
'connector_type': source.connector_type, 'rpa_profile_id': source.rpa_profile_id,
'excel_template_id': source.excel_template_id,
'warehouse_resolution_mode': source.warehouse_resolution_mode, 'fixed_warehouse_id': source.fixed_warehouse_id,
'onhand_report_config': (
_onhand_report_config_payload(source.onhand_report_config)
if source.onhand_report_config is not None else None
),
'snapshot_ttl_seconds': source.snapshot_ttl_seconds, 'enabled': bool(source.enabled),
'config_version': source.config_version, 'created_at': _iso(source.created_at), 'updated_at': _iso(source.updated_at),
'activation': get_source_activation_status(source),
}
def _validate_onhand_profile_binding(profile_id: Any) -> int | None:
"""校验在手配置绑定的解析方案:必须已发布且 purpose='onhand';空值/0 表示解绑。
Args:
profile_id: 请求载荷中的 parsing_profile_id;None/空串/0 视为解绑(与旧站点保存语义一致)。
Returns:
int | None: 规整后的方案 id 或 None。
Raises:
ValidationError: 方案 id 非法、不存在、未发布或用途不是 onhand
(fail-closed,防误绑入站/出站方案,统一 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED)。
"""
raw = str(profile_id).strip() if profile_id is not None else ''
if raw in {'', '0'}:
return None
if not raw.isdigit():
raise ValidationError(
'Onhand parsing profile must be published with purpose onhand',
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
)
profile = db.session.get(FreightRpaParsingProfile, int(raw))
if profile is None or profile.status != 'published' or profile.purpose != 'onhand':
raise ValidationError(
'Onhand parsing profile must be published with purpose onhand',
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
)
return profile.id
def _apply_onhand_report_config(
source: FreightRpaSource, data: dict[str, Any], *, actor_id: int | None,
) -> FreightRpaOnhandReportConfig:
"""把手报表三字段写入手配置行(无则插入),不触碰站点行已删除的三列。
核心逻辑:先全量校验路径对象/查询条件/解析绑定,失败时不留脏会话;
校验通过后无配置行则插入(created_by=actor),有则更新并递增 config_version。
报表路径按原样 JSON object 存取(Driver selector 等实现细节归 Worker/模板域,
管理端 DBS 四段路径由前端 normaliseInventoryReportPath 规整后提交)。
Args:
source: 已存在的库存站点(新配置行经 inventory_source 关系级联挂载)。
data: 含 report_path_json / query_parameters_json / parsing_profile_id 的载荷。
actor_id: 当前管理员主键,仅写审计字段。
Returns:
FreightRpaOnhandReportConfig: 已写入(尚未提交)的配置行。
"""
# [STEP 1] 全量校验先行,任何失败都不会留下半写的配置行。
report_path = _json_object(data, 'report_path_json')
# DBS 四段路径按原样 JSON object 存取(前端 normaliseInventoryReportPath 规整);
# 非 DBS(Crane)站点不得误填 DBS 报表路径(fail-closed,与列搬迁前契约一致)。
if source.connector_type != 'dbs' and report_path:
raise ValidationError(
'Only DBS inventory sources can define report_path_json',
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID',
)
parameters = _validate_query_parameters(data)
parsing_profile_id = _validate_onhand_profile_binding(data.get('parsing_profile_id'))
# [STEP 2] 校验通过后写配置行:无则插入,有则更新并递增 config_version。
config = source.onhand_report_config
if config is None:
config = FreightRpaOnhandReportConfig(source=source)
config.created_by = actor_id
db.session.add(config)
else:
config.config_version += 1
config.report_path_json = report_path
config.query_parameters_json = parameters
config.parsing_profile_id = parsing_profile_id
config.updated_by = actor_id
return config
def save_onhand_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""保存站点一对一在手报表配置:没有配置行时插入,有则更新并递增该行 config_version。
核心逻辑:委托 _apply_onhand_report_config 校验并写行;启用中的站点借保存拆掉
启用门禁(缺解析绑定/模板)时由 assert_onhand_source_can_enable fail-closed 拒绝。
Args:
source_id: 库存站点主键,必须已存在。
data: 含 report_path_json / query_parameters_json / parsing_profile_id 的载荷。
actor_id: 当前管理员主键,仅写审计字段。
Returns:
dict[str, Any]: 配置行 DTO(id / report_path_json / query_parameters_json / parsing_profile_id)。
Raises:
NotFoundError: 站点不存在。
ValidationError: 解析方案不存在/未发布/purpose 不是 onhand,或启用中站点门禁被拆。
"""
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
config = _apply_onhand_report_config(source, data, actor_id=actor_id)
# 启用中的站点不得借配置保存解绑解析方案(excel_template 缺失同样拒绝)。
assert_onhand_source_can_enable(source)
db.session.commit()
return _onhand_report_config_payload(config)
def assert_onhand_source_can_enable(source: FreightRpaSource) -> None:
"""启用中的库存站点必须已有在手配置行(含解析方案绑定)与发货模板。
【AI 触发时机】:保存站点(save_source 载荷含 enabled=true 或保留启用态)、
保存在手配置(save_onhand_report_config 拆绑定前)时调用;
PostgreSQL CHECK 不能跨表,解析方案存在性只能由服务层执行。
Args:
source: 站点对象(可为未提交的暂态行,配置行经 onhand_report_config 关系读取)。
Returns:
None: 门禁通过(站点未启用时恒通过)。
Raises:
ValidationError: enabled 为真但缺配置行、配置行未绑解析方案或站点未绑模板,
统一 code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED'。
"""
if not source.enabled:
return
config = source.onhand_report_config
if config is None or not config.parsing_profile_id or not source.excel_template_id:
raise ValidationError(
'Enabled inventory source requires onhand report config, parsing profile and excel template',
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
)
def _binding_snapshot(source: FreightRpaSource) -> dict[str, Any]:
"""冻结解析绑定变更的最小站点上下文,避免审计依赖后续可变主数据。
s18 起解析绑定挂在 onhand_report_config 配置行上,快照同样取自配置行。
"""
config = source.onhand_report_config
return {
'source_id': source.id,
'source_code': source.source_code,
'enabled': bool(source.enabled),
'parsing_profile_id': config.parsing_profile_id if config is not None else None,
'parsing_profile_checksum': (
config.parsing_profile.checksum
if config is not None and config.parsing_profile is not None else None
),
'excel_template_id': source.excel_template_id,
'config_version': source.config_version,
}
def _validate_source_parsing_binding(source: FreightRpaSource, profile: FreightRpaParsingProfile) -> None:
"""校验站点可直接采用的已发布方案与当前发货模板字段契约;启用中的站点同样允许更换解析绑定。"""
if profile.status != 'published':
raise ValidationError('Published parsing profile is required', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
mapping = definition.get('field_mapping') if isinstance(definition.get('field_mapping'), dict) else {}
if not mapping:
raise ValidationError('Published parsing profile is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
template = source.excel_template
if template is None:
return
if template.status != 'published':
raise ValidationError('Published excel template is required', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED')
template_definition = template.definition_json if isinstance(template.definition_json, dict) else {}
template_mappings = template_definition.get('mappings') if isinstance(template_definition.get('mappings'), list) else []
missing_fields = sorted({
str(item.get('source_key') or '')
for item in template_mappings
if isinstance(item, dict)
and item.get('source_kind') == 'inventory_field'
and str(item.get('source_key') or '') not in mapping
})
if missing_fields:
raise ValidationError(
'Parsing profile does not provide all inventory fields required by the excel template',
code='SHIPPING.ONHAND_SOURCE_BINDING_TEMPLATE_INVALID', details={'inventory_field_ids': missing_fields},
)
def bind_source_parsing_profile(
source_ids: list[int], profile_id: int, *, actor_id: int | None, reason: str | None = None, operation: str,
) -> list[dict[str, Any]]:
"""为一个或多个库存站点原子绑定已发布解析方案并写入追加式审计(含已启用站点)。
Args:
source_ids: 待绑定的库存站点主键,不能为空且不得重复。
profile_id: 必须为已发布解析方案主键。
actor_id: 当前管理员主键,仅写入审计。
reason: 可选的补充说明;未填写时由系统记录本次直接或批量绑定动作。
operation: 审计操作类型,仅允许 ``direct`` 或 ``bulk``。
Returns:
list[dict[str, Any]]: 已更新站点的管理端 DTO。
Raises:
ValidationError: 任一站点、方案或模板字段契约不合法;批量请求不会部分写入。
ConflictError: 试图变更已启用站点的正式解析方案。
"""
try:
normalized_ids = sorted({int(item) for item in source_ids if int(item) > 0})
except (TypeError, ValueError) as exc:
raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM') from exc
if not normalized_ids or len(normalized_ids) != len(source_ids):
raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM')
if operation not in {'direct', 'bulk'}:
raise ValidationError('Binding operation is invalid', code='VALIDATION.INVALID_PARAM')
normalized_reason = str(reason or '').strip()
if len(normalized_reason) > 500:
raise ValidationError('Binding note must not exceed 500 characters', code='VALIDATION.INVALID_PARAM')
# 审计必须保留可读动作,但不应把技术审计字段变成管理员的额外填写负担。
if not normalized_reason:
normalized_reason = '管理员直接绑定已发布解析方案' if operation == 'direct' else '管理员批量绑定已发布解析方案'
try:
normalized_profile_id = int(profile_id)
except (TypeError, ValueError) as exc:
raise ValidationError('parsing_profile_id is required', code='VALIDATION.INVALID_PARAM') from exc
profile = db.session.get(FreightRpaParsingProfile, normalized_profile_id)
if profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
sources = [db.session.get(FreightRpaSource, source_id) for source_id in normalized_ids]
if any(source is None for source in sources):
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
typed_sources = [source for source in sources if source is not None]
# [STEP 1] 全量预检后才变更,避免多站点操作出现部分绑定。
for source in typed_sources:
_validate_source_parsing_binding(source, profile)
for source in typed_sources:
before = _binding_snapshot(source)
# s18 起解析绑定写 onhand_report_config 配置行(无则插入),站点行不再承载该外键。
config = source.onhand_report_config
previous_profile_id = config.parsing_profile_id if config is not None else None
if config is None:
config = FreightRpaOnhandReportConfig(source=source)
config.created_by = actor_id
db.session.add(config)
else:
config.config_version += 1
config.parsing_profile_id = profile.id
config.updated_by = actor_id
source.updated_by = actor_id
# 站点 config_version 仍随绑定递增:配置测试锁定版本与运行期失效判断依赖它。
source.config_version += 1
db.session.flush()
db.session.add(FreightRpaSourceParsingBindingAudit(
source_id=source.id, previous_parsing_profile_id=previous_profile_id,
parsing_profile_id=config.parsing_profile_id, operation=operation, reason=normalized_reason, actor_id=actor_id,
source_config_version_before=before['config_version'], source_config_version_after=source.config_version,
before_snapshot_json=before, after_snapshot_json=_binding_snapshot(source),
))
db.session.commit()
return [_source_payload(source) for source in typed_sources]
def get_source_parsing_binding_audits(source_id: int) -> list[dict[str, Any]]:
"""读取库存站点解析绑定审计,仅返回配置快照和操作者标识。"""
if db.session.get(FreightRpaSource, source_id) is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
rows = FreightRpaSourceParsingBindingAudit.query.filter_by(
source_id=source_id,
).order_by(FreightRpaSourceParsingBindingAudit.id.desc()).all()
return [{
'id': row.id, 'operation': row.operation, 'reason': row.reason, 'actor_id': row.actor_id,
'previous_parsing_profile_id': row.previous_parsing_profile_id, 'parsing_profile_id': row.parsing_profile_id,
'source_config_version_before': row.source_config_version_before,
'source_config_version_after': row.source_config_version_after,
'before': row.before_snapshot_json, 'after': row.after_snapshot_json,
'created_at': row.created_at.isoformat() if row.created_at else None,
} for row in rows]
def list_sources() -> list[dict[str, Any]]:
"""列出库存源及其稳定业务配置。"""
return [_source_payload(item) for item in FreightRpaSource.query.order_by(FreightRpaSource.source_code).all()]
def delete_source(source_id: int) -> None:
"""删除未参与映射、快照或规则的错误库存源,避免破坏历史路由身份。"""
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
source_code = str(source.source_code or '').strip().upper()
has_mapping = FreightRpaOnhandExternalMapping.query.filter_by(source_id=source.id).count() > 0
has_snapshot = FreightRpaOnhandReportFile.query.filter_by(source_code=source_code).count() > 0
has_rule = any(
source_code in {str(code).strip().upper() for code in candidates}
for rule in FreightRpaOnhandRoutingRule.query.all()
for candidates in [(rule.action_payload_json or {}).get('source_codes', [])]
if isinstance(candidates, list)
)
has_task = db.session.query(ShippingNoticeLine.id).filter(
ShippingNoticeLine.inventory_source_code == source_code,
).first() is not None or db.session.query(ShippingNoticeLineOnhandMatch.id).filter(
ShippingNoticeLineOnhandMatch.source_code == source_code,
).first() is not None
has_export_run = any(
source_code in {str(code).strip().upper() for code in source_codes}
for run in ScheduleRun.query.all()
for source_codes in [(run.api_request_json or {}).get('source_codes', [])]
if isinstance(source_codes, list)
)
if has_mapping or has_snapshot or has_rule or has_task or has_export_run:
raise ConflictError('Inventory Source has operational references', code='SHIPPING.ONHAND_SOURCE_DELETE_BLOCKED')
db.session.delete(source)
db.session.commit()
def _template_validation_missing(source: FreightRpaSource) -> list[str]:
"""确认发货模板引用的库存字段均由当前解析方案提供,避免启用后才发现字段断链。"""
template = source.excel_template
# s18 起解析方案绑定取自 onhand_report_config 配置行。
config = source.onhand_report_config
profile = config.parsing_profile if config is not None else None
if template is None or profile is None:
return []
definition = template.definition_json if isinstance(template.definition_json, dict) else {}
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
profile_definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
inventory_fields = {str(field_id) for field_id in (profile_definition.get('field_mapping') or {}).keys()}
invalid = any(
isinstance(item, dict)
and item.get('source_kind') == 'inventory_field'
and str(item.get('source_key') or '') not in inventory_fields
for item in mappings
)
return ['template_validation'] if not mappings or invalid else []
def _activation_check(
code: str, *, passed: bool, action: str, evidence: dict[str, Any], status: str | None = None,
blocking: bool | None = None,
) -> dict[str, Any]:
"""构造单项启用门禁结果,确保管理端只展示服务端已判定的业务事实。"""
return {
'code': code,
'status': status or ('passed' if passed else 'pending'),
'blocking': not passed if blocking is None else blocking,
'action': action,
'evidence': evidence,
}
def _source_activation_checks(source: FreightRpaSource) -> list[dict[str, Any]]:
"""构建库存站点启用硬门槛:可用连接、已发布解析方案、已绑定已发布发货模板及字段契约。
测试导出不再参与启用门禁;启停由管理员显式开关完成。
"""
profile_ready = source.rpa_profile is not None and bool(source.rpa_profile.enabled)
# s18 起解析方案绑定取自 onhand_report_config 配置行;配置行缺失即解析门禁未就绪。
config = source.onhand_report_config
parsing_profile = config.parsing_profile if config is not None else None
parsing_ready = parsing_profile is not None and parsing_profile.status == 'published'
template_ready = source.excel_template is not None and source.excel_template.status == 'published'
template_invalid = bool(_template_validation_missing(source)) if template_ready and parsing_ready else False
return [
_activation_check(
'rpa_profile', passed=profile_ready, action='configure_connection',
evidence={'profile_id': source.rpa_profile_id, 'enabled': profile_ready},
),
_activation_check(
'parsing_profile', passed=parsing_ready, action='configure_parsing_profile',
evidence={'profile_id': parsing_profile.id if parsing_profile is not None else None, 'published': parsing_ready},
),
_activation_check(
'excel_template', passed=template_ready, action='configure_excel_template',
evidence={'template_id': source.excel_template_id, 'published': template_ready},
),
_activation_check(
'template_validation', passed=not template_invalid,
action='configure_excel_template', evidence={}, blocking=template_invalid,
),
]
def get_source_activation_status(source: FreightRpaSource) -> dict[str, Any]:
"""返回库存站点启用硬门槛的结构化结果。
Args:
source: 已持久化的库存站点,关联配置由当前数据库事务提供。
Returns:
dict[str, Any]: ``checks`` 为前端唯一的检查真相;``ready`` 为启用结论;
``missing_requirements`` 是由 checks 派生的紧凑摘要,供现有调用方读取。
"""
checks = _source_activation_checks(source)
missing = [item['code'] for item in checks if item['blocking']]
return {
'ready': not missing,
'checks': checks,
'missing_requirements': missing,
}
def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""启用已满足硬门槛的库存站点;未通过任一前置条件时保持停用。"""
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
status = get_source_activation_status(source)
if not status['ready']:
raise ConflictError(
'Inventory Source is not ready for activation',
code='SHIPPING.ONHAND_SOURCE_ACTIVATION_BLOCKED',
details=status,
)
source.enabled = True
source.updated_by = actor_id
db.session.commit()
return _source_payload(source)
def deactivate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""停用库存站点,保留其解析方案和历史运行审计。"""
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
source.enabled = False
source.updated_by = actor_id
db.session.commit()
return _source_payload(source)
def save_source(
data: dict[str, Any], *, actor_id: int | None, source_id: int | None = None,
allow_enable_transition: bool = True,
) -> dict[str, Any]:
"""保存库存站点基础配置;管理 API 不允许通过普通保存直接启用站点。
s18 起站点头部仅编辑 source_code / display_name / connector_type / rpa_profile_id /
excel_template_id / 仓库模式 / snapshot_ttl_seconds;报表路径、查询条件与解析方案
绑定经载荷内嵌的 ``onhand_report_config`` 对象写入配置行(与独立保存同一校验路径)。
"""
source = db.session.get(FreightRpaSource, source_id) if source_id else None
if source_id and source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
try:
profile_id = int(data.get('rpa_profile_id'))
except (TypeError, ValueError) as exc:
raise ValidationError('rpa_profile_id is required') from exc
profile = db.session.get(FreightRpaProfile, profile_id)
if profile is None:
raise ValidationError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
requested_enabled = _bool(data, 'enabled', bool(source.enabled) if source_id else False)
if not allow_enable_transition:
# 普通保存不承担状态切换:首次一律停用,已启用站点保留当前状态。
enabled = bool(source.enabled) if source is not None else False
else:
enabled = requested_enabled
if enabled and not profile.enabled:
raise ValidationError(
'Enabled Inventory Source requires an enabled RPA Profile',
code='SHIPPING.RPA_PROFILE_DISABLED',
)
excel_template_id = data.get('excel_template_id')
excel_template = db.session.get(ShippingExcelTemplate, int(excel_template_id)) if str(excel_template_id or '').isdigit() else None
if excel_template_id not in (None, '', 0, '0') and (excel_template is None or excel_template.status != 'published'):
raise ValidationError('excel_template_id must reference a published template', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED')
is_new = source is None
source = source or FreightRpaSource(
source_code='', display_name='', connector_type='', warehouse_resolution_mode='fixed',
)
source.source_code = str(_text(data, 'source_code', required=True)).upper()
source.display_name = str(_text(data, 'display_name', required=True))
source.connector_type = str(_text(data, 'connector_type', required=True)).lower()
source.rpa_profile = profile
source.excel_template = excel_template
source.warehouse_resolution_mode = str(_text(data, 'warehouse_resolution_mode', required=True)).lower()
source.fixed_warehouse_id = _text(data, 'fixed_warehouse_id')
source.snapshot_ttl_seconds = int(data.get('snapshot_ttl_seconds') or 86400)
source.enabled = enabled
source.updated_by = actor_id
if source_id:
source.config_version += 1
if is_new:
source.created_by = actor_id
db.session.add(source)
# [STEP 1] 启用门禁先行:缺模板在写库前给出可解释错误,避免撞站点行 CHECK 的 IntegrityError
# (模板缺失复用 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED,不新造码)。
if enabled and excel_template is None:
raise ValidationError(
'published excel_template_id is required',
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
)
try:
# flush 让 excel_template_id / 新行主键先行落位,后续门禁读取规整后的外键。
db.session.flush()
except Exception as exc:
db.session.rollback()
raise ValidationError('Invalid Inventory Source configuration', code='SHIPPING.ONHAND_SOURCE_INVALID') from exc
# [STEP 2] 载荷内嵌 onhand_report_config 时与独立保存走同一校验/写行路径(无则插入配置行)。
config_data = data.get('onhand_report_config')
if isinstance(config_data, dict):
_apply_onhand_report_config(source, config_data, actor_id=actor_id)
# [STEP 3] 启用门禁复核(缺配置行/解析绑定/模板统一 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED)。
if enabled:
assert_onhand_source_can_enable(source)
validate_source_profile(source, profile)
try:
db.session.commit()
except Exception as exc:
db.session.rollback()
raise ValidationError('Invalid Inventory Source configuration', code='SHIPPING.ONHAND_SOURCE_INVALID') from exc
return _source_payload(source)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,391 @@
"""
services/admin/shipping_onhand_admin_service.py
用途:在手域管理——库存快照只读、导出运行记录、路由规则、外部仓库映射。
依赖:db、FreightRpaOnhandReportFile / FreightRpaOnhandRoutingRule /
FreightRpaOnhandExternalMapping、order_schema、routing_operators、ALLOWED_ACTIONS。
逻辑:admin_freight_rpa 的 snapshots / export-records / rules / external-mappings 委托本服务;
登录连接与来源站点见 freight_rpa_source_admin_service。
"""
from __future__ import annotations
from typing import Any
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.extensions import db
from app.models import (
FreightRpaOnhandExternalMapping,
FreightRpaOnhandReportFile,
FreightRpaOnhandRoutingRule,
FreightRpaOnhandRoutingRuleCondition,
FreightRpaOnhandRoutingRuleVersion,
FreightRpaSource,
ScheduleRun,
ScheduleTask,
ShippingOrderField,
)
from app.services.admin.freight_rpa_form_utils import iso as _iso
from app.services.shipping_notice.onhand_routing_engine import ALLOWED_ACTIONS
from app.services.shipping_notice.order_schema import service as order_schema_service
from app.services.shipping_notice.routing_operators import ALLOWED_OPERATORS
def _text(data: dict[str, Any], field: str, *, required: bool = False) -> str | None:
"""读取并清洗字符串表单字段。"""
value = str(data.get(field) or '').strip()
if required and not value:
raise ValidationError(f'{field} is required', code='VALIDATION.INVALID_PARAM', details={'field': field})
return value or None
def _bool(data: dict[str, Any], field: str, default: bool = True) -> bool:
"""读取布尔表单字段。"""
value = data.get(field, default)
if not isinstance(value, bool):
raise ValidationError(f'{field} must be a boolean', details={'field': field})
return value
def _snapshot_payload(snapshot: FreightRpaOnhandReportFile) -> dict[str, Any]:
"""投影库存快照的管理端只读行,不暴露存储路径或库存明细。"""
return {
'id': snapshot.id, 'inventory_file_no': snapshot.onhand_file_no,
'source_code': snapshot.source_code, 'warehouse_id': snapshot.warehouse_id,
'snapshot_status': snapshot.snapshot_status, 'identity_status': snapshot.identity_status,
'line_count': snapshot.line_count, 'share_mode': snapshot.share_mode,
'exported_at': _iso(snapshot.exported_at), 'expires_at': _iso(snapshot.expires_at),
'rpa_run_no': snapshot.rpa_run_no, 'schedule_run_id': snapshot.schedule_run_id,
'source_file_name': snapshot.source_file_name, 'created_at': _iso(snapshot.created_at),
'download_available': bool(snapshot.storage_path and not str(snapshot.storage_path).startswith('failed://')),
'error_message': (snapshot.schema_preview_json or {}).get('error') if snapshot.snapshot_status == 'failed' else None,
}
def list_snapshots(*, limit: int = 100) -> list[dict[str, Any]]:
"""列出最新库存快照,供管理员确认当前可用的库存文件。"""
rows = FreightRpaOnhandReportFile.query.order_by(
FreightRpaOnhandReportFile.exported_at.desc(), FreightRpaOnhandReportFile.id.desc(),
).limit(max(1, min(limit, 200))).all()
return [_snapshot_payload(row) for row in rows]
def get_snapshot_download(snapshot_id: int) -> tuple[str, str]:
"""返回管理员可下载的库存快照路径及安全文件名。
Args:
snapshot_id: 库存快照主键。
Returns:
本地托管文件绝对路径和面向下载的文件名。
Raises:
NotFoundError: 快照不存在或托管文件已不存在。
"""
from pathlib import Path
snapshot = db.session.get(FreightRpaOnhandReportFile, snapshot_id)
if snapshot is None:
raise NotFoundError('Inventory snapshot not found', code='SHIPPING.ONHAND_SNAPSHOT_NOT_FOUND')
path = Path(str(snapshot.storage_path or '')).resolve()
if not str(snapshot.storage_path or '') or str(snapshot.storage_path).startswith('failed://') or not path.is_file():
raise NotFoundError('Inventory snapshot file not found', code='SHIPPING.ONHAND_SNAPSHOT_FILE_NOT_FOUND')
filename = str(snapshot.source_file_name or f'{snapshot.onhand_file_no}{path.suffix or ".xlsx"}')
return str(path), filename
def list_export_records(*, limit: int = 100) -> list[dict[str, Any]]:
"""列出 RPA 导出记录,合并已归档文件与排程失败/跳过结果。"""
file_rows = FreightRpaOnhandReportFile.query.filter(
FreightRpaOnhandReportFile.rpa_run_no.is_not(None),
).order_by(
FreightRpaOnhandReportFile.exported_at.desc(), FreightRpaOnhandReportFile.id.desc(),
).limit(max(1, min(limit, 200))).all()
records = [_snapshot_payload(row) for row in file_rows]
known_identities = {
(str(item.get('rpa_run_no') or ''), str(item.get('source_code') or ''), str(item.get('warehouse_id') or ''))
for item in records
}
# 失败或跳过的 RPA 执行不会生成库存文件,必须从 ScheduleRun 补齐审计记录。
schedule_runs = ScheduleRun.query.join(ScheduleTask).filter(
ScheduleTask.platform_api_path == 'freight-rpa-onhand',
).order_by(ScheduleRun.created_at.desc()).limit(max(1, min(limit, 200))).all()
for run in schedule_runs:
response = run.api_response_json if isinstance(run.api_response_json, dict) else {}
request_data = run.api_request_json if isinstance(run.api_request_json, dict) else {}
run_no = str(response.get('run_no') or request_data.get('run_no') or run.run_no or '').strip()
items: list[tuple[str, dict[str, Any]]] = []
for status, key in (('skipped', 'skipped'), ('failed', 'failed')):
for item in response.get(key) if isinstance(response.get(key), list) else []:
if isinstance(item, dict):
items.append((status, item))
if not items and run.status in {'queued', 'running'}:
pending = (run.response_summary_json or {}).get('pending_details', [])
for item in pending if isinstance(pending, list) else []:
if isinstance(item, dict):
items.append(('awaiting_rpa', item))
if not items and run.status in {'failed', 'partial_failed'}:
for source_code in request_data.get('source_codes') if isinstance(request_data.get('source_codes'), list) else []:
items.append(('failed', {'source_code': source_code, 'error_message': run.error_message}))
for status, item in items:
source_code = str(item.get('source_code') or '').strip()
warehouse_id = str(item.get('warehouse_id') or '').strip()
identity = (run_no, source_code, warehouse_id)
if identity in known_identities:
continue
known_identities.add(identity)
records.append({
'id': f'schedule-{run.id}-{status}-{source_code}-{warehouse_id}',
'inventory_file_no': None,
'source_code': source_code or None,
'warehouse_id': warehouse_id or None,
'snapshot_status': status,
'export_status': status,
'identity_status': None,
'line_count': 0,
'share_mode': None,
'exported_at': _iso(run.finished_at or run.created_at),
'expires_at': None,
'rpa_run_no': run_no or None,
'schedule_run_id': run.id,
'source_file_name': None,
'created_at': _iso(run.created_at),
'error_message': str(item.get('error_message') or item.get('error') or run.error_message or '')[:500] or None,
})
records.sort(key=lambda item: str(item.get('exported_at') or item.get('created_at') or ''), reverse=True)
return records[:max(1, min(limit, 200))]
def _rule_payload(rule: FreightRpaOnhandRoutingRule) -> dict[str, Any]:
return {
'id': rule.id, 'rule_code': rule.rule_code, 'rule_name': rule.rule_name, 'scope': rule.scope,
'priority': rule.priority, 'match_mode': rule.match_mode, 'status': rule.status,
'action_type': rule.action_type, 'action_payload_json': rule.action_payload_json or {}, 'version': rule.version,
'conditions': [{'source_kind': c.source_kind, 'order_field_id': c.order_field_id,
'operator': c.operator, 'expected_value_json': c.expected_value_json,
'condition_group': c.condition_group, 'sequence': c.sequence} for c in rule.conditions],
}
def _validate_rule_condition_expected(operator: str, value: Any) -> Any:
"""按匹配符号规范化期望值,避免自由 JSON 在运行期才暴露配置错误。"""
if operator in {'is_empty', 'is_not_empty'}:
return None
if operator in {'in', 'not_in'}:
if not isinstance(value, list):
raise ValidationError('List operator requires a string list', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
normalized = [str(item).strip() for item in value if str(item).strip()]
if not normalized:
raise ValidationError('List operator requires at least one value', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
return normalized
if operator in {'numeric_length', 'string_length'}:
try:
length = int(value)
except (TypeError, ValueError) as exc:
raise ValidationError('Length operator requires an integer', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID') from exc
if length < 0:
raise ValidationError('Length must not be negative', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
return length
if not isinstance(value, str) or not value.strip():
raise ValidationError('Routing condition requires an expected value', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
return value.strip()
def list_rules() -> list[dict[str, Any]]:
"""列出规则及条件,用于草稿编辑和已发布规则查看。"""
return [_rule_payload(item) for item in FreightRpaOnhandRoutingRule.query.order_by(FreightRpaOnhandRoutingRule.priority.desc()).all()]
def delete_draft_rule(rule_id: int) -> None:
"""删除从未发布的草稿规则;发布过的规则必须归档以保留审计定义。"""
rule = db.session.get(FreightRpaOnhandRoutingRule, rule_id)
if rule is None:
raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND')
if rule.status != 'draft':
raise ConflictError('Only draft routing rules can be deleted', code='SHIPPING.ONHAND_RULE_DELETE_BLOCKED')
db.session.delete(rule)
db.session.commit()
def retire_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""归档已发布规则,使其不再参与新路由,同时保留已发布版本。"""
rule = db.session.get(FreightRpaOnhandRoutingRule, rule_id)
if rule is None:
raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND')
if rule.status != 'published':
raise ConflictError('Only published routing rules can be retired', code='SHIPPING.ONHAND_RULE_RETIRE_INVALID')
rule.status = 'retired'
rule.updated_by = actor_id
db.session.commit()
return _rule_payload(rule)
def save_rule(data: dict[str, Any], *, actor_id: int | None, rule_id: int | None = None) -> dict[str, Any]:
"""保存草稿规则;发布规则必须以新版本创建,避免篡改历史定义。"""
if rule_id:
current = db.session.get(FreightRpaOnhandRoutingRule, rule_id)
if current is None:
raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND')
if current.status != 'draft':
raise ConflictError('Only draft routing rules can be updated', code='SHIPPING.ONHAND_RULE_IMMUTABLE')
rule = current if rule_id else FreightRpaOnhandRoutingRule(
rule_code='', rule_name='', scope='', action_type='', action_payload_json={}
)
rule.rule_code = str(_text(data, 'rule_code', required=True)).upper()
rule.rule_name = str(_text(data, 'rule_name', required=True))
rule.scope = str(_text(data, 'scope', required=True)).lower()
rule.priority = int(data.get('priority') or 0)
rule.match_mode = str(data.get('match_mode') or 'all').lower()
rule.status = 'draft'
rule.action_type = str(_text(data, 'action_type', required=True)).lower()
rule.action_payload_json = data.get('action_payload_json') if isinstance(data.get('action_payload_json'), dict) else {}
rule.version = int(data.get('version') or 1)
if not rule_id:
rule.created_by = actor_id
rule.updated_by = actor_id
if rule.action_type not in ALLOWED_ACTIONS or rule.scope not in {'task', 'line'} or rule.match_mode not in {'all', 'any'}:
raise ValidationError('Invalid routing rule metadata', code='SHIPPING.ONHAND_RULE_INVALID')
conditions = data.get('conditions')
if not isinstance(conditions, list) or not conditions:
raise ValidationError('Routing rule requires conditions', code='SHIPPING.ONHAND_RULE_CONDITIONS_REQUIRED')
# 草稿更新在同一版本内替换条件;发布后不可原地修改。
if rule_id:
db.session.query(FreightRpaOnhandRoutingRuleCondition).filter_by(rule_id=rule.id).delete(
synchronize_session=False
)
db.session.flush()
db.session.expire(rule, ['conditions'])
for index, item in enumerate(conditions, start=1):
if not isinstance(item, dict) or item.get('operator') not in ALLOWED_OPERATORS:
raise ValidationError('Routing rule condition is not allowed', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
source_kind = str(item.get('source_kind') or 'order_field')
order_field_id = str(item.get('order_field_id') or '') or None
field = db.session.get(ShippingOrderField, order_field_id) if order_field_id else None
if source_kind == 'order_field':
if field is None or field.status != 'active' or field.scope != rule.scope.replace('task', 'header'):
raise ValidationError('Routing order field is invalid for rule scope', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
published_fields = {
str(config.get('field_id'))
for config in order_schema_service.get_published_contract()['fields']
if config.get('scope') == field.scope
}
if field.id not in published_fields:
raise ValidationError('Routing order field is not published', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
else:
raise ValidationError('Routing conditions must use a published order field', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
operator = str(item['operator'])
rule.conditions.append(FreightRpaOnhandRoutingRuleCondition(
condition_group=int(item.get('condition_group') or 1), source_kind=source_kind,
order_field_id=order_field_id,
operator=operator, expected_value_json=_validate_rule_condition_expected(
operator, item.get('expected_value_json'),
), sequence=index,
))
if not rule_id:
db.session.add(rule)
try:
db.session.commit()
except Exception as exc:
db.session.rollback()
raise ConflictError('Routing rule code and version already exist', code='SHIPPING.ONHAND_RULE_CONFLICT') from exc
return _rule_payload(rule)
def publish_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""发布草稿并写入不可变规则定义快照。
路由规则只声明库存源候选,允许引用已配置但暂时停用的 Source;实际
库存 RPA 运行时仍由库存源门禁拒绝停用 Source,避免发布配置误触发 RPA。
"""
rule = db.session.get(FreightRpaOnhandRoutingRule, rule_id)
if rule is None:
raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND')
if rule.status != 'draft':
raise ConflictError('Only draft routing rules can be published', code='SHIPPING.ONHAND_RULE_PUBLISH_INVALID')
if rule.action_type in {'add_source_candidates', 'exclude_source_candidates'}:
payload = rule.action_payload_json if isinstance(rule.action_payload_json, dict) else {}
source_codes = {
str(code or '').strip().upper()
for code in payload.get('source_codes', [])
if str(code or '').strip()
}
existing_codes = {
str(code).strip().upper()
for (code,) in db.session.query(FreightRpaSource.source_code).all()
}
missing_codes = sorted(source_codes - existing_codes)
if missing_codes:
raise ValidationError(
'Routing rule references unavailable inventory sources',
code='SHIPPING.ONHAND_RULE_SOURCE_INVALID',
details={'source_codes': missing_codes},
)
rule.status = 'published'
rule.updated_by = actor_id
db.session.add(FreightRpaOnhandRoutingRuleVersion(
rule_id=rule.id, version=rule.version, definition_json=_rule_payload(rule), published_by=actor_id,
))
db.session.commit()
return _rule_payload(rule)
def _external_payload(mapping: FreightRpaOnhandExternalMapping) -> dict[str, Any]:
return {
'id': mapping.id, 'source_id': mapping.source_id,
'freight_warehouse_id': mapping.freight_warehouse_id, '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,
'in_transit_warehouse_code': mapping.in_transit_warehouse_code,
'enabled': bool(mapping.enabled), 'version': mapping.version,
}
def list_external_mappings() -> list[dict[str, Any]]:
"""列出库存源到外部系统仓库的映射,不执行调拨判断。"""
return [_external_payload(item) for item in FreightRpaOnhandExternalMapping.query.order_by(FreightRpaOnhandExternalMapping.id).all()]
def delete_external_mapping(mapping_id: int) -> None:
"""删除错误的外部仓库映射;历史文件和任务不回写此实时配置。"""
record = db.session.get(FreightRpaOnhandExternalMapping, mapping_id)
if record is None:
raise NotFoundError('External mapping not found', code='SHIPPING.ONHAND_EXTERNAL_MAPPING_NOT_FOUND')
db.session.delete(record)
db.session.commit()
def save_external_mapping(data: dict[str, Any], *, actor_id: int | None, mapping_id: int | None = None) -> dict[str, Any]:
"""创建或更新精确/默认外部系统映射。"""
record = db.session.get(FreightRpaOnhandExternalMapping, mapping_id) if mapping_id else None
if mapping_id and record is None:
raise NotFoundError('External mapping not found', code='SHIPPING.ONHAND_EXTERNAL_MAPPING_NOT_FOUND')
try:
source_id = int(data.get('source_id'))
except (TypeError, ValueError) as exc:
raise ValidationError('source_id is required') from exc
if db.session.get(FreightRpaSource, source_id) is None:
raise ValidationError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
record = record or FreightRpaOnhandExternalMapping(source_id=source_id, external_system_code='', external_warehouse_code='', external_warehouse_name='')
record.source_id = source_id
# 货代仓库改为可选维度:inventory_match 源按「收料文件仓库 == 货代仓库」匹配映射行,
# 空值即「空库位」默认映射行;归一化为大写以与收料仓库值精确比对。
record.freight_warehouse_id = str(_text(data, 'freight_warehouse_id') or '').upper() or None
# 在途仓编码是在途调拨拨出库位来源(DefaultRouteResolver),保存端必填并大写归一。
record.in_transit_warehouse_code = str(_text(data, 'in_transit_warehouse_code', required=True)).upper()
record.external_system_code = str(_text(data, 'external_system_code', required=True)).upper()
record.external_organization_code = _text(data, 'external_organization_code')
record.external_site_code = _text(data, 'external_site_code')
record.external_warehouse_code = str(_text(data, 'external_warehouse_code', required=True)).upper()
record.external_warehouse_name = str(_text(data, 'external_warehouse_name', required=True))
record.enabled = _bool(data, 'enabled', bool(record.enabled) if mapping_id else True)
record.updated_by = actor_id
if not mapping_id:
record.created_by = actor_id
db.session.add(record)
try:
db.session.commit()
except Exception as exc:
db.session.rollback()
raise ConflictError('Active external mapping already exists for this freight identity', code='SHIPPING.ONHAND_EXTERNAL_MAPPING_CONFLICT') from exc
return _external_payload(record)
@@ -162,6 +162,8 @@ agent_types:
handler_config_schema: {} handler_config_schema: {}
in_transit_transfer: in_transit_transfer:
label: 在途仓自动调拨 label: 在途仓自动调拨
# 调拨类型来自平台配置(管理端「在途调拨类型」维护,GET /transfer-types 下发),
# 本清单与提示词不硬编码类型列表;Dify 平台侧如有副本需人工同步。
conversation_mode_default: task_chat conversation_mode_default: task_chat
runtime_provider_default: hybrid runtime_provider_default: hybrid
models: models:
@@ -6,6 +6,9 @@
输出结构化 message.completed 卡片,并经 Run API 恢复;本 Handler 负责 hybrid 输出结构化 message.completed 卡片,并经 Run API 恢复;本 Handler 负责 hybrid
运行时的上下文钩子与领域 UI State 扩展位(transfer_ui_state),暂不注入 运行时的上下文钩子与领域 UI State 扩展位(transfer_ui_state),暂不注入
Dify Chatflow 生命周期。 Dify Chatflow 生命周期。
【调拨类型语义 2026-10-14】调拨类型来自平台配置(管理端「在途调拨类型」
维护,`GET /api/in-transit-transfer/transfer-types` 下发);提示词与本
Handler 一律不硬编码类型列表,Dify 平台侧如有副本需人工同步。
""" """
from __future__ import annotations from __future__ import annotations
+6 -1
View File
@@ -97,7 +97,12 @@ def raise_auth_error(source, *, context: str, status_code: int = 401) -> None:
) )
if 'invalid or expired casdoor state' in lowered_raw: if 'invalid or expired casdoor state' in lowered_raw:
raise ValidationError('Invalid or expired Casdoor state') raise ValidationError('Invalid or expired Casdoor state')
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s', context, data) # [STEP 2] 未识别错误必须保留原始异常堆栈,否则本地换票后的崩溃会被吞成一行 payload={}。
current_app.logger.warning(
'[casdoor] unmapped auth error context=%s payload=%s source=%r',
context, data, source,
exc_info=source if isinstance(source, BaseException) else None,
)
raise AppError( raise AppError(
code='CASDOOR_AUTH_FAILED', code='CASDOOR_AUTH_FAILED',
message='Authentication failed, please try again', message='Authentication failed, please try again',
+2 -1
View File
@@ -77,12 +77,13 @@ def try_fast_route(
_log_fast_route('faq_cache', agent_code=agent_code, agent_id=agent_id, session_id=session_id) _log_fast_route('faq_cache', agent_code=agent_code, agent_id=agent_id, session_id=session_id)
return FastRouteResult( return FastRouteResult(
generator=FaqCacheService.stream_chat( generator=FaqCacheService.stream_chat(
faq_hit, faq_hit.entry,
query, query,
user, user,
agent, agent,
external_conversation_id, external_conversation_id,
session_id=session_id, session_id=session_id,
match=faq_hit,
), ),
route_name='faq_cache', route_name='faq_cache',
) )
+24 -2
View File
@@ -141,7 +141,21 @@ def emit_run_failed(
conversation_id: str, conversation_id: str,
message: str, message: str,
code: str | None = None, code: str | None = None,
user_facing: bool = False,
) -> str: ) -> str:
"""
发出本轮失败事件,并附带兼容用的 error 帧。
核心逻辑:user_facing 为 True 时两帧都带标记,前端原样展示 message。
Args:
message: 失败说明。user_facing 为 True 时必须已是给用户看的句子。
code: 业务错误码,可选。
user_facing: 为 True 时前端不再把 message 收成通用失败提示。
Returns:
连续两段 SSE 帧:run.failed 与 error。
"""
error_payload: dict[str, Any] = { error_payload: dict[str, Any] = {
"event": "run.failed", "event": "run.failed",
"run_id": run_id, "run_id": run_id,
@@ -150,10 +164,18 @@ def emit_run_failed(
"message": message, "message": message,
"session_status": "error", "session_status": "error",
} }
legacy_payload: dict[str, Any] = {
"event": "error",
"message": message,
"conversation_id": conversation_id,
"session_status": "error",
}
if code: if code:
error_payload["code"] = code error_payload["code"] = code
legacy = sse_frame({"event": "error", "message": message, "conversation_id": conversation_id, "session_status": "error"}) if user_facing:
return sse_frame(error_payload) + legacy error_payload["user_facing"] = True
legacy_payload["user_facing"] = True
return sse_frame(error_payload) + sse_frame(legacy_payload)
def emit_turn_event(event: TurnEvent, *, conversation_id: str) -> str: def emit_turn_event(event: TurnEvent, *, conversation_id: str) -> str:
@@ -194,6 +194,7 @@ class ChatTurnRuntime:
conversation_id=session.session_id, conversation_id=session.session_id,
message=exc.message, message=exc.message,
code=str(getattr(exc, "code", "") or "") or None, code=str(getattr(exc, "code", "") or "") or None,
user_facing=True,
) )
except Exception as exc: except Exception as exc:
current_app.logger.exception("[chat-turn] unexpected failure request_id=%s turn_id=%s", req_id, turn_id) current_app.logger.exception("[chat-turn] unexpected failure request_id=%s turn_id=%s", req_id, turn_id)
@@ -5,6 +5,7 @@ backend/app/services/contract_payment/parse_service.py
依赖:标准库正则与日期处理;原文抽取由调用方传入,避免绑定某一种文件解析器。 依赖:标准库正则与日期处理;原文抽取由调用方传入,避免绑定某一种文件解析器。
逻辑:先识别固定字段和付款比例,再校验金额/比例/日期;无法确定的事实进入 needs_review,不猜测。 逻辑:先识别固定字段和付款比例,再校验金额/比例/日期;无法确定的事实进入 needs_review,不猜测。
合同金额以正文抽出的正数为准;OA 的 0 与空值都不是有效总额。同一付款阶段的相同比例重复抽取不报重复。 合同金额以正文抽出的正数为准;OA 的 0 与空值都不是有效总额。同一付款阶段的相同比例重复抽取不报重复。
增值税税率和「收到定金后 N 天」不计入付款比例。
""" """
from __future__ import annotations from __future__ import annotations
@@ -24,7 +25,12 @@ from app.services.procurement_contract.analyze import extract_text_from_bytes
_DATE_RE = re.compile(r"(20\d{2})[\s_]*[年./-][\s_]*(\d{1,2})[\s_]*[月./-][\s_]*(\d{1,2})[\s_]*日?") _DATE_RE = re.compile(r"(20\d{2})[\s_]*[年./-][\s_]*(\d{1,2})[\s_]*[月./-][\s_]*(\d{1,2})[\s_]*日?")
_MONEY_RE = re.compile(r"(?:设备总价款\s*[((]?含税[))]?|人民币合同金额|合同金额|合同总价|含税总价)[::\s¥¥]*([\d,]+(?:\.\d+)?)", re.I) _MONEY_RE = re.compile(r"(?:设备总价款\s*[((]?含税[))]?|人民币合同金额|合同金额|合同总价|含税总价)[::\s¥¥]*([\d,]+(?:\.\d+)?)", re.I)
_PERCENT_RE = re.compile(r"(预付款|定金|出货款|货款|验收款|质保款|保款|尾款)[^。;;\n]{0,140}?(\d+(?:\.\d+)?)\s*%", re.S) _STAGE_LABEL_RE = re.compile(r"预付款|定金|出货款|货款|验收款|质保款|保款|尾款")
_PERCENT_VALUE_RE = re.compile(r"(\d+(?:\.\d+)?)\s*%")
_DEPOSIT_SCHEDULE_RE = re.compile(r"定金\s*后\s*\d+\s*(?:个)?(?:工作日|天|日)")
_SENTENCE_BREAK_RE = re.compile(r"[。;;\n]")
_TAX_PREFIX_RE = re.compile(r"(?:增值税|税率)\s*$")
_TAX_SUFFIX_RE = re.compile(r"\s*(?:的\s*)?增值税")
_DELIVERY_RE = re.compile(r"(?:交货期限|约定到货日期|交付期限|交货期)[::\s]*[^。;;\n]{0,60}?(20\d{2}[^\n。;;]*)") _DELIVERY_RE = re.compile(r"(?:交货期限|约定到货日期|交付期限|交货期)[::\s]*[^。;;\n]{0,60}?(20\d{2}[^\n。;;]*)")
_WARRANTY_RE = re.compile(r"(?:质保期|保修期|保固期|质保款[^。;;\n]{0,100}?)(?:满后|为|:|:)?\s*(\d+)\s*(年|个月|月|天)") _WARRANTY_RE = re.compile(r"(?:质保期|保修期|保固期|质保款[^。;;\n]{0,100}?)(?:满后|为|:|:)?\s*(\d+)\s*(年|个月|月|天)")
_WARRANTY_PAYMENT_RE = re.compile( _WARRANTY_PAYMENT_RE = re.compile(
@@ -146,12 +152,82 @@ def unique_parse_issues(issues: list[Any] | None) -> list[str]:
return result return result
def _is_tax_percentage(body: str, number_start: int, percent_end: int) -> bool:
"""
判断百分号是增值税或税率,而不是付款比例。
核心逻辑:数字前紧挨「增值税」或「税率」,或百分号后紧挨「增值税」,都视为税率。
「含13%增值税」靠百分号后面的「增值税」识别;单独的「含30%」仍可当作付款比例。
Args:
body: 合同正文。
number_start: 百分数数字在正文中的起始下标。
percent_end: 百分号结束下标,不含其后的文字。
Returns:
该百分号是税率时返回 True。
"""
before = body[max(0, number_start - 16):number_start]
after = body[percent_end:percent_end + 16]
return _TAX_PREFIX_RE.search(before) is not None or _TAX_SUFFIX_RE.match(after) is not None
def _first_payment_percentage(body: str, label_end: int) -> re.Match[str] | None:
"""
在阶段词后的同一句、140 字内取第一个非税率百分号。
核心逻辑:税率百分号跳过并继续看,避免「含13%增值税」挡住同一句里的「总价款的30%」。
遇到句号、分号或换行即停止,窗口长度与原先一致。
Args:
body: 合同正文。
label_end: 阶段词结束下标。
Returns:
付款比例的正则匹配;窗口内没有可用百分号时返回 None。
"""
window_end = label_end + 140
sentence = _SENTENCE_BREAK_RE.search(body, label_end)
if sentence and sentence.start() < window_end:
window_end = sentence.start()
cursor = label_end
while cursor < window_end:
value_match = _PERCENT_VALUE_RE.search(body, cursor, window_end)
if value_match is None:
return None
if _is_tax_percentage(body, value_match.start(1), value_match.end()):
cursor = value_match.end()
continue
return value_match
return None
def _matched_payment_percentages(body: str) -> list[tuple[str, str]]:
"""
抽出每个付款阶段词对应的第一个付款比例。
核心逻辑:「收到定金后 N 天」是完成日期,不作为预付款锚点。
其余阶段词沿用原窗口,但丢掉增值税、税率百分号。
Args:
body: 已抽取的合同正文。
Returns:
(阶段词, 百分数字符串) 列表,按出现顺序。未命中付款比例的阶段词不出现。
"""
matched: list[tuple[str, str]] = []
for label_match in _STAGE_LABEL_RE.finditer(body):
label = label_match.group(0)
if label == "定金" and _DEPOSIT_SCHEDULE_RE.match(body, label_match.start()):
continue
value_match = _first_payment_percentage(body, label_match.end())
if value_match is None:
continue
matched.append((label, value_match.group(1)))
return matched
def _extract_payment_percentages(body: str) -> tuple[dict[str, Decimal], list[str]]: def _extract_payment_percentages(body: str) -> tuple[dict[str, Decimal], list[str]]:
""" """
提取四阶段付款比例,并校验阶段完整性及比例合计。 提取四阶段付款比例,并校验阶段完整性及比例合计。
核心逻辑:同一语义阶段只允许一个比例。正文里同一比例被抽到多次(表格/页眉重复) 核心逻辑:同一语义阶段只允许一个比例。正文里同一比例被抽到多次(表格/页眉重复)
视为同一事实,不报重复;只有同一阶段出现不同比例才阻断。四阶段须完整且合计 100%。 视为同一事实,不报重复;只有同一阶段出现不同比例才阻断。四阶段须完整且合计 100%。
增值税税率和「收到定金后 N 天」不计入付款比例。
Args: Args:
body: 已抽取的合同正文。 body: 已抽取的合同正文。
Returns: Returns:
@@ -159,8 +235,8 @@ def _extract_payment_percentages(body: str) -> tuple[dict[str, Decimal], list[st
""" """
found: dict[str, list[Decimal]] = {node_type: [] for node_type in _PAYMENT_NODE_TYPES} found: dict[str, list[Decimal]] = {node_type: [] for node_type in _PAYMENT_NODE_TYPES}
issues: list[str] = [] issues: list[str] = []
for match in _PERCENT_RE.finditer(body): matched = _matched_payment_percentages(body)
label, raw = match.groups() for label, raw in matched:
node_type = _PAYMENT_LABEL_TO_NODE_TYPE[label] node_type = _PAYMENT_LABEL_TO_NODE_TYPE[label]
percentage = _parse_decimal(raw) percentage = _parse_decimal(raw)
if percentage is None: if percentage is None:
@@ -181,7 +257,6 @@ def _extract_payment_percentages(body: str) -> tuple[dict[str, Decimal], list[st
if missing: if missing:
issues.append(f"付款阶段比例无法识别:{'、'.join(_PAYMENT_NODE_LABELS[item] for item in missing)}") issues.append(f"付款阶段比例无法识别:{'、'.join(_PAYMENT_NODE_LABELS[item] for item in missing)}")
try: try:
matched = [(m.group(1), m.group(2)) for m in _PERCENT_RE.finditer(body)]
snippet = "" snippet = ""
for label in ("质保款", "验收款", "尾款"): for label in ("质保款", "验收款", "尾款"):
idx = body.find(label) idx = body.find(label)
@@ -0,0 +1,7 @@
"""
backend/app/services/equipment_acceptance/__init__.py
用途:设备验收预警同步包。
依赖:snapshot_rules、source_group、query_sql、sync_service。
逻辑:本包只做 OA 只读同步和本地快照,不发送企业微信。
"""
@@ -0,0 +1,90 @@
"""
backend/app/services/equipment_acceptance/alert_notice.py
用途:把一名收件人的待发送记录收成企微汇总文案和 Excel 明细。
依赖:openpyxl。
逻辑:发送服务按企业微信账号调用。卡片只写张数,逐张明细进工作簿。不写主送、抄送。
"""
from __future__ import annotations
from io import BytesIO
from typing import Any
from openpyxl import Workbook
from openpyxl.styles import Font
NOTICE_HEADERS = (
"验收单号",
"采购单号",
"申请人",
"轮次",
"停留天数",
"当前节点",
"当前处理人",
"通知身份",
)
NOTICE_FILE_NAME = "设备验收停留提醒.xlsx"
def summary_message(lines: list[dict[str, Any]]) -> str:
"""
拼一名收件人的文字卡片。第一行写已逾期的验收单张数,不列单号。
核心逻辑:一张发送记录算一张。同一轮次的张数写在一起,顺序跟传入的明细一致。
Args:
lines: 已按发送记录去重的明细。每项含 threshold_days。
Returns:
卡片正文。没有明细时仍返回可发送的空汇总。
"""
counts: dict[int, int] = {}
order: list[int] = []
for line in lines:
day = int(line.get("threshold_days") or 0)
if day not in counts:
order.append(day)
counts[day] = 0
counts[day] += 1
detail = ",".join(f"超过 {day} 天 {counts[day]} 张" for day in order) or "无"
return f"共 {len(lines)} 张验收单已逾期。\n{detail}。\n明细见下一条文件。"
def build_notice_workbook(lines: list[dict[str, Any]]) -> bytes:
"""
生成这名收件人的验收停留明细。
核心逻辑:一行对应一张发送记录。通知身份写他为什么收到,不写主送或抄送。
Args:
lines: 验收单号、采购单号、申请人、轮次天数、停留天数、当前节点、当前处理人和通知身份。
Returns:
xlsx 字节。
"""
workbook = Workbook()
sheet = workbook.active
sheet.title = "停留提醒"
sheet.append(list(NOTICE_HEADERS))
for cell in sheet[1]:
cell.font = Font(bold=True)
for line in lines:
dwell = line.get("dwell_days")
sheet.append([
_cell(line.get("acceptance_no")),
_cell(line.get("purchase_order_no")),
_cell(line.get("applicant")),
f"超过 {int(line.get('threshold_days') or 0)} 天",
"—" if dwell is None or dwell == "" else dwell,
_cell(line.get("node_name")),
_cell(line.get("handlers")),
_cell(line.get("identity")),
])
sheet.freeze_panes = "A2"
sheet.auto_filter.ref = sheet.dimensions
output = BytesIO()
workbook.save(output)
return output.getvalue()
def _cell(value: Any) -> str:
"""空值写成横线,避免 Excel 里出现空白列。"""
text = str(value or "").strip()
return text or "—"
@@ -0,0 +1,244 @@
"""
backend/app/services/equipment_acceptance/alert_plan.py
用途:判断验收单跨了哪几档,并把主送、抄送收成一条待发送。
依赖:无。不读数据库,不访问 OA,不发企业微信。
逻辑:扫描服务先解析出人员,再调用本模块去重和定状态。超过天数才进档,等于阈值不算。
"""
from __future__ import annotations
from typing import Any
def due_tiers(
dwell_days: int | None,
thresholds: tuple[int, int, int, int],
*,
max_tier: int = 4,
) -> list[int]:
"""
按累计天数给出已经跨过的档位。
核心逻辑:需求是「超过 N 天」。停留刚好等于阈值时还不发。四档各自独立,一次可以跨多档。
第 4 轮关闭时最高只到第 3 档,超过第 4 档天数也不产生总经理那一轮。
Args:
dwell_days: 签核自然日。没有计时起点时为空。
thresholds: 四个天数,对应第 1 到第 4 档。
max_tier: 允许的最高档,1 到 4。第 4 轮未启用时传 3。
Returns:
档位号列表。没有跨档时为空。
"""
if dwell_days is None:
return []
return [
index + 1
for index, day in enumerate(thresholds)
if dwell_days > day and index + 1 <= max_tier
]
def make_person(
*,
slot: str,
label: str,
name: str | None = None,
user_id: int | None = None,
wecom_userid: str | None = None,
oa_employee_id: int | None = None,
error: str | None = None,
) -> dict[str, Any]:
"""
收成一名收件人。
核心逻辑:解析失败时留下 error,不改成别的人。
Args:
slot: to 主送,cc 抄送。
label: 角色名称,例如当前处理人、直接主管。
name: 展示姓名。
user_id: 系统用户主键。对不上时为空。
wecom_userid: 已绑定的企业微信 userid。
oa_employee_id: E10 employee.ID。
error: 解析失败原因。成功时为空。
Returns:
写入 recipients_json 的字典。
"""
return {
"slot": slot,
"label": label,
"name": name,
"user_id": user_id,
"wecom_userid": wecom_userid or None,
"oa_employee_id": oa_employee_id,
"error": error,
}
def resolve_account(
*,
slot: str,
label: str,
name: str | None,
job_num: str | None,
user: Any,
missing_job_error: str,
oa_employee_id: int | None = None,
) -> dict[str, Any]:
"""
用工号对上系统用户,并要求已绑定企业微信。
核心逻辑:没有工号、对不上用户、没绑企微都记失败,不换成别人。
Args:
slot: to 或 cc。
label: 角色名称。
name: OA 或快照上的姓名。
job_num: employee.JOB_NUM,对应 users.employee_id。
user: 已按工号找到的用户。需要 id、wecom_userid,姓名优先 real_name。
missing_job_error: 没有工号时的失败原因。
oa_employee_id: E10 人员 ID。
Returns:
一名收件人。
"""
if not str(job_num or "").strip():
return make_person(
slot=slot,
label=label,
name=name,
oa_employee_id=oa_employee_id,
error=missing_job_error,
)
if user is None:
return make_person(
slot=slot,
label=label,
name=name,
oa_employee_id=oa_employee_id,
error="未对上系统用户",
)
display = _user_name(user) or name
wecom = str(getattr(user, "wecom_userid", None) or "").strip()
if not wecom:
return make_person(
slot=slot,
label=label,
name=display,
user_id=getattr(user, "id", None),
oa_employee_id=oa_employee_id,
error="未绑定企业微信",
)
return make_person(
slot=slot,
label=label,
name=display,
user_id=getattr(user, "id", None),
wecom_userid=wecom,
oa_employee_id=oa_employee_id,
)
def resolve_configured_user(*, slot: str, label: str, user: Any, missing_error: str) -> dict[str, Any]:
"""
把预警配置里的固定岗位收成收件人。
核心逻辑:没选人或没绑企微都记失败。不使用代码里的姓名兜底。
Args:
slot: to 或 cc。
label: 采购经副理、COO 或总经理。
user: 配置指向的系统用户。空表示未选。
missing_error: 未选人时的失败原因。
Returns:
一名收件人。
"""
if user is None:
return make_person(slot=slot, label=label, error=missing_error)
return resolve_account(
slot=slot,
label=label,
name=_user_name(user),
job_num="configured",
user=user,
missing_job_error=missing_error,
)
def assemble_tier(
*,
tier: int,
threshold_days: int,
to_people: list[dict[str, Any]],
cc_people: list[dict[str, Any]],
) -> dict[str, Any]:
"""
把一档的主送和抄送收成一条发送记录草稿。
核心逻辑:同一人同时出现在主送和抄送时只留主送。至少有一名可发的人则为待发送,否则整档失败。
失败原因留在记录上,不把名额转给别人。
Args:
tier: 1 到 4。
threshold_days: 这一档的天数。
to_people: 主送。
cc_people: 抄送。
Returns:
tier、threshold_days、to_text、cc_text、recipients、status、error_message。
"""
primary = _dedupe(to_people)
copied = _drop_already_primary(_dedupe(cc_people), primary)
recipients = primary + copied
errors = [item["error"] for item in recipients if item.get("error")]
ready = any(item.get("wecom_userid") and not item.get("error") for item in recipients)
return {
"tier": tier,
"threshold_days": threshold_days,
"to_text": _names(primary) or None,
"cc_text": _names(copied) or None,
"recipients": recipients,
"status": "pending" if ready else "failed",
"error_message": ";".join(errors) or None,
}
def _dedupe(people: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""同一系统用户或同一 OA 人员只留第一次。解析失败的行各自保留。"""
seen: set[tuple[Any, ...]] = set()
kept: list[dict[str, Any]] = []
for person in people:
if person.get("user_id"):
key: tuple[Any, ...] = ("user", person["user_id"])
elif person.get("oa_employee_id") and not person.get("error"):
key = ("oa", person["oa_employee_id"])
else:
key = ("error", person.get("label"), person.get("name"), person.get("error"))
if key in seen:
continue
seen.add(key)
kept.append(person)
return kept
def _drop_already_primary(copied: list[dict[str, Any]], primary: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""抄送里已经是主送的人不再重复。"""
keys = {_identity(person) for person in primary}
return [person for person in copied if _identity(person) not in keys]
def _identity(person: dict[str, Any]) -> tuple[Any, ...]:
"""用系统用户或 OA 人员识别同一个人。失败行用原因区分。"""
if person.get("user_id"):
return ("user", person["user_id"])
if person.get("oa_employee_id") and not person.get("error"):
return ("oa", person["oa_employee_id"])
return ("error", person.get("label"), person.get("name"), person.get("error"))
def _names(people: list[dict[str, Any]]) -> str:
"""只拼接解析成功的姓名。"""
return "、".join(str(person["name"]) for person in people if person.get("name") and not person.get("error"))
def _user_name(user: Any) -> str | None:
"""系统用户展示名:真实姓名优先,其次用户名。"""
real_name = str(getattr(user, "real_name", None) or "").strip()
if real_name:
return real_name
username = str(getattr(user, "username", None) or "").strip()
return username or None
@@ -0,0 +1,682 @@
"""
backend/app/services/equipment_acceptance/alert_service.py
用途:每日扫描生成设备验收待发送记录,并在周五按收件人发送企业微信。
依赖:同步服务、OA 人员目录、alert_plan、alert_notice、发送记录模型、企微通知。
逻辑:扫描先同步 E10,再按停留天数跨档。第 4 轮关闭时不生成、也不发送总经理那一轮。
周五按收件人发一条汇总卡片,紧跟着一份 Excel。卡片和文件都成功才算已发送。停表取消未发送记录。已发送的不重发、不改收件人。
"""
from __future__ import annotations
import logging
from datetime import datetime
from typing import Any
from zoneinfo import ZoneInfo
from app.extensions import db
from app.models.equipment_acceptance import (
EquipmentAcceptanceNode,
EquipmentAcceptanceOperator,
EquipmentAcceptanceOrder,
EquipmentAcceptanceSendFile,
EquipmentAcceptanceSendRecord,
EquipmentAcceptanceSetting,
)
from app.models.user import User
from app.services.equipment_acceptance.alert_notice import (
NOTICE_FILE_NAME,
build_notice_workbook,
summary_message,
)
from app.services.equipment_acceptance.alert_plan import (
assemble_tier,
due_tiers,
make_person,
resolve_account,
resolve_configured_user,
)
from app.services.equipment_acceptance.config_service import is_round_4_enabled, reminder_days
from app.services.equipment_acceptance.snapshot_rules import WATCHING
_LOGGER = logging.getLogger(__name__)
_SETTING_ID = 1
_EVENT = "equipment_acceptance_warning"
_UNSENT = ("pending", "failed")
def generate_alerts() -> dict[str, Any]:
"""
同步 E10 后生成或更新待发送记录。
核心逻辑:先拉最新节点和停表状态,再按当前处理人解析收件人。本函数不发企业微信。
Returns:
sync 摘要,以及 created、updated、cancelled 条数。
"""
from app.services.equipment_acceptance.sync_service import sync_acceptance_snapshots
sync_result = sync_acceptance_snapshots()
summary = refresh_pending_alerts()
# 同步提交时已经取消的未发送,刷新阶段不会再数到,这里加回去。
summary["cancelled"] += int(sync_result.get("cancelled") or 0)
summary["sync"] = sync_result
return summary
def refresh_pending_alerts(
*,
directory: tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]] | None = None,
) -> dict[str, Any]:
"""
按本地快照刷新待发送记录。
核心逻辑:计时中的单据跨过哪一档就保留哪一档。第 4 轮关闭时最高只到第 3 档。已发送和已取消不改。
未计时或已停表的单据,把还没发出的记录改成已取消。
Args:
directory: 测试注入的人员目录和经副理。空则查询 E10。
Returns:
created、updated、cancelled。
"""
orders = db.session.query(EquipmentAcceptanceOrder).all()
operators = _operators_by_order([order.id for order in orders])
people, deputies = directory if directory is not None else _load_directory(orders, operators)
users_by_job = _users_by_job(_job_numbers(orders, operators, people, deputies))
roles = _configured_users()
thresholds = reminder_days()
max_tier = 4 if is_round_4_enabled() else 3
existing = {
(row.order_id, row.tier): row
for row in db.session.query(EquipmentAcceptanceSendRecord).all()
if row.order_id is not None
}
created = 0
updated = 0
cancelled = 0
for order in orders:
if order.monitor_status != WATCHING:
cancelled += cancel_unsent(order.id)
continue
for draft in _drafts(
order,
operators.get(order.id, []),
people,
deputies,
users_by_job,
roles,
thresholds,
max_tier=max_tier,
):
current = existing.get((order.id, draft["tier"]))
if current is not None and current.status in ("sent", "cancelled"):
continue
if current is None:
current = EquipmentAcceptanceSendRecord(
order_id=order.id,
tier=draft["tier"],
threshold_days=draft["threshold_days"],
status=draft["status"],
created_at=datetime.utcnow(),
)
db.session.add(current)
existing[(order.id, draft["tier"])] = current
created += 1
else:
updated += 1
_apply_draft(current, order, draft)
db.session.commit()
return {"created": created, "updated": updated, "cancelled": cancelled}
def cancel_unsent(order_id: int) -> int:
"""
取消一张验收单上还没发出的预警。
核心逻辑:待发送和解析失败都还没出企业微信,停表后改成已取消。已发送的保留。
Args:
order_id: 本地验收单主键。
Returns:
改成已取消的行数。
"""
rows = (
db.session.query(EquipmentAcceptanceSendRecord)
.filter(
EquipmentAcceptanceSendRecord.order_id == order_id,
EquipmentAcceptanceSendRecord.status.in_(_UNSENT),
EquipmentAcceptanceSendRecord.sent_at.is_(None),
)
.all()
)
for row in rows:
row.status = "cancelled"
return len(rows)
def send_pending_alerts() -> dict[str, Any]:
"""
把待发送记录按收件人合并成一条企业微信。
核心逻辑:同一个人本轮只收一条汇总卡片和一份 Excel。卡片只写张数,明细在文件里。
解析失败的人不改发给别人。已取消和已发送不参与。
第 4 轮关闭时,已生成的待发送第 4 轮也不发出,避免通知总经理。
卡片或附件任一失败都记失败原因,并打一条 warning 日志。
每位收件人的 Excel 都写入 equipment_acceptance_send_files,发送失败也保留。
Returns:
成功人数、失败人数,以及对应的记录条数。
"""
from app.models import Agent
from app.services.integrations.wecom.notify import (
send_wecom_event_message,
send_wecom_file_message,
upload_wecom_temp_media,
)
rows = (
db.session.query(EquipmentAcceptanceSendRecord)
.filter(EquipmentAcceptanceSendRecord.status == "pending")
.all()
)
if not is_round_4_enabled():
rows = [row for row in rows if row.tier != 4]
orders = {
order.id: order
for order in db.session.query(EquipmentAcceptanceOrder)
.filter(EquipmentAcceptanceOrder.id.in_([row.order_id for row in rows if row.order_id]))
.all()
} if rows else {}
order_ids = [row.order_id for row in rows if row.order_id]
nodes = _nodes_by_order(order_ids)
operators = _operators_by_order(order_ids)
users = _users_by_id(_recipient_user_ids(rows))
buckets: dict[str, list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]]] = {}
for row in rows:
for person in list(row.recipients_json or []):
wecom_id = str(person.get("wecom_userid") or "").strip()
if person.get("error") or not wecom_id:
continue
buckets.setdefault(wecom_id, []).append((row, person))
agent = db.session.query(Agent).filter_by(agent_code="equipment_acceptance", is_active=True).first()
jump_path = f"/chat/{agent.id}" if agent is not None else "/workspace"
jump_params = {"view": "sends"} if agent is not None else None
sent_ids: set[str] = set()
failed_reasons: dict[str, str] = {}
for wecom_id, entries in buckets.items():
user = _audit_user(entries, users)
lines = _notice_lines(entries, orders, nodes, operators)
workbook = build_notice_workbook(lines)
archived = _archive_send_file(user, entries, workbook)
failure = ""
try:
result = send_wecom_event_message(
event_type=_EVENT,
user=user,
title="设备验收停留提醒",
content=summary_message(lines),
jump_path=jump_path,
jump_params=jump_params,
wecom_userid=wecom_id,
)
except Exception:
_LOGGER.exception("equipment acceptance wecom send failed")
failure = "企业微信发送异常"
result = {}
if not failure and not result.get("ok"):
failure = _wecom_failure_text(result)
_LOGGER.warning(
"equipment acceptance wecom send failed reason=%s trace_id=%s detail=%s",
result.get("reason"),
result.get("trace_id"),
failure,
)
if not failure:
try:
media_id = upload_wecom_temp_media(workbook, archived.excel_file_name or NOTICE_FILE_NAME)
file_result = send_wecom_file_message(wecom_id, media_id)
except Exception:
_LOGGER.exception("equipment acceptance wecom file upload failed")
failure = "企业微信附件上传失败"
file_result = {}
if not failure and file_result.get("errcode") != 0:
failure = _file_failure_text(file_result)
_LOGGER.warning(
"equipment acceptance wecom file failed errcode=%s errmsg=%s",
file_result.get("errcode"),
failure,
)
if failure:
failed_reasons[wecom_id] = failure
archived.status = "failed"
archived.error_message = failure
else:
sent_ids.add(wecom_id)
archived.status = "sent"
archived.sent_at = datetime.utcnow()
records_sent = 0
records_failed = 0
now = datetime.utcnow()
for row in rows:
ready = {
str(person.get("wecom_userid") or "").strip()
for person in list(row.recipients_json or [])
if person.get("wecom_userid") and not person.get("error")
}
ready.discard("")
if not ready:
continue
hit = [failed_reasons[item] for item in ready if item in failed_reasons]
if hit:
row.status = "failed"
row.error_message = _join_error(row.error_message, ";".join(dict.fromkeys(hit)))
records_failed += 1
elif ready <= sent_ids:
row.status = "sent"
row.sent_at = now
records_sent += 1
db.session.commit()
return {
"sent": len(sent_ids),
"failed": len(failed_reasons),
"records_sent": records_sent,
"records_failed": records_failed,
}
def _drafts(
order: EquipmentAcceptanceOrder,
operators: list[EquipmentAcceptanceOperator],
people: dict[int, dict[str, Any]],
deputies: dict[str, list[dict[str, Any]]],
users_by_job: dict[str, User],
roles: dict[str, User | None],
thresholds: tuple[int, int, int, int],
*,
max_tier: int = 4,
) -> list[dict[str, Any]]:
"""按当前处理人展开已经跨过、且配置允许的档。第 4 轮关闭时最高到第 3 档。"""
due = due_tiers(order.dwell_days, thresholds, max_tier=max_tier)
if not due:
return []
handlers: list[dict[str, Any]] = []
supervisors: list[dict[str, Any]] = []
deputy_people: list[dict[str, Any]] = []
if not operators:
handlers.append(make_person(slot="to", label="当前处理人", error="没有当前处理人"))
deputy_people.append(make_person(slot="to", label="经副理", error="没有当前处理人,查不到经副理"))
for operator in operators:
fact = people.get(operator.user_id) or {}
name = fact.get("name") or operator.handler_name
job_num = fact.get("job_num") or operator.handler_job_num
shown = name or "处理人"
handlers.append(resolve_account(
slot="to",
label="当前处理人",
name=name,
job_num=job_num,
user=users_by_job.get(str(job_num or "")),
missing_job_error=f"{shown}没有工号",
oa_employee_id=operator.user_id,
))
superior_id = fact.get("superior_id")
if superior_id is None:
supervisors.append(make_person(slot="cc", label="直接主管", name=name, error=f"{shown}没有直接主管"))
else:
supervisors.append(resolve_account(
slot="cc",
label="直接主管",
name=fact.get("superior_name"),
job_num=fact.get("superior_job_num"),
user=users_by_job.get(str(fact.get("superior_job_num") or "")),
missing_job_error=f"{shown}的直接主管没有工号",
oa_employee_id=superior_id,
))
found = deputies.get(str(fact.get("department_id") or ""), [])
if not found:
deputy_people.append(make_person(slot="to", label="经副理", name=name, error=f"{shown}没有经副理"))
else:
for item in found:
deputy_people.append(resolve_account(
slot="to",
label="经副理",
name=item.get("name"),
job_num=item.get("job_num"),
user=users_by_job.get(str(item.get("job_num") or "")),
missing_job_error=f"{shown}的经副理没有工号",
oa_employee_id=item.get("oa_id"),
))
applicant_fact = people.get(order.applicant_oa_id) if order.applicant_oa_id else None
applicant = resolve_account(
slot="cc",
label="采购担当",
name=(applicant_fact or {}).get("name") or order.applicant_name,
job_num=(applicant_fact or {}).get("job_num") or order.applicant_job_num,
user=users_by_job.get(str(((applicant_fact or {}).get("job_num") or order.applicant_job_num) or "")),
missing_job_error="没有申请人工号",
oa_employee_id=order.applicant_oa_id,
)
drafts: list[dict[str, Any]] = []
if 1 in due:
drafts.append(assemble_tier(
tier=1,
threshold_days=thresholds[0],
to_people=handlers,
cc_people=[*supervisors, applicant],
))
if 2 in due:
drafts.append(assemble_tier(
tier=2,
threshold_days=thresholds[1],
to_people=deputy_people,
cc_people=[
resolve_configured_user(slot="cc", label="COO", user=roles.get("coo"), missing_error="未配置COO"),
resolve_configured_user(slot="cc", label="采购经副理", user=roles.get("buyer"), missing_error="未配置采购经副理"),
],
))
if 3 in due:
drafts.append(assemble_tier(
tier=3,
threshold_days=thresholds[2],
to_people=[resolve_configured_user(slot="to", label="COO", user=roles.get("coo"), missing_error="未配置COO")],
cc_people=[resolve_configured_user(slot="cc", label="采购经副理", user=roles.get("buyer"), missing_error="未配置采购经副理")],
))
if 4 in due:
drafts.append(assemble_tier(
tier=4,
threshold_days=thresholds[3],
to_people=[resolve_configured_user(slot="to", label="总经理", user=roles.get("executive"), missing_error="未配置总经理")],
cc_people=[
resolve_configured_user(slot="cc", label="COO", user=roles.get("coo"), missing_error="未配置COO"),
resolve_configured_user(slot="cc", label="采购经副理", user=roles.get("buyer"), missing_error="未配置采购经副理"),
],
))
return drafts
def _apply_draft(row: EquipmentAcceptanceSendRecord, order: EquipmentAcceptanceOrder, draft: dict[str, Any]) -> None:
"""把草稿写进未发送的记录。不改创建时间,也不填发送时间。"""
row.acceptance_no = order.acceptance_no
row.purchase_order_no = order.purchase_order_no
row.threshold_days = draft["threshold_days"]
row.to_text = draft["to_text"]
row.cc_text = draft["cc_text"]
row.recipients_json = draft["recipients"]
row.status = draft["status"]
row.error_message = draft["error_message"]
def _load_directory(
orders: list[EquipmentAcceptanceOrder],
operators: dict[int, list[EquipmentAcceptanceOperator]],
) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]]:
"""向 E10 要当前处理人和申请人的主管、部门、经副理。"""
from app.services.equipment_acceptance.oa_repository import fetch_alert_directory
ids: set[int] = set()
for group in operators.values():
for operator in group:
if operator.user_id:
ids.add(operator.user_id)
for order in orders:
if order.monitor_status == WATCHING and order.applicant_oa_id:
ids.add(order.applicant_oa_id)
return fetch_alert_directory(sorted(ids))
def _job_numbers(
orders: list[EquipmentAcceptanceOrder],
operators: dict[int, list[EquipmentAcceptanceOperator]],
people: dict[int, dict[str, Any]],
deputies: dict[str, list[dict[str, Any]]],
) -> set[str]:
"""收集要对系统用户的工号。"""
found: set[str] = set()
for order in orders:
if order.applicant_job_num:
found.add(order.applicant_job_num)
for group in operators.values():
for operator in group:
if operator.handler_job_num:
found.add(operator.handler_job_num)
for fact in people.values():
if fact.get("job_num"):
found.add(str(fact["job_num"]))
if fact.get("superior_job_num"):
found.add(str(fact["superior_job_num"]))
for group in deputies.values():
for item in group:
if item.get("job_num"):
found.add(str(item["job_num"]))
return found
def _users_by_job(job_nums: set[str]) -> dict[str, User]:
"""用工号索引系统用户。"""
if not job_nums:
return {}
rows = db.session.query(User).filter(User.employee_id.in_(job_nums)).all()
return {str(row.employee_id): row for row in rows if row.employee_id}
def _configured_users() -> dict[str, User | None]:
"""读取三个固定岗位。没选时对应值是空。"""
setting = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
ids = []
if setting is not None:
ids = [item for item in (setting.buyer_manager_user_id, setting.coo_user_id, setting.executive_user_id) if item]
found = _users_by_id(ids)
if setting is None:
return {"buyer": None, "coo": None, "executive": None}
return {
"buyer": found.get(setting.buyer_manager_user_id or 0),
"coo": found.get(setting.coo_user_id or 0),
"executive": found.get(setting.executive_user_id or 0),
}
def _users_by_id(user_ids: list[int]) -> dict[int, User]:
"""按主键取出系统用户。"""
if not user_ids:
return {}
rows = db.session.query(User).filter(User.id.in_(user_ids)).all()
return {row.id: row for row in rows}
def _nodes_by_order(order_ids: list[int]) -> dict[int, list[EquipmentAcceptanceNode]]:
"""取出这些验收单的当前节点名称。"""
if not order_ids:
return {}
grouped: dict[int, list[EquipmentAcceptanceNode]] = {}
rows = (
db.session.query(EquipmentAcceptanceNode)
.filter(EquipmentAcceptanceNode.order_id.in_(order_ids))
.all()
)
for row in rows:
grouped.setdefault(row.order_id, []).append(row)
return grouped
def _operators_by_order(order_ids: list[int]) -> dict[int, list[EquipmentAcceptanceOperator]]:
"""取出这些验收单的当前处理人。"""
if not order_ids:
return {}
grouped: dict[int, list[EquipmentAcceptanceOperator]] = {}
rows = (
db.session.query(EquipmentAcceptanceOperator)
.filter(EquipmentAcceptanceOperator.order_id.in_(order_ids))
.all()
)
for row in rows:
grouped.setdefault(row.order_id, []).append(row)
return grouped
def _recipient_user_ids(rows: list[EquipmentAcceptanceSendRecord]) -> list[int]:
"""从待发送收件人里取出系统用户主键。"""
found: list[int] = []
for row in rows:
for person in list(row.recipients_json or []):
if person.get("user_id"):
found.append(int(person["user_id"]))
return found
def _audit_user(
entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]],
users: dict[int, User],
) -> User | None:
"""取这名收件人在系统里的账号,供企微审计。没有账号时仍按企微 userid 发送。"""
for _row, person in entries:
user_id = person.get("user_id")
if user_id and int(user_id) in users:
return users[int(user_id)]
return None
def _archive_send_file(
user: User | None,
entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]],
workbook: bytes,
) -> EquipmentAcceptanceSendFile:
"""
把这次准备发给一名收件人的 Excel 先落库。
核心逻辑:发送成功或失败都保留同一份字节,并记下里面的发送记录,供表格列下载。不保存企微 userid。
Args:
user: 系统用户。对不上账号时只留姓名。
entries: 这名收件人的发送记录和席位,用来取展示名。
workbook: xlsx 字节。
Returns:
已加入当前事务、尚未提交的文件行。
"""
now = datetime.utcnow()
name = _recipient_display_name(user, entries)
row = EquipmentAcceptanceSendFile(
recipient_user_id=None if user is None else user.id,
recipient_name=name or None,
excel_file_name=_archive_file_name(name, now),
excel_file_data=workbook,
excel_file_size=len(workbook),
send_record_ids=[row.id for row, _person in entries if row.id],
status="pending",
created_at=now,
)
db.session.add(row)
return row
def _recipient_display_name(
user: User | None,
entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]],
) -> str:
"""优先用系统姓名,没有账号时用收件人席位上的名字。"""
if user is not None:
named = str(user.real_name or user.username or "").strip()
if named:
return named
for _row, person in entries:
named = str(person.get("name") or "").strip()
if named:
return named
return ""
def _archive_file_name(recipient_name: str, moment: datetime) -> str:
"""文件名带上海日期和收件人,避免多次发送都叫同一个名字。"""
local = moment.replace(tzinfo=ZoneInfo("UTC")).astimezone(ZoneInfo("Asia/Shanghai"))
safe = "".join(char for char in recipient_name if char not in '\\/:*?"<>|').strip() or "收件人"
return f"设备验收停留提醒-{local:%Y%m%d}-{safe}.xlsx"[:255]
def _notice_lines(
entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]],
orders: dict[int, EquipmentAcceptanceOrder],
nodes: dict[int, list[EquipmentAcceptanceNode]],
operators: dict[int, list[EquipmentAcceptanceOperator]],
) -> list[dict[str, Any]]:
"""
把一名收件人的发送记录收成 Excel 行。
核心逻辑:同一条发送记录只占一行。通知身份用角色名,例如当前处理人、直接主管,不写主送或抄送。
Args:
entries: 这名收件人挂到的发送记录和对应席位。
orders: 验收单主键到快照。
nodes: 验收单主键到当前节点。
operators: 验收单主键到当前处理人。
Returns:
传给汇总文案和 Excel 的明细行。
"""
grouped: dict[int, dict[str, Any]] = {}
order_keys: list[int] = []
for row, person in entries:
label = str(person.get("label") or "").strip()
bucket = grouped.get(row.id)
if bucket is None:
bucket = {"row": row, "labels": []}
grouped[row.id] = bucket
order_keys.append(row.id)
if label and label not in bucket["labels"]:
bucket["labels"].append(label)
lines: list[dict[str, Any]] = []
for key in order_keys:
row = grouped[key]["row"]
order = orders.get(row.order_id or 0)
node_names = _unique_text(node.node_name for node in nodes.get(row.order_id or 0, []))
handler_names = _unique_text(operator.handler_name for operator in operators.get(row.order_id or 0, []))
lines.append({
"acceptance_no": row.acceptance_no,
"purchase_order_no": row.purchase_order_no,
"applicant": None if order is None else order.applicant_name,
"threshold_days": row.threshold_days,
"dwell_days": None if order is None else order.dwell_days,
"node_name": "、".join(node_names),
"handlers": "、".join(handler_names),
"identity": "、".join(grouped[key]["labels"]),
})
return lines
def _unique_text(values) -> list[str]:
"""按出现顺序去掉空白和重复名称。"""
found: list[str] = []
for value in values:
text = str(value or "").strip()
if text and text not in found:
found.append(text)
return found
def _file_failure_text(result: dict[str, Any]) -> str:
"""把企微文件消息的返回收成失败原因。不写入 userid。"""
code = result.get("errcode")
message = str(result.get("errmsg") or "").strip()
text = f"企业微信附件发送失败 {code} {message}".strip()
return text[:255]
def _wecom_failure_text(result: dict[str, Any]) -> str:
"""把企微发送结果收成页面和日志都能看的失败原因。不写入 userid。"""
reason = str(result.get("reason") or "")
if reason == "notify_disabled":
return "企业微信通知总开关已关闭"
if reason == "event_disabled":
return "未开启设备验收预警的企业微信事件"
if reason == "user_unbound":
return "收件人未绑定企业微信"
raw = result.get("raw") if isinstance(result.get("raw"), dict) else {}
if reason == "send_failed":
code = raw.get("errcode")
message = str(raw.get("errmsg") or "").strip()
text = f"企业微信返回 {code} {message}".strip()
return text[:255]
if reason == "exception":
return "企业微信发送异常"
return "企业微信发送失败"
def _join_error(current: str | None, extra: str) -> str:
"""把新的失败原因接在原有原因后面。相同句子不重复。"""
parts = [part for part in (current, extra) if part]
unique: list[str] = []
for part in parts:
if part not in unique:
unique.append(part)
return ";".join(unique)
@@ -0,0 +1,245 @@
"""
backend/app/services/equipment_acceptance/config_service.py
用途:读写设备验收预警配置:四档天数、第 4 轮开关和三个固定岗位。
依赖:extensions.db、EquipmentAcceptanceSetting、User、统一错误。
逻辑:配置页和停留列表调用。岗位只存系统用户主键。发送时刻不在这里,由排程 Cron 决定。
没有配置行时按冻结默认值 30/37/44/51 返回,第 4 轮默认关闭,不把姓名写进代码。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app.core.errors import ValidationError
from app.core.response import utc_iso
from app.extensions import db
from app.models.equipment_acceptance import EquipmentAcceptanceSetting
from app.models.user import User
from app.services.equipment_acceptance.snapshot_rules import FIRST_REMINDER_DAY
DEFAULT_REMINDER_DAYS = (FIRST_REMINDER_DAY, 37, 44, 51)
_SETTING_ID = 1
_ROLE_FIELDS = (
"buyer_manager_user_id",
"coo_user_id",
"executive_user_id",
)
_MAX_DAY = 3650
def is_round_4_enabled() -> bool:
"""
读取第 4 轮是否启用。
核心逻辑:没有配置行或字段为假时关闭。关闭后扫描不生成、发送不推出总经理那一轮。
Returns:
启用为 True。
"""
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
if row is None:
return False
return bool(row.round_4_enabled)
def parse_round_4_enabled(raw: Any) -> bool:
"""
校验第 4 轮开关。
核心逻辑:缺省按关闭处理,避免旧请求误打开总经理提醒。传入值必须是布尔。
Args:
raw: 接口里的 round_4_enabled。缺省为 None。
Returns:
是否启用第 4 轮。
Raises:
ValidationError: 传入了布尔以外的值。
"""
if raw is None:
return False
if not isinstance(raw, bool):
raise ValidationError(
"第 4 轮开关必须是是否启用",
code="EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID",
details={"field": "round_4_enabled"},
)
return raw
def reminder_days() -> tuple[int, int, int, int]:
"""
读取四档天数。
核心逻辑:没有配置行时用冻结默认值。扫描用这四个数判断有没有跨档。
Returns:
四个逐档增大的正整数。
"""
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
if row is None:
return DEFAULT_REMINDER_DAYS
return (int(row.day_1), int(row.day_2), int(row.day_3), int(row.day_4))
def first_reminder_day() -> int:
"""
读取第 1 档天数,供停留列表判断已逾期。
核心逻辑:没有配置行时用冻结默认值,避免列表在未保存配置前失去阈值。
Returns:
正整数天数。
"""
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
if row is None:
return DEFAULT_REMINDER_DAYS[0]
return int(row.day_1)
def get_acceptance_config(*, include_candidates: bool) -> dict[str, Any]:
"""
组装配置页数据。
核心逻辑:天数和已选用户谁都能看。候选人名单只给平台管理员,避免把全员目录交给普通用户。
Args:
include_candidates: 为 True 时附带在职用户,供选人弹窗使用。
Returns:
days、第 4 轮开关、三个岗位用户主键、已选用户、候选人和更新时间。
"""
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
selected_ids = _selected_ids(row)
return {
"days": list(_days_of(row)),
"round_4_enabled": False if row is None else bool(row.round_4_enabled),
"buyer_manager_user_id": None if row is None else row.buyer_manager_user_id,
"coo_user_id": None if row is None else row.coo_user_id,
"executive_user_id": None if row is None else row.executive_user_id,
"selected_users": _briefs(selected_ids),
"users": _candidate_users() if include_candidates else [],
"updated_at": None if row is None else utc_iso(row.updated_at),
}
def save_acceptance_config(payload: dict[str, Any], *, updated_by: int) -> dict[str, Any]:
"""
保存四档天数、第 4 轮开关和三个岗位用户。
核心逻辑:天数必须逐档增大。第 4 轮缺省为关闭。岗位为空表示未选;有值时必须是已存在的系统用户。
保存后只影响以后的预警,这里不改历史发送记录。已有的待发送第 4 轮在发送时会被跳过。
Args:
payload: days 为四个整数;round_4_enabled 为布尔;三个岗位字段为用户主键或空。
updated_by: 操作人的系统用户主键。
Returns:
与读取接口相同的配置,并带候选人。
Raises:
ValidationError: 天数不合法,或岗位用户不存在。
"""
days = validate_reminder_days(payload.get("days"))
round_4_enabled = parse_round_4_enabled(payload.get("round_4_enabled"))
role_ids = {field: _require_user_id(payload.get(field), field) for field in _ROLE_FIELDS}
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
if row is None:
row = EquipmentAcceptanceSetting(id=_SETTING_ID)
db.session.add(row)
row.day_1, row.day_2, row.day_3, row.day_4 = days
row.round_4_enabled = round_4_enabled
row.buyer_manager_user_id = role_ids["buyer_manager_user_id"]
row.coo_user_id = role_ids["coo_user_id"]
row.executive_user_id = role_ids["executive_user_id"]
row.updated_at = datetime.utcnow()
row.updated_by = updated_by
db.session.commit()
return get_acceptance_config(include_candidates=True)
def validate_reminder_days(raw: Any) -> tuple[int, int, int, int]:
"""
校验四档天数。
核心逻辑:必须是四个逐档增大的正整数。布尔值在 Python 里也是 int,这里明确拒绝。
Args:
raw: 接口里的 days。
Returns:
四个天数。
Raises:
ValidationError: 不是四个逐档增大的天数。
"""
if not isinstance(raw, list) or len(raw) != 4:
_reject_days()
parsed: list[int] = []
for value in raw:
if isinstance(value, bool) or not isinstance(value, int) or value < 1 or value > _MAX_DAY:
_reject_days()
parsed.append(value)
if not (parsed[0] < parsed[1] < parsed[2] < parsed[3]):
_reject_days()
return parsed[0], parsed[1], parsed[2], parsed[3]
def _reject_days() -> None:
"""四档天数不合法时用同一错误码拒绝。"""
raise ValidationError(
"设备验收预警的四档天数须逐档增大",
code="EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID",
details={"field": "days"},
)
def _require_user_id(raw: Any, field: str) -> int | None:
"""空岗位允许保存。有值时必须指向 users 表里的一行。"""
if raw is None or raw == "":
return None
if isinstance(raw, bool) or not isinstance(raw, int) or raw <= 0:
raise ValidationError(
"设备验收预警岗位必须选择系统用户",
code="EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID",
details={"field": field},
)
if db.session.get(User, raw) is None:
raise ValidationError(
"设备验收预警岗位必须选择系统用户",
code="EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID",
details={"field": field},
)
return raw
def _days_of(row: EquipmentAcceptanceSetting | None) -> tuple[int, int, int, int]:
"""没有配置行时返回冻结默认值。"""
if row is None:
return DEFAULT_REMINDER_DAYS
return (int(row.day_1), int(row.day_2), int(row.day_3), int(row.day_4))
def _selected_ids(row: EquipmentAcceptanceSetting | None) -> list[int]:
"""收集三个岗位里已经选中的用户主键,供姓名回显。"""
if row is None:
return []
return [user_id for user_id in (row.buyer_manager_user_id, row.coo_user_id, row.executive_user_id) if user_id]
def _candidate_users() -> list[dict[str, Any]]:
"""在职用户,带部门和企微绑定标记,供选人弹窗分组。"""
rows = db.session.query(User).filter(User.status == "active").order_by(User.username).all()
return [_user_brief(user) for user in rows]
def _briefs(user_ids: list[int]) -> list[dict[str, Any]]:
"""按主键取出已选用户。停用用户也返回,避免页面上只剩一个数字。"""
if not user_ids:
return []
rows = db.session.query(User).filter(User.id.in_(user_ids)).all()
return [_user_brief(user) for user in rows]
def _user_brief(user: User) -> dict[str, Any]:
"""选人组件要的展示字段。姓名只从用户资料来,不另存一份。"""
return {
"id": user.id,
"username": user.username,
"real_name": user.real_name,
"employee_id": user.employee_id,
"department": user.department,
"wecom_bound": bool(user.wecom_userid),
}
@@ -0,0 +1,279 @@
"""
backend/app/services/equipment_acceptance/oa_repository.py
用途:只读拉取 E10 验收单、当前节点、操作人,以及直接主管和经副理。
依赖:pyodbc、settings、query_sql。不调用 E8 的 OA_SQLSERVER_* 连接。
逻辑:先探测实例上的库名,再执行联表查询。经副理矩阵固定在 eteams。查询失败不把连接串写入日志。
"""
from __future__ import annotations
import logging
from typing import Any
from app.core.errors import ServiceUnavailableError, ValidationError
from app.services.equipment_acceptance.query_sql import _qualified, build_acceptance_sql, resolve_catalogs
from app.services.equipment_acceptance.snapshot_rules import as_int
from app.services.equipment_acceptance.settings import (
EquipmentAcceptanceSqlSettings,
load_equipment_acceptance_sql_settings,
)
_LOGGER = logging.getLogger(__name__)
# 苏州和信「HXJM-审批矩阵」。取值配置是该矩阵下 config_name 为「经副理」的 id。
_MATRIX_TENANT = "temkc46eme"
_MATRIX_ID = 1115770797884751874
_DEPUTY_CONFIG_ID = 1115771897387991041
_MATRIX_CATALOG = "eteams"
_PREFERRED_DRIVERS = (
"ODBC Driver 18 for SQL Server",
"ODBC Driver 17 for SQL Server",
"SQL Server",
)
def fetch_acceptance_rows() -> list[dict[str, Any]]:
"""
从 E10 拉验收单联表结果。
核心逻辑:连接 ecology10 所在实例,按实际库名组装 SQL。不查询 isremark。
Returns:
字段名为小写别名的字典行。
Raises:
ValidationError: 连接配置不完整,或库名非法。
ServiceUnavailableError: 驱动、连接或查询失败。
"""
settings = load_equipment_acceptance_sql_settings()
connection = _open_connection(settings)
try:
cursor = connection.cursor()
cursor.execute("SELECT name FROM sys.databases")
names = {str(row[0]) for row in cursor.fetchall() if row and row[0]}
try:
catalogs = resolve_catalogs(
names,
form=settings.form_catalog or None,
employee=settings.employee_catalog or None,
request=settings.request_catalog or None,
node=settings.node_catalog or None,
)
except ValueError as exc:
raise ValidationError(
"设备验收同步找不到要查询的数据库",
code="EQUIPMENT_ACCEPTANCE.CONFIG_INVALID",
details={"reason": str(exc)},
) from exc
_LOGGER.info(
"equipment acceptance catalogs form=%s employee=%s request=%s node=%s",
catalogs.form,
catalogs.employee,
catalogs.request,
catalogs.node,
)
cursor.execute(build_acceptance_sql(catalogs))
columns = [str(col[0]).lower() for col in cursor.description]
return [
{columns[index]: raw[index] for index in range(len(columns))}
for raw in cursor.fetchall()
]
except (ValidationError, ServiceUnavailableError):
raise
except Exception as exc:
_LOGGER.warning("equipment acceptance sql failed error=%s", type(exc).__name__)
raise ServiceUnavailableError(
"查询 E10 设备验收数据失败",
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
) from exc
finally:
connection.close()
def _open_connection(settings: EquipmentAcceptanceSqlSettings):
"""
打开 E10 只读连接。初始库固定为 ecology10,跨库表名在 SQL 里写全。
Raises:
ServiceUnavailableError: 没有 pyodbc、没有 ODBC 驱动或连接失败。
"""
try:
import pyodbc
except ImportError as exc:
raise ServiceUnavailableError(
"未安装 pyodbc,无法连接 E10 SQL Server",
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
) from exc
driver = _pick_driver(pyodbc, settings.driver)
database = settings.form_catalog or "ecology10"
conn_str = (
f"DRIVER={{{driver}}};"
f"SERVER={settings.host},{settings.port};"
f"DATABASE={database};"
f"UID={settings.username};"
f"PWD={settings.password};"
)
if driver != "SQL Server":
conn_str += f"Encrypt={settings.encrypt};TrustServerCertificate={settings.trust_cert};"
try:
return pyodbc.connect(conn_str, timeout=settings.timeout)
except Exception as exc:
_LOGGER.warning("equipment acceptance connect failed error=%s", type(exc).__name__)
raise ServiceUnavailableError(
"连接 E10 SQL Server 失败",
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
) from exc
def fetch_alert_directory(employee_ids: list[int]) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]]:
"""
读取处理人的直接主管,并按部门查出经副理。
核心逻辑:主管在 employee.SUPERIOR。经副理不在这一列,按部门 ID 走 eteams 矩阵条件表。
人员 ID 必须是整数。没有人员时不连库。
Args:
employee_ids: 当前处理人和申请人的 employee.ID。
Returns:
(人员字典, 部门 ID 到经副理列表)。人员字典的键是 employee.ID。
Raises:
ValidationError: 库名不合法。
ServiceUnavailableError: 连接或查询失败。
"""
ids = sorted({int(item) for item in employee_ids})
if not ids:
return {}, {}
settings = load_equipment_acceptance_sql_settings()
connection = _open_connection(settings)
try:
cursor = connection.cursor()
cursor.execute("SELECT name FROM sys.databases")
names = {str(row[0]) for row in cursor.fetchall() if row and row[0]}
catalogs = resolve_catalogs(
names,
form=settings.form_catalog or None,
employee=settings.employee_catalog or None,
request=settings.request_catalog or None,
node=settings.node_catalog or None,
)
employee = _qualified(catalogs.employee, "employee")
people = _load_people(cursor, employee, ids)
departments = sorted({item["department_id"] for item in people.values() if item.get("department_id")})
deputies = _load_deputies(cursor, employee, departments)
return people, deputies
except (ValidationError, ServiceUnavailableError):
raise
except Exception as exc:
_LOGGER.warning("equipment acceptance directory sql failed error=%s", type(exc).__name__)
raise ServiceUnavailableError(
"查询 E10 直接主管和经副理失败",
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
) from exc
finally:
connection.close()
def _load_people(cursor: Any, employee: str, employee_ids: list[int]) -> dict[int, dict[str, Any]]:
"""按人员 ID 取出姓名、工号、直接主管和部门。"""
found: dict[int, dict[str, Any]] = {}
for chunk in _chunks(employee_ids):
marks = ",".join("?" for _ in chunk)
cursor.execute(
f"""
SELECT e.ID, e.USERNAME, e.JOB_NUM, e.SUPERIOR, e.DEPARTMENT,
sup.USERNAME, sup.JOB_NUM
FROM {employee} AS e
LEFT JOIN {employee} AS sup ON sup.ID = e.SUPERIOR
WHERE e.ID IN ({marks})
""",
chunk,
)
for raw in cursor.fetchall():
oa_id = as_int(raw[0])
if oa_id is None:
continue
department = _clean(raw[4])
found[oa_id] = {
"oa_id": oa_id,
"name": _clean(raw[1]),
"job_num": _clean(raw[2]),
"superior_id": as_int(raw[3]),
"department_id": department,
"superior_name": _clean(raw[5]),
"superior_job_num": _clean(raw[6]),
}
return found
def _load_deputies(cursor: Any, employee: str, department_ids: list[str]) -> dict[str, list[dict[str, Any]]]:
"""按部门 ID 字符串查出经副理。部门不在矩阵里时不产生人员。"""
found: dict[str, list[dict[str, Any]]] = {}
if not department_ids:
return found
matrix_condition = _qualified(_MATRIX_CATALOG, "hrm_matrix_condition_data")
matrix_value = _qualified(_MATRIX_CATALOG, "hrm_matrix_value_data")
for chunk in _chunks(department_ids):
marks = ",".join("?" for _ in chunk)
params: list[Any] = [_DEPUTY_CONFIG_ID, _MATRIX_TENANT, _MATRIX_ID, *_chunk_params(chunk)]
cursor.execute(
f"""
SELECT c.relate_id, v.relate_id, emp.USERNAME, emp.JOB_NUM
FROM {matrix_condition} AS c
INNER JOIN {matrix_value} AS v
ON v.matrix_data_id = c.matrix_data_id
AND v.tenant_key = c.tenant_key
AND v.matrix_id = c.matrix_id
AND v.delete_type = 0
AND v.matrix_value_config_id = ?
LEFT JOIN {employee} AS emp ON emp.ID = v.relate_id
WHERE c.tenant_key = ?
AND c.matrix_id = ?
AND c.delete_type = 0
AND c.relate_id IN ({marks})
""",
params,
)
for raw in cursor.fetchall():
department_id = _clean(raw[0])
person_id = as_int(raw[1])
if not department_id or person_id is None:
continue
found.setdefault(department_id, []).append({
"oa_id": person_id,
"name": _clean(raw[2]),
"job_num": _clean(raw[3]),
})
return found
def _chunk_params(chunk: list[Any]) -> list[Any]:
"""部门 ID 按原字符串传给条件表。"""
return list(chunk)
def _chunks(values: list[Any], size: int = 400) -> list[list[Any]]:
"""把 IN 列表拆开,避免一条 SQL 的参数过多。"""
return [values[index:index + size] for index in range(0, len(values), size)]
def _clean(value: Any) -> str | None:
"""去掉空白。数字部门 ID 也收成字符串,供矩阵条件表比较。"""
if value is None:
return None
text = str(value).strip()
return text or None
def _pick_driver(pyodbc: Any, configured: str) -> str:
"""选用已配置且本机存在的 ODBC 驱动,否则按 18、17、SQL Server 的顺序挑。"""
available = list(pyodbc.drivers())
if configured and configured in available:
return configured
for name in _PREFERRED_DRIVERS:
if name in available:
return name
if not available:
raise ServiceUnavailableError(
"未找到 SQL Server ODBC 驱动",
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
)
return available[-1]
@@ -0,0 +1,167 @@
"""
backend/app/services/equipment_acceptance/query_sql.py
用途:决定 E10 各表所在库,并组装只读联表 SQL。
依赖:无 Flask。库名只允许字母、数字和下划线。
逻辑:同步仓库调用。验收单用 FORM_DATA_ID 经 wfc_form_data 挂到流程实例。
不读流程编号、第二合同编号、验收日期、optgroupid、batch_number、operate_log_id、isremark。无法验收说明读取 ycsm。字典库看不到时,流程表回退到 ecology10。
"""
from __future__ import annotations
import re
from dataclasses import dataclass
_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
_FORM_CATALOG = "ecology10"
_EMPLOYEE_CATALOG = "eteams"
_REQUEST_CATALOG = "weaver_wfc"
_NODE_CATALOG = "weaver_wfp"
@dataclass(frozen=True)
class AcceptanceCatalogs:
"""一次同步使用的四个库名。"""
form: str
employee: str
request: str
node: str
def resolve_catalogs(
database_names: set[str],
*,
form: str | None = None,
employee: str | None = None,
request: str | None = None,
node: str | None = None,
) -> AcceptanceCatalogs:
"""
按数据字典和实例上实际存在的库选择库名。
核心逻辑:显式传入的库名优先。否则流程库优先 weaver_wfc、节点库优先 weaver_wfp,
实例里没有这两个库时用 ecology10。人员库只认 eteams,不猜测到别的库。
Args:
database_names: sys.databases 里的库名。
form: 验收单库覆盖值。
employee: 人员库覆盖值。
request: 流程库覆盖值。
node: 节点定义库覆盖值。
Returns:
AcceptanceCatalogs。
Raises:
ValueError: 库名非法,或人员库、回退后的流程库仍然不存在。
"""
present = {name.lower(): name for name in database_names if name}
return AcceptanceCatalogs(
form=_pick(form, _FORM_CATALOG, present, allow_fallback=_FORM_CATALOG),
employee=_pick(employee, _EMPLOYEE_CATALOG, present, allow_fallback=None),
request=_pick(request, _REQUEST_CATALOG, present, allow_fallback=_FORM_CATALOG),
node=_pick(node, _NODE_CATALOG, present, allow_fallback=_FORM_CATALOG),
)
def build_acceptance_sql(catalogs: AcceptanceCatalogs) -> str:
"""
组装验收单、人员、流程实例、当前节点、节点定义、操作人的只读 SQL。
核心逻辑:用 FORM_DATA_ID 对齐 wfc_form_data.dataid,再按 requestid 挂到流程实例。
不查询流程编号、第二合同编号、验收日期和 isremark。当前节点和操作人按 requestid + nodeid 对齐,
delete_type 只取 0。当前处理人就是这些 userid。
Args:
catalogs: 已解析的库名。
Returns:
一条 SELECT。
Raises:
ValueError: 库名不是合法标识符。
"""
form = _qualified(catalogs.form, "ft_gdzcysdv2")
employee = _qualified(catalogs.employee, "employee")
form_data = _qualified(catalogs.request, "wfc_form_data")
request = _qualified(catalogs.request, "wfc_requestbase")
current = _qualified(catalogs.request, "wfc_currentnode")
node = _qualified(catalogs.node, "wfp_node")
operate = _qualified(catalogs.request, "wfc_operate")
return f"""
SELECT
f.ysddh,
f.cgdh,
f.htbh,
f.sbsyrjssj,
f.sfzfth,
f.sfkyzcys,
f.ycsm,
f.sybmdd,
owner.USERNAME AS owner_name,
owner.JOB_NUM AS owner_job_num,
f.sbglry,
equip.USERNAME AS equip_name,
equip.JOB_NUM AS equip_job_num,
f.sqr,
applicant.USERNAME AS applicant_name,
applicant.JOB_NUM AS applicant_job_num,
r.requestid,
r.flowstatus,
r.finishdatetime,
c.nodeid,
n.nodename,
n.nodetype,
op.userid,
handler.USERNAME AS handler_name,
handler.JOB_NUM AS handler_job_num
FROM {form} AS f
LEFT JOIN {employee} AS owner ON owner.ID = f.sybmdd
LEFT JOIN {employee} AS equip ON equip.ID = f.sbglry
LEFT JOIN {employee} AS applicant ON applicant.ID = f.sqr
LEFT JOIN {form_data} AS d
ON d.dataid = f.FORM_DATA_ID
AND d.delete_type = 0
LEFT JOIN {request} AS r
ON r.requestid = d.requestid
AND r.delete_type = 0
LEFT JOIN {current} AS c
ON c.requestid = r.requestid
AND c.delete_type = 0
LEFT JOIN {node} AS n
ON n.id = c.nodeid
AND n.delete_type = 0
LEFT JOIN {operate} AS op
ON op.requestid = c.requestid
AND op.nodeid = c.nodeid
AND op.delete_type = 0
LEFT JOIN {employee} AS handler ON handler.ID = op.userid
WHERE ISNULL(f.delete_type, 0) = 0
AND r.requestid IS NOT NULL
""".strip()
def _pick(
override: str | None,
preferred: str,
present: dict[str, str],
*,
allow_fallback: str | None,
) -> str:
"""选择一个实际可用的库名。覆盖值不要求已经出现在探测结果里。"""
if override and override.strip():
return _ident(override.strip())
if preferred.lower() in present:
return _ident(present[preferred.lower()])
if allow_fallback and allow_fallback.lower() in present:
return _ident(present[allow_fallback.lower()])
raise ValueError(f"缺少数据库 {preferred}")
def _qualified(catalog: str, table: str) -> str:
"""返回 [库].[dbo].[表]。"""
return f"[{_ident(catalog)}].[dbo].[{_ident(table)}]"
def _ident(name: str) -> str:
"""拒绝不是普通标识符的库名或表名。"""
if not _IDENT.match(name):
raise ValueError(f"非法 SQL 标识符: {name}")
return name
@@ -0,0 +1,74 @@
"""
backend/app/services/equipment_acceptance/schedule_seed.py
用途:设备验收预警的默认排程:每日扫描和周五 18:00 发送。
依赖:ScheduleTask、permission_roles.service.first_schedule_owner_user、timezone_util。
逻辑:应用启动时幂等创建。已有同编号或同任务键时不覆盖管理员改过的 Cron。
"""
from __future__ import annotations
from datetime import datetime
from app import db
from app.models import ScheduleTask
from app.services.permission_roles.service import first_schedule_owner_user
from app.services.schedule.timezone_util import compute_next_run_at
_DEFAULTS = (
("SCH-EQUIPMENT-ACCEPTANCE-SCAN", "equipment-acceptance-alert-scan", "设备验收预警扫描(日批)", "0 6 * * *"),
("SCH-EQUIPMENT-ACCEPTANCE-WEEKLY", "equipment-acceptance-alert-weekly", "设备验收预警发送(周五 18:00)", "0 18 * * 5"),
)
def ensure_default_equipment_acceptance_schedules(*, commit: bool = True):
"""
幂等创建设备验收每日扫描和周五发送两个排程。
核心逻辑:发送时刻不在预警配置表。默认与合同付款一样,周五 18:00,时区 Asia/Shanghai。
Args:
commit: 为 False 时只 flush,交给外层事务提交。
Returns:
新建的排程。没有可当负责人的用户时返回空列表。
"""
owner = first_schedule_owner_user()
if owner is None:
return []
created = []
for schedule_no, platform_path, name, cron in _DEFAULTS:
existing = (
db.session.query(ScheduleTask)
.filter((ScheduleTask.schedule_no == schedule_no) | (ScheduleTask.platform_api_path == platform_path))
.first()
)
if existing:
continue
now = datetime.utcnow()
task = ScheduleTask(
schedule_no=schedule_no,
name=name,
schedule_type="platform_job",
owner_user_id=owner.id,
cron_expr=cron,
schedule_timezone="Asia/Shanghai",
wait_seconds=0,
platform_api_path=platform_path,
job_params={},
kb_sync_enabled=False,
notify_user_ids_json=[],
notify_enabled=False,
enabled=True,
next_run_at=compute_next_run_at(cron, timezone_name="Asia/Shanghai") or now,
created_by=owner.id,
updated_by=owner.id,
created_at=now,
updated_at=now,
)
db.session.add(task)
created.append(task)
if commit and created:
db.session.commit()
elif not commit:
db.session.flush()
return created
@@ -0,0 +1,176 @@
"""
backend/app/services/equipment_acceptance/send_record_service.py
用途:分页读取设备验收预警的发送记录。
依赖:extensions.db、EquipmentAcceptanceSendRecord、EquipmentAcceptanceSendFile、utc_iso。
逻辑:由发送记录列表和 Excel 下载接口调用。列表按 send_record_ids 把 Excel 挂到对应行,不读文件字节。
"""
from __future__ import annotations
from typing import Any
from sqlalchemy.orm import defer
from app.core.errors import NotFoundError
from app.core.response import utc_iso
from app.extensions import db
from app.models.equipment_acceptance import EquipmentAcceptanceSendFile, EquipmentAcceptanceSendRecord
def list_send_records(*, page: int, page_size: int) -> dict[str, Any]:
"""
按创建时间倒序分页列出发送记录。
核心逻辑:只读已落库的记录。扫描还没跑过时列表为空。
Args:
page: 从 1 开始。
page_size: 每页条数,上限 100。
Returns:
items、total、page、page_size。
"""
page = max(1, page)
page_size = min(100, max(1, page_size))
query = db.session.query(EquipmentAcceptanceSendRecord)
total = query.count()
rows = (
query.order_by(EquipmentAcceptanceSendRecord.created_at.desc(), EquipmentAcceptanceSendRecord.id.desc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
file_rows = _file_rows_for([row.id for row in rows])
return {
"items": [
send_record_payload(row, _files_for_record(row.id, file_rows))
for row in rows
],
"total": total,
"page": page,
"page_size": page_size,
}
def list_send_files(*, limit: int = 20) -> list[dict[str, Any]]:
"""
列出最近留下的收件人 Excel,不含文件字节。
核心逻辑:按创建时间倒序。发送失败的文件也返回,方便对照当时准备发出的明细。
Args:
limit: 最多返回条数,上限 50。
Returns:
文件名、收件人、状态和发送时间。
"""
limit = min(50, max(1, limit))
rows = (
db.session.query(EquipmentAcceptanceSendFile)
.order_by(EquipmentAcceptanceSendFile.created_at.desc(), EquipmentAcceptanceSendFile.id.desc())
.limit(limit)
.all()
)
return [send_file_payload(row) for row in rows]
def get_send_file(file_id: int) -> EquipmentAcceptanceSendFile:
"""
取出一份已归档的 Excel。
Args:
file_id: 文件行主键。
Returns:
含字节的文件行。
Raises:
NotFoundError: 记录不存在或没有文件内容。
"""
row = db.session.get(EquipmentAcceptanceSendFile, file_id)
if row is None or not row.excel_file_data:
raise NotFoundError("设备验收预警附件不存在")
return row
def send_file_payload(row: EquipmentAcceptanceSendFile) -> dict[str, Any]:
"""列表用的文件摘要。不返回 Excel 字节。"""
return {
"id": row.id,
"recipient_name": row.recipient_name,
"excel_file_name": row.excel_file_name,
"excel_file_size": row.excel_file_size,
"status": row.status,
"sent_at": utc_iso(row.sent_at),
"created_at": utc_iso(row.created_at),
}
def _file_rows_for(record_ids: list[int]) -> list[EquipmentAcceptanceSendFile]:
"""
取出可能挂在这些发送记录上的 Excel 摘要。
核心逻辑:延迟加载文件字节,只留下文件名和记录编号,避免列表把整份 xlsx 读进内存。
Args:
record_ids: 当前页发送记录主键。为空时不查。
Returns:
归档文件行,不含 excel_file_data。
"""
if not record_ids:
return []
return (
db.session.query(EquipmentAcceptanceSendFile)
.options(defer(EquipmentAcceptanceSendFile.excel_file_data))
.order_by(EquipmentAcceptanceSendFile.id.asc())
.all()
)
def _files_for_record(record_id: int, file_rows: list[EquipmentAcceptanceSendFile]) -> list[dict[str, Any]]:
"""
挑出包含这条发送记录的 Excel。
核心逻辑:send_record_ids 里有这条记录才挂上。没有文件名的不展示。
Args:
record_id: 发送记录主键。
file_rows: 已去掉文件字节的归档行。
Returns:
下载按钮需要的 id 和文件名。
"""
found: list[dict[str, Any]] = []
for row in file_rows:
ids = {int(item) for item in list(row.send_record_ids or []) if item}
if record_id in ids and row.excel_file_name:
found.append({
"id": row.id,
"excel_file_name": row.excel_file_name,
})
return found
def send_record_payload(
row: EquipmentAcceptanceSendRecord,
files: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""
把一条发送记录收成接口数据。
核心逻辑:单号和主送、抄送用写入时的快照,不回读当前岗位。Excel 只带文件名和主键。
Args:
row: 本地发送记录。
files: 这份记录出现过的归档 Excel。
Returns:
页签表格用的字段。
"""
return {
"id": row.id,
"order_id": row.order_id,
"acceptance_no": row.acceptance_no,
"purchase_order_no": row.purchase_order_no,
"tier": row.tier,
"threshold_days": row.threshold_days,
"to_text": row.to_text,
"cc_text": row.cc_text,
"recipients": list(row.recipients_json or []),
"status": row.status,
"sent_at": utc_iso(row.sent_at),
"error_message": row.error_message,
"created_at": utc_iso(row.created_at),
"files": files or [],
}
@@ -0,0 +1,116 @@
"""
backend/app/services/equipment_acceptance/settings.py
用途:读取设备验收同步要用的 E10 SQL Server 连接。
依赖:Flask current_app、环境变量 OA_E10_SQLSERVER_HOST / USERNAME / PASSWORD。
逻辑:主机、账号、密码不回退到 E8 的 OA_SQLSERVER_*。库名由查询时再探测。
"""
from __future__ import annotations
import os
from dataclasses import dataclass
from flask import current_app, has_app_context
from app.core.errors import ValidationError
@dataclass(frozen=True)
class EquipmentAcceptanceSqlSettings:
"""E10 只读连接。repr 不包含密码。"""
host: str
port: str
username: str
password: str
driver: str
encrypt: str
trust_cert: str
timeout: int
form_catalog: str
employee_catalog: str
request_catalog: str
node_catalog: str
def __repr__(self) -> str:
return (
"EquipmentAcceptanceSqlSettings("
f"host={self.host!r}, port={self.port!r}, username={self.username!r}, "
f"form_catalog={self.form_catalog!r}, employee_catalog={self.employee_catalog!r}, "
f"request_catalog={self.request_catalog!r}, node_catalog={self.node_catalog!r})"
)
def load_equipment_acceptance_sql_settings() -> EquipmentAcceptanceSqlSettings:
"""
读取同步连接配置。
核心逻辑:三个必填变量只认 OA_E10_SQLSERVER_*。库名覆盖可空,空则交给实例探测。
Returns:
EquipmentAcceptanceSqlSettings。
Raises:
ValidationError: 主机、账号或密码缺失。
"""
host = _cfg("OA_E10_SQLSERVER_HOST")
username = _cfg("OA_E10_SQLSERVER_USERNAME")
password = _cfg_raw("OA_E10_SQLSERVER_PASSWORD")
missing = [
key
for key, value in (
("OA_E10_SQLSERVER_HOST", host),
("OA_E10_SQLSERVER_USERNAME", username),
("OA_E10_SQLSERVER_PASSWORD", password),
)
if not str(value or "").strip()
]
if missing:
raise ValidationError(
"设备验收同步的 E10 数据库配置不完整",
code="EQUIPMENT_ACCEPTANCE.CONFIG_INVALID",
details={"missing": missing},
)
return EquipmentAcceptanceSqlSettings(
host=host,
port=_cfg("OA_E10_SQLSERVER_PORT") or "1433",
username=username,
password=password,
driver=_cfg("OA_E10_SQLSERVER_DRIVER"),
encrypt=(_cfg("OA_E10_SQLSERVER_ENCRYPT") or "no").lower(),
trust_cert=(_cfg("OA_E10_SQLSERVER_TRUST_CERT") or "yes").lower(),
timeout=_as_int(_cfg("OA_E10_SQLSERVER_TIMEOUT") or "60", 60),
form_catalog=_cfg("EQUIPMENT_ACCEPTANCE_FORM_CATALOG"),
employee_catalog=_cfg("EQUIPMENT_ACCEPTANCE_EMPLOYEE_CATALOG"),
request_catalog=_cfg("EQUIPMENT_ACCEPTANCE_REQUEST_CATALOG"),
node_catalog=_cfg("EQUIPMENT_ACCEPTANCE_NODE_CATALOG"),
)
def _cfg(key: str) -> str:
"""优先 Flask config,再读环境变量,并去掉首尾空白。"""
if has_app_context():
value = current_app.config.get(key)
if value is not None and str(value).strip():
return str(value).strip()
return str(os.getenv(key) or "").strip()
def _cfg_raw(key: str) -> str:
"""读取密码,保留中间空格。"""
if has_app_context():
value = current_app.config.get(key)
if value is not None and str(value) != "":
return str(value)
env = os.getenv(key)
if env is not None and env != "":
return env
return ""
def _as_int(raw: str, default: int) -> int:
"""超时秒数,非法时用默认值。"""
try:
return max(1, int(str(raw).strip() or default))
except (TypeError, ValueError):
return default
@@ -0,0 +1,243 @@
"""
backend/app/services/equipment_acceptance/snapshot_rules.py
用途:把 OA 原值收成同步快照上的监控状态和签核天数。
依赖:无。不读数据库,也不使用 isremark。
逻辑:同步服务对每一张验收单调用本模块。OA 的 0=是、1=否先翻成标准 0=否、1=是。
flowstatus 为 7、8、99、-99 时记为已撤销,不再提醒。
"""
from __future__ import annotations
from datetime import date, datetime
from typing import Any
NOT_STARTED = "not_started"
WATCHING = "watching"
STOPPED_CANNOT_ACCEPT = "stopped_cannot_accept"
STOPPED_RETURNED = "stopped_returned"
STOPPED_ARCHIVED = "stopped_archived"
STOPPED_FORCE_FINISHED = "stopped_force_finished"
STOPPED_VOIDED = "stopped_voided"
STOPPED_REVOKED = "stopped_revoked"
EXCLUDED = "excluded"
MONITOR_STATUSES = (
NOT_STARTED,
WATCHING,
STOPPED_CANNOT_ACCEPT,
STOPPED_RETURNED,
STOPPED_ARCHIVED,
STOPPED_FORCE_FINISHED,
STOPPED_VOIDED,
STOPPED_REVOKED,
EXCLUDED,
)
# 需求冻结的第 1 档是超过 30 天。列表上的「已逾期」按这一档判断,还没有发送记录。
FIRST_REMINDER_DAY = 30
_FLOW_APPROVING = 1
_FLOW_ARCHIVED = 3
_FLOW_FORCE_FINISHED = 4
_FLOW_VOIDED = 5
# 7、8、99 已确认按撤销停表。字典截断值是 -99,一并按撤销处理。
_REVOKED_FLOW = {7, 8, 99, -99}
_TERMINAL_FLOW = {_FLOW_ARCHIVED, _FLOW_FORCE_FINISHED, _FLOW_VOIDED, *_REVOKED_FLOW}
def as_int(value: Any) -> int | None:
"""
把 OA 数字收成 int。空值保持空。
核心逻辑:布尔值不是业务枚举;0 是有效取值,不能当成空。
Args:
value: 查询结果里的数字、数字字符串或空。
Returns:
整数或 None。
"""
if value is None or isinstance(value, bool):
return None
if isinstance(value, int):
return value
if isinstance(value, float):
if value != value:
return None
return int(value)
text = str(value).strip()
if not text:
return None
try:
return int(text)
except ValueError:
try:
number = float(text)
except ValueError:
return None
return int(number)
def as_date(value: Any) -> date | None:
"""
把 OA 日期收成 date。
核心逻辑:datetime 取日期部分;常见字符串只认日期前 10 位。
Args:
value: datetime、date 或字符串。
Returns:
date 或 None。
"""
if value is None or isinstance(value, bool):
return None
if isinstance(value, datetime):
return value.date()
if isinstance(value, date):
return value
text = str(value).strip()
if len(text) < 10:
return None
try:
return date.fromisoformat(text[:10])
except ValueError:
return None
def as_datetime(value: Any) -> datetime | None:
"""
把 OA 时间收成去掉时区的 datetime,供本地快照保存。
Args:
value: datetime 或可解析字符串。
Returns:
naive datetime 或 None。
"""
if value is None or isinstance(value, bool):
return None
if isinstance(value, datetime):
return value.replace(tzinfo=None)
if isinstance(value, date):
return datetime(value.year, value.month, value.day)
text = str(value).strip().replace("T", " ")
if not text:
return None
for fmt in ("%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d"):
try:
return datetime.strptime(text[:26], fmt)
except ValueError:
continue
parsed = as_date(text)
if parsed is None:
return None
return datetime(parsed.year, parsed.month, parsed.day)
def can_accept_from_oa(value: int | None) -> int | None:
"""
把 OA「是否可以正常验收」翻成标准布尔。
核心逻辑:OA sfkyzcys 是 0=是、1=否。本地 can_accept 用 0=否、1=是。
空值表示未标明,保持空,不收成否。0、1 以外的值原样留下,交给状态判断排除。
Args:
value: sfkyzcys 的整数。0 可以,1 不可以。
Returns:
1 表示可以验收,0 表示不可以,空保持空。
"""
# [STEP] OA 0=是、1=否,与本地 0=否、1=是对调。空不是「否」。
if value == 0:
return 1
if value == 1:
return 0
return value
def is_returned_from_oa(value: int | None) -> int | None:
"""
把 OA「是否退回」翻成标准布尔。
核心逻辑:OA sfzfth 是 0=是(退回),1=否(正常)。本地 is_returned 用 0=否、1=是。
空和 1 都已确认是未退回,所以空收成 0。0、1、空以外的值原样留下。
Args:
value: sfzfth 的整数。0 退回,1 和空为正常。
Returns:
1 表示已退回,0 表示未退回。
"""
# [STEP] OA 0=是、1=否,翻成 0=否、1=是。空按已确认口径当作未退回。
if value == 0:
return 1
if value in (1, None):
return 0
return value
def classify_monitor_status(
*,
can_accept: int | None,
is_returned: int | None,
flow_status: int | None,
timer_started: bool,
) -> str:
"""
按已确认规则给出监控状态。入参已是标准 0=否、1=是。
核心逻辑:退回、无法验收、作废、归档、强制结束、撤销优先于未开始。
审批中、可以验收、未退回、已有计时起点才是计时中。
flowstatus 为 7、8、99、-99 时记为已撤销,有没有计时起点都不再提醒。
Args:
can_accept: 本地是否可以正常验收。0 否,1 是,空为未标明。
is_returned: 本地是否退回。0 否,1 是。
flow_status: wfc_requestbase.flowstatus。
timer_started: sbsyrjssj 是否有值。
Returns:
MONITOR_STATUSES 中的一个代码。
"""
# [STEP 1] 表单上的停表原因优先于流程是否已经结束
if is_returned == 1:
return STOPPED_RETURNED
if can_accept == 0:
return STOPPED_CANNOT_ACCEPT
if flow_status == _FLOW_VOIDED:
return STOPPED_VOIDED
if flow_status == _FLOW_ARCHIVED:
return STOPPED_ARCHIVED
if flow_status == _FLOW_FORCE_FINISHED:
return STOPPED_FORCE_FINISHED
if flow_status in _REVOKED_FLOW:
return STOPPED_REVOKED
if not timer_started:
return NOT_STARTED
# [STEP 2] 只有审批中、可以验收、未退回时继续计时
if can_accept == 1 and flow_status == _FLOW_APPROVING and is_returned == 0:
return WATCHING
return EXCLUDED
def dwell_days(
*,
timer_started_at: datetime | date | None,
flow_status: int | None,
finished_at: datetime | date | None,
as_of: date,
) -> int | None:
"""
计算同步日看到的签核自然日。
核心逻辑:起点为空则没有天数。归档、强制结束、作废、撤销且有结束时间时,
截止到结束日,避免停表后每次同步继续加天。退回和无法验收没有结束时间,截止到同步日。
Args:
timer_started_at: sbsyrjssj。
flow_status: 流程状态原值。
finished_at: finishdatetime。
as_of: 同步当日,使用 Asia/Shanghai 的日期。
Returns:
非负天数;没有起点时为 None。
"""
start = as_date(timer_started_at)
if start is None:
return None
end = as_of
if flow_status in _TERMINAL_FLOW:
finished = as_date(finished_at)
if finished is not None:
end = finished if finished < as_of else as_of
if end < start:
return 0
return (end - start).days
@@ -0,0 +1,162 @@
"""
backend/app/services/equipment_acceptance/source_group.py
用途:把验收单联表的扁平行收成一张单一条草稿。
依赖:snapshot_rules。
逻辑:同步服务先分组再落库。是否可以验收、是否退回在这里从 OA 的 0=是、1=否
翻成标准 0=否、1=是。无法验收说明取 ycsm,不参与停表。操作人按节点和人员去重,不读 isremark。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
from app.services.equipment_acceptance.snapshot_rules import (
as_datetime,
as_int,
can_accept_from_oa,
is_returned_from_oa,
)
@dataclass
class OperatorDraft:
"""当前节点上的一名操作人。不带操作状态。"""
node_id: int
user_id: int
handler_name: str | None
handler_job_num: str | None
@dataclass
class NodeDraft:
"""一条当前节点。"""
node_id: int
node_name: str | None
node_type: int | None
@dataclass
class AcceptanceDraft:
"""一张验收单在一次同步中的快照草稿。不包含流程编号、第二合同编号和验收日期。"""
request_id: int
acceptance_no: str | None
purchase_order_no: str | None
contract_no: str | None
timer_started_at: datetime | None
can_accept: int | None
cannot_accept_note: str | None
is_returned: int | None
flow_status_raw: int | None
finished_at: datetime | None
request_match_count: int
owner_oa_id: int | None
owner_name: str | None
owner_job_num: str | None
equip_oa_id: int | None
equip_name: str | None
equip_job_num: str | None
applicant_oa_id: int | None
applicant_name: str | None
applicant_job_num: str | None
nodes: list[NodeDraft] = field(default_factory=list)
operators: list[OperatorDraft] = field(default_factory=list)
def group_acceptance_rows(rows: list[dict[str, Any]]) -> tuple[list[AcceptanceDraft], int]:
"""
按流程实例 requestid 合并联表结果。
核心逻辑:没有 requestid 的行跳过。同一请求上的节点和操作人收成一张单。
不读取流程编号、第二合同编号和验收日期。
Args:
rows: 查询别名组成的字典行。
Returns:
(草稿列表, 因缺少 requestid 而跳过的行数)。
"""
skipped = 0
buckets: dict[int, list[dict[str, Any]]] = {}
for row in rows:
request_id = as_int(row.get("requestid"))
if request_id is None:
skipped += 1
continue
buckets.setdefault(request_id, []).append(row)
return [_draft_from_rows(request_id, items) for request_id, items in buckets.items()], skipped
def _draft_from_rows(request_id: int, items: list[dict[str, Any]]) -> AcceptanceDraft:
"""同一流程实例的多行收成一条草稿。"""
header = items[0]
return AcceptanceDraft(
request_id=request_id,
acceptance_no=_text(header.get("ysddh")),
purchase_order_no=_text(header.get("cgdh")),
contract_no=_text(header.get("htbh")),
timer_started_at=as_datetime(header.get("sbsyrjssj")),
can_accept=can_accept_from_oa(as_int(header.get("sfkyzcys"))),
cannot_accept_note=_text(header.get("ycsm")),
is_returned=is_returned_from_oa(as_int(header.get("sfzfth"))),
flow_status_raw=as_int(header.get("flowstatus")),
finished_at=as_datetime(header.get("finishdatetime")),
request_match_count=1,
nodes=_nodes(items),
operators=_operators(items),
owner_oa_id=as_int(header.get("sybmdd")),
owner_name=_text(header.get("owner_name")),
owner_job_num=_text(header.get("owner_job_num")),
equip_oa_id=as_int(header.get("sbglry")),
equip_name=_text(header.get("equip_name")),
equip_job_num=_text(header.get("equip_job_num")),
applicant_oa_id=as_int(header.get("sqr")),
applicant_name=_text(header.get("applicant_name")),
applicant_job_num=_text(header.get("applicant_job_num")),
)
def _nodes(rows: list[dict[str, Any]]) -> list[NodeDraft]:
"""按节点 ID 去重,保留节点名称。"""
found: dict[int, NodeDraft] = {}
for row in rows:
node_id = as_int(row.get("nodeid"))
if node_id is None or node_id in found:
continue
found[node_id] = NodeDraft(
node_id=node_id,
node_name=_text(row.get("nodename")),
node_type=as_int(row.get("nodetype")),
)
return list(found.values())
def _operators(rows: list[dict[str, Any]]) -> list[OperatorDraft]:
"""按节点和人员去重。不读 isremark,同一人只留一行。"""
found: dict[tuple[int, int], OperatorDraft] = {}
for row in rows:
node_id = as_int(row.get("nodeid"))
user_id = as_int(row.get("userid"))
if node_id is None or user_id is None:
continue
key = (node_id, user_id)
if key in found:
continue
found[key] = OperatorDraft(
node_id=node_id,
user_id=user_id,
handler_name=_text(row.get("handler_name")),
handler_job_num=_text(row.get("handler_job_num")),
)
return list(found.values())
def _text(value: Any) -> str | None:
"""去空白;空串视为没有值。"""
if value is None:
return None
text = str(value).strip()
return text or None
@@ -0,0 +1,412 @@
"""
backend/app/services/equipment_acceptance/sync_service.py
用途:把 E10 验收单快照写入本地表,并提供管理员查询。
依赖:extensions.db、equipment_acceptance 模型、snapshot_rules、source_group、oa_repository。
逻辑:手动同步 upsert 主表并替换子表。列表按原型分组过滤,并附带全部单据的汇总。
停表时取消该单未发送的预警。操作人不保存 isremark。
"""
from __future__ import annotations
from collections import Counter
from datetime import datetime
from typing import Any
from zoneinfo import ZoneInfo
from app.core.errors import NotFoundError, ValidationError
from app.core.response import utc_iso
from app.extensions import db
from app.models.equipment_acceptance import (
EquipmentAcceptanceNode,
EquipmentAcceptanceOperator,
EquipmentAcceptanceOrder,
)
from app.services.equipment_acceptance.config_service import first_reminder_day
from app.services.equipment_acceptance.snapshot_rules import (
MONITOR_STATUSES,
classify_monitor_status,
dwell_days,
)
from app.services.equipment_acceptance.source_group import AcceptanceDraft, group_acceptance_rows
_SHANGHAI = ZoneInfo("Asia/Shanghai")
_LEDGER_FOCUSES = ("watching", "overdue", "stopped", "not_started")
_STOPPED_STATUSES = (
"stopped_returned",
"stopped_cannot_accept",
"stopped_archived",
"stopped_force_finished",
"stopped_voided",
"stopped_revoked",
)
def sync_acceptance_snapshots(rows: list[dict[str, Any]] | None = None) -> dict[str, Any]:
"""
同步验收单快照。
核心逻辑:未传入行时自己读 E10。按流程实例 request_id 更新主表,子表整批替换。
本次查询里消失的单据保留上次内容,只把 present_in_source 标成否。
Args:
rows: 测试或调用方已经取好的联表行。None 时访问 E10。
Returns:
本次写入条数、跳过条数、停表取消的未发送条数,以及各监控状态计数。
"""
if rows is None:
from app.services.equipment_acceptance.oa_repository import fetch_acceptance_rows
rows = fetch_acceptance_rows()
drafts, skipped = group_acceptance_rows(rows)
as_of = datetime.now(_SHANGHAI).date()
counts: Counter[str] = Counter()
request_ids: list[int] = []
cancelled = 0
for draft in drafts:
order, cancelled_now = _upsert_order(draft, as_of=as_of)
request_ids.append(order.request_id)
counts[order.monitor_status] += 1
cancelled += cancelled_now
absent = _mark_absent(request_ids)
db.session.commit()
return {
"upserted": len(drafts),
"skipped_without_request_id": skipped,
"absent": absent,
"cancelled": cancelled,
"by_status": dict(counts),
}
def list_acceptance_orders(
*,
monitor_status: str | None,
focus: str | None,
page: int,
page_size: int,
) -> dict[str, Any]:
"""
分页列出本地快照。
核心逻辑:focus 按原型的全部、进行中、已逾期、不再提醒、未开始过滤。
已逾期是计时中且签核天数超过第 1 档。汇总数字始终看全部单据。
Args:
monitor_status: 可选的单个监控状态代码。与 focus 同时传时以 focus 为准。
focus: watching、overdue、stopped、not_started 或空。
page: 从 1 开始。
page_size: 每页条数,上限 100。
Returns:
items、total、page、page_size、summary。
Raises:
ValidationError: focus 或监控状态不是已定义值。
"""
status = _clean_status(monitor_status)
ledger_focus = _clean_focus(focus)
reminder_day = first_reminder_day()
page = max(1, page)
page_size = min(100, max(1, page_size))
query = db.session.query(EquipmentAcceptanceOrder)
if ledger_focus:
query = _apply_focus(query, ledger_focus, reminder_day)
elif status:
query = query.filter(EquipmentAcceptanceOrder.monitor_status == status)
total = query.count()
orders = (
query.order_by(EquipmentAcceptanceOrder.synced_at.desc(), EquipmentAcceptanceOrder.id.desc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
order_ids = [order.id for order in orders]
nodes = _nodes_by_order(order_ids)
operators = _operators_by_order(order_ids)
pages = (total + page_size - 1) // page_size if total else 1
return {
"items": [
_order_payload(order, nodes.get(order.id, []), operators.get(order.id, []), reminder_day)
for order in orders
],
"total": total,
"page": page,
"page_size": page_size,
"pages": pages,
"summary": _ledger_summary(reminder_day),
}
def get_acceptance_order(order_id: int) -> dict[str, Any]:
"""
读取一张验收单快照,含当前节点和操作人原值。
Args:
order_id: 本地主键。
Returns:
快照详情。
Raises:
NotFoundError: 记录不存在。
"""
order = db.session.get(EquipmentAcceptanceOrder, order_id)
if order is None:
raise NotFoundError("设备验收同步记录不存在", code="EQUIPMENT_ACCEPTANCE.NOT_FOUND")
return _order_payload(
order,
_nodes_by_order([order.id]).get(order.id, []),
_operators_by_order([order.id]).get(order.id, []),
first_reminder_day(),
)
def _upsert_order(draft: AcceptanceDraft, *, as_of) -> tuple[EquipmentAcceptanceOrder, int]:
"""
按流程实例 request_id 更新主表,并替换该单的节点和操作人。
核心逻辑:不再计时的单据顺手取消未发送预警。已发送的记录不动。
Returns:
更新后的验收单,以及本次改成已取消的发送记录条数。
"""
order = (
db.session.query(EquipmentAcceptanceOrder)
.filter(EquipmentAcceptanceOrder.request_id == draft.request_id)
.one_or_none()
)
now = datetime.utcnow()
if order is None:
order = EquipmentAcceptanceOrder(
request_id=draft.request_id,
monitor_status="excluded",
synced_at=now,
created_at=now,
updated_at=now,
)
db.session.add(order)
db.session.flush()
order.acceptance_no = draft.acceptance_no
order.purchase_order_no = draft.purchase_order_no
order.contract_no = draft.contract_no
order.timer_started_at = draft.timer_started_at
order.can_accept = draft.can_accept
order.cannot_accept_note = draft.cannot_accept_note
order.is_returned = draft.is_returned
order.flow_status_raw = draft.flow_status_raw
order.finished_at = draft.finished_at
order.request_id = draft.request_id
order.request_match_count = draft.request_match_count
order.owner_oa_id = draft.owner_oa_id
order.owner_name = draft.owner_name
order.owner_job_num = draft.owner_job_num
order.equip_oa_id = draft.equip_oa_id
order.equip_name = draft.equip_name
order.equip_job_num = draft.equip_job_num
order.applicant_oa_id = draft.applicant_oa_id
order.applicant_name = draft.applicant_name
order.applicant_job_num = draft.applicant_job_num
order.monitor_status = classify_monitor_status(
can_accept=draft.can_accept,
is_returned=draft.is_returned,
flow_status=draft.flow_status_raw,
timer_started=draft.timer_started_at is not None,
)
order.dwell_days = dwell_days(
timer_started_at=draft.timer_started_at,
flow_status=draft.flow_status_raw,
finished_at=draft.finished_at,
as_of=as_of,
)
order.present_in_source = True
order.synced_at = now
order.updated_at = now
cancelled = 0
if order.monitor_status != "watching":
from app.services.equipment_acceptance.alert_service import cancel_unsent
cancelled = cancel_unsent(order.id)
# [STEP] 先从会话里删掉旧子行,再插入本次节点和操作人,避免批量 delete 后旧对象被重新写回
for node in db.session.query(EquipmentAcceptanceNode).filter(EquipmentAcceptanceNode.order_id == order.id).all():
db.session.delete(node)
for operator in (
db.session.query(EquipmentAcceptanceOperator)
.filter(EquipmentAcceptanceOperator.order_id == order.id)
.all()
):
db.session.delete(operator)
db.session.flush()
for node in draft.nodes:
db.session.add(
EquipmentAcceptanceNode(
order_id=order.id,
node_id=node.node_id,
node_name=node.node_name,
node_type=node.node_type,
)
)
for operator in draft.operators:
db.session.add(
EquipmentAcceptanceOperator(
order_id=order.id,
node_id=operator.node_id,
user_id=operator.user_id,
handler_name=operator.handler_name,
handler_job_num=operator.handler_job_num,
)
)
return order, cancelled
def _mark_absent(request_ids: list[int]) -> int:
"""把这次没拉到的单据标成源里不存在。"""
query = db.session.query(EquipmentAcceptanceOrder).filter(EquipmentAcceptanceOrder.present_in_source.is_(True))
if request_ids:
query = query.filter(EquipmentAcceptanceOrder.request_id.notin_(request_ids))
return query.update({EquipmentAcceptanceOrder.present_in_source: False}, synchronize_session=False)
def _clean_focus(focus: str | None) -> str | None:
"""空白视为全部。未知分组拒绝,避免把原型筛选项写错后悄悄查出空表。"""
value = str(focus or "").strip()
if not value or value == "all":
return None
if value not in _LEDGER_FOCUSES:
raise ValidationError(
"未知的设备验收列表分组",
code="EQUIPMENT_ACCEPTANCE.CONFIG_INVALID",
details={"focus": value},
)
return value
def _apply_focus(query, focus: str, reminder_day: int):
"""按停留列表分组过滤。已逾期只含计时中且超过当前第 1 档的单据。"""
if focus == "watching":
return query.filter(EquipmentAcceptanceOrder.monitor_status == "watching")
if focus == "not_started":
return query.filter(EquipmentAcceptanceOrder.monitor_status == "not_started")
if focus == "stopped":
return query.filter(EquipmentAcceptanceOrder.monitor_status.in_(_STOPPED_STATUSES))
return query.filter(
EquipmentAcceptanceOrder.monitor_status == "watching",
EquipmentAcceptanceOrder.dwell_days > reminder_day,
)
def _ledger_summary(reminder_day: int) -> dict[str, int]:
"""统计全部单据的进行中、已逾期、不再提醒、未开始,不受当前筛选影响。"""
base = db.session.query(EquipmentAcceptanceOrder)
return {
"watching": base.filter(EquipmentAcceptanceOrder.monitor_status == "watching").count(),
"overdue": base.filter(
EquipmentAcceptanceOrder.monitor_status == "watching",
EquipmentAcceptanceOrder.dwell_days > reminder_day,
).count(),
"stopped": base.filter(EquipmentAcceptanceOrder.monitor_status.in_(_STOPPED_STATUSES)).count(),
"not_started": base.filter(EquipmentAcceptanceOrder.monitor_status == "not_started").count(),
}
def _clean_status(monitor_status: str | None) -> str | None:
"""空白过滤视为不筛选。未知状态拒绝,避免把撤回等未定义值写进查询。"""
status = str(monitor_status or "").strip()
if not status:
return None
if status not in MONITOR_STATUSES:
raise ValidationError(
"未知的设备验收监控状态",
code="EQUIPMENT_ACCEPTANCE.CONFIG_INVALID",
details={"monitor_status": status},
)
return status
def _nodes_by_order(order_ids: list[int]) -> dict[int, list[EquipmentAcceptanceNode]]:
"""一次取出当前页的节点,避免逐单查询。"""
if not order_ids:
return {}
grouped: dict[int, list[EquipmentAcceptanceNode]] = {}
rows = (
db.session.query(EquipmentAcceptanceNode)
.filter(EquipmentAcceptanceNode.order_id.in_(order_ids))
.order_by(EquipmentAcceptanceNode.id.asc())
.all()
)
for row in rows:
grouped.setdefault(row.order_id, []).append(row)
return grouped
def _operators_by_order(order_ids: list[int]) -> dict[int, list[EquipmentAcceptanceOperator]]:
"""一次取出当前页的操作人,避免逐单查询。"""
if not order_ids:
return {}
grouped: dict[int, list[EquipmentAcceptanceOperator]] = {}
rows = (
db.session.query(EquipmentAcceptanceOperator)
.filter(EquipmentAcceptanceOperator.order_id.in_(order_ids))
.order_by(EquipmentAcceptanceOperator.id.asc())
.all()
)
for row in rows:
grouped.setdefault(row.order_id, []).append(row)
return grouped
def _order_payload(
order: EquipmentAcceptanceOrder,
nodes: list[EquipmentAcceptanceNode],
operators: list[EquipmentAcceptanceOperator],
reminder_day: int,
) -> dict[str, Any]:
"""把快照收成 API 数据。人员主键用字符串,避免长整型在前端丢精度。overdue 只标记计时中且超过第 1 档的单据。"""
payload: dict[str, Any] = {
"id": order.id,
"acceptance_no": order.acceptance_no,
"purchase_order_no": order.purchase_order_no,
"contract_no": order.contract_no,
"timer_started_at": utc_iso(order.timer_started_at),
"dwell_days": order.dwell_days,
"can_accept": order.can_accept,
"cannot_accept_note": order.cannot_accept_note,
"is_returned": order.is_returned,
"flow_status_raw": order.flow_status_raw,
"finished_at": utc_iso(order.finished_at),
"request_id": _id_text(order.request_id),
"request_match_count": order.request_match_count,
"owner_oa_id": _id_text(order.owner_oa_id),
"owner_name": order.owner_name,
"owner_job_num": order.owner_job_num,
"equip_oa_id": _id_text(order.equip_oa_id),
"equip_name": order.equip_name,
"equip_job_num": order.equip_job_num,
"applicant_oa_id": _id_text(order.applicant_oa_id),
"applicant_name": order.applicant_name,
"applicant_job_num": order.applicant_job_num,
"monitor_status": order.monitor_status,
"overdue": order.monitor_status == "watching" and (order.dwell_days or 0) > reminder_day,
"present_in_source": order.present_in_source,
"synced_at": utc_iso(order.synced_at),
"nodes": [
{
"node_id": _id_text(node.node_id),
"node_name": node.node_name,
"node_type": node.node_type,
}
for node in nodes
],
"operators": [
{
"node_id": _id_text(item.node_id),
"user_id": _id_text(item.user_id),
"handler_name": item.handler_name,
"handler_job_num": item.handler_job_num,
}
for item in operators
],
}
return payload
def _id_text(value: int | None) -> str | None:
"""OA 长整型主键序列化成字符串。"""
if value is None:
return None
return str(value)
+114 -32
View File
@@ -2,11 +2,14 @@
backend/app/services/faq_cache.py backend/app/services/faq_cache.py
用途:全局常用问题 FAQ 缓存匹配与 SSE 直答,避免重复调用 Dify。 用途:全局常用问题 FAQ 缓存匹配与 SSE 直答,避免重复调用 Dify。
依赖:models.QuickQuestion、ChatLog、SQLAlchemy db。 依赖:models.QuickQuestion、ChatLog、SQLAlchemy db、faq_text_utils(归一化与模糊评分)。
逻辑:chat.py 在调用 DifyService 前委托本模块 try_match(只看 cache_enabled,不看首页展示 is_enabled);命中则 stream_chat 返回预置答案。 逻辑:chat router 在调用 DifyService 前委托本模块 try_match(只看 cache_enabled,不看首页展示 is_enabled)。
匹配分两阶段:[STEP 1] 归一化精确命中(所有启用缓存的条目);[STEP 2] 模糊兜底
(仅 fuzzy_enabled 条目,得分达该条目阈值才命中),命中后 stream_chat 返回预置答案。
""" """
import json import json
import time import time
from dataclasses import dataclass
from datetime import datetime from datetime import datetime
from typing import Any, Optional from typing import Any, Optional
@@ -14,7 +17,26 @@ from flask import current_app
from app import db from app import db
from app.models import ChatLog, QuickQuestion from app.models import ChatLog, QuickQuestion
from app.services.faq_text_utils import normalize_faq_query from app.services.faq_text_utils import (
FUZZY_MIN_LENGTH,
clamp_fuzzy_threshold,
fuzzy_match_score,
normalize_faq_query,
)
# 命中类型(写入 ChatLog payload 与 SSE metadata,供审计与排障)
MATCH_TYPE_EXACT = 'exact'
MATCH_TYPE_FUZZY = 'fuzzy'
@dataclass(frozen=True)
class FaqCacheMatch:
"""FAQ 缓存命中结果:条目本体 + 命中方式审计信息。"""
entry: QuickQuestion
match_type: str # 'exact' 归一化全等;'fuzzy' 模糊兜底
match_score: Optional[float] = None
matched_text: Optional[str] = None
class FaqCacheService: class FaqCacheService:
@@ -43,33 +65,48 @@ class FaqCacheService:
return expires_at <= datetime.utcnow() return expires_at <= datetime.utcnow()
@staticmethod @staticmethod
def _candidate_texts(entry: QuickQuestion) -> list[str]: def _candidate_pairs(entry: QuickQuestion) -> list[tuple[str, str]]:
""" """
收集条目可用于匹配的标准化文本集合。 收集条目可用于匹配的 (原文, 归一化文本) 对。
核心逻辑:候选来源为 question、title 与 aliases;原文用于审计展示,归一化文本用于比对。
@param entry - QuickQuestion 实例 @param entry - QuickQuestion 实例
@returns 归一化后的候选文本列表 @returns (原文, 归一化文本) 列表
""" """
texts: list[str] = [] pairs: list[tuple[str, str]] = []
for raw in (entry.question, entry.title): for raw in (entry.question, entry.title):
normalized = FaqCacheService._normalize_text(raw) normalized = FaqCacheService._normalize_text(raw)
if normalized: if normalized:
texts.append(normalized) pairs.append((str(raw), normalized))
aliases = entry.aliases if isinstance(entry.aliases, list) else [] aliases = entry.aliases if isinstance(entry.aliases, list) else []
for alias in aliases: for alias in aliases:
normalized = FaqCacheService._normalize_text(str(alias)) normalized = FaqCacheService._normalize_text(str(alias))
if normalized: if normalized:
texts.append(normalized) pairs.append((str(alias), normalized))
return texts return pairs
@staticmethod @staticmethod
def try_match(query: str, agent_id: int) -> Optional[QuickQuestion]: def _candidate_texts(entry: QuickQuestion) -> list[str]:
""" """
尝试为指定 Agent 命中全局 FAQ 缓存条目。 收集条目可用于匹配的标准化文本集合。
核心逻辑:加载 cache_enabled 的全局条目,对 question/title/aliases 做归一化精确匹配。 核心逻辑:委托 _candidate_pairs 取归一化列;热点聚合(hot_faq_aggregator)依赖本方法做去重比对。
@param entry - QuickQuestion 实例
@returns 归一化后的候选文本列表
"""
return [normalized for _, normalized in FaqCacheService._candidate_pairs(entry)]
@staticmethod
def try_match(query: str, agent_id: int) -> Optional[FaqCacheMatch]:
"""
尝试为指定 Agent 命中全局 FAQ 缓存条目(两阶段)。
核心逻辑:
[STEP 1] 精确阶段——所有 cache_enabled 条目的 question/title/aliases 归一化后与输入全等比对;
[STEP 2] 模糊兜底——精确未命中且输入长度达 FUZZY_MIN_LENGTH 时,仅对 fuzzy_enabled 条目
计算 fuzzy_match_score,最高分达到该条目阈值(钳制在 0.5~1.0)才命中;
同分时先出现的条目(sort_order 靠前)胜出。
is_enabled 只控制工作台首页是否展示快捷入口,不影响本方法是否直答。 is_enabled 只控制工作台首页是否展示快捷入口,不影响本方法是否直答。
@param query - 用户提问 @param query - 用户提问
@param agent_id - 当前 Agent 主键 @param agent_id - 当前 Agent 主键
@returns 命中的 QuickQuestion;未命中返回 None @returns FaqCacheMatch;未命中返回 None
""" """
normalized_query = FaqCacheService._normalize_text(query) normalized_query = FaqCacheService._normalize_text(query)
if not normalized_query or not agent_id: if not normalized_query or not agent_id:
@@ -89,12 +126,50 @@ class FaqCacheService:
.all() .all()
) )
# [STEP 1] 精确命中:归一化后全等,任何启用缓存的条目参与
for entry in entries: for entry in entries:
if FaqCacheService._is_expired(entry): if FaqCacheService._is_expired(entry):
continue continue
if normalized_query in FaqCacheService._candidate_texts(entry): for raw, normalized in FaqCacheService._candidate_pairs(entry):
return entry if normalized_query == normalized:
return None return FaqCacheMatch(
entry=entry, match_type=MATCH_TYPE_EXACT, match_score=1.0, matched_text=raw
)
# [STEP 2] 模糊兜底:仅参与模糊开关打开的条目,取最高分;短问句不参与
if len(normalized_query) < FUZZY_MIN_LENGTH:
return None
best: Optional[FaqCacheMatch] = None
for entry in entries:
if not entry.fuzzy_enabled:
continue
if FaqCacheService._is_expired(entry):
continue
threshold = clamp_fuzzy_threshold(entry.fuzzy_threshold)
for raw, normalized in FaqCacheService._candidate_pairs(entry):
if len(normalized) < FUZZY_MIN_LENGTH:
continue
score = fuzzy_match_score(normalized_query, normalized)
if score >= threshold and (best is None or score > (best.match_score or 0.0)):
best = FaqCacheMatch(
entry=entry, match_type=MATCH_TYPE_FUZZY, match_score=score, matched_text=raw
)
return best
@staticmethod
def _match_audit_fields(match: Optional[FaqCacheMatch]) -> dict[str, Any]:
"""
构造命中方式的审计字段,写入 ChatLog payload 与 SSE metadata。
@param match - try_match 的命中结果;可为 None(历史调用方未传)
@returns 含 match_type / match_score / matched_text 的字典
"""
if match is None:
return {}
return {
'match_type': match.match_type,
'match_score': round(match.match_score, 4) if match.match_score is not None else None,
'matched_text': match.matched_text,
}
@staticmethod @staticmethod
def _increment_hit_count(entry_id: int) -> None: def _increment_hit_count(entry_id: int) -> None:
@@ -124,28 +199,38 @@ class FaqCacheService:
agent, agent,
conversation_id: str | None = None, conversation_id: str | None = None,
session_id: str | None = None, session_id: str | None = None,
match: Optional[FaqCacheMatch] = None,
): ):
""" """
以 SSE 形式返回 FAQ 预置答案,并写入 ChatLog。 以 SSE 形式返回 FAQ 预置答案,并写入 ChatLog。
核心逻辑:产出 message + message_end 事件,标记 payload.source=faq_cache。 核心逻辑:产出 message + message_end 事件,标记 payload.source=faq_cache;
match 非空时附带 match_type / match_score / matched_text 供审计与排障。
@param entry - 命中的 QuickQuestion @param entry - 命中的 QuickQuestion
@param query - 用户原始提问 @param query - 用户原始提问
@param user - 当前用户代理对象(需含 id) @param user - 当前用户代理对象(需含 id)
@param agent - 当前 Agent 代理对象(需含 id) @param agent - 当前 Agent 代理对象(需含 id)
@param conversation_id - Dify/外部会话 ID @param conversation_id - Dify/外部会话 ID
@param session_id - 本地会话 ID @param session_id - 本地会话 ID
@param match - try_match 的命中结果;历史调用方可不传
@yields SSE 格式字符串 @yields SSE 格式字符串
""" """
start_time = time.time() start_time = time.time()
final_conversation_id = conversation_id or f"faq_{int(time.time())}" final_conversation_id = conversation_id or f"faq_{int(time.time())}"
answer = str(entry.answer or "").strip() answer = str(entry.answer or "").strip()
retriever_resources = entry.retriever_resources if isinstance(entry.retriever_resources, list) else [] retriever_resources = entry.retriever_resources if isinstance(entry.retriever_resources, list) else []
audit_fields = FaqCacheService._match_audit_fields(match)
yield f"data: {json.dumps({'event': 'message', 'answer': answer}, ensure_ascii=False)}\n\n" yield f"data: {json.dumps({'event': 'message', 'answer': answer}, ensure_ascii=False)}\n\n"
latency = int((time.time() - start_time) * 1000) latency = int((time.time() - start_time) * 1000)
chat_log_id = None chat_log_id = None
try: try:
payload: dict[str, Any] = {
'source': 'faq_cache',
'faq_id': entry.id,
'faq_title': entry.title,
}
payload.update(audit_fields)
chat_log = ChatLog( chat_log = ChatLog(
user_id=user.id, user_id=user.id,
agent_id=agent.id, agent_id=agent.id,
@@ -156,11 +241,7 @@ class FaqCacheService:
tokens_used=0, tokens_used=0,
latency=latency, latency=latency,
retriever_resources=retriever_resources, retriever_resources=retriever_resources,
payload={ payload=payload,
"source": "faq_cache",
"faq_id": entry.id,
"faq_title": entry.title,
},
) )
db.session.add(chat_log) db.session.add(chat_log)
db.session.commit() db.session.commit()
@@ -173,15 +254,16 @@ class FaqCacheService:
FaqCacheService._increment_hit_count(entry.id) FaqCacheService._increment_hit_count(entry.id)
end_data: dict[str, Any] = { end_data: dict[str, Any] = {
"event": "message_end", 'event': 'message_end',
"answer": answer, 'answer': answer,
"replace_answer": True, 'replace_answer': True,
"chat_log_id": chat_log_id, 'chat_log_id': chat_log_id,
"conversation_id": final_conversation_id, 'conversation_id': final_conversation_id,
"metadata": { 'metadata': {
"retriever_resources": retriever_resources, 'retriever_resources': retriever_resources,
"source": "faq_cache", 'source': 'faq_cache',
"faq_id": entry.id, 'faq_id': entry.id,
**audit_fields,
}, },
} }
if retriever_resources: if retriever_resources:
+45 -4
View File
@@ -1,11 +1,19 @@
""" """
backend/app/services/faq_text_utils.py backend/app/services/faq_text_utils.py
用途:FAQ / 热点问句归一化等纯文本工具,供 faq_cache 与 hot_faq_aggregator 共用。 用途:FAQ / 热点问句归一化、模糊相似度评分等纯文本工具,供 faq_cache 与 hot_faq_aggregator 共用。
依赖:无外部业务模块。 依赖:difflib(Python 标准库,无第三方依赖)。
逻辑:保证离线聚合与在线命中使用同一 normalize 规则。 逻辑:保证离线聚合与在线命中使用同一 normalize 规则;模糊评分供 FAQ 兜底直答使用。
""" """
import re import re
from difflib import SequenceMatcher
# 模糊兜底参与的最低归一化长度:过短问句(如「帮助」)误命中代价高,只走精确匹配。
FUZZY_MIN_LENGTH = 4
# 模糊阈值的安全钳制区间与默认值:下限防止管理员设得过低导致大面积误直答。
FUZZY_THRESHOLD_MIN = 0.5
FUZZY_THRESHOLD_MAX = 1.0
FUZZY_THRESHOLD_DEFAULT = 0.8
def normalize_faq_query(text: str) -> str: def normalize_faq_query(text: str) -> str:
@@ -16,5 +24,38 @@ def normalize_faq_query(text: str) -> str:
@returns 归一化后的字符串;空输入返回空串 @returns 归一化后的字符串;空输入返回空串
""" """
value = str(text or "").strip().lower() value = str(text or "").strip().lower()
value = re.sub(r"[\s\u3000,。!?、;:""''()()\[\]【】\-—·,.!?;:'\"]+", "", value) value = re.sub(r"[\s\u3000,。!?、;:“”‘’()()\[\]【】\-—·,.!?;:'\"]+", "", value)
return value return value
def clamp_fuzzy_threshold(value) -> float:
"""
将模糊匹配阈值钳制到安全区间 [0.5, 1.0]。
核心逻辑:空值/非法值回退默认 0.8,越界值收敛到边界,保证在线匹配不会因配置异常失真。
@param value - 数据库或请求体中的阈值原始值
@returns 钳制后的浮点阈值
"""
try:
threshold = float(value)
except (TypeError, ValueError):
return FUZZY_THRESHOLD_DEFAULT
return min(FUZZY_THRESHOLD_MAX, max(FUZZY_THRESHOLD_MIN, threshold))
def fuzzy_match_score(query: str, candidate: str) -> float:
"""
计算两段归一化问句的模糊相似度得分(0~1),供 FAQ 模糊兜底匹配使用。
核心逻辑:取编辑距离类相似度(SequenceMatcher.ratio)与包含覆盖率的最大值——
前者容忍换字/错字(能→可以),后者容忍加前后缀(我还能问什么 vs 还能问什么);
真问题偶含候选短语时(如「怎么用你查MES服务器」vs「怎么用你」)覆盖率很低,不会误命中。
@param query - 归一化后的用户问句
@param candidate - 归一化后的候选问句(标题/标准问句/同义问法)
@returns 0~1 之间的相似度得分
"""
if not query or not candidate:
return 0.0
score = SequenceMatcher(None, query, candidate).ratio()
if query in candidate or candidate in query:
coverage = min(len(query), len(candidate)) / max(len(query), len(candidate))
score = max(score, coverage)
return score
+113 -8
View File
@@ -3,7 +3,10 @@ backend/app/services/file_assets/storage.py
用途:私有 MinIO 业务文件存储适配层(与 agent-guides 公开 bucket 隔离)。 用途:私有 MinIO 业务文件存储适配层(与 agent-guides 公开 bucket 隔离)。
依赖:minio、app.core.config.settings、app.core.errors.ServiceUnavailableError。 依赖:minio、app.core.config.settings、app.core.errors.ServiceUnavailableError。
逻辑:由 file_assets.service 调用;禁止 public-read policy 与本地静默回退;读写删失败统一抛 503。 逻辑:由 file_assets.service 与调拨证据清单调用;禁止 public-read policy 与本地静默回退;
读写删走 MINIO_ENDPOINT(容器内网)。浏览器预签走 MINIO_PUBLIC_BASE_URL,
因为签名包含 Host,不能把 host.docker.internal 交给浏览器后再替换。
读写删失败统一抛 503。预签下载可附带 response-content-disposition,避免保存名落成对象键。
""" """
from __future__ import annotations from __future__ import annotations
@@ -12,6 +15,7 @@ import io
import logging import logging
from datetime import timedelta from datetime import timedelta
from typing import BinaryIO from typing import BinaryIO
from urllib.parse import urlparse
from minio import Minio from minio import Minio
from minio.error import S3Error from minio.error import S3Error
@@ -23,16 +27,75 @@ _LOGGER = logging.getLogger(__name__)
_cfg = config[ACTIVE_ENV_NAME] _cfg = config[ACTIVE_ENV_NAME]
def resolve_presign_endpoint(
public_base: str,
fallback_endpoint: str,
fallback_secure: bool,
) -> tuple[str, bool]:
"""把浏览器可访问的 MinIO 基址收成预签名客户端的 endpoint 与 secure。
核心逻辑:SigV4 把 Host 写进签名。正式环境容器用 host.docker.internal:9000
读写,浏览器必须打开 MINIO_PUBLIC_BASE_URL(如 http://ai.well-trust.com:9000)。
基址为空或解析不出主机时退回内网端点。80/443 省略端口,交给 Minio 客户端按协议补。
Args:
public_base: MINIO_PUBLIC_BASE_URL,可带或不带协议。
fallback_endpoint: 容器内访问用的 host:port。
fallback_secure: 内网端点是否走 HTTPS。
Returns:
(endpoint, secure)。endpoint 形如 ai.well-trust.com:9000。
"""
raw = (public_base or "").strip()
if not raw:
return fallback_endpoint, fallback_secure
parsed = urlparse(raw if "://" in raw else f"http://{raw}")
host = parsed.hostname
if not host:
return fallback_endpoint, fallback_secure
if ":" in host:
host = f"[{host}]"
secure = parsed.scheme.lower() == "https"
port = parsed.port
if port and not ((secure and port == 443) or (not secure and port == 80)):
return f"{host}:{port}", secure
return host, secure
class FileAssetStorage: class FileAssetStorage:
"""私有业务文件 MinIO 存储客户端。""" """私有业务文件 MinIO 存储客户端。"""
def __init__(self) -> None: def __init__(self) -> None:
"""分别建立内网读写客户端与浏览器预签名客户端。
核心逻辑:两端点主机与协议相同时共用一个客户端。预签名客户端只在
生成 URL 时做本地签名,不靠它访问内网 MinIO。
"""
endpoint = str(_cfg.MINIO_ENDPOINT or "").strip()
access_key = _cfg.MINIO_ACCESS_KEY
secret_key = _cfg.MINIO_SECRET_KEY
secure = bool(_cfg.MINIO_SECURE)
self.client = Minio( self.client = Minio(
_cfg.MINIO_ENDPOINT, endpoint,
access_key=_cfg.MINIO_ACCESS_KEY, access_key=access_key,
secret_key=_cfg.MINIO_SECRET_KEY, secret_key=secret_key,
secure=_cfg.MINIO_SECURE, secure=secure,
) )
# [STEP 1] 预签名单独用浏览器主机。只改 URL 字符串会使签名失效。
presign_endpoint, presign_secure = resolve_presign_endpoint(
str(_cfg.MINIO_PUBLIC_BASE_URL or ""),
endpoint,
secure,
)
if presign_endpoint == endpoint and presign_secure == secure:
self.presign_client = self.client
else:
self.presign_client = Minio(
presign_endpoint,
access_key=access_key,
secret_key=secret_key,
secure=presign_secure,
)
self.bucket_name = str(_cfg.MINIO_FILE_ASSETS_BUCKET or 'hxops-file-assets').strip() self.bucket_name = str(_cfg.MINIO_FILE_ASSETS_BUCKET or 'hxops-file-assets').strip()
def _ensure_bucket_exists(self) -> None: def _ensure_bucket_exists(self) -> None:
@@ -119,13 +182,55 @@ class FileAssetStorage:
except S3Error: except S3Error:
return False return False
def presigned_get_url(self, storage_key: str, *, expires_seconds: int) -> str: def _bind_presign_region(self) -> None:
"""生成短期受控下载 URL。""" """把内网客户端已探到的 region 抄给预签名客户端。
核心逻辑:minio-py 在签名前会请求 GetBucketLocation。若用公网客户端发这次请求,
容器里可能访问不到浏览器入口,或每次下载多一次公网探测。
bucket 检查已经通过内网客户端写入 _region_map;这里只复用该结果。
尚未探测到时用 MinIO 默认 us-east-1。
"""
if self.presign_client is self.client:
return
region = self.client._region_map.get(self.bucket_name) or "us-east-1"
self.presign_client._region_map[self.bucket_name] = region
def presigned_get_url(
self,
storage_key: str,
*,
expires_seconds: int,
download_name: str | None = None,
) -> str:
"""生成短期受控下载 URL。
核心逻辑:先把内网探到的 region 绑到 presign_client,再用它签名。
主机来自 MINIO_PUBLIC_BASE_URL。签名在本地完成,不再向公网探测 bucket 区域。
对象键常为内容哈希,浏览器会把它当成保存名。
download_name 非空时把 response-content-disposition 签进 URL,
让保存对话框使用业务文件名。预览地址不要传这个参数。
Args:
storage_key: MinIO 对象键。
expires_seconds: 链接有效秒数,短于 60 秒时抬到 60。
download_name: 附件保存名;只接受调用方已洗净的文件名。
Returns:
带过期签名的 GET URL,主机是浏览器可访问的 MinIO 地址。
"""
self._ensure_bucket_exists() self._ensure_bucket_exists()
return self.client.presigned_get_object( self._bind_presign_region()
response_headers = None
if download_name:
safe = download_name.replace('"', '').replace('\\', '').replace('\r', '').replace('\n', '')
response_headers = {
'response-content-disposition': f'attachment; filename="{safe}"',
}
return self.presign_client.presigned_get_object(
self.bucket_name, self.bucket_name,
storage_key, storage_key,
expires=timedelta(seconds=max(int(expires_seconds or 60), 60)), expires=timedelta(seconds=max(int(expires_seconds or 60), 60)),
response_headers=response_headers,
) )
@@ -0,0 +1 @@
"""货代 RPA 模块根:承载 freight_rpa 域代码(common/onhand/inbound/upload)。"""
@@ -0,0 +1 @@
"""common:域中立件(跨 RPA Worker 共用、不依赖具体业务域)。"""
@@ -0,0 +1,58 @@
"""
services/freight_rpa/common/callback_sinks.py
用途:RPA 回调「进度类」sink 注册表——freight_rpa 侧的回调分发缝(批次 B Task 6 起
与文件事实分发分工:文件/报表就绪类回调走 freight_rpa.reports.dispatch.
dispatch_report_fact——归档入口先 db.session.commit() 再投递 ReportFact,
kind 未注册同样 404 FREIGHT_RPA.SINK_NOT_REGISTERED;进度类 kind
(inbound-unit-progress / inbound-batch-progress / onhand-batch-claimed 等)
仍走本模块的 register_sink / dispatch_sink,不改 envelope)。
依赖:app.core.errors.AppError。
逻辑:Worker 回调进入 /api/freight-rpa/* 蓝图后,进度类端点按 kind 分发到
组合根(create_app / api 层)注册的业务处理器;未注册的 kind 显式 404,
绝不静默吞回调。Task 9/10 落地 workflow_protocol / report_archive 时由
组合根调用 register_sink 注入真实业务持久化处理器。
"""
from __future__ import annotations
from typing import Any, Callable
from app.core.errors import AppError
_SINKS: dict[str, Callable[..., Any]] = {}
def register_sink(kind: str, handler: Callable[..., Any]) -> None:
"""
注册一个回调 sink 处理器(由组合根在应用启动时调用)。
Args:
kind: 回调种类,命名 = 回调路由名去前缀(如 "onhand-ready"、
"onhand-configuration-test-complete");同一 kind 重复注册为覆盖。
handler: 业务处理器;契约:接收回调载荷的关键字参数并返回可 jsonify 的业务结果。
"""
_SINKS[kind] = handler
def dispatch_sink(kind: str, **payload: Any) -> Any:
"""
按 kind 分发回调载荷到已注册 sink。
Args:
kind: register_sink 注册过的回调种类。
payload: 回调载荷键值对;键必须为合法 Python 标识符(回调 schema 均为 snake_case)。
Returns:
handler 的返回值(业务结果 dict,由蓝图 jsonify)。
Raises:
AppError: code=FREIGHT_RPA.SINK_NOT_REGISTERED、http_status=404——kind 未注册时
显式失败(Task 9/10 注册真实 sink 前的既定语义)。
"""
handler = _SINKS.get(kind)
if handler is None:
raise AppError(
code='FREIGHT_RPA.SINK_NOT_REGISTERED',
message=f'No callback sink registered for kind: {kind}',
http_status=404,
)
return handler(**payload)
@@ -1,10 +1,11 @@
""" """
services/shipping_notice/credential_crypto.py services/freight_rpa/common/credential_crypto.py
用途:加密和解密库存 RPA Profile 的登录凭据(委托通用 core 模块,仅固定本域密钥键与错误码)。 用途:加密和解密库存 RPA Profile 的登录凭据(委托通用 core 模块,仅固定本域密钥键与错误码)。
依赖:app.core.credential_crypto(Fernet 加解密);调用方仅保存密文,不将凭据写入日志或 API 响应。 依赖:app.core.credential_crypto(Fernet 加解密);调用方仅保存密文,不将凭据写入日志或 API 响应。
逻辑:管理服务写入 Profile 前调用 encrypt_credential;RPA 配置读取服务在受控内存中调用 逻辑:管理服务写入 Profile 前调用 encrypt_credential;管理端读取 Profile 时只解密用户名用于展示;
decrypt_credential。主密钥键 FREIGHT_RPA_CREDENTIAL_KEY(2026-09-18 RPA 命名空间)。 密码仅在 RPA 执行内存中调用 decrypt_credential。密码与密文不得进入 API 响应或日志。
主密钥键 FREIGHT_RPA_CREDENTIAL_KEY(2026-09-18 RPA 命名空间)。
""" """
from __future__ import annotations from __future__ import annotations
@@ -48,7 +49,7 @@ def decrypt_credential(ciphertext: str) -> str:
ciphertext: 数据库中保存的 Fernet 密文。 ciphertext: 数据库中保存的 Fernet 密文。
Returns: Returns:
str: 仅供 RPA 执行内存使用的明文。 str: 明文。密码只留在 RPA 执行内存;用户名可由管理端 Profile 接口返回。禁止写入日志。
Raises: Raises:
ServiceUnavailableError: 未配置或配置了无效的主密钥。 ServiceUnavailableError: 未配置或配置了无效的主密钥。
@@ -0,0 +1,384 @@
"""freight_rpa/common/report_audit.py
用途:货代 RPA 域(inbound 回调归档、保留期清理、通知投递)写入
ShippingAuditEvent 统一审计账本的唯一入口(批次 B Task 6)。
依赖:app.models.ShippingAuditEvent(允许 import 模型)、app.core.errors.
ValidationError、SQLAlchemy 会话(app.db)。
逻辑:替代此前对 app.services.shipping_notice.audit_service 的依赖——freight_rpa
包禁止 import app.services.shipping_notice.*(import 边界由 tests/services/
freight_rpa/test_import_boundary.py 的空白名单锁定),故本模块以与
append_shipping_audit_event 相同的关键字面直接写同一个 ShippingAuditEvent
模型,事件名(shipping_inbound_rpa_callback_received /
shipping_inbound_report_archived 等)与聚合键保持不变,避免审计查询断档。
与 audit_service 的有意差异(均为本域受控场景):
(1)before/after 快照不做白名单投影——本域快照键均为受控诊断键
(status/error_code/sha256/file_size 等),原样入 snapshot 列;
(2)不做 XFA 加密完整快照(本域无敏感完整载荷);
(3)保留期恒为 None(货代统一审计账本永久保留);
(4)event_hash 以本地稳定哈希对核心字段集合计算,previous_event_hash
取同聚合最新一条已 flush 事件的 event_hash(链结构与 audit_service 同构)。
本模块不提交事务,由调用方与业务写入同一事务提交;写入失败时业务不得 commit。
"""
from __future__ import annotations
import hashlib
import json
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import ValidationError
from app.models import ShippingAuditEvent
# 与 audit_service 同源的 actor/result 白名单(模型 CHECK 约束同集)。
_ALLOWED_ACTOR_TYPES = frozenset({'user', 'system', 'rpa', 'chatflow', 'admin', 'worker'})
_ALLOWED_RESULTS = frozenset({'success', 'failure', 'rejected', 'ignored'})
# 审计元数据/快照禁止键本地冻结子集(凭据 / 正文 / URL 类;自
# shipping_notice.progress_audit_contract.AUDIT_FORBIDDEN_KEYS 裁剪,仅供本域防呆)。
_FORBIDDEN_AUDIT_KEYS = frozenset({
'api_key',
'api_base_url',
'authorization',
'body',
'content',
'document_text',
'email_body',
'minio',
'object_key',
'object_url',
'password',
'prompt',
'provider_config',
'quote',
'raw_content',
'raw_output',
'secret',
'token',
'url',
'user_agent',
})
def _is_forbidden_audit_key(key: str) -> bool:
"""键名大小写不敏感命中本地禁止键集合(与 audit_service 判定同构)。"""
return str(key or '').strip().lower() in _FORBIDDEN_AUDIT_KEYS
def _collect_forbidden_keys(payload: Any, *, path: str = '') -> list[str]:
"""
递归收集命中敏感黑名单的键路径(dict/list 均遍历,嵌套路径稳定拼接)。
Returns:
命中键路径列表(调用方排序后入 ValidationError.details)。
"""
found: list[str] = []
if isinstance(payload, dict):
for key, child in payload.items():
key_text = str(key)
child_path = f'{path}.{key_text}' if path else key_text
if _is_forbidden_audit_key(key_text):
found.append(child_path)
found.extend(_collect_forbidden_keys(child, path=child_path))
elif isinstance(payload, list):
for index, child in enumerate(payload):
found.extend(_collect_forbidden_keys(child, path=f'{path}[{index}]'))
return found
def _sanitize_metadata(metadata: dict[str, Any] | None) -> dict[str, Any]:
"""验证元数据仅含脱敏诊断事实,阻断凭据、正文与 URL 进入审计账本。"""
safe = dict(metadata or {})
forbidden = _collect_forbidden_keys(safe)
if forbidden:
raise ValidationError(
'RPA report audit metadata contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN',
details={'forbidden_keys': sorted(set(forbidden))},
)
return safe
def _sanitize_refs(refs: list[dict[str, Any]] | None, *, field_name: str) -> list[dict[str, Any]] | None:
"""校验证据/产物引用仅含标识类字段,拒绝 URL 与正文。"""
if refs is None:
return None
if not isinstance(refs, list):
raise ValidationError(
f'RPA report audit {field_name} must be a list',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
)
forbidden = _collect_forbidden_keys(refs)
if forbidden:
raise ValidationError(
f'RPA report audit {field_name} contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
details={'forbidden_keys': sorted(set(forbidden))},
)
return refs
def _stable_hash(value: Any) -> str:
"""对受控状态对象生成 SHA-256(排序键 + 紧凑分隔符,与 audit_service 同构)。"""
encoded = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str)
return hashlib.sha256(encoded.encode('ascii')).hexdigest()
def _snapshot_diff(before: Any, after: Any) -> dict[str, Any] | None:
"""
计算前后快照顶层差异(changed/added/removed 三段;无变化返回 None)。
核心逻辑:值均为受控诊断键原样比较(本域快照不做白名单投影,见模块 docstring)。
"""
left = before if isinstance(before, dict) else {}
right = after if isinstance(after, dict) else {}
changed: dict[str, Any] = {}
added: dict[str, Any] = {}
removed: dict[str, Any] = {}
for key in sorted(set(left) | set(right)):
if key in left and key in right:
if left[key] != right[key]:
changed[key] = {'from': left[key], 'to': right[key]}
elif key in right:
added[key] = right[key]
else:
removed[key] = left[key]
if not changed and not added and not removed:
return None
return {'changed': changed, 'added': added, 'removed': removed}
def _resolve_previous_event_hash(*, aggregate_type: str, aggregate_id: str) -> str | None:
"""
读取同聚合最新一条事件的 event_hash 作为哈希链前驱。
核心逻辑:按 id 倒序取一条;缺失或旧数据无 hash 时返回 None(链从本条起锚)。
调用方须先 flush 保证同事务先前事件可查(与 audit_service 顺序一致)。
"""
previous = (
ShippingAuditEvent.query
.filter_by(aggregate_type=str(aggregate_type)[:64], aggregate_id=str(aggregate_id)[:128])
.order_by(ShippingAuditEvent.id.desc())
.first()
)
if previous is None:
return None
return str(previous.event_hash) if previous.event_hash else None
def _event_hash_payload(
*,
event_type: str,
aggregate_type: str,
aggregate_id: str,
action: str | None,
result: str | None,
reason_code: str | None,
run_no: str | None,
task_no: str | None,
operation_id: str | None,
request_id: str | None,
actor_type: str,
actor_id: str | None,
before_snapshot: dict[str, Any] | None,
after_snapshot: dict[str, Any] | None,
diff_json: dict[str, Any] | None,
previous_event_hash: str | None,
sensitivity_level: str | None,
) -> dict[str, Any]:
"""组装参与 event_hash 计算的稳定字段集合(字段集与 audit_snapshot_service 同构)。"""
return {
'event_type': event_type,
'aggregate_type': aggregate_type,
'aggregate_id': aggregate_id,
'action': action,
'result': result,
'reason_code': reason_code,
'workflow_id': None,
'workflow_item_id': None,
'workflow_item_version_id': None,
'version_no': None,
'run_no': run_no,
'document_id': None,
'review_case_no': None,
'task_no': task_no,
'operation_id': operation_id,
'request_id': request_id,
'actor_type': actor_type,
'actor_id': actor_id,
'before_snapshot': before_snapshot,
'after_snapshot': after_snapshot,
'diff': diff_json,
'previous_event_hash': previous_event_hash,
'sensitivity_level': sensitivity_level,
}
def append_rpa_report_event(
*,
event_type: str,
aggregate_type: str,
aggregate_id: str,
run_no: str | None = None,
task_no: str | None = None,
intake_no: str | None = None,
actor_type: str = 'system',
actor_id: str | int | None = None,
actor_role: str | None = None,
actor_display: str | None = None,
request_id: str | None = None,
operation_id: str | None = None,
correlation_id: str | None = None,
source: str | None = None,
result: str | None = None,
error_code: str | None = None,
conversation_id: str | None = None,
unit_id: str | int | None = None,
document_id: str | int | None = None,
review_case_no: str | None = None,
owner_user_id: str | int | None = None,
attempt_no: int | None = None,
action: str | None = None,
reason_code: str | None = None,
reason: str | None = None,
before: Any = None,
after: Any = None,
evidence_refs: list[dict[str, Any]] | None = None,
artifact_refs: list[dict[str, Any]] | None = None,
context_refs: dict[str, Any] | None = None,
metadata: dict[str, Any] | None = None,
sensitivity_level: str | None = None,
) -> ShippingAuditEvent:
"""
追加一条货代 RPA 审计事实(freight_rpa 域唯一审计写入口)。
用途:与 shipping_notice.audit_service.append_shipping_audit_event 关键字兼容的
RPA 域替代品——调用方(report_archive 等)自 audit_service 迁移时仅改函数名,
事件名与聚合键原样保持,避免审计查询断档(见模块 docstring 的四处有意差异)。
核心逻辑:[STEP 1] 校验 actor_type/result 白名单 + 元数据/引用脱敏;
[STEP 2] 计算 before/after 稳定哈希与顶层 diff;
[STEP 3] flush 后取同聚合前驱 event_hash,对核心字段集合计算 event_hash;
[STEP 4] 写入 ShippingAuditEvent(保留期恒 None=永久)并 flush,不 commit。
Args:
event_type: 稳定业务事件名(如 shipping_inbound_rpa_callback_received);
禁止传入用户自由文本。
aggregate_type/aggregate_id: 业务聚合类型与稳定编号(软引用,不使用外键)。
run_no/task_no: 排程 run / task 软引用(截断 64)。
actor_type/actor_id/actor_role/actor_display: 操作主体四元组
(actor_type 必须在 user/system/rpa/chatflow/admin/worker 内)。
result: success / failure / rejected / ignored(白名单外抛 ValidationError)。
before/after: 受控状态快照(本域不做白名单投影,键须为诊断类,禁敏感键)。
evidence_refs/artifact_refs: FileAsset ID、SHA-256 等标识引用;禁止 URL/正文。
metadata: 仅允许原因码、计数等脱敏诊断事实(禁止键见 _FORBIDDEN_AUDIT_KEYS)。
unit_id/document_id/review_case_no/owner_user_id/attempt_no: 业务关联软引用。
action/reason_code/reason/error_code/conversation_id/correlation_id/source/
request_id/operation_id/intake_no/sensitivity_level: 追溯与分级补充字段。
Returns:
尚未提交的 ShippingAuditEvent,由调用方与业务写入在同一事务提交。
Raises:
ValidationError: actor/result 非法,或元数据/快照引用包含正文、凭据等敏感键。
"""
# [STEP 1] 校验与脱敏(错误码与 audit_service 共用,避免同义分裂)。
if actor_type not in _ALLOWED_ACTOR_TYPES:
raise ValidationError('Invalid shipping audit actor type', code='SHIPPING_NOTICE.AUDIT_ACTOR_INVALID')
if result is not None and result not in _ALLOWED_RESULTS:
raise ValidationError('Invalid shipping audit result', code='SHIPPING_NOTICE.AUDIT_RESULT_INVALID')
safe_metadata = _sanitize_metadata(metadata)
if before is not None and _collect_forbidden_keys(before):
raise ValidationError(
'RPA report audit snapshot contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
details={'forbidden_keys': sorted(set(_collect_forbidden_keys(before)))},
)
if after is not None and _collect_forbidden_keys(after):
raise ValidationError(
'RPA report audit snapshot contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
details={'forbidden_keys': sorted(set(_collect_forbidden_keys(after)))},
)
# [STEP 2] 快照哈希与顶层差异。
before_snapshot = before if isinstance(before, dict) else None
after_snapshot = after if isinstance(after, dict) else None
diff_json = _snapshot_diff(before, after)
# [STEP 3] 哈希链:flush 保证同事务先前事件可查,再取前驱并计算本条 event_hash。
db.session.flush()
previous_event_hash = _resolve_previous_event_hash(
aggregate_type=str(aggregate_type)[:64], aggregate_id=str(aggregate_id)[:128],
)
resolved_run_no = str(run_no)[:64] if run_no else None
resolved_task_no = str(task_no)[:64] if task_no else None
resolved_actor_id = str(actor_id)[:128] if actor_id is not None else None
resolved_operation_id = str(operation_id)[:64] if operation_id else None
resolved_request_id = str(request_id)[:64] if request_id else None
resolved_sensitivity = str(sensitivity_level)[:16] if sensitivity_level else None
event_hash = _stable_hash(_event_hash_payload(
event_type=str(event_type)[:64],
aggregate_type=str(aggregate_type)[:64],
aggregate_id=str(aggregate_id)[:128],
action=str(action)[:64] if action else None,
result=result,
reason_code=str(reason_code)[:128] if reason_code else None,
run_no=resolved_run_no,
task_no=resolved_task_no,
operation_id=resolved_operation_id,
request_id=resolved_request_id,
actor_type=actor_type,
actor_id=resolved_actor_id,
before_snapshot=before_snapshot,
after_snapshot=after_snapshot,
diff_json=diff_json,
previous_event_hash=previous_event_hash,
sensitivity_level=resolved_sensitivity,
))
# [STEP 4] 写入事件(保留期恒 None=永久保留;不 commit,由调用方保证原子性)。
event = ShippingAuditEvent(
event_type=str(event_type)[:64],
aggregate_type=str(aggregate_type)[:64],
aggregate_id=str(aggregate_id)[:128],
run_no=resolved_run_no,
task_no=resolved_task_no,
intake_no=str(intake_no)[:64] if intake_no else None,
actor_type=actor_type,
actor_id=resolved_actor_id,
actor_role=str(actor_role)[:64] if actor_role else None,
actor_display=str(actor_display)[:128] if actor_display else None,
request_id=resolved_request_id,
operation_id=resolved_operation_id,
correlation_id=str(correlation_id)[:64] if correlation_id else None,
source=str(source)[:32] if source else None,
result=result,
error_code=str(error_code)[:64] if error_code else None,
conversation_id=str(conversation_id)[:100] if conversation_id else None,
unit_id=str(unit_id)[:64] if unit_id is not None else None,
document_id=str(document_id)[:64] if document_id is not None else None,
review_case_no=str(review_case_no)[:64] if review_case_no else None,
owner_user_id=str(owner_user_id)[:64] if owner_user_id is not None else None,
attempt_no=int(attempt_no) if attempt_no is not None else None,
action=str(action)[:64] if action else None,
reason_code=str(reason_code)[:128] if reason_code else None,
reason=str(reason)[:2000] if reason else None,
before_hash=_stable_hash(before_snapshot) if before_snapshot is not None else None,
after_hash=_stable_hash(after_snapshot) if after_snapshot is not None else None,
before_snapshot_json=before_snapshot,
after_snapshot_json=after_snapshot,
diff_json=diff_json,
previous_event_hash=previous_event_hash,
event_hash=event_hash,
sensitivity_level=resolved_sensitivity,
evidence_refs_json=_sanitize_refs(evidence_refs, field_name='evidence_refs'),
artifact_refs_json=_sanitize_refs(artifact_refs, field_name='artifact_refs'),
context_refs_json=dict(context_refs or {}) if context_refs else None,
metadata_json=safe_metadata,
retention_expires_at=None,
)
db.session.add(event)
db.session.flush()
return event
# 供测试与契约引用的冻结黑名单导出(与 audit_service.FORBIDDEN_AUDIT_METADATA_KEYS 对应的本地子集)。
RPA_FORBIDDEN_AUDIT_KEYS = _FORBIDDEN_AUDIT_KEYS
@@ -0,0 +1,36 @@
"""
services/freight_rpa/common/rpa_runtime.py
用途:RPA 运行模式(browser/mock)的展示助手——把任务回调记录或后端配置规范化为前端安全摘要。
依赖:Flask current_app 配置(FREIGHT_RPA_WORKER_MOCK);不依赖目录 IO 与 Worker 文件契约。
逻辑:由 shipping_notice.query_service(任务序列化注入 rpa_runtime 摘要)、
同包 worker_heartbeat(mock 模式下跳过真实 Worker 在线探测)消费;
仅做展示归一,不承载触发/回调逻辑。
"""
from __future__ import annotations
from typing import Any
from flask import current_app
def _runtime_summary(mode: str) -> dict[str, str | bool]:
"""将 browser/mock 规范化为前端安全展示摘要。"""
normalized = "mock" if str(mode or "").strip().lower() == "mock" else "browser"
mock_enabled = normalized == "mock"
return {
"mode": normalized,
"label": "Mock RPA" if mock_enabled else "真实 RPA",
"mock": mock_enabled,
}
def rpa_runtime_mode(runtime: dict[str, Any] | None = None) -> dict[str, str | bool]:
"""返回 RPA 运行模式摘要;优先使用任务最近一次回调实际模式,兜底读取当前后端配置。"""
if isinstance(runtime, dict):
mode = str(runtime.get("mode") or runtime.get("rpa_mode") or "").strip().lower()
if mode in {"browser", "mock"}:
return _runtime_summary(mode)
raw = str(current_app.config.get("FREIGHT_RPA_WORKER_MOCK", "false") or "false").strip().lower()
return _runtime_summary("mock" if raw in {"1", "true", "yes", "on"} else "browser")
@@ -1,11 +1,14 @@
""" """
services/shipping_notice/rpa_worker_heartbeat.py services/freight_rpa/common/worker_heartbeat.py
用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传/收料就绪检查与状态查询。 用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传/入站/出站就绪检查与状态查询。
依赖:Flask current_app、redis_client、shipping_notice.rpa(库存与上传目录、mock 模式)、 依赖:Flask current_app、redis_client、同包 rpa_runtime(mock 模式)、
shipping_notice.receipt_rpa(收料 trigger 目录)。 freight_rpa.onhand.trigger_io(onhand trigger 目录)、
逻辑:freight_rpa_worker 调 POST /rpa/heartbeat;写 inventory/upload/receipt trigger 前强制就绪检查; freight_rpa.upload.trigger_io(上传目录)、
管理端 /rpa-workers/status?scope=inventory|receipt 展示对应 Worker 心跳徽标。 freight_rpa.inbound.trigger_io(inbound trigger 目录)、
freight_rpa.outbound.trigger_io(outbound trigger 目录)。
逻辑:Windows Worker 调 POST /api/freight-rpa/heartbeat;写 onhand/upload/inbound/outbound trigger 前强制就绪检查;
管理端 /rpa-workers/status?scope=onhand|inbound|outbound 展示对应 Worker 心跳徽标。
""" """
from __future__ import annotations from __future__ import annotations
@@ -24,18 +27,25 @@ from flask import current_app
from app.core.config.settings import _normalize_env_name from app.core.config.settings import _normalize_env_name
from app.core.errors import ServiceUnavailableError from app.core.errors import ServiceUnavailableError
from app.services.shipping_notice.rpa import inventory_trigger_dir, rpa_runtime_mode from app.services.freight_rpa.onhand.trigger_io import onhand_trigger_dir
from .rpa_runtime import rpa_runtime_mode
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
RPA_WORKER_OFFLINE_MESSAGE = "RPA Worker 未在线,请启动 Windows RPA 服务后重试" RPA_WORKER_OFFLINE_MESSAGE = "RPA Worker 未在线,请启动 Windows RPA 服务后重试"
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE = "RPA Worker 心跳存储不可用,请检查 Redis 连接" RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE = "RPA Worker 心跳存储不可用,请检查 Redis 连接"
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE = "货代上传 RPA 未就绪,请检查 Worker、凭据与共享目录后重试" RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE = "货代上传 RPA 未就绪,请检查 Worker、凭据与共享目录后重试"
INVENTORY_EXPORT_CAPABILITY = "inventory_export" # [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:能力串随 Worker 侧(Task 12)切换——
FREIGHT_UPLOAD_CAPABILITY = "freight_upload" # inventory_export→onhand_export、receipt_export→inbound_export;上传能力为 freight_rpa_upload;
RECEIPT_EXPORT_CAPABILITY = "receipt_export" # worker_id 后缀判定 -receipt→-inbound(ps1 注入值随发布窗口改配,见 cutover runbook)。
# 收料 Worker 由 start_receipt_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-receipt。 ONHAND_EXPORT_CAPABILITY = "onhand_export"
RECEIPT_WORKER_ID_SUFFIX = "-receipt" FREIGHT_RPA_UPLOAD_CAPABILITY = "freight_rpa_upload"
INBOUND_EXPORT_CAPABILITY = "inbound_export"
OUTBOUND_EXPORT_CAPABILITY = "outbound_export"
# inbound Worker 由 start_inbound_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-inbound。
INBOUND_WORKER_ID_SUFFIX = "-inbound"
# outbound Worker 由 start_outbound_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-outbound。
OUTBOUND_WORKER_ID_SUFFIX = "-outbound"
_REDIS_INDEX_KEY = "shipping:rpa:heartbeat:index" _REDIS_INDEX_KEY = "shipping:rpa:heartbeat:index"
_REDIS_WORKER_KEY_PREFIX = "shipping:rpa:heartbeat:worker:" _REDIS_WORKER_KEY_PREFIX = "shipping:rpa:heartbeat:worker:"
_MEMORY_STORE: dict[str, dict[str, Any]] = {} _MEMORY_STORE: dict[str, dict[str, Any]] = {}
@@ -51,8 +61,10 @@ _REASON_USER_HINTS: dict[str, str] = {
"shared_scope_mismatch": "共享目录 scope 与后端配置不一致", "shared_scope_mismatch": "共享目录 scope 与后端配置不一致",
"trigger_dir_not_writable": "trigger 目录不可写", "trigger_dir_not_writable": "trigger 目录不可写",
"environment_mismatch": "Worker 环境与后端环境不一致", "environment_mismatch": "Worker 环境与后端环境不一致",
"missing_inventory_export_capability": "Worker 未声明 inventory_export 能力", "missing_onhand_export_capability": "Worker 未声明 onhand_export 能力",
"missing_freight_upload_capability": "Worker 未声明 freight_upload 能力", "missing_inbound_export_capability": "Worker 未声明 inbound_export 能力",
"missing_outbound_export_capability": "Worker 未声明 outbound_export 能力",
"missing_freight_rpa_upload_capability": "Worker 未声明 freight_rpa_upload 能力",
"credential_key_missing": "未配置 FREIGHT_RPA_CREDENTIAL_KEY", "credential_key_missing": "未配置 FREIGHT_RPA_CREDENTIAL_KEY",
"upload_queue_dir_not_configured": "未配置货代上传队列目录", "upload_queue_dir_not_configured": "未配置货代上传队列目录",
"upload_queue_dir_not_accessible": "货代上传队列目录不可访问", "upload_queue_dir_not_accessible": "货代上传队列目录不可访问",
@@ -139,7 +151,7 @@ def shared_scope_id() -> str:
explicit = _config_str("FREIGHT_RPA_SHARED_SCOPE_ID", "") explicit = _config_str("FREIGHT_RPA_SHARED_SCOPE_ID", "")
if explicit: if explicit:
return explicit return explicit
trigger_dir = inventory_trigger_dir() trigger_dir = onhand_trigger_dir()
if not trigger_dir: if not trigger_dir:
return "" return ""
for part in Path(trigger_dir).parts: for part in Path(trigger_dir).parts:
@@ -362,7 +374,7 @@ def _verify_shared_trigger_mount(
trigger_dir: Path | None, *, require_sentinel: bool = True, trigger_dir: Path | None, *, require_sentinel: bool = True,
) -> tuple[bool, list[str]]: ) -> tuple[bool, list[str]]:
""" """
校验 trigger 目录可写;默认要求共享哨兵(库存与收料同口径)。 校验 trigger 目录可写;默认要求共享哨兵(库存与入站同口径)。
Args: Args:
trigger_dir: 共享 trigger 目录。 trigger_dir: 共享 trigger 目录。
@@ -400,18 +412,39 @@ def _verify_shared_trigger_mount(
return not reasons, reasons return not reasons, reasons
def is_receipt_rpa_worker(worker: dict[str, Any]) -> bool: def is_inbound_rpa_worker(worker: dict[str, Any]) -> bool:
""" """
判断心跳是否来自收料 Worker。 判断心跳是否来自 inbound(原收料)Worker。
优先认 <主机名>-receipt(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、 优先认 <主机名>-inbound(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、
回退为 <主机名>-<pid> 的进程——用心跳 trigger_dir 与收料目录对齐判定。 回退为 <主机名>-<pid> 的进程——用心跳 trigger_dir 与 inbound 目录对齐判定。
""" """
if str(worker.get("worker_id") or "").strip().lower().endswith(RECEIPT_WORKER_ID_SUFFIX): if str(worker.get("worker_id") or "").strip().lower().endswith(INBOUND_WORKER_ID_SUFFIX):
return True return True
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
expected = receipt_trigger_dir() expected = inbound_trigger_dir()
actual = str(worker.get("trigger_dir") or "").strip()
if expected is None or not actual:
return False
try:
return Path(actual).resolve() == expected.resolve()
except OSError:
return False
def is_outbound_rpa_worker(worker: dict[str, Any]) -> bool:
"""
判断心跳是否来自 outbound Worker。
优先认 <主机名>-outbound(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、
回退为 <主机名>-<pid> 的进程——用心跳 trigger_dir 与 outbound 目录对齐判定。
"""
if str(worker.get("worker_id") or "").strip().lower().endswith(OUTBOUND_WORKER_ID_SUFFIX):
return True
from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir
expected = outbound_trigger_dir()
actual = str(worker.get("trigger_dir") or "").strip() actual = str(worker.get("trigger_dir") or "").strip()
if expected is None or not actual: if expected is None or not actual:
return False return False
@@ -437,7 +470,7 @@ def _worker_is_eligible(
backend_env: str, backend_env: str,
ttl_seconds: int, ttl_seconds: int,
now: float, now: float,
required_capability: str = INVENTORY_EXPORT_CAPABILITY, required_capability: str = ONHAND_EXPORT_CAPABILITY,
) -> tuple[bool, list[str]]: ) -> tuple[bool, list[str]]:
""" """
判断单 Worker 是否满足心跳新鲜度、能力声明与环境/scope 隔离。 判断单 Worker 是否满足心跳新鲜度、能力声明与环境/scope 隔离。
@@ -447,7 +480,7 @@ def _worker_is_eligible(
backend_env: 后端归一环境(dev/test/prod)。 backend_env: 后端归一环境(dev/test/prod)。
ttl_seconds: 心跳 TTL。 ttl_seconds: 心跳 TTL。
now: 当前 epoch 秒。 now: 当前 epoch 秒。
required_capability: 必选能力(inventory_export / freight_upload)。 required_capability: 必选能力(onhand_export / inbound_export / outbound_export / freight_rpa_upload)。
Returns: Returns:
(是否合格, 不合格原因列表)。 (是否合格, 不合格原因列表)。
@@ -461,10 +494,7 @@ def _worker_is_eligible(
capabilities = _parse_capabilities(worker.get("capabilities")) capabilities = _parse_capabilities(worker.get("capabilities"))
if required_capability and required_capability not in capabilities: if required_capability and required_capability not in capabilities:
if required_capability == FREIGHT_UPLOAD_CAPABILITY: reasons.append(_missing_capability_reason(required_capability))
reasons.append("missing_freight_upload_capability")
else:
reasons.append("missing_inventory_export_capability")
worker_env = str(worker.get("environment") or "").strip().lower() worker_env = str(worker.get("environment") or "").strip().lower()
if worker_env and worker_env != backend_env: if worker_env and worker_env != backend_env:
@@ -477,6 +507,11 @@ def _worker_is_eligible(
return not reasons, reasons return not reasons, reasons
def _missing_capability_reason(required_capability: str) -> str:
"""按必选能力生成缺失原因码(onhand_export / inbound_export / outbound_export / freight_rpa_upload)。"""
return f"missing_{required_capability}_capability"
def _summarize_reasons(reasons: list[str]) -> str: def _summarize_reasons(reasons: list[str]) -> str:
hints: list[str] = [] hints: list[str] = []
for reason in reasons: for reason in reasons:
@@ -512,8 +547,8 @@ def _check_rpa_worker_ready_for_capability(
trigger_dir: 待校验的共享 trigger 目录。 trigger_dir: 待校验的共享 trigger 目录。
required_capability: 必选 Worker 能力;空字符串表示不校验能力。 required_capability: 必选 Worker 能力;空字符串表示不校验能力。
extra_reasons: 调用方预检附加原因(凭据/队列等)。 extra_reasons: 调用方预检附加原因(凭据/队列等)。
worker_predicate: 可选过滤(如仅收料 Worker);不匹配的心跳不进入列表。 worker_predicate: 可选过滤(如仅入站 Worker);不匹配的心跳不进入列表。
require_sentinel: 是否要求共享哨兵(收料为 False)。 require_sentinel: 是否要求共享哨兵(库存/入站同口径均 True)。
Returns: Returns:
RpaWorkerReadiness。 RpaWorkerReadiness。
@@ -601,7 +636,7 @@ def _check_rpa_worker_ready_for_capability(
message, detail_message = "ready", "ready" message, detail_message = "ready", "ready"
else: else:
failure = RpaWorkerReadiness(ready=False, message="", reasons=sorted(set(reasons))) failure = RpaWorkerReadiness(ready=False, message="", reasons=sorted(set(reasons)))
if required_capability == FREIGHT_UPLOAD_CAPABILITY: if required_capability == FREIGHT_RPA_UPLOAD_CAPABILITY:
detail = _summarize_reasons(failure.reasons) detail = _summarize_reasons(failure.reasons)
message = RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE message = RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE
detail_message = f"{message}({detail})" if detail else message detail_message = f"{message}({detail})" if detail else message
@@ -623,41 +658,41 @@ def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness:
核心逻辑:Redis 可用、共享哨兵有效、最近心跳在 TTL 内、环境/scope 匹配。 核心逻辑:Redis 可用、共享哨兵有效、最近心跳在 TTL 内、环境/scope 匹配。
""" """
return _check_rpa_worker_ready_for_capability( return _check_rpa_worker_ready_for_capability(
trigger_dir=inventory_trigger_dir(), trigger_dir=onhand_trigger_dir(),
required_capability=INVENTORY_EXPORT_CAPABILITY, required_capability=ONHAND_EXPORT_CAPABILITY,
) )
def check_receipt_rpa_worker_ready() -> RpaWorkerReadiness: def check_inbound_rpa_worker_ready() -> RpaWorkerReadiness:
""" """
检查收料 RPA Worker 是否在线(管理端徽标 + 写 trigger 前 fail-fast)。 检查入站 RPA Worker 是否在线(管理端徽标 + 写 trigger 前 fail-fast)。
核心逻辑:仅看收料 Worker 心跳(*-receipt 或 trigger_dir 对齐);要求 核心逻辑:仅看 inbound Worker 心跳(*-inbound 或 trigger_dir 对齐);要求
receipt_export 能力;校验收料 trigger 目录可写;与库存同口径要求共享哨兵。 inbound_export 能力;校验 inbound trigger 目录可写;与 onhand 同口径要求共享哨兵。
""" """
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
return _check_rpa_worker_ready_for_capability( return _check_rpa_worker_ready_for_capability(
trigger_dir=receipt_trigger_dir(), trigger_dir=inbound_trigger_dir(),
required_capability=RECEIPT_EXPORT_CAPABILITY, required_capability=INBOUND_EXPORT_CAPABILITY,
worker_predicate=is_receipt_rpa_worker, worker_predicate=is_inbound_rpa_worker,
require_sentinel=True, require_sentinel=True,
) )
def assert_receipt_rpa_worker_ready() -> None: def assert_inbound_rpa_worker_ready() -> None:
""" """
写收料 trigger 前的强制就绪检查。 写入站 trigger 前的强制就绪检查。
核心逻辑:镜像 assert_inventory_rpa_worker_ready;离线则抛 ServiceUnavailableError, 核心逻辑:镜像 assert_inventory_rpa_worker_ready;离线则抛 ServiceUnavailableError,
排程不得进入 awaiting_receipt_rpa。 排程不得进入 awaiting_inbound_rpa。
Raises: Raises:
ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。 ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。
""" """
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
result = check_receipt_rpa_worker_ready() result = check_inbound_rpa_worker_ready()
if result.ready: if result.ready:
return return
code = 'RPA.WORKER_OFFLINE' code = 'RPA.WORKER_OFFLINE'
@@ -677,7 +712,61 @@ def assert_receipt_rpa_worker_ready() -> None:
'detail_message': result.detail_message, 'detail_message': result.detail_message,
'checked_at': result.checked_at, 'checked_at': result.checked_at,
'shared_scope_id': shared_scope_id(), 'shared_scope_id': shared_scope_id(),
'trigger_dir': str(receipt_trigger_dir() or ''), 'trigger_dir': str(inbound_trigger_dir() or ''),
},
)
def check_outbound_rpa_worker_ready() -> RpaWorkerReadiness:
"""
检查出站 RPA Worker 是否在线(写 trigger 前 fail-fast)。
核心逻辑:仅看 outbound Worker 心跳(*-outbound 或 trigger_dir 对齐);要求
outbound_export 能力;校验 outbound trigger 目录可写;与 onhand/inbound 同口径要求共享哨兵。
"""
from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir
return _check_rpa_worker_ready_for_capability(
trigger_dir=outbound_trigger_dir(),
required_capability=OUTBOUND_EXPORT_CAPABILITY,
worker_predicate=is_outbound_rpa_worker,
require_sentinel=True,
)
def assert_outbound_rpa_worker_ready() -> None:
"""
写出站 trigger 前的强制就绪检查。
核心逻辑:镜像 assert_inbound_rpa_worker_ready;离线则抛 ServiceUnavailableError,
排程不得进入 awaiting_outbound_rpa_callback。
Raises:
ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。
"""
from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir
result = check_outbound_rpa_worker_ready()
if result.ready:
return
code = 'RPA.WORKER_OFFLINE'
if 'heartbeat_storage_unavailable' in result.reasons:
code = 'RPA.HEARTBEAT_STORAGE_UNAVAILABLE'
logger.warning(
'[rpa-heartbeat] outbound readiness blocked code=%s reasons=%s detail=%s',
code,
result.reasons,
result.detail_message,
)
raise ServiceUnavailableError(
result.message,
code=code,
details={
'reasons': result.reasons,
'detail_message': result.detail_message,
'checked_at': result.checked_at,
'shared_scope_id': shared_scope_id(),
'trigger_dir': str(outbound_trigger_dir() or ''),
}, },
) )
@@ -689,7 +778,7 @@ def _freight_upload_config_reasons() -> list[str]:
Returns: Returns:
不合规原因码列表(空表示静态配置通过)。 不合规原因码列表(空表示静态配置通过)。
""" """
from app.services.shipping_notice.rpa import upload_queue_dir, upload_trigger_dir from app.services.freight_rpa.upload.trigger_io import upload_queue_dir, upload_trigger_dir
reasons: list[str] = [] reasons: list[str] = []
credential_key = _config_str("FREIGHT_RPA_CREDENTIAL_KEY", "") credential_key = _config_str("FREIGHT_RPA_CREDENTIAL_KEY", "")
@@ -722,16 +811,16 @@ def check_freight_upload_rpa_ready() -> RpaWorkerReadiness:
检查货代上传 RPA 是否可安全自动触发。 检查货代上传 RPA 是否可安全自动触发。
核心逻辑:凭据/队列/回调基址预检 + 上传 trigger 共享挂载 + Worker 心跳与 核心逻辑:凭据/队列/回调基址预检 + 上传 trigger 共享挂载 + Worker 心跳与
freight_upload 能力 + 环境/scope 隔离。Mock 模式跳过心跳。 freight_rpa_upload 能力 + 环境/scope 隔离。Mock 模式跳过心跳。
Returns: Returns:
RpaWorkerReadiness(含 reasons 供建单前/启动日志展示)。 RpaWorkerReadiness(含 reasons 供建单前/启动日志展示)。
""" """
from app.services.shipping_notice.rpa import upload_trigger_dir from app.services.freight_rpa.upload.trigger_io import upload_trigger_dir
return _check_rpa_worker_ready_for_capability( return _check_rpa_worker_ready_for_capability(
trigger_dir=upload_trigger_dir(), trigger_dir=upload_trigger_dir(),
required_capability=FREIGHT_UPLOAD_CAPABILITY, required_capability=FREIGHT_RPA_UPLOAD_CAPABILITY,
extra_reasons=_freight_upload_config_reasons(), extra_reasons=_freight_upload_config_reasons(),
) )
@@ -757,7 +846,7 @@ def assert_freight_upload_rpa_ready() -> None:
result.reasons, result.reasons,
result.detail_message, result.detail_message,
) )
from app.services.shipping_notice.rpa import upload_trigger_dir from app.services.freight_rpa.upload.trigger_io import upload_trigger_dir
raise ServiceUnavailableError( raise ServiceUnavailableError(
result.message, result.message,
@@ -768,7 +857,7 @@ def assert_freight_upload_rpa_ready() -> None:
"checked_at": result.checked_at, "checked_at": result.checked_at,
"shared_scope_id": shared_scope_id(), "shared_scope_id": shared_scope_id(),
"trigger_dir": str(upload_trigger_dir() or ""), "trigger_dir": str(upload_trigger_dir() or ""),
"capability": FREIGHT_UPLOAD_CAPABILITY, "capability": FREIGHT_RPA_UPLOAD_CAPABILITY,
}, },
) )
@@ -836,29 +925,34 @@ def assert_inventory_rpa_worker_ready() -> None:
"detail_message": result.detail_message, "detail_message": result.detail_message,
"checked_at": result.checked_at, "checked_at": result.checked_at,
"shared_scope_id": shared_scope_id(), "shared_scope_id": shared_scope_id(),
"trigger_dir": str(inventory_trigger_dir() or ""), "trigger_dir": str(onhand_trigger_dir() or ""),
}, },
) )
def serialize_rpa_worker_status(*, scope: str = "inventory") -> dict[str, Any]: def serialize_rpa_worker_status(*, scope: str = "onhand") -> dict[str, Any]:
""" """
管理端展示:按 scope 返回库存或收料 Worker 心跳摘要。 管理端展示:按 scope 返回在手(onhand)、入站(inbound)或出站(outbound)Worker 心跳摘要。
Args: Args:
scope: inventory(默认)或 receipt。 scope: onhand(默认,库存 RPA 工作台)、inbound(入站)或 outbound(出站);
取值为后端内部与前端查询参数约定,与 Worker 上报能力标识无关。
""" """
from app.services.shipping_notice.rpa import upload_trigger_dir from app.services.freight_rpa.upload.trigger_io import upload_trigger_dir
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir
normalized = str(scope or "inventory").strip().lower() normalized = str(scope or "onhand").strip().lower()
if normalized == "receipt": if normalized == "inbound":
readiness = check_receipt_rpa_worker_ready() readiness = check_inbound_rpa_worker_ready()
trigger_path = str(receipt_trigger_dir() or "") trigger_path = str(inbound_trigger_dir() or "")
elif normalized == "outbound":
readiness = check_outbound_rpa_worker_ready()
trigger_path = str(outbound_trigger_dir() or "")
else: else:
readiness = check_inventory_rpa_worker_ready() readiness = check_inventory_rpa_worker_ready()
trigger_path = str(inventory_trigger_dir() or "") trigger_path = str(onhand_trigger_dir() or "")
normalized = "inventory" normalized = "onhand"
freight_readiness = check_freight_upload_rpa_ready() freight_readiness = check_freight_upload_rpa_ready()
ttl_seconds = _heartbeat_ttl_seconds() ttl_seconds = _heartbeat_ttl_seconds()
@@ -896,7 +990,7 @@ def serialize_rpa_worker_status(*, scope: str = "inventory") -> dict[str, Any]:
"upload_trigger_dir": str(upload_trigger_dir() or ""), "upload_trigger_dir": str(upload_trigger_dir() or ""),
"reasons": readiness.reasons, "reasons": readiness.reasons,
"workers": workers, "workers": workers,
"freight_upload": { "freight_rpa_upload": {
"ready": freight_readiness.ready, "ready": freight_readiness.ready,
"message": freight_readiness.message, "message": freight_readiness.message,
"detail_message": freight_readiness.detail_message, "detail_message": freight_readiness.detail_message,
Loaded 100 of 1034 files, more files were not shown because too many files have changed in this diff. Show more