Compare commits

...
Author SHA1 Message Date
super 668d0c4a67 Merge branch 'dev' into super 2026-10-22 19:52:51 +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
sophie 55e56e4dc9 fix: 在AGENTS.md约束增加element plus 2026-10-21 20:12:25 +08:00
sophie cdc8610ec1 fix(admin): 管理控制台界面使用element plus 2026-10-20 17:01:24 +08:00
HTEWJ\26070045 9236f2949c style(chat-format): 修改回复样式为序号缩进等 2026-10-16 15:15:48 +08:00
sophie 6c47d0639c build: 修改frontend lint报错 2026-10-15 15:13:10 +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 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 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 dde2093e06 fix(shipping-notice): 收口激活按 run_id 取 Run 修变量作用域 2026-10-15 01:39:37 +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 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 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 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
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
sophie 041bb73b9a fix: update docs 2026-10-14 13:44:56 +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 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
super 8d14b8a100 Merge branch 'dev' into super 2026-09-21 17:07:47 +08:00
337 changed files with 33900 additions and 7058 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`。
+5 -5
View File
@@ -102,7 +102,6 @@ SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
# 复核工作台字段级 AI 建议;仅开发环境启用,建议仍须证据校验与人工裁决
SHIPPING_NOTICE_LLM_REVIEW_ENABLED=true
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
@@ -110,7 +109,6 @@ SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
@@ -135,7 +133,6 @@ SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_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
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
@@ -157,10 +154,13 @@ FREIGHT_RPA_WORKER_MOCK=false
# 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false
FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK=true
# 企微心跳告警总开关(默认关闭;需要时改为 true)
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
# --- 10. 运维、告警与维护工具 ---
# 设备维保助手后端工具调用密钥
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
+3 -8
View File
@@ -25,6 +25,7 @@ HXOPS_PUBLIC_BASE_URL=https://ai.well-trust.com
AUTH_LOGIN_MODE=casdoor
# 如果需要用户密码登录,修改该值为password
# AUTH_LOGIN_MODE=password
# 是否启用 JWT 认证
AUTH_JWT_REQUIRED=true
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=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
# --- 5. 数据库与基础设施 ---
@@ -116,7 +116,6 @@ SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
# 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享)
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
@@ -138,7 +137,6 @@ SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=false
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=false
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
# RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。
# 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。
FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
@@ -146,8 +144,6 @@ FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
# 企微心跳告警总开关(默认关闭;需要时改为 true)
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
FREIGHT_RPA_WORKER_ALERT_USERNAMES=
FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
@@ -162,10 +158,9 @@ FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/arc
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_queue
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_triggers
# 固资履历共享盘(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_SHARE_USERNAME=SBLL00001
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
# 订单交期回复 Agent(2026-10-10 上线边界):只同步订单日期 ≥ 起始日的订单行,早于边界的历史行随 erp_missing 语义自动移出工作台;留空/删除 = 全量同步(dev/test 不配置)
ORDER_DELIVERY_SYNC_DATE_FROM=2026-10-10
# --- 10. 运维、告警与维护工具 ---
# 设备维保助手后端工具调用密钥
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
+1 -1
View File
@@ -150,7 +150,7 @@ WECOM_TRUSTED_DOMAIN=
WECOM_PUBLIC_BASE_URL=
WECOM_NOTIFY_ENABLED=true
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_BASE_URL=http://ai.well-trust.com:8881
# 企业微信群机器人 webhook,按环境写入 .env.<env> 或部署平台变量;不要提交真实 URL。
+4 -12
View File
@@ -24,8 +24,6 @@ HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
# 如果需要用户密码登录,修改该值为password
#AUTH_LOGIN_MODE=casdoor
AUTH_LOGIN_MODE=casdoor
# 是否启用 JWT 认证
AUTH_JWT_REQUIRED=true
# 必须与 CASDOOR_BASE_URL discovery 返回的 issuer 完全一致,不能填写 HXOPS 地址。
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=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
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_ORDER_EXTRACTION_CANCEL_ENABLED=true
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
# 货代专用 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_NATIVE_PAGE_REUSE_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
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐)
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
# 两域超时须覆盖最坏批次总时长(10 站串行 + 单站失败重试可达 30 分钟+),
# 否则每轮对账会把仍在飞的健康批次误回收(2026-10-08 RUN20261008003113B726 实测教训)
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=3600
FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS=3600
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
# 企微心跳告警总开关(默认关闭;需要时改为 true)
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
# 两者皆无则告警只写日志、不会发企微
FREIGHT_RPA_WORKER_ALERT_USERNAMES=
@@ -185,10 +180,7 @@ FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inven
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
# 固资履历共享盘(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_SHARE_USERNAME=SBLL00001
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
# --- 10. 运维、告警与维护工具 ---
# 设备维保助手后端工具调用密钥
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
.trae/*
.cursor/*
!.cursor/rules/
!.cursor/rules/*.mdc
.cursor/rules/* copy.mdc
.idea/
*.swp
*.swo
+2
View File
@@ -150,6 +150,7 @@ docker compose logs -f hxops-backend
- 🧬 **修改数据库表结构必须配套迁移**:任何对 `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)**。
- 🌍 **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,改动需保持流式不被破坏。
- 🔌 **外部集成依赖**:Oracle Instant Client 19.30 / `pyodbc` / `zeep`(OA、PLM、HR)等本地未必可运行,涉及这些 service 时谨慎并说明。
- ➕ **新增依赖需克制**:不擅自引入未经评审的第三方依赖;如需新增,在提交说明中给出理由。
@@ -207,6 +208,7 @@ docker compose logs -f hxops-backend
| FAQ 缓存 / 热点发现运维 | [docs/faq_cache_ops_manual.md](docs/faq_cache_ops_manual.md) |
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.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) |
| 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) |
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)') {
// when {
// expression { env.FRONTEND_CHANGED == 'true' }
+5
View File
@@ -122,6 +122,11 @@ def create_app(config_name='default'):
ensure_default_contract_payment_schedules()
except Exception as exc: # pragma: no cover - 表未就绪时容忍
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:
from app.services.order_delivery_reply.schedule_seed import ensure_default_order_delivery_schedules
ensure_default_order_delivery_schedules()
+2
View File
@@ -49,6 +49,7 @@ def register_blueprints(app: Flask) -> None:
)
from app.api.files import files_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.in_transit_transfer import in_transit_transfer_bp
from app.api.integration_connector import integration_connector_bp
@@ -81,6 +82,7 @@ def register_blueprints(app: Flask) -> None:
app.register_blueprint(files_bp, url_prefix='/api/files')
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(equipment_acceptance_bp, url_prefix='/api/equipment-acceptance')
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(integration_connector_bp, url_prefix='/api/integration-connector')
@@ -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
@@ -793,6 +793,32 @@ def retry_source_rpa_api(source_code: str):
}, status=202)
@in_transit_transfer_bp.route("/sources/retry-rpa-batch", methods=["POST"])
@require_transfer_permission
def retry_sources_rpa_batch_api():
"""批量重试多来源收料 RPA:全部有效来源合并写**一个** batch trigger(一文件 N units)。
【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个来源编码时调用;
逐来源调用单来源端点会产生 N 个 trigger 文件,Worker 每文件开/关一次浏览器;
合并单文件后 Worker 单次登录串行导出全部来源(与收料排程路径同效率)。
请求体:{"source_codes": ["DSV360_AWSBI", ...]}。逐来源解析失败分层与
fail-closed 语义同单来源端点;单源配置缺失跳过并记录,不阻断其余来源。
"""
payload = request.get_json(silent=True) or {}
source_codes = [str(code).strip() for code in (payload.get("source_codes") or []) if str(code).strip()]
if not source_codes:
raise ValidationError("source_codes is required")
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa_batch
outcome = trigger_receipt_rpa_batch(
source_codes=source_codes,
business_date=str(business_date_now()),
reason="transfer_retry_receipt",
)
return _ok(outcome)
@in_transit_transfer_bp.route("/backlog", methods=["GET"])
@require_transfer_permission
def backlog_api():
+29 -1
View File
@@ -16,7 +16,11 @@ backend/app/api/order_delivery_reply.py
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.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__)
XLSX_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
def _utc_to_shanghai(value) -> str | None:
"""
@@ -121,6 +127,28 @@ def list_lines():
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>")
def get_line(order_no: str, line_no: int):
"""
+20
View File
@@ -334,6 +334,26 @@ def rpa_receipt_batch_ready():
return jsonify({'success': True, 'data': ingest_receipt_callback(_payload())})
@shipping_notice_bp.route('/rpa/receipt-unit-progress', methods=['POST'])
def rpa_receipt_unit_progress():
"""收料单元领取/导出中:awaiting_rpa → processing,供管理端实时看到进行中。
本路由同时是收料超时对账的活动锚数据源(mark 落单元 started_at);
曾因重构分叉合并丢失(2026-10-08),Worker 上报全程 404,勿再从旧路径文件删除。
"""
from app.services.schedule.freight_receipt_rpa_finalize import mark_receipt_unit_processing
return jsonify({'success': True, 'data': mark_receipt_unit_processing(_payload())})
@shipping_notice_bp.route('/rpa/receipt-batch-progress', methods=['POST'])
def rpa_receipt_batch_progress():
"""收料 RPA 每完成一笔导出的累计进度回写(非终态,对齐库存 inventory-batch-progress)。"""
from app.services.schedule.freight_receipt_rpa_finalize import report_receipt_batch_progress
return jsonify({'success': True, 'data': report_receipt_batch_progress(_payload())})
@shipping_notice_bp.route('/rpa/inventory-batch-claimed', methods=['POST'])
def rpa_inventory_batch_claimed():
"""v2 Worker 领取回调:仅记录 Attempt 执行阶段。"""
+189 -12
View File
@@ -20,7 +20,7 @@ from flask import Blueprint, Response, current_app, g, request, send_file
from app import db
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.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice, ShippingOrderTask
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
@@ -186,6 +186,7 @@ def workspace_shipping_tasks():
lifecycle_status=lifecycle_status,
page=page,
page_size=page_size,
is_admin=bool(user.is_platform_admin()),
))
@@ -394,14 +395,38 @@ def workspace_batch_restore_shipping_tasks():
@workspace_shipping_notice_bp.route('/shipping-exports/archive', methods=['POST'])
def workspace_shipping_export_archive():
"""按显式任务号下载当前用户可访问的 ready 发货 Excel ZIP。"""
"""按显式任务号下载当前用户可下载(创建者或管理员)的 ready 发货 Excel ZIP。"""
user = _require_user()
data = request.get_json(silent=True) or {}
task_nos = data.get('task_nos')
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')
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.call_on_close(stream.close)
return response
@@ -455,7 +480,11 @@ def workspace_confirm_shipping_customer(task_no: str):
details={'field': 'customer_id'},
) from exc
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'])
@@ -499,7 +528,7 @@ def workspace_create_shipping_task_from_notice():
db.session.commit()
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
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'])
def workspace_replace_shipping_task_notice(task_no: str):
@@ -657,7 +686,12 @@ def workspace_shipping_task_ui_state(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
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'])
def workspace_shipping_task_chat_actions(task_no: str):
@@ -1032,6 +1066,38 @@ def _load_business_notice_for_user(*, business_no: str, user_id: int) -> Shippin
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]:
"""按 business_no 发起单张通知的货代 RPA 上传或重试。"""
task = _load_business_notice_for_user(business_no=business_no, user_id=user_id)
@@ -1138,9 +1204,13 @@ def workspace_batch_start_shipping_notice_rpa_upload():
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/export', methods=['GET'])
def workspace_shipping_notice_export(business_no: str):
"""按发货通知单号下载该通知唯一的正式 Excel,并保留下载审计。"""
"""按发货通知单号下载该通知唯一的正式 Excel(创建者或管理员),并保留下载审计。"""
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)
if err_msg:
raise NotFoundError(err_msg)
@@ -1162,7 +1232,7 @@ def workspace_shipping_notice_export(business_no: str):
@workspace_shipping_notice_bp.route('/shipping-notices/batch/export', methods=['POST'])
def workspace_shipping_notice_export_archive():
"""按多个 business_no 下载各自唯一 Excel 的 ZIP;任一越权或缺文件均整体拒绝。"""
"""按多个 business_no 下载各自唯一 Excel 的 ZIP(创建者或管理员);任一越权或缺文件均整体拒绝。"""
user = _require_user()
data = request.get_json(silent=True) or {}
raw_values = data.get('business_nos')
@@ -1174,8 +1244,32 @@ def workspace_shipping_notice_export_archive():
if not business_nos or len(business_nos) > 100:
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.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.call_on_close(stream.close)
return response
@@ -1183,9 +1277,10 @@ def workspace_shipping_notice_export_archive():
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
def workspace_shipping_task_export(task_no: str):
"""下载当前用户可访问任务的出货 Excel;写入统一访问审计。"""
"""下载当前用户可下载任务的出货 Excel(创建者或管理员);写入统一访问审计。"""
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)
err_msg = task_export_error_message(task)
if err_msg:
@@ -2103,6 +2198,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(
'/shipping-notice/order-review-cases/<case_no>/reservation/revalidate',
methods=['POST'],
+1 -1
View File
@@ -499,7 +499,7 @@ class Config:
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
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>)。
# 缺省 0 = 不显式指定,由后端按 handler_config.content_profile='training' 动态解析各环境的培训 Agent
# (测试/正式环境 Agent ID 不同,动态解析保证卡片均可定位「员工培训-精益管理」);
@@ -724,6 +724,58 @@ def _handoff_continue_order_extraction(
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:
"""
判断异常是否为瞬时锁冲突(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)
_emit_reservation_heuristic_audit(run=run, merged_by_unit_id=merged_by_unit_id)
append_shipping_audit_event(
event_type='ORDER_EMAIL_ADJUDICATION_COMPLETED',
aggregate_type='order_extraction_run',
+15 -1
View File
@@ -2,7 +2,7 @@
backend/app/models/__init__.py
用途:按业务域拆分的 ORM 模型包入口;聚合导出以保持 `from app.models import User` 兼容。
依赖:models/* 子模块(含 voucher_check)、app.extensions.db(经 base.Base)。
依赖:models/* 子模块(含 voucher_check、equipment_acceptance)、app.extensions.db(经 base.Base)。
逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。
"""
@@ -238,6 +238,14 @@ from app.models.contract_payment import (
ContractPaymentSyncState,
ContractPaymentVendorRequest,
)
from app.models.equipment_acceptance import (
EquipmentAcceptanceNode,
EquipmentAcceptanceOperator,
EquipmentAcceptanceOrder,
EquipmentAcceptanceSendFile,
EquipmentAcceptanceSendRecord,
EquipmentAcceptanceSetting,
)
from app.models.order_delivery_reply import (
OrderDeliveryAuditEvent,
OrderDeliveryBatch,
@@ -434,6 +442,12 @@ __all__ = [
'ContractPaymentAlert',
'ContractPaymentAlertBatch',
'ContractPaymentSyncState',
'EquipmentAcceptanceOrder',
'EquipmentAcceptanceNode',
'EquipmentAcceptanceOperator',
'EquipmentAcceptanceSetting',
'EquipmentAcceptanceSendFile',
'EquipmentAcceptanceSendRecord',
'TransferRun',
'TransferSourceJob',
'TransferMatching',
+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)
@@ -30,8 +30,9 @@ class ShippingDocumentProfileAutoFreezeQualification(Base):
"status IN ('manual_confirmation', 'auto_freeze_approved', 'auto_freeze_suspended')",
name='ck_shipping_document_profile_auto_freeze_qualification_status',
),
# 索引名沿用迁移 0aa34b5c6d7e 的短名;PostgreSQL 标识符上限 63 字符,超长名会导致建库失败。
Index(
'ix_shipping_document_profile_auto_freeze_qualification_profile_status',
'ix_ship_doc_prof_auto_freeze_profile_status',
'profile_id', 'status',
),
)
@@ -104,6 +104,9 @@ class ShippingNoticeLineInventoryMatch(Base):
required_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)
# 料号维度总可用量(忽略预约号、行允许源内汇总);预约号不匹配行的放行兜底依据。
# 历史行与无快照行为 NULL,前端显示占位符;重新匹配后回填。
part_available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
reservation_id: 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)
@@ -204,9 +204,10 @@ class ShippingOrderDocumentProfileSuggestionDecision(Base):
__tablename__ = 'shipping_order_document_profile_suggestion_decisions'
__table_args__ = (
CheckConstraint("decision IN ('accepted', 'accepted_adjusted', 'rejected')", name='ck_shipping_order_document_profile_suggestion_decisions_decision'),
UniqueConstraint('profile_id', 'suggestion_id', name='uq_shipping_order_document_profile_suggestion_decisions_suggestion'),
Index('ix_shipping_order_document_profile_suggestion_decisions_profile_revision', 'profile_id', 'revision_no'),
# 约束/索引名沿用迁移的短名;PostgreSQL 标识符上限 63 字符,超长名会导致建库失败。
CheckConstraint("decision IN ('accepted', 'accepted_adjusted', 'rejected')", name='ck_order_profile_suggestion_decision'),
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)
@@ -238,8 +239,8 @@ class ShippingOrderDocumentProfileValidationRun(Base):
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'),
Index('ix_shipping_order_document_profile_validation_runs_profile_created', 'profile_id', 'created_at'),
Index('ix_shipping_order_document_profile_validation_runs_checksum', 'profile_id', 'definition_checksum'),
Index('ix_order_profile_validation_created', 'profile_id', 'created_at'),
Index('ix_order_profile_validation_checksum', 'profile_id', 'definition_checksum'),
)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -268,10 +269,10 @@ class ShippingOrderDocumentProfilePublishCheckReport(Base):
__tablename__ = 'shipping_order_document_profile_publish_check_reports'
__table_args__ = (
CheckConstraint("status IN ('valid', 'invalidated', 'consumed')", name='ck_shipping_order_document_profile_publish_check_reports_status'),
UniqueConstraint('profile_id', 'operation_id', name='uq_shipping_order_document_profile_publish_check_reports_operation'),
Index('ix_shipping_order_document_profile_publish_check_reports_profile_created', 'profile_id', 'created_at'),
Index('ix_shipping_order_document_profile_publish_check_reports_report_no', 'report_no', unique=True),
CheckConstraint("status IN ('valid', 'invalidated', 'consumed')", name='ck_sodppcr_status'),
UniqueConstraint('profile_id', 'operation_id', name='uq_sodppcr_profile_operation'),
Index('ix_sodppcr_profile_created', 'profile_id', 'created_at'),
Index('ix_sodppcr_report_no', 'report_no', unique=True),
)
id: Mapped[int] = mapped_column(primary_key=True)
+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:
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(
code='CASDOOR_AUTH_FAILED',
message='Authentication failed, please try again',
+24 -2
View File
@@ -141,7 +141,21 @@ def emit_run_failed(
conversation_id: str,
message: str,
code: str | None = None,
user_facing: bool = False,
) -> 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] = {
"event": "run.failed",
"run_id": run_id,
@@ -150,10 +164,18 @@ def emit_run_failed(
"message": message,
"session_status": "error",
}
legacy_payload: dict[str, Any] = {
"event": "error",
"message": message,
"conversation_id": conversation_id,
"session_status": "error",
}
if code:
error_payload["code"] = code
legacy = sse_frame({"event": "error", "message": message, "conversation_id": conversation_id, "session_status": "error"})
return sse_frame(error_payload) + legacy
if user_facing:
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:
@@ -194,6 +194,7 @@ class ChatTurnRuntime:
conversation_id=session.session_id,
message=exc.message,
code=str(getattr(exc, "code", "") or "") or None,
user_facing=True,
)
except Exception as exc:
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,不猜测。
合同金额以正文抽出的正数为准;OA 的 0 与空值都不是有效总额。同一付款阶段的相同比例重复抽取不报重复。
增值税税率和「收到定金后 N 天」不计入付款比例。
"""
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_]*日?")
_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。;;]*)")
_WARRANTY_RE = re.compile(r"(?:质保期|保修期|保固期|质保款[^。;;\n]{0,100}?)(?:满后|为|:|:)?\s*(\d+)\s*(年|个月|月|天)")
_WARRANTY_PAYMENT_RE = re.compile(
@@ -146,12 +152,82 @@ def unique_parse_issues(issues: list[Any] | None) -> list[str]:
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]]:
"""
提取四阶段付款比例,并校验阶段完整性及比例合计。
核心逻辑:同一语义阶段只允许一个比例。正文里同一比例被抽到多次(表格/页眉重复)
视为同一事实,不报重复;只有同一阶段出现不同比例才阻断。四阶段须完整且合计 100%。
增值税税率和「收到定金后 N 天」不计入付款比例。
Args:
body: 已抽取的合同正文。
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}
issues: list[str] = []
for match in _PERCENT_RE.finditer(body):
label, raw = match.groups()
matched = _matched_payment_percentages(body)
for label, raw in matched:
node_type = _PAYMENT_LABEL_TO_NODE_TYPE[label]
percentage = _parse_decimal(raw)
if percentage is None:
@@ -181,7 +257,6 @@ def _extract_payment_percentages(body: str) -> tuple[dict[str, Decimal], list[st
if missing:
issues.append(f"付款阶段比例无法识别:{'、'.join(_PAYMENT_NODE_LABELS[item] for item in missing)}")
try:
matched = [(m.group(1), m.group(2)) for m in _PERCENT_RE.finditer(body)]
snippet = ""
for label in ("质保款", "验收款", "尾款"):
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)
@@ -32,6 +32,8 @@ class AutoTransferOutcome:
def run_auto_transfer(*, business_date: str, deps: TransferDeps,
source_codes: list[str] | None = None,
recover_history: bool = True,
receipt_date_from: str | None = None,
receipt_date_to: str | None = None,
sender: WeComSender | None = None,
recipients: list[str] | None = None) -> AutoTransferOutcome:
"""执行一次自动调拨排程。
@@ -44,6 +46,8 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
deps: 注入依赖。
source_codes: 来源实例列表(缺省全部启用来源)。
recover_history: 是否执行历史恢复。
receipt_date_from / receipt_date_to: 可选收料日期范围(测试/排障缩小
匹配面;留空=全部成熟积压;非法范围由匹配层抛 ValidationError)。
sender / recipients: 企微通知(None 则跳过通知;run_no 为空时不发送)。
Returns:
AutoTransferOutcome;空数据日时 run_no/run_status 均为 None 且 errors 为空。
@@ -59,6 +63,8 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
source_codes=source_codes or [],
business_date=business_date,
deps=deps,
receipt_date_from=receipt_date_from,
receipt_date_to=receipt_date_to,
)
# [STEP 2] 空数据日跳过执行:匹配后无可执行行(含恢复后仍为 0)时不建票、
# 不写 ERP、不通知(产品决策 C5);该日仅留痕 Run/Matching,不视作失败。
@@ -112,17 +112,26 @@ class MatchingItemDTO:
# 不参与匹配身份与 Hash 快照;空值行在匹配阶段落 blocked_missing_unit。
unit: str = ""
# 行装饰字段(restore 按 scope 实时视图时填齐;run_matching 快照路径保持缺省):
# item_id=行主键(批量操作/待处理池回链);checked_at=行评估时间(updated_at);
# stale=评估时间距今超过确认 TTL;file_current=行评估版本戳仍是该来源当前可用文件。
# item_id=行主键(批量操作/待处理池回链);checked_at=行库存查得时刻(见 _item_dto);
# stale=距库存取数超过展示阈值;file_current=行评估版本戳仍是该来源当前可用文件。
item_id: int = 0
checked_at: str | None = None
stale: bool = False
file_current: bool = False
# [2026-10-12 单据数口径修正] 执行建单五元组首键:路由解析所得外部组织
# (execution_service.prepare_execution 同款 .strip() 口径)。匹配评估路径填齐,
# 供「预计 ERP 单据数」按五元组去重与前端勾选行预估;restore 视图路径缺省 ""。
external_org: str = ""
@dataclass(frozen=True)
class MatchingSummaryDTO:
"""匹配摘要(含预计调拨数量、预计 外部系统 写入数与匹配 Hash)。"""
"""匹配摘要(含预计调拨数量、预计 ERP 单据数与匹配 Hash)。
estimated_external_write_count(2026-10-12 口径修正):可执行行按执行建单
五元组 (external_org, source_code, receipt_date, from_warehouse, to_warehouse)
去重后的单据数,非可执行行数——同组多行在执行期合并一张 ERP 单。
"""
matching_id: str
status: str
@@ -10,7 +10,7 @@ from __future__ import annotations
from dataclasses import dataclass
from datetime import date, datetime
from decimal import Decimal
from decimal import Decimal, InvalidOperation
from typing import Any, Iterable, Mapping
from app.core.errors import AppError
@@ -59,16 +59,26 @@ def _fail(rows: list[dict[str, Any]], *, row_no: Any, reason: str) -> None:
rows.append({"row_no": row_no, "reason": reason})
def _is_unreceived_row(date_value: Any) -> bool:
"""判断是否为"无收料事实的在途行":无异动日期即跳过。
def _is_unusable_receipt_row(date_value: Any, quantity_raw: Any) -> bool:
"""判断是否为"非可用收料事实"的行:跳过,不参与匹配,也不阻断整文件。
WMS 异动报告会携带两类无日期行,均不是可用的收料事实:
WMS 异动报告会携带三类非可用收料行,均不是可用的收料事实:
① 未收料在途 ASN(Date Received 空、Qty Received 0);
② 收料执行中(ASN Status=Executing,Qty Received 已计数但收料日期未盖章)。
收料日期是匹配身份与成熟过滤的必要字段,缺失即无法参与匹配;
跳过后由下次排程抓取补齐(ASN 完成时盖章日期),不得整文件阻断。
② 收料执行中(ASN Status=Executing,Qty Received 已计数但收料日期未盖章);
③ 零数量收料行(Date Received 已盖章但 Qty Received = 0;2026-10-08 CRANE
WTP26082227 实测——扫码收货数量记在他行/收货取消的占位行)。
收料日期与正数量是行级匹配身份与成熟过滤的必要字段;此类行跳过后由下次排程
抓取补齐(WMS 补数量/盖章后自然带出),不得整文件阻断。
"""
return not (isinstance(date_value, (date, datetime)) or str(date_value or "").strip())
if not (isinstance(date_value, (date, datetime)) or str(date_value or "").strip()):
return True
try:
# 只跳过恰好为 0 的零收料行;负数属数据损坏,交由 validate_receipt_quantity 阻断。
return Decimal(str(quantity_raw)) == 0
except (InvalidOperation, ValueError, TypeError):
# 数量缺失/空:日期已盖章但无数量,同为零收料家族;非数字垃圾交由
# validate_receipt_quantity 按非法数量阻断,不在此吞掉。
return not str(quantity_raw or "").strip()
def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
@@ -174,7 +184,7 @@ def _parse_rows(
if row_source and row_source.upper() != str(source_code).upper():
_fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}")
continue
if _is_unreceived_row(receipt_date_value):
if _is_unusable_receipt_row(receipt_date_value, quantity_raw):
continue
try:
receipt_date = parse_date(receipt_date_value)
@@ -202,5 +212,8 @@ def _parse_rows(
unit=str(row.get("unit") or "").strip(),
))
if errors:
raise ReceiptFileSchemaError(rows=errors)
# 诊断落库:消息携带前 3 条行级明细(行号+原因),随 parse_error_message
# 落库自描述(2026-10-08 CRANE 零数量行事故:此前只有通用消息、无法定位)。
summary = '; '.join(f"row {r.get('row_no')}: {r.get('reason')}" for r in errors[:3])
raise ReceiptFileSchemaError(f"receipt file schema invalid: {summary}", rows=errors)
return parsed
@@ -389,6 +389,23 @@ def run_matching(
estimated_quantity = sum(
(item.to_quantity for item in items if item.result == RESULT_EXECUTABLE), Decimal("0")
)
# [2026-10-12 单据数口径修正] 预计 ERP 单据数 ≠ 可执行行数:执行建单按五元组
# (external_org, source_code, receipt_date, from_warehouse, to_warehouse) 分组,
# 同组多行合并一张 ERP 单(execution_service.prepare_execution 同键同 .strip()
# 规范化)。本值 = 可执行行按同款五元组去重后的组数;行上 external_org 由
# 匹配评估随路由解析填齐(_matching_rows 评估分支)。原「= executable_count」
# 口径在多行同组时高估单据数,误导用户。
estimated_document_keys = {
(
item.external_org,
str(item.source_code or "").strip(),
str(item.receipt_date or "").strip(),
str(item.from_warehouse or "").strip(),
str(item.to_warehouse or "").strip(),
)
for item in items
if item.result == RESULT_EXECUTABLE
}
snapshot = {
"scope": sorted(set(source_codes)),
"business_date": business_date,
@@ -433,7 +450,7 @@ def run_matching(
expires_at="",
counts=counts,
estimated_transfer_quantity=str(estimated_quantity),
estimated_external_write_count=counts.executable_count,
estimated_external_write_count=len(estimated_document_keys),
matching_hash=matching_hash,
)
return MatchingRunResult(summary=summary, items=tuple(items), sources=sources_tuple)
@@ -621,8 +638,11 @@ def _matching_rows(
row.result_code = match
row.result_message = "strict quantity mismatch"
row.updated_at = now
# 本行已完成路由解析:external_org 随行透出(执行建单五元组首键,
# 2026-10-12 单据数口径修正——预计单据数按五元组去重依赖本字段)。
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
int(deps.strategy.inventory_stale_ttl_seconds)))
int(deps.strategy.inventory_stale_ttl_seconds),
external_org=str(route.external_org or "").strip()))
return output, pending_count
@@ -944,6 +964,7 @@ def _item_dto(
latest: dict,
moment: datetime,
inventory_stale_ttl_seconds: int,
external_org: str = "",
) -> MatchingItemDTO:
"""把 InvoiceItem 装饰为前端行 DTO(restore 视图与可调拨明细队列共用)。
@@ -953,8 +974,10 @@ def _item_dto(
moment: 新鲜度判定基准时间。
inventory_stale_ttl_seconds: stale 展示阈值(strategy.inventory_stale_ttl_seconds;
仅驱动 stale 徽标提示,不阻断执行——2026-09-25 TTL 门禁退役)。
external_org: 路由解析所得外部组织(执行建单五元组首键,2026-10-12 单据数
口径修正);仅匹配评估路径可填,restore 视图路径缺省 ""。
Returns:
MatchingItemDTO(含 item_id / checked_at / stale / file_current)。
MatchingItemDTO(含 item_id / checked_at / stale / file_current / external_org)。
"""
evaluated_sha = _item_evaluated_sha(item)
inventory_checked_at = item.inventory_checked_at
@@ -1002,6 +1025,7 @@ def _item_dto(
stale=bool(inventory_checked_at)
and (moment - inventory_checked_at).total_seconds() > inventory_stale_ttl_seconds,
file_current=bool(evaluated_sha) and evaluated_sha == latest.get("file_sha256"),
external_org=external_org,
)
@@ -1,6 +1,6 @@
"""在途调拨真实收料 RPA 触发服务。
用途:为单个来源触发一次收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。
用途:为单个或多个来源触发收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。
按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile,
先落 ShippingReceiptRpaUnitRun(awaiting_rpa,回调按 callback_id 查库可达),
再装配收料 trigger unit 并调用 write_receipt_export_batch_trigger 原子写 trigger。
@@ -8,11 +8,14 @@
逻辑:list_receipt_capable_source_codes 供排程 source_codes 留空时的缺省范围;
一源一单元,query_parameters 原样下发;来源停用/收料配置缺失/rpa_profile 缺失时
fail-closed;写 trigger 失败把单元行标 failed 并 commit。
trigger_receipt_rpa_batch(2026-10-09)把多来源合并为一个 batch trigger 文件:
Worker 对单文件按 profile 分组共享一次浏览器会话,避免逐来源开/关浏览器。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from typing import Any, Callable
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
@@ -151,3 +154,117 @@ def trigger_receipt_rpa(
unit.trigger_snapshot_json = unit_payload
db.session.commit()
return {"ok": True, "callback_id": unit_payload['callback_id'], "trigger_path": path}
def trigger_receipt_rpa_batch(
*,
source_codes: list[str],
business_date: str,
reason: str = 'transfer_retry_receipt',
writer: RouteTriggerWriter | None = None,
) -> dict[str, Any]:
"""批量触发多来源收料 RPA:全部有效来源合并写**一个** batch trigger 文件。
【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个来源编码时调用;
行级单来源重试仍走 trigger_receipt_rpa(一源一文件语义不变)。
核心逻辑:逐来源装配 unit(来源级隔离——配置缺失/停用跳过并记录,不炸整批;
parse_failed 先本地重解析,恢复 ready 则不触发 RPA),有效 units 先各落一行
ShippingReceiptRpaUnitRun 再一次性 write_receipt_export_batch_trigger 原子落盘。
Worker 对单文件按 profile 分组共享一次浏览器会话串行导出,避免逐来源开/关浏览器。
Args:
source_codes: 来源实例编码列表(去重保序;空串自动剔除)。
business_date: 业务日期。
reason: 触发原因(写入 trigger payload)。
writer: 触发写者;缺省复用 write_receipt_export_batch_trigger。
Returns:
{"ok": True/False, "triggered": bool, "results": [...], "trigger_path"?/「error_code」?}。
ok=本次请求产生了主效果(写盘成功,或无需写盘且全部来源经本地重解析恢复);
triggered=是否写了 batch trigger;results 逐来源携带真实结果
(触发:{source_code, ok: true};重解析:{..., reparsed: true, file_status};
跳过:{source_code, ok: false, error_code, error_message})。
"""
from app import db
from app.models import ShippingReceiptRpaUnitRun
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
codes = list(dict.fromkeys(str(code).strip() for code in source_codes if str(code).strip()))
results: list[dict[str, Any]] = []
units: list[ShippingReceiptRpaUnitRun] = []
unit_payloads: list[dict[str, Any]] = []
# [STEP 1] 解析失败分层(对齐单来源端点)+ 逐来源装配 unit;单源失败跳过不阻断整批。
for code in codes:
status = resolve_source_file_status(source_code=code)
if status.get('file_status') == 'parse_failed' and status.get('file_sha256'):
sync_and_commit_for_callback(
source_code=code, business_date=business_date, now=datetime.utcnow(),
)
status = resolve_source_file_status(source_code=code)
results.append({
'source_code': code,
'ok': status.get('file_status') == 'ready',
'reparsed': True,
'file_status': status.get('file_status'),
})
continue
try:
unit_payloads.append(_build_trigger_unit(source_code=code, business_date=business_date, reason=reason))
except RuntimeError as exc:
results.append({
'source_code': code, 'ok': False,
'error_code': 'RPA_RECEIPT_CONFIG_MISSING', 'error_message': str(exc),
})
if not unit_payloads:
# 无可触发来源:全部经重解析恢复 → 请求已达成目的;否则如实报无可用来源。
reparse_recovered = any(item.get('reparsed') and item.get('ok') for item in results)
db.session.commit()
if reparse_recovered:
return {"ok": True, "triggered": False, "results": results}
return {"ok": False, "triggered": False, "error_code": "RPA_RECEIPT_NO_TRIGGERABLE_SOURCE", "results": results}
# [STEP 2] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库(与单来源同模式)。
for payload in unit_payloads:
unit = ShippingReceiptRpaUnitRun(
inventory_source_id=payload['inventory_source_id'],
source_code=payload['source_code'],
connector_type=payload['connector_type'],
warehouse_id=payload.get('warehouse_id'),
callback_id=payload['callback_id'],
status='awaiting_rpa',
config_snapshot_json=dict(payload['config_snapshot']),
)
db.session.add(unit)
units.append(unit)
db.session.flush()
for unit, payload in zip(units, unit_payloads):
payload['unit_run_id'] = unit.id
# [STEP 3] 一个 batch trigger 原子落盘;目录不可用则本批单元全部标 failed(不留永久 awaiting)。
run_no = f"TRIG-BATCH-{uuid.uuid4().hex[:8].upper()}"
writer_fn = writer or write_receipt_export_batch_trigger
path = writer_fn(run_no, unit_payloads, payload={
'schema_version': 'shipping_receipt_rpa.v1',
'action': 'receipt_export_batch',
'business_date': business_date,
'reason': reason,
'source_codes': [payload['source_code'] for payload in unit_payloads],
})
if not path:
for unit in units:
unit.status = 'failed'
unit.error_code = 'RPA_RECEIPT_TRIGGER_UNAVAILABLE'
unit.error_message = 'receipt trigger directory unavailable'
db.session.commit()
return {"ok": False, "triggered": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE", "results": results}
# [STEP 4] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。
for unit, payload in zip(units, unit_payloads):
unit.trigger_snapshot_json = payload
results.append({'source_code': unit.source_code, 'ok': True})
db.session.commit()
return {"ok": True, "triggered": True, "trigger_path": path, "results": results}
@@ -81,6 +81,9 @@ def serialize_item(item) -> dict[str, Any]:
"to_quantity": str(item.to_quantity),
# 交易单位原值透传(movement 契约第 11 字段 unit,T7 交接:序列化缺口补齐)。
"unit": item.unit,
# [2026-10-12 单据数口径修正] 执行建单五元组首键透传:前端按勾选行
# 预估 ERP 单据数与后端同口径分组(匹配评估路径填齐,历史回放缺省 "")。
"external_org": item.external_org,
"result": item.result,
"reason": item.reason,
"raw_lines": [
@@ -26,7 +26,10 @@ from app.services.in_transit_transfer.receipt_file_gate import (
)
RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing')
FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled')
FAILED_UNIT_STATUSES = ('failed', 'cancelled')
# 空数据(no_receipt_data):抓取成功但当日无收料记录,属业务结果而非故障,
# 独立投影 no_data 供前端如实展示(2026-10-08:曾误并入 failed 致无法分辨真失败)。
NO_DATA_UNIT_STATUSES = ('empty',)
def resolve_source_file_status(*, source_code: str) -> dict:
@@ -37,7 +40,7 @@ def resolve_source_file_status(*, source_code: str) -> dict:
Returns:
{"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...},
file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'expired', 'none'};
file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'no_data', 'expired', 'none'};
parse_failed 表示文件仍可用但解析失败:has_ready_file=False,
仍带 file_no/file_sha256 便于诊断与前端提示。
"""
@@ -84,6 +87,9 @@ def resolve_source_file_status(*, source_code: str) -> dict:
.order_by(ShippingReceiptRpaUnitRun.id.desc())
.first()
)
if latest_unit is not None and latest_unit.status in NO_DATA_UNIT_STATUSES:
# 空数据:抓取成功但当日无收料记录——如实投影 no_data,不得与抓取失败混淆。
return {'file_status': 'no_data', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
if latest_unit is not None and latest_unit.status in FAILED_UNIT_STATUSES:
return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
+92 -3
View File
@@ -103,6 +103,9 @@ class DifyService:
def _friendly_workflow_failure_message(raw_error: str, agent_name: str | None = None) -> str:
"""
将 Dify/Tool 技术错误转成用户可读提示。
核心逻辑:优先识别知识库重排授权和知识检索失败,再按工具、上下文长度等归类。
Args:
raw_error: Dify 返回的原始错误文本。
agent_name: 当前触发错误的 Agent 名称,用于返回更贴合页面上下文的提示文案。
@@ -112,6 +115,19 @@ class DifyService:
text = str(raw_error or "")
lower = text.lower()
resolved_agent_name = str(agent_name or "").strip() or "当前智能体"
if "rerank" in lower and ("403" in lower or "forbidden" in lower):
return (
f"{resolved_agent_name}的知识检索重排服务授权失败。"
"请联系管理员在 Dify 中更新 Rerank 模型供应商的 API Key 后重新发布应用。"
)
if any(token in lower for token in (
"knowledge-retrieval",
"knowledge retrieval",
"dataset not found",
"embedding model",
"知识库",
)):
return f"{resolved_agent_name}的知识库检索失败,请稍后重试;如持续失败请联系管理员检查知识库与模型配置。"
if "keyword is required" in lower or re.search(r"\bstatus code 400\b", lower):
return "没有识别到要查询的设备编号或设备名称,请补充完整设备信息后再试。"
if re.search(r"\b(401|403)\b", lower) or "unauthorized" in lower or "invalid_auth" in lower:
@@ -124,6 +140,52 @@ class DifyService:
return "当前会话上下文过长,模型无法继续回答。请新建对话后重新查询。"
return f"{resolved_agent_name}暂时无法完成查询,请稍后重试。"
@staticmethod
def _present_stream_error_message(raw_message: str, status_code: int | None, agent_name: str | None = None) -> str:
"""
把 Dify 流内 error 事件转成可直接展示的提示。
核心逻辑:重排授权、鉴权、地址和网关状态走上游 HTTP 文案;其余走工作流失败文案。
Args:
raw_message: Dify error 事件的 message。
status_code: 事件里的 HTTP 状态;没有时传 0。
agent_name: 当前智能体名称。
Returns:
面向用户的中文提示。
"""
text = str(raw_message or "")
lower = text.lower()
try:
code = int(status_code or 0)
except (TypeError, ValueError):
code = 0
if "rerank" in lower or code in (401, 403, 404, 429, 502, 503, 504):
return DifyService._friendly_upstream_error_message(code, text, agent_name)
return DifyService._friendly_workflow_failure_message(text, agent_name)
@staticmethod
def _friendly_stream_request_failure_message(exc: Exception, agent_name: str | None = None) -> str:
"""
将连接 Dify 时的网络异常转成用户可读提示。
核心逻辑:超时和连接失败分开说明;其余 RequestException 使用当前智能体名称的通用失败句。
Args:
exc: requests 抛出的连接、超时或协议异常。
agent_name: 当前智能体名称。
Returns:
面向用户的中文提示,不包含异常原文。
"""
resolved_agent_name = str(agent_name or "").strip() or "当前智能体"
if isinstance(exc, (requests.exceptions.ReadTimeout, requests.exceptions.ConnectTimeout)):
return f"{resolved_agent_name}等待 AI 服务响应超时,请稍后重试。"
if isinstance(exc, requests.exceptions.ConnectionError):
return f"暂时无法连接{resolved_agent_name}的 AI 服务,请稍后重试。"
return f"{resolved_agent_name}暂时无法完成查询,请稍后重试。"
@staticmethod
def _friendly_upstream_error_message(status_code: int, raw_body: str, agent_name: str | None = None) -> str:
"""将 Dify HTTP 错误转换为可执行的用户提示。
@@ -1106,7 +1168,7 @@ class DifyService:
},
'error',
)
yield f"data: {json.dumps({'event': 'error', 'message': message}, ensure_ascii=False)}\n\n"
yield f"data: {json.dumps({'event': 'error', 'message': message, 'user_facing': True}, ensure_ascii=False)}\n\n"
return
response.raise_for_status()
yield f"data: {json.dumps({'event': 'upstream_connected', 'message': 'Dify 已连接'}, ensure_ascii=False)}\n\n"
@@ -1140,7 +1202,29 @@ class DifyService:
data.get('conversation_id') or normalized_conversation_id,
)
if event == 'node_finished':
if event == 'error':
status_raw = data.get('status')
try:
status_code = int(status_raw)
except (TypeError, ValueError):
status_code = 0
raw_message = str(data.get('message') or '')
# [STEP] 流内 error 先转成用户提示再转发,避免前端只能看到笼统的请求失败。
data['message'] = DifyService._present_stream_error_message(
raw_message,
status_code,
getattr(agent, 'name', None),
)
data['user_facing'] = True
if current_app:
current_app.logger.warning(
"[chat-stream] dify error event request_id=%s agent_id=%s status=%s raw_error=%s",
request_id,
getattr(agent, 'id', None),
status_code,
raw_message,
)
elif event == 'node_finished':
# [STEP] Chatflow 知识检索结果在 node_finished.outputs.result,不在 message_end
DifyService._collect_knowledge_retrieval_from_node(retriever_resources, data)
@@ -1180,6 +1264,7 @@ class DifyService:
)
data['message'] = friendly_error
data['error'] = friendly_error
data['user_facing'] = True
if isinstance(data.get('data'), dict):
data['data']['message'] = friendly_error
data['data']['error'] = friendly_error
@@ -1226,13 +1311,17 @@ class DifyService:
if not is_timeout and attempt < max_retries:
time.sleep(attempt * 2)
continue
message = DifyService._friendly_stream_request_failure_message(e)
message = DifyService._friendly_stream_request_failure_message(
e,
getattr(agent, 'name', None),
)
# [STEP 4] 错误事件与持久化对象必须是同一个 dict,确保 chat_log_id 能继续传给 relay/领域 Handler。
error_event = {
'event': 'error',
'conversation_id': normalized_conversation_id,
'answer': message,
'message': message,
'user_facing': True,
'metadata': {},
}
persist_stream_chat(error_event, 'error')
@@ -5,8 +5,10 @@ backend/app/services/lean_training_push_service.py
同时承担"每周自动滚动创建当周任务"与"推送成功后立即提醒已延期人员"两项周任务规则。
依赖:LeanTrainingWeeklyTask/LeanTrainingVideoPushLog/LeanTrainingReminder/User、lean_training_service(受训对象/当周边界)、lean_training_reminder_service(企微发送模板/延期提醒)、wecom_notify。
逻辑:以 task.pushed_video_count 为游标,每次从游标向后取 weekly_count 个"未被任何任务推送过"的视频(跨任务
按已推送前缀并集去重,推过的视频绝不重复推);员工端展示已推送前缀;
企微 event_key 按"批次区间"幂等防止重复打扰;每轮执行写入 lean_training_video_push_logs 便于管理端查看失败明细;
按已推送前缀并集去重,推过的视频绝不重复推);员工端展示与考核口径为本任务首次推送的视频
(上一期已推送视频不重复展示、不要求重学,见 lean_training_service._own_pushed_video_ids);
企微 event_key 按"批次区间"幂等防止重复打扰(推送后的延期提醒与排程扫描共用"每人每天最多一条"去重,
由 lean_training_reminder_service 统一生成事件键);每轮执行写入 lean_training_video_push_logs 便于管理端查看失败明细;
排程入口每周一 09:00 先自动滚动创建当周任务(复制最近一期配置并自动追加配置新增视频,无需人工维护;
视频库全部推完且无新增视频时暂停滚动、不创建内容重复的新一期),再对各任务推进一批推送。
"""
@@ -234,10 +236,10 @@ def push_lean_training_videos(
)
db.session.add(log)
db.session.commit()
# [STEP 4] 消息推送规则:本批推送成功后立马对任务中"已延期"(过截止未提交)的受训人员发送企微提醒
# [STEP 4] 消息推送规则:本批推送成功后立马对任务中"已延期"(过截止未提交)的受训人员发送企微提醒;
# 延期提醒与排程扫描共用"每人每天最多一条"判定(event_key 由提醒服务按北京日期统一生成)
notify_overdue_users_after_push(
task,
event_key=f"overdue-after-push-{start_index}-{start_index + len(batch)}",
current=current,
)
return serialize_push_log(log)
@@ -4,12 +4,15 @@ backend/app/services/lean_training_reminder_service.py
用途:执行精益管理周度培训的企微提醒生成与发送。
依赖:精益培训任务/完成/提醒模型、User、wecom_notify。
逻辑:排程按周日截止、周一/周三/周五催学规则写入幂等提醒,再由统一企微服务发送并落审计。
催办文案携带期次标签(第N期+周次区间)供员工区分期次;多期过期任务对同一员工合并为
一条汇总提醒,且所有自动催办(排程扫描/推送后延期)共用"每人每天最多一条"判定,
历史期任务过截止超过 OVERDUE_REMINDER_STOP_AFTER_DAYS 天后停止催办。
"""
from __future__ import annotations
import uuid
from datetime import datetime, timezone
from datetime import date, datetime, time, timedelta, timezone
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
@@ -19,9 +22,75 @@ from app.models import LeanTrainingCompletion, LeanTrainingReminder, LeanTrainin
from app.services.lean_training_service import (
resolve_lean_training_jump_agent_id,
target_user_ids_for_task,
week_index_for_task,
)
from app.services.integrations.wecom.notify import send_wecom_event_message
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, utc_now_naive
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, to_utc_naive, utc_now_naive
# 历史期任务停止催办的宽限天数:过截止超过该天数后不再发送任何逾期/延期提醒。
# 任务仍保持 published 供管理端查询与统计,仅静默催办(2026-09-30 用户反馈旧期任务永久催办造成重复打扰)。
OVERDUE_REMINDER_STOP_AFTER_DAYS = 100
# 周中催学发送日(周一/周三/周五,Asia/Shanghai),与排程契约一致。
OVERDUE_REMINDER_WEEKDAYS = {0, 2, 4}
def _period_labels(task: LeanTrainingWeeklyTask) -> tuple[str, str]:
"""
返回周任务的期次标签二元组,供催办文案区分期次。
用途:多期任务并存扫描时,各期提醒文案完全相同,员工完成当期后仍会收到历史期催办,
无法分辨提醒归属哪一期而误以为系统误推(2026-09-30 正式环境用户反馈)。
期号与学员端"第N期"口径一致(week_key 全局升序,最早为第 1 期)。
Returns:
(短标签「第N期」用于标题后缀, 完整标签「第N期(MM-DD至MM-DD)」用于内容前缀);
week_key 脏数据解析失败时返回 ("", ""),调用方回退历史文案,提醒不因标签失败而中断。
"""
try:
week_start = date.fromisoformat(task.week_key)
except ValueError:
return "", ""
week_end = week_start + timedelta(days=6)
index = week_index_for_task(task)
return f"第{index}期", f"第{index}期({week_start.strftime('%m-%d')}至{week_end.strftime('%m-%d')})"
def _overdue_event_key(now: datetime) -> str | None:
"""
返回催办轮次唯一键(overdue-<北京日期>),仅周一/周三/周五返回键,其余日期返回 None。
排程扫描与推送后延期提醒共用同一键空间:同一员工同一自然天的全部自动催办只允许一条,
LeanTrainingReminder 唯一约束 + 发送前"当天已催办"前置查询双重拦截重复推送
(2026-09-30 用户反馈同一员工同一天收到多条相同催办)。
"""
local_now = now.replace(tzinfo=timezone.utc).astimezone(resolve_schedule_tzinfo("Asia/Shanghai"))
if local_now.weekday() not in OVERDUE_REMINDER_WEEKDAYS:
return None
return f"overdue-{local_now.date().isoformat()}"
def _is_overdue_active(task: LeanTrainingWeeklyTask, now: datetime) -> bool:
"""判断任务处于"可催办"窗口:已过截止、且过截止未超过宽限期(超期历史期停止催办)。"""
return task.due_at < now <= task.due_at + timedelta(days=OVERDUE_REMINDER_STOP_AFTER_DAYS)
def _has_overdue_reminder_today(user_id: int, now: datetime) -> bool:
"""
判断员工北京时间当天是否已收到过任意精益自动催办(逾期/延期),实现"每人每天最多一条"。
用途:多期过期任务并存、排程扫描与批次推送两条催办路径同天先后执行时,
后执行的一方据此跳过,避免同一员工同一天收到多条相同催办。
"""
local_tz = resolve_schedule_tzinfo("Asia/Shanghai")
local_now = now.replace(tzinfo=timezone.utc).astimezone(local_tz)
day_floor_utc = to_utc_naive(datetime.combine(local_now.date(), time(0, 0, 0), tzinfo=local_tz))
existing = db.session.execute(
select(LeanTrainingReminder.id).where(
LeanTrainingReminder.recipient_user_id == user_id,
LeanTrainingReminder.event_key.like("overdue-%"),
LeanTrainingReminder.created_at >= day_floor_utc,
).limit(1)
).scalar_one_or_none()
return existing is not None
def _send_reminder(
@@ -126,6 +195,9 @@ def send_targeted_reminders(task_id: int, user_ids: list[int], *, now: datetime
if forbidden_ids:
raise ValueError("Some reminder recipients are outside the task target")
totals = {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
short_label, full_label = _period_labels(task)
title_suffix = f"({short_label})" if short_label else ""
content_prefix = full_label if full_label else "本周"
for recipient in recipients:
if recipient.id in completed_user_ids:
totals["skipped"] += 1
@@ -135,8 +207,8 @@ def send_targeted_reminders(task_id: int, user_ids: list[int], *, now: datetime
recipient=recipient,
event_key=f"targeted-{uuid.uuid4().hex}",
event_type="training_lean_targeted_reminder",
title="精益管理培训定向提醒",
content="您尚未完成本周精益管理培训,请观看指定视频并提交不少于50字的学习感悟。",
title=f"精益管理培训定向提醒{title_suffix}",
content=f"您尚未完成{content_prefix}精益管理培训,请观看指定视频并提交不少于50字的学习感悟。",
current=current,
)
totals["created"] += result != "skipped"
@@ -148,25 +220,27 @@ def send_targeted_reminders(task_id: int, user_ids: list[int], *, now: datetime
def notify_overdue_users_after_push(
task: LeanTrainingWeeklyTask,
*,
event_key: str,
current: datetime | None = None,
) -> dict[str, int]:
"""
视频批次推送成功后,立即对该任务中"已延期"(已过截止时间且未提交感悟)的受训人员发送企微提醒。
对应周任务消息推送规则:每次推送周任务成功后立马推送延期提醒(与批次 event_key 绑定幂等,同批重推不重复打扰)。
对应周任务消息推送规则:每次推送周任务成功后立马推送延期提醒。
去重规则(2026-09-30 用户反馈消息太多):与排程扫描共用 overdue-<北京日期> 事件键与
"每人每天最多一条自动催办"前置判定——员工当天已收到过任意精益催办(含排程扫描、
其它批次延期提醒)时本路径静默跳过,确保同一员工同一自然天只收到一条催办。
已过截止超过 OVERDUE_REMINDER_STOP_AFTER_DAYS 天的历史期任务不再发送(历史期补推不再催办旧账)。
Args:
task: 刚完成视频推送的周任务(必须已发布)。
event_key: 幂等键,建议携带批次区间(如 overdue-after-push-0-2),与推送批次一一对应。
current: 覆盖当前时间(UTC naive,测试用)。
Returns:
{"created", "sent", "skipped", "failed"} 汇总统计。
"""
now = current or utc_now_naive()
totals = {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
# 未过截止时间不存在"已延期"人员,直接返回,避免无意义扫描
if now <= task.due_at:
# 未过截止时间不存在"已延期"人员;超宽限期的历史期任务同样跳过,避免对旧账无限催办
if not _is_overdue_active(task, now):
return totals
completed_user_ids = set(
db.session.execute(
@@ -178,14 +252,21 @@ def notify_overdue_users_after_push(
)
overdue_ids = target_user_ids_for_task(task) - completed_user_ids
users = db.session.execute(select(User).where(User.id.in_(overdue_ids), User.status == "active")).scalars().all() if overdue_ids else []
event_key = _overdue_event_key(now)
short_label, full_label = _period_labels(task)
title_suffix = f"({short_label})" if short_label else ""
content_prefix = full_label if full_label else "本周"
for user in users:
if _has_overdue_reminder_today(user.id, now):
totals["skipped"] += 1
continue
result = _send_reminder(
task=task,
recipient=user,
event_key=event_key,
event_key=event_key or f"overdue-after-push-{uuid.uuid4().hex}",
event_type="training_lean_overdue",
title="精益管理培训延期提醒",
content="您本周精益管理培训已延期,尚未完成视频观看与学习感悟提交,请尽快完成。",
title=f"精益管理培训延期提醒{title_suffix}",
content=f"您{content_prefix}精益管理培训已延期,尚未完成视频观看与学习感悟提交,请尽快完成。",
current=now,
)
totals["created"] += result != "skipped"
@@ -194,45 +275,65 @@ def notify_overdue_users_after_push(
return totals
def _event_key(task: LeanTrainingWeeklyTask, now: datetime) -> str | None:
"""按周日截止后的周一、周三、周五计算本轮逾期提醒唯一键。"""
if now <= task.due_at:
return None
local_now = now.replace(tzinfo=timezone.utc).astimezone(resolve_schedule_tzinfo("Asia/Shanghai"))
weekday = local_now.weekday()
if weekday not in {0, 2, 4}:
return None
return f"overdue-{local_now.date().isoformat()}"
def run_lean_training_reminders(*, now: datetime | None = None) -> dict[str, int]:
"""扫描未完成人员并发送本轮提醒,重复运行由唯一约束确保不重复推送。"""
"""扫描全部已发布任务,按"每人每天一条"发送合并逾期提醒,重复运行由当天去重与唯一约束兜底。
合并规则(2026-09-30 用户反馈多期并存时每人收到多条相同催办):周一/周三/周五扫描时,
同一员工名下全部可催办期次(已过截止且未超宽限期、本人未完成)合并为一条提醒——单期文案
携带该期次标签,多期汇总各期标签并注明期数;卡片跳转定位到其最近一期未完成任务。
提醒文案携带期次标签(第N期+周次区间)供员工区分期次,避免完成当期后仍收到历史期
相同提醒而被误认为系统误推。
"""
current = now or utc_now_naive()
event_key = _overdue_event_key(current)
if not event_key:
return {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
tasks = db.session.execute(select(LeanTrainingWeeklyTask).where(LeanTrainingWeeklyTask.status == "published")).scalars().all()
created = sent = skipped = failed = 0
# [STEP 1] 汇总各员工全部可催办期次:已过截止、未超宽限期、本人属于受训对象且未完成
pending: dict[int, list[LeanTrainingWeeklyTask]] = {}
for task in tasks:
event_key = _event_key(task, current)
if not event_key:
if not _is_overdue_active(task, current):
continue
completed_user_ids = set(db.session.execute(select(LeanTrainingCompletion.user_id).where(LeanTrainingCompletion.weekly_task_id == task.id, LeanTrainingCompletion.status == "completed")).scalars())
target_user_ids = target_user_ids_for_task(task)
users = db.session.execute(select(User).where(User.id.in_(target_user_ids - completed_user_ids))).scalars().all() if target_user_ids else []
for user in users:
result = _send_reminder(
task=task,
recipient=user,
event_key=event_key,
event_type="training_lean_overdue",
title="精益管理培训逾期提醒",
content="本周精益管理培训尚未完成,请观看指定视频并提交不少于50字的学习感悟。",
current=current,
)
created += result != "skipped"
if result == "sent":
sent += 1
elif result == "failed":
failed += 1
else:
skipped += 1
for user_id in sorted(target_user_ids_for_task(task) - completed_user_ids):
pending.setdefault(user_id, []).append(task)
if not pending:
return {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
# [STEP 2] 每人仅发一条:按周次倒序取最近一期未完成任务作卡片跳转主任务,多期时汇总各期标签
users = db.session.execute(select(User).where(User.id.in_(list(pending)))).scalars().all()
created = sent = skipped = failed = 0
for user in users:
if _has_overdue_reminder_today(user.id, current):
skipped += 1
continue
user_tasks = sorted(pending[user.id], key=lambda item: item.week_key, reverse=True)
primary = user_tasks[0]
period_labels = [_period_labels(item) for item in reversed(user_tasks)]
if len(user_tasks) == 1:
short_label, full_label = period_labels[0]
title_suffix = f"({short_label})" if short_label else ""
content_prefix = full_label if full_label else "本周"
title = f"精益管理培训逾期提醒{title_suffix}"
content = f"{content_prefix}精益管理培训尚未完成,请观看指定视频并提交不少于50字的学习感悟。"
else:
joined_labels = "、".join(full for _, full in period_labels if full)
title = f"精益管理培训逾期提醒(共{len(user_tasks)}期未完成)"
content = f"您共有{len(user_tasks)}期精益管理培训尚未完成:{joined_labels},请观看指定视频并提交不少于50字的学习感悟。"
result = _send_reminder(
task=primary,
recipient=user,
event_key=event_key,
event_type="training_lean_overdue",
title=title,
content=content,
current=current,
)
created += result != "skipped"
if result == "sent":
sent += 1
elif result == "failed":
failed += 1
else:
skipped += 1
db.session.commit()
return {"created": created, "sent": sent, "skipped": skipped, "failed": failed}
+77 -24
View File
@@ -3,8 +3,9 @@ backend/app/services/lean_training_service.py
用途:精益管理培训的周任务、员工提交、看板和提醒规则服务。
依赖:TrainingConfig/Resource、精益培训模型、User、统一 ValidationError。
逻辑:管理端冻结每周视频列表、每周推送数量与受训对象;员工仅对已推送批次提交观看事实与学习感悟;
服务端按 50 字门槛判定完成,管理看板只读取已授权范围。
逻辑:管理端冻结每周视频列表、每周推送数量与受训对象;学员端"本期视频"口径为本任务首次推送的
视频(已推送前缀扣除其它更早期任务已推送部分,推过的视频不重复展示、不要求重学);
员工仅对本期视频提交观看事实与学习感悟,服务端按 50 字门槛判定完成,管理看板只读取已授权范围。
"""
from __future__ import annotations
@@ -267,15 +268,21 @@ def is_task_targeted_to_user(task: LeanTrainingWeeklyTask, user: User) -> bool:
return user.status == "active" and (user.id in set(task.target_user_ids or []) or user.role in set(task.target_roles or []))
def serialize_weekly_task(task: LeanTrainingWeeklyTask, *, learner_view: bool = False) -> dict[str, Any]:
"""序列化精益周任务;员工端视图仅含已推送视频前缀(游标内),管理端返回全量选择列表。
def serialize_weekly_task(task: LeanTrainingWeeklyTask, *, learner_view: bool = False, own_pushed_ids: list[int] | None = None) -> dict[str, Any]:
"""
序列化精益周任务;管理端返回全量选择列表,学员端视图仅含本任务首次推送的视频(本期视频)。
videos 每项附带 file_url(MinIO 公开地址),供学员端视频缩略图与点击播放使用。
附带 week_index(第 N 期)与 week_end(周日),供前后端拼装"第N周 MM-DD至MM-DD"周次标签。
Args:
own_pushed_ids: 调用方已批量算好的本任务首推视频列表(如列表页一次归一遍历);
缺省时内部单任务计算,避免调用方重复查询。
"""
visible_ids = list(task.video_resource_ids or [])
if learner_view:
visible_ids = visible_ids[: task.pushed_video_count]
# [RULE] 学员端"本期视频"不含其它更早期任务已推送的视频:自动滚动复制上一期冻结列表时,
# 上一期已推送视频不再重复展示、也不要求重学(推过的视频不能重复再推)
visible_ids = own_pushed_ids if own_pushed_ids is not None else _own_pushed_video_ids(task)
resources = db.session.execute(
select(TrainingConfigResource).where(TrainingConfigResource.id.in_(visible_ids))
).scalars().all()
@@ -327,6 +334,46 @@ def _already_pushed_resource_ids(*, exclude_task_id: int | None = None) -> set[i
return pushed
def _first_pushed_video_ids_map() -> dict[int, list[int]]:
"""
一次性计算全部已发布周任务的"本任务首次推送视频"归属映射。
用途:修复自动滚动把上一期冻结列表原样复制进新一期后,学员端按累积前缀(video_resource_ids[:pushed_video_count])
展示与考核,导致上一期已推送视频在第2期重复出现、并要求员工重看重写感悟的问题
(对应"前面任务中推送过的视频不能重复再推"规则,2026-09-29 方案 A)。
核心逻辑:按周次升序(同期唯一)遍历已发布任务,维护"此前已被推送过"的全局集合;
各任务已推送前缀中首次出现的视频归属本任务,与更早期任务重复的视频不属于本任务(本期无需重学)。
Returns:
{task_id: 本任务首次推送的视频资源 ID 顺序列表(保持冻结列表内的相对顺序)}。
"""
tasks = db.session.execute(
select(LeanTrainingWeeklyTask)
.where(LeanTrainingWeeklyTask.status == "published")
.order_by(LeanTrainingWeeklyTask.week_key, LeanTrainingWeeklyTask.id)
).scalars().all()
seen: set[int] = set()
ownership: dict[int, list[int]] = {}
for task in tasks:
prefix_ids = [int(resource_id) for resource_id in list(task.video_resource_ids or [])[: task.pushed_video_count]]
ownership[task.id] = [resource_id for resource_id in prefix_ids if resource_id not in seen]
seen.update(prefix_ids)
return ownership
def _own_pushed_video_ids(task: LeanTrainingWeeklyTask) -> list[int]:
"""
返回指定任务的"本期视频":已推送前缀中本任务首次推送(此前其它任务未推送过)的部分。
用途:学员端展示、观看/完成校验、管理看板视频列统一按此口径取"本周期实际布置的视频",
保证自动滚动复制上一期列表后,上一期已推送视频不再重复出现在新一期。
Args:
task: 精益周任务。
Returns:
本任务首次推送的视频资源 ID 顺序列表。
"""
return _first_pushed_video_ids_map().get(task.id, [])
def _inherited_pushed_video_count(video_ids: list[int]) -> int:
"""
计算手动新建周任务应继承的推送游标:新视频列表的"最长已推送前缀"长度。
@@ -436,7 +483,7 @@ def list_my_weekly_tasks(user: User) -> list[dict[str, Any]]:
"""
返回当前员工被指派的全部已发布精益周任务(按周期倒序,最新在最上),供员工端时间树展示。
每项为学员视角序列化(仅已推送视频前缀),并附加:
每项为学员视角序列化(仅本任务首次推送的视频),并附加:
- task_status: completed=已完成感悟提交(completed_at 非空);overdue=未完成且已过截止时间;in_progress=未完成且未到截止;
- completion: 观看草稿(仅记录了视频观看、感悟未提交)或完成记录的总结/观看时间/完成时间摘要,两者均无时为 None。
"""
@@ -446,6 +493,8 @@ def list_my_weekly_tasks(user: User) -> list[dict[str, Any]]:
targeted = [item for item in tasks if is_task_targeted_to_user(item, user)]
if not targeted:
return []
# [STEP] 一次遍历算出各任务首推视频归属,列表页逐任务序列化复用,避免 N 个任务各查一遍全表
own_pushed_map = _first_pushed_video_ids_map()
completions = {
item.weekly_task_id: item
for item in db.session.execute(
@@ -459,7 +508,7 @@ def list_my_weekly_tasks(user: User) -> list[dict[str, Any]]:
items: list[dict[str, Any]] = []
for task in targeted:
completion = completions.get(task.id)
item = serialize_weekly_task(task, learner_view=True)
item = serialize_weekly_task(task, learner_view=True, own_pushed_ids=own_pushed_map.get(task.id, []))
# 只有感悟提交完成(completed_at 非空)才算"已完成";仅有观看草稿时仍按截止时间判定进行中/已延期
item["task_status"] = "completed" if completion and completion.completed_at else ("overdue" if now > task.due_at else "in_progress")
item["completion"] = {
@@ -478,19 +527,19 @@ def mark_video_watched(user: User, data: dict[str, Any]) -> dict[str, Any]:
Args:
user: 当前登录员工。
data: 需包含 weekly_task_id 与 resource_id;resource_id 必须属于该任务已推送的前缀视频。
data: 需包含 weekly_task_id 与 resource_id;resource_id 必须属于本任务首次推送(本期要求学习)的视频。
Returns:
{"watched_at": {resource_id: 观看时间iso字符串}},该任务当前的全部观看记录。
Raises:
NotFoundError: 任务不存在、未发布、未指派给该员工或视频不在已推送范围。
NotFoundError: 任务不存在、未发布、未指派给该员工或视频不属于本期学习范围。
"""
task_id = int(data.get("weekly_task_id") or 0)
resource_id = int(data.get("resource_id") or 0)
task = db.session.get(LeanTrainingWeeklyTask, task_id)
if not task or task.status != "published" or not is_task_targeted_to_user(task, user):
raise NotFoundError("Lean training weekly task not found")
# 员工只能记录已推送前缀视频的观看,防止越权观看未发布视频
if resource_id not in list(task.video_resource_ids or [])[: task.pushed_video_count]:
# 员工只能记录本期视频的观看:其它更早期任务已推送的视频不属于本周期学习范围,防止越权观看未布置内容
if resource_id not in _own_pushed_video_ids(task):
raise NotFoundError("Video resource not in pushed scope")
completion = db.session.execute(
select(LeanTrainingCompletion).where(LeanTrainingCompletion.weekly_task_id == task.id, LeanTrainingCompletion.user_id == user.id)
@@ -514,8 +563,9 @@ def save_completion(user: User, data: dict[str, Any]) -> dict[str, Any]:
raise NotFoundError("Lean training weekly task not found")
if not is_task_targeted_to_user(task, user):
raise NotFoundError("Lean training weekly task not found")
# 员工只能观看已推送的前缀视频,完成校验同样基于已推送范围而非全量选择列表
required_ids = list(task.video_resource_ids or [])[: task.pushed_video_count]
# 员工只能观看本期视频,完成校验同样只考核本任务首次推送的视频:
# 自动滚动复制的上一期已推送视频不要求重学,防止重复学习(推过的视频不能重复再推)
required_ids = _own_pushed_video_ids(task)
# 观看记录以服务端持久化为准(mark_video_watched 已逐个保存),客户端仅作回显兜底,防止伪造观看
# 兜底值入库前归一为 UTC:客户端可能提交北京时间(+08:00)或 UTC(Z)格式,存储一律 UTC
watched = {str(key): parse_client_iso_to_utc_text(value) for key, value in (data.get("watched_at") or {}).items()}
@@ -539,28 +589,29 @@ def save_completion(user: User, data: dict[str, Any]) -> dict[str, Any]:
return serialize_completion(completion, task, user)
def _task_video_rows(task: LeanTrainingWeeklyTask, completion: LeanTrainingCompletion | None) -> list[dict[str, Any]]:
def _task_video_rows(task: LeanTrainingWeeklyTask, completion: LeanTrainingCompletion | None, own_video_ids: list[int] | None = None) -> list[dict[str, Any]]:
"""
生成看板行的视频明细:仅展示本周期内已推送、要求员工学习的视频(推送游标前缀),与学员端可见范围一致。
生成看板行的视频明细:仅展示本周期内布置、要求员工学习的视频(本任务首次推送部分),与学员端可见范围一致。
Args:
task: 当前周任务,视频顺序按管理端冻结时的选择顺序展示(截断到推送游标)。
task: 当前周任务,视频顺序按冻结列表内的相对顺序展示。
completion: 该员工的完成记录;从未观看(无完成记录)时传 None,仅返回视频名称清单(观看时间为 None)。
own_video_ids: 调用方已批量算好的本任务首推视频列表(看板逐行透传,避免每行重算);缺省时内部单任务计算。
Returns:
[{"name": 视频名, "watched_at": 观看时间iso或None}];尚未推送任何视频(游标为 0)时返回空列表,前端展示 "--"。
[{"name": 视频名, "watched_at": 观看时间iso或None}];本任务无首推视频(游标为 0 或前缀全为历史视频)时返回空列表,前端展示 "--"。
"""
titles = {resource.id: resource.title or (resource.agent_guide.file_name if resource.agent_guide else "") for resource in task.config.resources}
watched = dict(completion.watched_at_json or {}) if completion else {}
# [RULE] 看板视频列只展示已推送前缀(video_resource_ids[:pushed_video_count]):未推送视频不属于本周期学习范围,避免名单出现从未布置过的视频
visible_ids = task.video_resource_ids[: task.pushed_video_count]
# [RULE] 看板视频列只展示本期布置的视频(本任务首推部分):上一期已推送的视频不属于本周期学习范围,避免要求重学
visible_ids = own_video_ids if own_video_ids is not None else _own_pushed_video_ids(task)
return [
{"name": titles.get(resource_id, ""), "watched_at": format_beijing_iso(watched.get(str(resource_id)))}
for resource_id in visible_ids
]
def serialize_completion(completion: LeanTrainingCompletion, task: LeanTrainingWeeklyTask, user: User) -> dict[str, Any]:
"""组合看板所需人员、视频观看、总结和完成状态字段。"""
def serialize_completion(completion: LeanTrainingCompletion, task: LeanTrainingWeeklyTask, user: User, own_video_ids: list[int] | None = None) -> dict[str, Any]:
"""组合看板所需人员、视频观看、总结和完成状态字段;own_video_ids 供看板批量透传本期视频口径。"""
# 状态三态归一:已提交感悟为 completed;未完成时按截止时间区分进行中/已延期,管理端状态列直接展示中文
if completion.status == "completed":
status = "completed"
@@ -572,7 +623,7 @@ def serialize_completion(completion: LeanTrainingCompletion, task: LeanTrainingW
"employee_id": user.employee_id,
"name": user.real_name or user.username,
"department": user.department,
"videos": _task_video_rows(task, completion),
"videos": _task_video_rows(task, completion, own_video_ids=own_video_ids),
"summary_text": completion.summary_text,
"status": status,
"completed_at": format_beijing_iso(completion.completed_at),
@@ -595,12 +646,14 @@ def list_dashboard(task_id: int | None) -> dict[str, Any]:
target_user_ids = target_user_ids_for_task(task)
users = db.session.execute(select(User).where(User.id.in_(target_user_ids)).order_by(User.department, User.employee_id)).scalars().all() if target_user_ids else []
completions = {item.user_id: item for item in db.session.execute(select(LeanTrainingCompletion).where(LeanTrainingCompletion.weekly_task_id == task.id)).scalars().all()}
# [STEP] 本期视频口径一次算好逐行透传:看板按人逐行输出,避免每行重算首推归属
own_video_ids = _own_pushed_video_ids(task)
completed: list[dict[str, Any]] = []
incomplete: list[dict[str, Any]] = []
for user in users:
item = completions.get(user.id)
# 无完成记录的指派对象同样三态归一:截止前进行中、截止后已延期;视频列全员一致(仅已推送前缀),仅观看时间为空
row = serialize_completion(item, task, user) if item else {"user_id": user.id, "employee_id": user.employee_id, "name": user.real_name or user.username, "department": user.department, "videos": _task_video_rows(task, None), "summary_text": None, "status": "overdue" if utc_now_naive() > task.due_at else "in_progress", "completed_at": None}
# 无完成记录的指派对象同样三态归一:截止前进行中、截止后已延期;视频列全员一致(仅本期布置视频),仅观看时间为空
row = serialize_completion(item, task, user, own_video_ids=own_video_ids) if item else {"user_id": user.id, "employee_id": user.employee_id, "name": user.real_name or user.username, "department": user.department, "videos": _task_video_rows(task, None, own_video_ids=own_video_ids), "summary_text": None, "status": "overdue" if utc_now_naive() > task.due_at else "in_progress", "completed_at": None}
(completed if row["status"] == "completed" else incomplete).append(row)
return {"task": serialize_weekly_task(task), "completed": completed, "incomplete": incomplete, "periods": periods}
@@ -12,8 +12,10 @@ from __future__ import annotations
from datetime import date, datetime
from decimal import Decimal
from io import BytesIO
from typing import Any
from openpyxl import Workbook
from sqlalchemy import Select, func, or_, select
from app.extensions import db
@@ -30,6 +32,18 @@ STATUS_FILTER_VALUES = {"replied", "not_fully_replied"}
DEFAULT_PAGE_SIZE = 50
MAX_PAGE_SIZE = 200
# 导出兜底上限:防止极端筛选全量导出失控(当前数据量 ~1k 行,远低于该值)。
EXPORT_MAX_ROWS = 10000
# 导出表头(与工作台列顺序一致,交期回复批次合并为单列)。
EXPORT_HEADERS = [
"客户编号", "客户简称", "订单日期", "订单单号", "项次", "产品编号", "品名",
"客户产品编号", "数量", "约定交货日", "交期回复状态", "交期回复批次",
"业务员", "部门", "客户订单", "规格", "单位", "通知时间",
]
STATUS_EXPORT_LABELS = {"not_replied": "未回复", "partial_replied": "部分回复", "replied": "已回复"}
def _utc_to_shanghai(value) -> str | None:
"""naive-UTC 时间转北京时间展示串;仅用于序列化,详情见 api 层同名 helper 注释。"""
@@ -278,6 +292,82 @@ def list_lines(params: dict[str, Any]) -> dict[str, Any]:
return {"items": items, "page": page, "page_size": page_size, "total": total or 0}
def export_lines(params: dict[str, Any]) -> bytes:
"""
导出当前筛选下的全部订单行(xlsx 字节流)。
用途与触发时机:GET /api/order-delivery-reply/lines/export;工作台「导出 Excel」按钮。
核心逻辑:[STEP 1] 与 list_lines 同一筛选与默认排序,不分页(EXPORT_MAX_ROWS 兜底防失控);
[STEP 2] 批量预取批次与锁定状态后序列化;
[STEP 3] openpyxl 生成单工作表(中文表头同工作台列顺序,批次合并为「交期·数量」分号串,
行状态转中文)。
Args:
params: keyword / order_date / status(与列表筛选一致)。
Returns:
xlsx 文件字节流。
"""
stmt = _apply_filters(_base_query(), params).order_by(
OrderDeliveryErpLine.order_date.asc(),
OrderDeliveryErpLine.customer_no.asc(),
OrderDeliveryErpLine.order_no.asc(),
OrderDeliveryErpLine.line_no.asc(),
OrderDeliveryErpLine.part_no.asc(),
).limit(EXPORT_MAX_ROWS)
lines = list(db.session.scalars(stmt).all())
line_ids = [line.id for line in lines]
batches_by_line: dict[int, list[OrderDeliveryBatch]] = {}
states_by_line: dict[int, OrderDeliveryLineState] = {}
if line_ids:
for batch in db.session.scalars(
select(OrderDeliveryBatch)
.where(OrderDeliveryBatch.line_id.in_(line_ids))
.order_by(OrderDeliveryBatch.line_id, OrderDeliveryBatch.seq)
).all():
batches_by_line.setdefault(batch.line_id, []).append(batch)
for state in db.session.scalars(
select(OrderDeliveryLineState).where(OrderDeliveryLineState.line_id.in_(line_ids))
).all():
states_by_line[state.line_id] = state
workbook = Workbook()
sheet = workbook.active
sheet.title = "订单交期回复"
sheet.append(EXPORT_HEADERS)
for line in lines:
item = _serialize_line(line, batches_by_line.get(line.id, []), states_by_line.get(line.id))
batch_text = ";".join(
f"{batch['planned_date']}·{batch['qty']}" for batch in item["batches"] if batch["planned_date"]
)
sheet.append([
item["customer_no"] or "",
item["customer_short_name"] or "",
item["order_date"] or "",
item["order_no"] or "",
item["line_no"],
item["part_no"] or "",
item["part_name"] or "",
item["customer_part_no"] or "",
item["qty"] or "",
item["agreed_date"] or "",
STATUS_EXPORT_LABELS.get(item["status"], item["status"]),
batch_text,
item["salesperson_name"] or item["salesperson_code"] or "",
item["dept_name"] or item["dept_code"] or "",
item["customer_po"] or "",
item["spec"] or "",
item["unit"] or "",
item["notified_at"] or "",
])
buffer = BytesIO()
workbook.save(buffer)
return buffer.getvalue()
def get_line(order_no: str, line_no: int) -> dict[str, Any] | None:
"""
单行详情:快照 + 批次 + 锁定状态 + 该行审计事件。
@@ -11,6 +11,11 @@ backend/app/services/order_delivery_reply/sql.py
# 基础 SELECT:不带分页/排序,同步服务按 oea01 keyset 分页时在外层包装。
# 关联:oea01=oeb01;oeb04=ima01 且 oeb06=ima02;oea03=occ01;oea14=gen01;oea15=gem01。
# 别名与 docs/features/order-delivery-reply/technical-design.md §3.5 标准 SELECT 逐列一致。
# 可选起始日下界(2026-10-09 增补):正式环境经 ORDER_DELIVERY_SYNC_DATE_FROM 注入边界值
# (绑定为 date,oea02 为 Oracle DATE 列),只同步订单日期 ≥ 边界的订单行;
# 未配置边界时服务层不拼接此子句,SQL 本体保持全量口径不变。仅只读 SELECT 约束同上。
ORDER_DELIVERY_DATE_FROM_CLAUSE = "AND a.oea02 >= :order_date_from"
ORDER_DELIVERY_SQL = """
SELECT
a.oea01 AS order_no,
@@ -7,6 +7,9 @@ backend/app/services/order_delivery_reply/sync_service.py
逻辑:按 oea01 keyset 分页拉取合格订单行 → 对 (order_no, line_no) 做 upsert 且只更新 ERP 列白名单
(绝不覆盖批次/锁定)→ 本轮未命中的本地行置 erp_missing=true(不删除)→ 写 sync_runs。
全程模块级锁保证同时只有一个同步;失败保留上次快照并记录错误。
可选起始日下界(2026-10-09):ORDER_DELIVERY_SYNC_DATE_FROM(YYYY-MM-DD,仅正式环境配置)——
只同步订单日期 ≥ 边界的订单行(早于边界的历史行随 erp_missing 语义自动移出工作台);
未配置 = 全量同步(dev/test 现状);配置非法格式 fail-closed 拒绝同步。
"""
from __future__ import annotations
@@ -14,7 +17,7 @@ from __future__ import annotations
import logging
import os
import threading
from datetime import datetime
from datetime import date, datetime
from typing import Any
from sqlalchemy import select, update
@@ -25,10 +28,35 @@ from app.models.order_delivery_reply import (
OrderDeliveryErpLine,
OrderDeliverySyncRun,
)
from app.services.order_delivery_reply.sql import ORDER_DELIVERY_SQL
from app.services.order_delivery_reply.sql import ORDER_DELIVERY_DATE_FROM_CLAUSE, ORDER_DELIVERY_SQL
logger = logging.getLogger(__name__)
def _resolve_sync_date_from() -> date | None:
"""
解析同步起始日下界(环境变量 ORDER_DELIVERY_SYNC_DATE_FROM,YYYY-MM-DD,可选)。
用途与触发时机:run_sync 每轮同步开始时调用;正式环境配置上线日起只同步
订单日期 ≥ 边界的订单行,dev/test 不配置保持全量(需求 2026-10-09)。
约束:配置了但格式非法时 fail-closed 抛 ValueError 拒绝本轮同步——
绝不允许静默回退全量把历史数据抓进正式库。
Returns:
边界日期(含当日);未配置返回 None。
"""
raw = (os.getenv("ORDER_DELIVERY_SYNC_DATE_FROM") or "").strip()
if not raw:
return None
try:
return datetime.strptime(raw, "%Y-%m-%d").date()
except ValueError as exc:
raise ValueError(
f"ORDER_DELIVERY_SYNC_DATE_FROM 格式错误(应为 YYYY-MM-DD):{raw!r};"
"已拒绝执行同步以防止误抓边界外的历史数据"
) from exc
# 同步 upsert 只允许更新这些 ERP 快照列;触碰批次/锁定列会覆盖业务回复,禁止扩充业务列进来。
ERP_LINE_COLUMNS = (
"order_date",
@@ -147,27 +175,40 @@ class OrderDeliverySyncService:
return oracledb.connect(user=user, password=password, dsn=dsn)
@classmethod
def _fetch_page(cls, cursor, last_order_no: str | None) -> list[dict[str, Any]]:
def _fetch_page(
cls,
cursor,
last_order_no: str | None,
date_from: date | None = None,
) -> list[dict[str, Any]]:
"""
按 oea01 keyset 分页拉取一页订单行。
Args:
cursor: oracledb 游标。
last_order_no: 上一页最后一条订单单号;None 表示从头发起。
date_from: 起始日下界(含);None 表示不过滤。条件拼在内层视图
(ROWNUM 之前)——若加在外层会先截断再过滤造成每页缺行漏单。
Returns:
本页行字典列表(列为 sql.ORDER_DELIVERY_SQL 的别名)。
"""
# Oracle 空串即 NULL:首页不能带 `order_no > ''`(与 NULL 比较恒 UNKNOWN 会滤掉全部行),
# 因此首页与续页使用两个 SQL 变体。
binds: dict[str, Any] = {}
date_clause = ""
if date_from is not None:
date_clause = f" {ORDER_DELIVERY_DATE_FROM_CLAUSE}"
binds["order_date_from"] = date_from
if last_order_no:
page_sql = (
f"SELECT * FROM ({ORDER_DELIVERY_SQL} ORDER BY a.oea01) "
f"SELECT * FROM ({ORDER_DELIVERY_SQL}{date_clause} ORDER BY a.oea01) "
f"WHERE order_no > :last_order_no AND ROWNUM <= {_FETCH_SIZE}"
)
cursor.execute(page_sql, last_order_no=last_order_no)
binds["last_order_no"] = last_order_no
cursor.execute(page_sql, binds)
else:
page_sql = f"SELECT * FROM ({ORDER_DELIVERY_SQL} ORDER BY a.oea01) WHERE ROWNUM <= {_FETCH_SIZE}"
cursor.execute(page_sql)
page_sql = f"SELECT * FROM ({ORDER_DELIVERY_SQL}{date_clause} ORDER BY a.oea01) WHERE ROWNUM <= {_FETCH_SIZE}"
cursor.execute(page_sql, binds)
columns = [col[0].lower() for col in cursor.description]
return [dict(zip(columns, row)) for row in cursor.fetchall()]
@@ -230,6 +271,16 @@ class OrderDeliverySyncService:
Returns:
{"run_id", "status", "line_count"};并发冲突返回 status='skipped'。
"""
# 起始日边界先于抢锁解析:配置非法直接抛错(不写 sync_runs),防止误抓边界外历史数据
date_from = _resolve_sync_date_from()
if date_from:
logger.info(
"order-delivery-reply sync date-from boundary: %s (inclusive, order_date >= boundary)",
date_from.isoformat(),
)
else:
logger.info("order-delivery-reply sync date-from boundary: not configured (full sync)")
if not _sync_lock.acquire(blocking=False):
return {"run_id": None, "status": "skipped", "line_count": 0}
@@ -244,7 +295,7 @@ class OrderDeliverySyncService:
with conn.cursor() as cursor:
last_order_no: str | None = None
while True:
page = cls._fetch_page(cursor, last_order_no)
page = cls._fetch_page(cursor, last_order_no, date_from)
if not page:
break
hit_keys |= cls._upsert_page(page, synced_at)
@@ -344,8 +344,10 @@ def _register_headers_from_config() -> None:
if cfg.alias_order and cfg.header_labels:
register_schedule_header(name, cfg.alias_order, cfg.header_labels)
from app.services.schedule.shipping_inventory_rpa_finalize import register_inventory_rpa_excel_headers
from app.services.schedule.freight_receipt_rpa_finalize import register_receipt_rpa_excel_headers
register_inventory_rpa_excel_headers()
register_receipt_rpa_excel_headers()
def reload_config() -> dict[str, Any]:
@@ -0,0 +1,60 @@
"""
backend/app/services/schedule/equipment_acceptance_job.py
用途:把设备验收预警扫描和周五发送接到平台排程。
依赖:equipment_acceptance.alert_service、ScheduleTask、ScheduleRun。
逻辑:日批先同步再写待发送。周五任务只发送,不再同步。
"""
from __future__ import annotations
from typing import Any
from app.models import ScheduleRun, ScheduleTask
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
def run_equipment_acceptance_alert_scan_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行设备验收每日扫描。
核心逻辑:同步 E10 后生成待发送,不发企业微信。
Args:
task: 当前排程。
run: 本次执行记录。
Returns:
排程审计七元组。成功数是新增加更新,跳过数是停表取消的条数。
"""
from app.services.equipment_acceptance.alert_service import generate_alerts
summary = generate_alerts()
created = int(summary.get("created") or 0)
updated = int(summary.get("updated") or 0)
cancelled = int(summary.get("cancelled") or 0)
handled = created + updated
return handled + cancelled, handled, 0, cancelled, [summary], [], [
{"step": "equipment_acceptance_alert_scan", "status": "success", "detail": summary}
]
def run_equipment_acceptance_alert_weekly_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行周五设备验收企业微信汇总。
核心逻辑:按收件人各发一条。失败人数记入排程的失败计数。
Args:
task: 当前排程。
run: 本次执行记录。
Returns:
排程审计七元组。
"""
from app.services.equipment_acceptance.alert_service import send_pending_alerts
summary = send_pending_alerts()
sent = int(summary.get("sent") or 0)
failed = int(summary.get("failed") or 0)
status = "success" if not failed else "partial"
return sent + failed, sent, failed, 0, [summary], [], [
{"step": "equipment_acceptance_alert_weekly", "status": status, "detail": summary}
]
@@ -9,16 +9,83 @@ backend/app/services/schedule/freight_receipt_rpa_finalize.py
from __future__ import annotations
from datetime import datetime, timedelta
from typing import Any
from flask import current_app
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.models import ShippingReceiptRpaUnitRun
from app.services.schedule import normalize_platform_api_path
from app.services.schedule import normalize_platform_api_path, register_schedule_header, resolve_schedule_header
from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule.freight_receipt_rpa_job import AWAITING_RECEIPT_RPA_CALLBACK_STATUS, RECEIPT_RPA_JOB_KEY
from app.services.shipping_notice.audit_service import append_shipping_audit_event
_RECEIPT_RPA_HEADER_ORDER = [
"source_code",
"warehouse_id",
"connector_type",
"receipt_file_count",
"export_status",
"skip_reason",
"error_message",
]
_RECEIPT_RPA_HEADER_LABELS = {
"source_code": "收料源",
"warehouse_id": "仓库",
"connector_type": "连接器",
"receipt_file_count": "归档文件数",
"export_status": "导出状态",
"skip_reason": "跳过原因",
"error_message": "错误原因",
}
def register_receipt_rpa_excel_headers() -> None:
"""
注册货代收料 RPA 排程 Excel 列头(幂等)。
核心逻辑:由 schedule.__init__._register_headers_from_config 在 reload 后调用,避免被 clear 冲掉。
"""
register_schedule_header(
RECEIPT_RPA_JOB_KEY,
_RECEIPT_RPA_HEADER_ORDER,
_RECEIPT_RPA_HEADER_LABELS,
)
def _build_receipt_finalize_details(units: list[ShippingReceiptRpaUnitRun]) -> list[dict[str, Any]]:
"""
收料单元 → 排程 Excel 明细行(对齐库存 finalize 的行结构)。
核心逻辑:empty 归一为 skipped、cancelled 归一为 failed,与卡片 计数口径一致;
归档文件数便于与原始收料包内 {序号}_{source_code}.xlsx 条目对账。
Args:
units: 该 run 的全部收料单元(已全部终态)。
Returns:
list[dict]: 按 unit.id 升序的明细行。
"""
rows: list[dict[str, Any]] = []
for unit in sorted(units, key=lambda item: item.id):
status = unit.status
if status == 'empty':
export_status = 'skipped'
elif status == 'cancelled':
export_status = 'failed'
else:
export_status = status
rows.append({
'source_code': unit.source_code,
'warehouse_id': unit.warehouse_id or '',
'connector_type': unit.connector_type or '',
'receipt_file_count': len(unit.files or []),
'export_status': export_status,
'skip_reason': str(unit.error_code or '') if export_status == 'skipped' else '',
'error_message': str(unit.error_message or '')[:500] if export_status == 'failed' else '',
})
return rows
def should_defer_receipt_schedule_run(task: ScheduleTask, step_logs: list | None) -> bool:
"""仅当独立收料 job 成功写入 trigger 后延后终态,避免影响库存 job 判断。"""
@@ -176,6 +243,9 @@ def mark_receipt_unit_processing(payload: dict) -> dict:
if unit.status == 'processing':
return {'updated': True, 'status': 'processing', 'idempotent': True}
unit.status = 'processing'
# started_at 是收料超时对账的活动锚(_receipt_last_activity):在飞单元必须有
# 开始时间,否则长静默批次无法区分"在跑"与"worker 已死"。
unit.started_at = datetime.utcnow()
db.session.commit()
if unit.schedule_run_id:
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
@@ -210,6 +280,44 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed'
run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None
# [STEP] 对齐库存 finalize:终态前生成收料汇总 Excel,企微在 textcard+ZIP 之外多发一条 [文件] 消息。
register_receipt_rpa_excel_headers()
header_order, header_labels = resolve_schedule_header(RECEIPT_RPA_JOB_KEY)
excel_export_ok = True
excel_data, excel_name, excel_size = None, None, 0
try:
excel_data, _excel_name, excel_size = export_schedule_result_excel(
run_no=run.run_no,
summary={
'status': run.status,
'total_count': len(units),
'success_count': success_count,
'skipped_count': skipped_count,
'failed_count': failed_count,
'duration_ms': run.duration_ms,
},
details=_build_receipt_finalize_details(units),
header_order=header_order,
header_labels=header_labels,
)
except Exception as excel_exc:
excel_export_ok = False
current_app.logger.error(
'[schedule-run] receipt RPA excel export failed for run %s: %s', run.run_no, excel_exc,
)
# 对齐库存:全成功批次的 Excel 失败要降级,不得让收件人误以为一切正常。
if run.status == 'success':
run.status = 'partial_failed'
run.error_message = '; '.join(filter(None, [run.error_message, f'Excel导出失败: {excel_exc}']))[:2000]
else:
# 企微/下载展示名:收料RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。
from app.services.schedule.shipping_receipt_rpa_archive import receipt_rpa_result_excel_name
excel_name = receipt_rpa_result_excel_name(run)
run.excel_file_data = excel_data
run.excel_file_name = excel_name if excel_data else None
run.excel_file_size = excel_size or 0
# [STEP] 对齐库存:终态前预生成原始收料 ZIP,企微只发一个包。
archive_summary = {
'raw_receipt_zip_available': False,
@@ -234,6 +342,8 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
'success_count': success_count,
'empty_count': skipped_count,
'failed_count': failed_count,
'excel_export_status': 'ok' if excel_export_ok else 'failed',
'excel_failed': not excel_export_ok,
**archive_summary,
}
db.session.commit()
@@ -267,19 +377,40 @@ def is_freight_receipt_rpa_task(task: ScheduleTask | None) -> bool:
)
def _receipt_last_activity(run: ScheduleRun, units: list[ShippingReceiptRpaUnitRun]) -> datetime:
"""收料 run 的最后活动锚:run 开始时间与全部单元 started/finished 时间的最大值。
语义为「笔间静默」:worker 每开始/完成一笔都会推进锚点,锚点静默超过
FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS 才判定 worker 不再活动。刻意不含单元
created_at——批量 trigger 中排队单元的创建时间不代表活动,否则整批永不超时。
极端长单笔(单站点导出超过 timeout)会被判超时,需按最慢单笔调大该配置。
"""
stamps = [run.started_at] if run.started_at else []
for unit in units:
if unit.started_at:
stamps.append(unit.started_at)
if unit.finished_at:
stamps.append(unit.finished_at)
return max(stamps)
def _recover_stale_receipt_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool:
"""将无回调的独立收料运行收口为失败,保留其单元与触发审计事实。"""
"""将无回调的独立收料运行收口为失败,保留其单元与触发审计事实。
截止判据为最后活动锚(_receipt_last_activity)而非 run.started_at——
串行长批次(>timeout)只要仍有笔间活动就不得被误杀。
"""
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if not summary.get('awaiting_receipt_rpa') or run.status != 'running' or not run.started_at or run.started_at > cutoff:
if not summary.get('awaiting_receipt_rpa') or run.status != 'running' or not run.started_at:
return False
task = run.task or db.session.get(ScheduleTask, run.schedule_task_id)
if not is_freight_receipt_rpa_task(task):
return False
units = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all()
if _receipt_last_activity(run, units) > cutoff:
return False
now = datetime.utcnow()
pending = ShippingReceiptRpaUnitRun.query.filter(
ShippingReceiptRpaUnitRun.schedule_run_id == run.id,
ShippingReceiptRpaUnitRun.status.in_({'queued', 'awaiting_rpa', 'processing'}),
).all()
pending = [unit for unit in units if unit.status in {'queued', 'awaiting_rpa', 'processing'}]
for unit in pending:
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
unit.status = 'failed'
@@ -1,24 +1,27 @@
"""自动调拨排程。
用途:自动处理当日新成熟可调拨项与历史可恢复异常,并发送一次企微汇总通知。
依赖:auto_transfer、transfer deps、wecom_sender、job_registry.ScheduleExecuteResult、
receipt_trigger_service.list_receipt_capable_source_codes(缺省来源口径)。
用途:自动处理当日新成熟可调拨项与历史可恢复异常;执行结果通知统一走
排程「启用通知」通用企微通知,本任务不自建领域通知。
依赖:auto_transfer、transfer deps、job_registry.ScheduleExecuteResult、
receipt_trigger_service.list_receipt_capable_source_codes(缺省来源口径)、
date_policy(业务日与日期解析)。
逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发收料 RPA),
不依赖其他排程成功;来源留空兜底为全部启用收料来源;有通知人时构造
sender,仅在有 run_no 或空数据日(无 errors)后置 domain_notification_managed
抑制框架卡;硬失败不置标记以便框架兜底。
不依赖其他排程成功;来源留空兜底为全部启用收料来源;可选收料日期范围
以「T−N 偏移天数」配置,执行时按当日业务日换算为具体日期透传匹配层;
空数据日(无 run_no 且无 errors)置 domain_notification_managed 保持
静默(C5),有 Run 或硬失败交由框架完成卡按排程「启用通知」发送。
"""
from __future__ import annotations
from datetime import timedelta
from typing import Any
from app.models import ScheduleRun, ScheduleTask
from app.services.in_transit_transfer import deps as transfer_deps
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome, run_auto_transfer
from app.services.in_transit_transfer.date_policy import business_date_now
from app.services.in_transit_transfer.date_policy import business_date_now, parse_date
from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes
from app.services.in_transit_transfer.wecom_sender import WecomSummarySender
from app.services.schedule.job_registry import ScheduleExecuteResult
@@ -45,41 +48,77 @@ def _wanted_source_codes(task: ScheduleTask) -> list[str]:
return codes
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""自动调拨:恢复 + 匹配(严格相等)+ 执行 + 企微汇总通知。
核心逻辑:有通知人时构造 WecomSummarySender 传入 run_auto_transfer;
仅在返回后按结果决定是否置 domain_notification_managed——有 run_no
(成功/部分失败领域卡路径)或无 errors(空数据日 C5)时抑制框架卡;
硬失败(无 run_no 且有 errors)不置标记,允许框架完成卡兜底。
def _offset_to_date(business_date: str, offset_days: Any, label: str, errors: list[str]) -> str | None:
"""把「T−N 偏移天数」参数换算为执行日口径的具体收料日期(T−N)。
Args:
task: 排程任务(job_params: source_codes/recover_history/notify_user_ids)。
run: 排程执行批次(领域自管通知时写入 response_summary_json 标记)。
business_date: 业务日期 T(YYYY-MM-DD)。
offset_days: 偏移天数(须为非负整数;None/空视为未配置)。
label: 参数中文名(写错误信息用)。
errors: 错误累积列表(非法配置写入后返回 None,由调用方快速失败)。
Returns:
'YYYY-MM-DD';未配置或非法时为 None(非法同时落错误)。
"""
if offset_days is None or offset_days == "":
return None
try:
days = int(offset_days)
except (TypeError, ValueError):
errors.append(f"{label}须为非负整数(当前值 {offset_days!r})")
return None
if days < 0 or float(offset_days) != days:
errors.append(f"{label}须为非负整数(当前值 {offset_days!r})")
return None
return (parse_date(business_date) - timedelta(days=days)).isoformat()
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""自动调拨:恢复 + 匹配(严格相等)+ 执行;通知统一走排程「启用通知」。
核心逻辑:不自建领域汇总通知(任务级通知人参数已移除,收件人取排程表单
底部「启用通知」配置);仅在空数据日(无 run_no 且无 errors)置
domain_notification_managed 抑制框架完成卡(C5 空数据日静默);
有 run_no(成功/部分失败)或硬失败时框架卡照常发送/兜底。
可选收料日期范围以「T−N 偏移天数」配置(receipt_from/to_offset_days),
执行时按当日业务日换算为具体日期透传匹配层,供测试/排障缩小本轮处理面;
偏移非法(负数/小数/非数字)快速失败不执行;范围越界由匹配层
ValidationError 落 errors 走硬失败路径。
Args:
task: 排程任务(job_params: source_codes/recover_history/
receipt_from_offset_days/receipt_to_offset_days)。
run: 排程执行批次(空数据日写入 response_summary_json 标记)。
Returns:
ScheduleExecuteResult 七元组;空数据日 total=0 且不记 error(C5)。
"""
params = _task_params(task)
source_codes = _wanted_source_codes(task)
recover_history = bool(params.get("recover_history", True))
recipients = [str(item).strip() for item in (params.get("notify_user_ids") or []) if str(item).strip()]
business_date = str(business_date_now())
# 有通知人时构造 sender 传入领域层;是否抑制框架卡见下方按 outcome 判定。
sender = WecomSummarySender() if recipients else None
# [STEP] T−N 偏移换算:非法配置快速失败(不执行、交框架失败通知),
# 防止坏参数被静默忽略后退化成全量积压处理。
param_errors: list[str] = []
receipt_date_from = _offset_to_date(
business_date, params.get("receipt_from_offset_days"), "收料日期起点", param_errors)
receipt_date_to = _offset_to_date(
business_date, params.get("receipt_to_offset_days"), "收料日期终点", param_errors)
if param_errors:
return (0, 0, 0, 0, [], [f"sources={len(source_codes)}"], param_errors)
deps = transfer_deps.get_transfer_dependencies()
outcome = run_auto_transfer(
business_date=str(business_date_now()),
business_date=business_date,
deps=deps,
source_codes=source_codes,
recover_history=recover_history,
sender=sender,
recipients=recipients,
receipt_date_from=receipt_date_from,
receipt_date_to=receipt_date_to,
)
# [STEP] 领域自管通知门禁:仅在领域卡已发出(有 run_no)或空数据日
# (无 errors,C5 静默)时置标记;硬失败让框架完成卡兜底。
if recipients and (outcome.run_no or not outcome.errors):
# [STEP] 空数据日静默门禁:无 run 且无错误(匹配后无可执行行,C5)时置
# 标记抑制框架完成卡;有 run 或硬失败时框架卡照常通知/兜底。
if not outcome.run_no and not outcome.errors:
run.response_summary_json = {
**(run.response_summary_json or {}),
"domain_notification_managed": True,
@@ -94,7 +133,6 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
results.append({
"run_no": outcome.run_no,
"status": outcome.run_status,
"notification_status": outcome.notification_status,
})
elif not outcome.errors:
# 空数据日:匹配后无可执行行,执行与通知按 C5 跳过,不记失败。
+34 -11
View File
@@ -156,6 +156,10 @@ def _register_builtin_platform_jobs() -> None:
run_contract_payment_sync_schedule,
run_contract_payment_weekly_alert_schedule,
)
from app.services.schedule.equipment_acceptance_job import (
run_equipment_acceptance_alert_scan_schedule,
run_equipment_acceptance_alert_weekly_schedule,
)
from app.services.schedule.lean_training_job import run_lean_training_reminder_schedule, run_lean_training_video_push_schedule
register_platform_job(PlatformJobDefinition(
@@ -268,6 +272,20 @@ def _register_builtin_platform_jobs() -> None:
key="contract-payment-alert-weekly", label="合同付款预警周汇总", handler=run_contract_payment_weekly_alert_schedule,
description="每周五 18:00 按收件人发送一条付款预警汇总及 Excel 明细。", category="contract_payment",
))
register_platform_job(PlatformJobDefinition(
key="equipment-acceptance-alert-scan",
label="设备验收预警扫描",
handler=run_equipment_acceptance_alert_scan_schedule,
description="每日同步 E10 验收单,并按停留天数生成待发送记录。",
category="equipment_acceptance",
))
register_platform_job(PlatformJobDefinition(
key="equipment-acceptance-alert-weekly",
label="设备验收预警发送",
handler=run_equipment_acceptance_alert_weekly_schedule,
description="每周五 18:00 按收件人发送一条设备验收停留提醒。",
category="equipment_acceptance",
))
register_platform_job(PlatformJobDefinition(
key="contract-payment-sync",
@@ -566,10 +584,8 @@ def _register_builtin_platform_jobs() -> None:
label="在途自动调拨",
handler=run_in_transit_transfer_schedule,
description=(
"自动处理可调拨项与历史可恢复异常:调拨前确保各来源当日收料文件就绪"
"(就绪复用,缺失自动触发收料 RPA),数量严格相等匹配后自动生成 ERP 调拨单;"
"每非空 Run 发送一条企微汇总通知,通知失败不改变 ERP 结果。"
"执行时间由排程配置决定,建议配置在业务期望的调拨时点之前。"
"自动匹配可调拨项并生成 ERP 调拨单,含历史可恢复异常复核;"
"缺收料文件时自动触发收料 RPA。执行时间建议配置在期望调拨时点之前。"
),
category="platform",
params_schema=(
@@ -591,16 +607,23 @@ def _register_builtin_platform_jobs() -> None:
"default": True,
},
{
"key": "notify_user_ids",
"type": "multi_select",
"label": "通知人",
"label_key": "admin.schedule.form.transferNotifyUsers",
"key": "receipt_from_offset_days",
"type": "number",
"label": "收料日期起(T-N)",
"label_key": "admin.schedule.form.transferReceiptDateFrom",
"required": False,
"default": [],
"options_source": "users",
"help": "填天数 N,按执行日换算收料日期下限 T−N;例:4=从 T−4 起。留空=全部成熟积压(默认 ≤ T-2)。",
},
{
"key": "receipt_to_offset_days",
"type": "number",
"label": "收料日期止(T-N)",
"label_key": "admin.schedule.form.transferReceiptDateTo",
"required": False,
"help": "填天数 N,按执行日换算收料日期上限 T−N;例:起4止2=只处理 T−4~T−2。不得晚于成熟上限(默认 T-2)。",
},
),
defaults={"source_codes": [], "recover_history": True, "notify_user_ids": []},
defaults={"source_codes": [], "recover_history": True},
))
@@ -357,9 +357,6 @@ def prepare_schedule_queue() -> int:
recovered = recover_all_stale_awaiting_rpa_schedule_runs()
if recovered:
current_app.logger.info("[schedule-worker] recovered %d stale awaiting RPA runs", recovered)
receipt_recovered = recover_all_stale_receipt_rpa_schedule_runs()
if receipt_recovered:
current_app.logger.info("[schedule-worker] recovered %d stale receipt RPA runs", receipt_recovered)
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
recover_pending_rpa_callback_cleanup_jobs,
)
@@ -379,6 +376,13 @@ def prepare_schedule_queue() -> int:
if transfer_stale:
current_app.logger.info("[schedule-worker] recovered %d stale transfer waiting source jobs", transfer_stale)
# 收料 run 超时对账同为每轮领取维护(2026-10-07 从启动一次性分支迁出):
# 此前长驻进程期间超时 run 永不终态(RUN20261001131705E5E5 卡执行中的根因)。
# 回收判据为最后活动锚(笔间静默),健康长批次不被误杀,见 freight_receipt_rpa_finalize。
receipt_stale = recover_all_stale_receipt_rpa_schedule_runs()
if receipt_stale:
current_app.logger.info("[schedule-worker] recovered %d stale receipt RPA runs", receipt_stale)
try:
from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
@@ -110,6 +110,11 @@ def receipt_raw_zip_download_name(run: ScheduleRun) -> str:
return f'{receipt_rpa_attachment_stem(run)}-收料.zip'
def receipt_rpa_result_excel_name(run: ScheduleRun) -> str:
"""收料 RPA 结果 Excel 的企微/下载展示名(对齐库存 inventory_rpa_result_excel_name)。"""
return f'{receipt_rpa_attachment_stem(run)}-结果.xlsx'
def _receipt_raw_zip_archive_path(run_no: str) -> Path:
"""磁盘归档路径:<archive_dir>/<run_no>.zip。"""
return Path(get_receipt_archive_dir()) / f'{run_no}.zip'
@@ -73,6 +73,87 @@ _NON_BLOCKING_CONFLICT_REASONS = frozenset({'layout_table_needs_review'})
_EVIDENCE_GAP_REASONS = frozenset({'evidence_missing', 'pdf_evidence_missing'})
def resolve_satisfied_supplement_conflicts(candidate: Any) -> int:
"""
裸数字启发式冲突的字段若已有正式采纳裁决,自动标记已解决。
AI 触发时机:Run 收口持久化完成后调用(或修复脚本对存量 Candidate 执行);
投影与资格门禁共用 current_open_candidate_conflicts,标记 resolved 后
「字段冲突已解决」即达成,不再阻断提交订单。
核心逻辑:supplement_field_conflict 的定位证据来自邮件补充的裸数字候选;
当该字段的字段级裁决已为 accepted(PO 行收敛唯一路径或正式值源写入均算),
「多候选待人工选择」的前提消失——采纳即裁决。仅标记 resolution_status,
不删除审计记录,也不改动任何已写入的字段值。同一 field_code 可能在表头与
行级各配置一个字段:任一位置的裁决 accepted 即视为已满足。
Returns:
int: 实际标记为已解决的冲突条数。
"""
from sqlalchemy.orm.attributes import flag_modified
from app.models import (
ShippingOrderFieldDecision,
ShippingOrderSchemaVersion,
)
conflicts = candidate.conflicts_json if isinstance(candidate.conflicts_json, list) else []
if not conflicts:
return 0
extraction_id = (
getattr(candidate, 'order_extraction_id', None)
or getattr(candidate, 'extraction_id', None)
)
if extraction_id is None:
return 0
extraction = db.session.get(ShippingOrderExtraction, int(extraction_id))
version = (
db.session.get(ShippingOrderSchemaVersion, int(extraction.schema_version_id))
if extraction is not None and extraction.schema_version_id is not None else None
)
definition = (version.definition_json or {}) if version is not None else {}
# 同一 field_code 可能在表头与行级各配置一个字段(如预约单号):任一位置
# 的裁决 accepted 即视为该字段冲突已满足。
field_id_candidates: dict[str, set[str]] = {}
for item in definition.get('fields') or []:
if not isinstance(item, dict):
continue
code = str(item.get('field_code') or '').strip()
fid = str(item.get('field_id') or '').strip()
if code and fid:
field_id_candidates.setdefault(code, set()).add(fid)
changed = 0
for item in conflicts:
if not isinstance(item, dict):
continue
if str(item.get('reason') or '') != 'supplement_field_conflict':
continue
if str(item.get('resolution_status') or 'unresolved').strip() == 'resolved':
continue
field_code = str(item.get('field') or '').strip()
field_id_set = field_id_candidates.get(field_code) or set()
line_index = item.get('line_index')
line_id = int(line_index) if line_index is not None and int(line_index) >= 0 else None
decision = None
for field_id in sorted(field_id_set):
decision = ShippingOrderFieldDecision.query.filter_by(
extraction_id=int(extraction_id), field_id=field_id, line_id=line_id,
).first()
if decision is not None and decision.decision_status == 'accepted':
break
decision = None
if decision is None or decision.decision_status != 'accepted':
continue
item['resolution_status'] = 'resolved'
item['resolution'] = 'auto_scoped_value_accepted'
changed += 1
if changed:
from sqlalchemy.orm.attributes import flag_modified as _fm
_fm(candidate, 'conflicts_json')
return changed
def field_evidence_gap_is_non_blocking(candidate: Any, item: dict[str, Any]) -> bool:
"""按冻结字段配置判断证据缺失是否只是可选字段诊断。
@@ -169,7 +169,7 @@ class ShippingQueryShortageDetailsAction:
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
task = _require_task(ctx)
yield TurnEvent(event="step.started", data={"step_id": "query_shortage_details", "label": "查询缺口明细..."})
detail = serialize_task_detail(task)
detail = serialize_task_detail(task, viewer_user_id=int(ctx.user_id))
content = format_shortage_details_message(detail if isinstance(detail, dict) else {})
yield from stream_text_events(content, payload={"task_no": task.task_no})
yield TurnEvent(event="step.completed", data={"step_id": "query_shortage_details"})
@@ -1,10 +1,13 @@
"""
services/shipping_notice/customer_resolution_service.py
用途:提供订单任务的唯一客户识别结果读取与确认入口。
依赖:ShippingCustomerShadowResolution、ShippingOrderTask、ShippingOrderCandidate、ShippingCustomer。
用途:提供订单任务的唯一客户识别结果读取、确认与确认后改绑入口。
依赖:ShippingCustomerShadowResolution、ShippingOrderTask、ShippingOrderCandidate、ShippingCustomer、
ShippingNotice、ShippingOrderSnapshot、order_edit_window_service、order_freeze_service、audit_service。
逻辑:客户身份来自已发布规则生成的证据快照;订单字段(包括 bill_to)只能作为证据,
不能承担客户角色或流程门禁真相。
不能承担客户角色或流程门禁真相。确认后改绑(rebind_confirmed_customer)仅在订单
编辑窗 header 可编辑(无 Export Artifact 且无活动 Gate Attempt)时允许直接修改
确认结果,并原地刷新冻结快照客户(快照表 uq task_id 唯一约束决定不可另建新行)。
"""
from __future__ import annotations
@@ -14,7 +17,14 @@ from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import ShippingCustomer, ShippingCustomerShadowResolution, ShippingOrderCandidate, ShippingOrderTask
from app.models import (
ShippingCustomer,
ShippingCustomerShadowResolution,
ShippingNotice,
ShippingOrderCandidate,
ShippingOrderSnapshot,
ShippingOrderTask,
)
def resolution_for_task(task: Any) -> ShippingCustomerShadowResolution | None:
@@ -74,3 +84,265 @@ def confirm_customer_resolution(
resolution.status = 'confirmed'
db.session.flush()
return resolution
# 改绑后 audit 事件类型:已纳入 progress_audit_contract.REVIEW_WORKBENCH_AUDIT_EVENT_TYPES
# 冻结字典(review_* snake_case 命名;review_customer_confirmed 专指首次确认,改绑独立成码)。
REBIND_AUDIT_EVENT_TYPE = 'review_customer_rebound'
def _order_notice_for_task(task: Any) -> ShippingNotice | None:
"""回读该正式订单的任一通知作为编辑窗谓词入口;editable_scope 会按 order_task_id 聚合全部通知。"""
return (
ShippingNotice.query
.filter(ShippingNotice.order_task_id == int(task.id))
.order_by(ShippingNotice.id.asc())
.first()
) if getattr(task, 'id', None) is not None else None
def _review_case_no_for_task(task: Any) -> str | None:
"""
经建单确认修订反查正式任务所属复核 Case 编号(order_edit_window_service 同款反查模式)。
核心逻辑:ShippingOrderReviewConfirmedRevision.case_id → ShippingOrderReviewCase.case_no,
取最新一条修订;无修订(历史数据)时返回 None,审计事件照常落库。
"""
from app.models import ShippingOrderReviewCase, ShippingOrderReviewConfirmedRevision
if getattr(task, 'id', None) is None:
return None
row = (
db.session.query(ShippingOrderReviewCase.case_no)
.join(
ShippingOrderReviewConfirmedRevision,
ShippingOrderReviewConfirmedRevision.case_id == ShippingOrderReviewCase.id,
)
.filter(ShippingOrderReviewConfirmedRevision.task_id == int(task.id))
.order_by(ShippingOrderReviewConfirmedRevision.id.desc())
.first()
)
return str(row[0]).strip() or None if row is not None else None
def _assert_rebind_window_open(task: Any) -> None:
"""
改绑编辑窗守卫(fail-closed):header 不可编辑即拒绝,不区分原因放行。
核心逻辑:editable_scope(order_task)['header'] = 全部通知无 Export Artifact 且无活动
Gate Attempt;尚无通知的未发货订单视为可编辑。details 区分 excel_exists / active_attempt
供前端定位(“已产生发货通知/Excel,请先走撤销流程” vs 系统处理中)。
"""
from app.services.shipping_notice import order_edit_window_service as order_edit_window
notice = _order_notice_for_task(task)
if notice is None:
return
scope = order_edit_window.editable_scope(notice)
if bool(scope.get('header')):
return
excel_exists = any(
order_edit_window._notice_has_export_artifact(item)
for item in order_edit_window._order_notices(notice)
)
active_attempt = order_edit_window.order_has_active_attempt(notice)
raise ConflictError(
'Customer rebind is blocked after shipping notice or Excel generation',
code='SHIPPING.CUSTOMER_REBIND_BLOCKED',
details={'excel_exists': excel_exists, 'active_attempt': active_attempt},
)
def rebind_allowed_for_task(task: Any) -> bool:
"""
判定正式任务当前是否允许改绑确认客户(工作台「修改客户」按钮谓词,只读 fail-closed)。
核心逻辑:识别结果已确认,且编辑窗 header 可编辑(全部通知无 Export Artifact 且
无活动 Gate Attempt)。与 rebind_confirmed_customer 守卫①②同源;并发语义由 API 层
expected_order_data_version 承担,此处为只读投影不下发并发状态。
Args:
task: 正式任务(ShippingOrderTask/ShippingNotice,按 resolution_for_task 语义解析)。
Returns:
True 表示当前可改绑;False 表示未确认、Excel 已产生或存在活动 Attempt。
"""
row = resolution_for_task(task)
if row is None or row.status != 'confirmed' or not row.confirmed_customer_id:
return False
notice = _order_notice_for_task(task)
if notice is None:
return True
from app.services.shipping_notice import order_edit_window_service as order_edit_window
return bool(order_edit_window.editable_scope(notice).get('header'))
def _append_rebind_audit(
*,
task: Any,
previous_customer_id: int,
new_customer: ShippingCustomer,
actor_id: int,
reason: str | None,
) -> None:
"""写改绑审计事件:before/after 携带原/新确认客户(键须命中审计快照白名单),并挂 review_case_no 供 Case 时间线查询。"""
from app.services.shipping_notice.audit_service import append_shipping_audit_event
task_no = str(getattr(task, 'task_no', '') or '')
version = int(getattr(task, 'order_data_version', 0) or 1)
append_shipping_audit_event(
event_type=REBIND_AUDIT_EVENT_TYPE,
aggregate_type='shipping_task',
aggregate_id=task_no,
task_no=task_no,
review_case_no=_review_case_no_for_task(task),
actor_type='user',
actor_id=int(actor_id),
action='rebind_confirmed_customer',
result='success',
reason=str(reason or '').strip() or None,
before={'previous_value': previous_customer_id, 'task_no': task_no, 'order_data_version': version},
after={'new_value': int(new_customer.id), 'task_no': task_no, 'order_data_version': version},
metadata={
'previous_customer_id': int(previous_customer_id),
'confirmed_customer_id': int(new_customer.id),
},
)
def _refresh_frozen_snapshot_customer(task: Any, customer: ShippingCustomer) -> ShippingOrderSnapshot | None:
"""
原地刷新冻结快照的订购客户事实(customer_id / 客户简称)。
核心逻辑:快照表对 task_id 有唯一约束(uq_shipping_order_snapshots_task),且快照行身份
被 Notice 行 / 波次行 / 库存匹配以 snapshot_line_id 引用,因此改绑不能删行重建,只能按
新客户刷新客户身份字段;单头模板文本(customer_code/customer_name 等单据原文事实)不动。
"""
snapshot_id = getattr(task, 'order_snapshot_id', None)
if not snapshot_id:
return None
snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id))
if snapshot is None:
return None
snapshot.customer_id = int(customer.id)
snapshot.customer_short_code_snapshot = str(getattr(customer, 'short_code', None) or '')
db.session.flush()
return snapshot
def rebind_confirmed_customer(
task: Any,
*,
new_customer_id: int,
actor_id: int,
expected_order_data_version: int,
reason: str | None = None,
) -> dict[str, Any]:
"""
确认客户改绑:直接修改已确认的客户识别结果并刷新冻结快照客户。
核心逻辑:守卫顺序固定 fail-closed——⓪客户端乐观锁版本比较(expected_order_data_version
必填,与任务当前 order_data_version 不一致即 409,写任何数据之前执行,保证冲突零副作用;
freeze 对已冻结任务幂等早退、不重复做版本校验,故版本比较只在此处);①识别结果已确认
(未确认走既有确认流程);②订单编辑窗 header 可编辑(任一通知无 Export Artifact 且无
活动 Gate Attempt,即发货通知/Excel 未产生);③新客户存在、启用且 ≠ 当前确认客户。
通过后更新确认结果(追加 rebind 证据记录,保持 evidence_json 与 identity_rule_set_checksum
非空冻结契约)、写审计、原地刷新快照客户,最后按 freeze 契约复核并返回快照。
Args:
task: 正式订单任务 ShippingOrderTask(经 candidate_id 反查唯一识别结果)。
new_customer_id: 目标标准客户 id;必须存在且启用。
actor_id: 执行改绑的用户 id(必填,审计与 manual 冻结要求)。
expected_order_data_version: 客户端读到的订单数据版本;与任务当前版本不一致时拒绝,
防止并发编辑被静默覆盖(对齐 wave 路由 expected_draft_version 模式)。
reason: 可选改绑原因;进入证据记录、审计与确认原因链。
Returns:
dict: {'resolution': 更新后的识别结果行, 'snapshot': 客户已刷新的冻结快照}。
Raises:
ValidationError: 缺少执行人(SHIPPING.CUSTOMER_REBIND_ACTOR_REQUIRED,内部调用契约)。
ConflictError: 订单数据版本不一致(SHIPPING.ORDER_DATA_VERSION_MISMATCH)、识别结果
未确认(SHIPPING.CUSTOMER_RESOLUTION_REQUIRED)、编辑窗关闭
(SHIPPING.CUSTOMER_REBIND_BLOCKED,details 含 excel_exists/active_attempt)、
新客户停用(SHIPPING.CUSTOMER_INACTIVE)或与当前客户相同
(SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER)。
NotFoundError: 目标客户不存在(SHIPPING.CUSTOMER_NOT_FOUND)。
"""
if not actor_id:
# 内部调用契约缺失(非编辑窗状态),与 SHIPPING.CUSTOMER_REBIND_BLOCKED 的 A 管控语义区分。
raise ValidationError('Customer rebind requires an operator', code='SHIPPING.CUSTOMER_REBIND_ACTOR_REQUIRED')
# [STEP 1] 守卫⓪:客户端版本比较在写任何数据之前执行;freeze 幂等早退不重复校验。
actual_version = int(getattr(task, 'order_data_version', 0) or 1)
if actual_version != int(expected_order_data_version):
raise ConflictError(
'Order data version has changed',
code='SHIPPING.ORDER_DATA_VERSION_MISMATCH',
details={'expected': int(expected_order_data_version), 'actual': actual_version},
)
# [STEP 2] 守卫①:识别结果已确认(未确认走既有识别候选确认流程,不在此补确认)。
resolution = resolution_for_task(task)
if (
resolution is None or str(resolution.status or '') != 'confirmed'
or resolution.confirmed_customer_id is None
):
raise ConflictError(
'Confirmed customer resolution is required before rebind',
code='SHIPPING.CUSTOMER_RESOLUTION_REQUIRED',
)
# [STEP 3] 守卫②:编辑窗 header 谓词(发货通知/Excel 已产生或系统处理中即拒绝)。
_assert_rebind_window_open(task)
# [STEP 4] 守卫③:新客户存在、启用且 ≠ 当前确认客户。
customer = db.session.get(ShippingCustomer, int(new_customer_id))
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if str(customer.status or '') != 'active':
raise ConflictError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE')
previous_customer_id = int(resolution.confirmed_customer_id)
if int(customer.id) == previous_customer_id:
raise ConflictError(
'Rebind target equals the current confirmed customer',
code='SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER',
)
# [STEP 5] 更新确认结果:追加 rebind 证据记录(保留原识别证据;checksum 契约不动)。
resolution.confirmed_customer_id = int(customer.id)
resolution.evidence_json = [
*(list(resolution.evidence_json or [])),
{
'source': 'manual_rebind',
'rebind': {
'previous_customer_id': previous_customer_id,
'new_customer_id': int(customer.id),
'actor_id': int(actor_id),
'reason': str(reason or '').strip() or None,
'rebound_at': datetime.utcnow().isoformat(),
},
},
]
db.session.flush()
# [STEP 6] 审计:before/after 携带原/新确认客户(与业务写入同事务,挂 review_case_no)。
_append_rebind_audit(
task=task, previous_customer_id=previous_customer_id,
new_customer=customer, actor_id=int(actor_id), reason=reason,
)
# [STEP 7] 快照客户刷新 + freeze 契约复核:manual 冻结校验 actor_id;已冻结任务走幂等
# 早退返回当前快照(不重复版本校验——版本一致性已由守卫⓪保证)。
snapshot = _refresh_frozen_snapshot_customer(task, customer)
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
snapshot = freeze_order_snapshot(
task,
actor_id=int(actor_id),
expected_order_data_version=int(expected_order_data_version),
freeze_mode='manual',
)
db.session.flush()
return {'resolution': resolution, 'snapshot': snapshot}
@@ -47,6 +47,7 @@ from app.services.shipping_notice.order_candidate_builder import (
build_email_order_index,
merge_attachment_candidate,
)
from app.services.shipping_notice.reservation_id import find_bare_numeric_reservation_candidates
BODY_ATTACHMENT_KEY = 'body'
@@ -665,6 +666,13 @@ def persist_documents_and_candidates(
schema_definition=definition,
)
supplement['document_id'] = int(body_doc.id)
# [裸数字兜底] 无表头数据表解析不出补充行时,预置「整格纯数字」表格候选;
# 是否采纳由 merge_email_supplements 在合并末段结合已提取字段值裁决。
supplement['reservation_candidates'] = find_bare_numeric_reservation_candidates(
html_tables=canonical_html_tables,
content_hash=str(body_doc.content_hash or ''),
)
supplement['email_subject'] = str(email_meta.get('subject') or '')
body_doc.order_extraction_result_json = _json_safe_value({
'email_supplement': supplement,
})
@@ -680,6 +688,7 @@ def persist_documents_and_candidates(
'row_count': len(supplement.get('rows') or []),
'issue_codes': list(supplement.get('issues') or []),
'parser_version': supplement.get('version'),
'reservation_candidate_count': len(supplement.get('reservation_candidates') or []),
},
)
active_keys.add(BODY_ATTACHMENT_KEY)
@@ -95,6 +95,10 @@ class ProfileMatchCandidate(BaseModel):
dimension_states: dict[str, MatchDimensionState] = Field(default_factory=dict)
margin_to_next: float | None = Field(default=None, ge=0, le=1)
coordinate_transform: dict[str, Any] | None = None
identity_rescue_assisted: bool = Field(
default=False,
description='该候选的表头身份由表头带证据补洞达成(order_profile_ocr_rescue)。',
)
class ProfileMatchResult(BaseModel):
@@ -124,6 +128,10 @@ class ProfileMatchResult(BaseModel):
margin: float | None = Field(default=None, ge=0, le=1)
scoring_policy_version: str = MATCHER_POLICY_ID
parse_validation: dict[str, Any] | None = None
identity_rescue_source: str | None = Field(
default=None,
description='本次唯一命中的表头带证据补洞来源(acroform_widget / ocr_coordinate);None=未补洞。',
)
def match_frozen_coordinate_profiles(
@@ -1088,7 +1096,10 @@ def _header_normalized_words(text: str) -> list[str]:
核心逻辑:词级原子化与 Schema 别名短语匹配共用同一切词口径,保证两条路径
产出的身份原子完全同源;返回非空小写词序列(中文等非 [a-z0-9] 文本切词为空,
调用方按各自的跳过策略处理)。
调用方按各自的跳过策略处理)。有意不拆驼峰:真实表头大小写不可靠
('UnitCost'/'unitcost'/'UNITCOST' 皆可能出现),仅按大小写边界拆分对全小写
渲染不生效,反而制造两侧不对称;camelCase 别名的对齐由
schema_canonical_header_atoms/_tokens 的连写短语键承担。
"""
normalized = _HEADER_PAREN_GLOSS.sub(' ', str(text).casefold())
normalized = re.sub(r"['’]", '', normalized)
@@ -1180,10 +1191,12 @@ def schema_canonical_header_atoms(
具体措辞。未配置别名时零行为变化,完全退化为词级原子。
核心逻辑:
- header_to_field 为 None/空 dict 时直接返回词级原子(兼容旧签名,零风险);
- header_to_field 为 None/空 dict 时直接返回词级原子(兼容旧签名,零行为变化);
- 先把每个别名 key 经与 token 完全相同的词管线(剥括号注记 → casefold →
去撇号 → 按非字母数字切词)转为词元组;同一词元组 casefold 后指向多个
field_code 时整体弃用该短语——身份归属不允许歧义;
- 多词别名额外注册去空格连写短语键([STEP 1.1],如 'Unit Cost' ↔
'unitcost'),使 camelCase 无分隔符表头与空格措辞收敛到同一 field 原子;
- 逐 token 用同一词管线切词后做贪心最长短语匹配:命中即消费整段并产出
field::<field_code> 原子(短语内单词不再残留);未命中的剩余单词沿用词级
原子的既有过滤(长度 >= _HEADER_ATOM_MIN_LEN 且不在 _HEADER_ATOM_STOPWORDS);
@@ -1218,6 +1231,19 @@ def schema_canonical_header_atoms(
if len(codes) == 1
}
# [STEP 1.1] 连写短语键:camelCase 别名经 normalize_table_header 拆成
# 'Unit Cost' 类带空格键,但真实表头 token 常以无分隔符形式出现且大小写
# 不可靠('UnitCost'/'unitcost'),按大小写边界拆词对全小写渲染不生效。
# 为多词短语额外注册去空格连写键,使连写/空格/混合大小写拼写收敛到同一
# field 原子;只新增、不覆盖既有键,连写键跨字段歧义时整体弃用(同 [STEP 1])。
joined_candidates: dict[tuple[str, ...], set[str]] = {}
for words, code in phrase_to_field.items():
if len(words) > 1:
joined_candidates.setdefault((''.join(words),), set()).add(code)
for joined, codes in joined_candidates.items():
if len(codes) == 1 and joined not in phrase_to_field:
phrase_to_field[joined] = next(iter(codes))
# [STEP 2] 逐 token 贪心最长短语匹配;未命中单词走既有词级原子过滤。
atoms: set[str] = set()
for token in tokens:
@@ -1269,6 +1295,7 @@ def schema_canonical_header_tokens(
- header_to_field 为 None/空 dict 时原样返回输入列表(零归一、零行为变化);
- 短语字典构建与 atoms [STEP 1] 完全同源:别名 key 经同一词管线转词元组,
同一词元组 casefold 后指向多个 field_code 时整体弃用(身份不允许歧义);
多词别名同样注册连写短语键([STEP 1.1],与 atoms 同一口径);
- 逐 token 贪心最长短语匹配:命中片段消费整段并在原位置产出**单个**
`field::<field_code>` 列表项(短语内单词不残留);未命中词按 atoms 同一
过滤(长度 >= _HEADER_ATOM_MIN_LEN 且不在 _HEADER_ATOM_STOPWORDS)原词保留;
@@ -1301,6 +1328,17 @@ def schema_canonical_header_tokens(
if len(codes) == 1
}
# [STEP 1.1] 连写短语键:与 schema_canonical_header_atoms 的 [STEP 1.1] 同一
# 口径——为 camelCase 多词别名注册去空格连写键('Unit Cost' ↔ 'UnitCost'/
# 'unitcost'),只新增、不覆盖既有键,歧义整体弃用。
joined_candidates: dict[tuple[str, ...], set[str]] = {}
for words, code in phrase_to_field.items():
if len(words) > 1:
joined_candidates.setdefault((''.join(words),), set()).add(code)
for joined, codes in joined_candidates.items():
if len(codes) == 1 and joined not in phrase_to_field:
phrase_to_field[joined] = next(iter(codes))
# [STEP 2] 逐 token 贪心最长短语匹配;序列语义:命中产出单个标记列表项,
# 未命中单词原样保留(沿用 atoms 过滤),整体保序、允许重复。
canonical: list[str] = []
@@ -0,0 +1,418 @@
"""
backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py
用途:模板路由失败时的「表头带证据补洞」定向补救(Route B)。
依赖:order_profile_matcher(匹配器与观测管线)、xfa_acroform(AcroForm 控件定位)、
native_pdf(pdfium 渲染)、ocr_pdf(RapidOCR)、file_assets 服务、tool_common 配置。
逻辑:常规匹配 layout_drift/no_match 且存在「仅表头判别冲突 + 观测原子为期望原子
真子集」的可补救候选集合时,按优先级补齐页 1 主表表头带证据:
① AcroForm/XFA 控件展示值(确定性、精确坐标,覆盖供应商把表头文字放进
表单控件/矢量层的世代);② RapidOCR 表头带(纯扫描/图像兜底)。
补洞字形带 source 标记并入页 1 表头带后重跑完整匹配器;仅当结果恰好唯一
命中集合内某个候选时采纳并打 identity_rescue_source 标记,否则维持原判
(fail-closed 由构造保证:补洞引入外来原子会破坏候选自身集合全等,同时
满足多个候选则转 ambiguous,均被拒绝)。补洞字形只在本次匹配内存中生效,
禁止回写布局版本。
"""
from __future__ import annotations
import logging
import unicodedata
from typing import Any, Callable
from app.services.shipping_notice.document_layout.order_profile_matcher import (
ProfileMatchCandidate,
ProfileMatchResult,
_extract_matching_signature,
_header_token_atoms,
_observe_layout_features,
_profile_exclusion_regions,
_profile_termination_rules,
_resolve_coordinate_transform,
_signature_identity_header_tokens,
_translate_signature,
match_frozen_coordinate_profiles,
schema_canonical_header_atoms,
)
from app.services.shipping_notice.document_layout.order_profile import (
OrderCoordinateProfile,
)
logger = logging.getLogger(__name__)
# 与 ocr_pdf.OCR_CONFIDENCE_FLOOR 对齐;低于该置信度的 OCR 行不参与补洞。
OCR_RESCUE_CONFIDENCE_FLOOR = 0.8
# 表头带高度占主表高度的比例,与 _observe_header_candidates 的保守带一致。
_HEADER_BAND_RATIO = 0.30
_BAND_EPSILON = 0.005
def _fold_diacritics(text: str) -> str:
"""NFKD 折叠并剥离音变符号(Komárom→Komarom),与历史签名的无音变口径对齐。"""
decomposed = unicodedata.normalize('NFKD', str(text or ''))
return ''.join(ch for ch in decomposed if unicodedata.category(ch) != 'Mn')
def _candidate_header_atoms(
*,
raw_profile: dict[str, Any],
layout: dict[str, Any],
header_to_field: dict[str, str] | None,
) -> tuple[frozenset[str], frozenset[str], dict[str, Any]]:
"""按匹配器同一观测口径计算候选的期望/观测表头原子与观测特征。"""
signature_body, _meta = _extract_matching_signature(raw_profile)
definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {}
profile = OrderCoordinateProfile(
profile_code=str(raw_profile.get('profile_code') or ''),
version=int(raw_profile.get('version') or 0),
document_match=definition.get('document_match'),
table_regions=definition.get('table_regions'),
order_field_layouts=definition.get('order_field_layouts') or [],
coordinate_model=definition.get('coordinate_model') or {},
reference_page_frames=definition.get('reference_page_frames') or {},
)
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
transform, _reasons = _resolve_coordinate_transform(
profile=profile, pages=pages, page_glyphs=page_glyphs,
)
observed = _observe_layout_features(
layout=layout,
tables=[item for item in layout.get('tables') or [] if isinstance(item, dict)],
pages=pages,
glyph_tables=glyph_tables,
page_glyphs=page_glyphs,
signature=_translate_signature(signature=signature_body, coordinate_transform=transform),
termination_rules=_profile_termination_rules(profile),
exclusion_regions=_profile_exclusion_regions(profile),
)
expected_tokens = _signature_identity_header_tokens(signature_body)
observed_tokens = [str(item) for item in observed.get('header_tokens') or []]
if header_to_field:
expected_atoms = schema_canonical_header_atoms(expected_tokens, header_to_field)
observed_atoms = schema_canonical_header_atoms(observed_tokens, header_to_field)
else:
expected_atoms = _header_token_atoms(expected_tokens)
observed_atoms = _header_token_atoms(observed_tokens)
return expected_atoms, observed_atoms, observed
def _eligible_rescue_candidates(
*,
match: ProfileMatchResult,
profiles: list[dict[str, Any]],
layout: dict[str, Any],
header_to_field: dict[str, str] | None,
) -> dict[tuple[str, int], tuple[ProfileMatchCandidate, dict[str, Any]]]:
"""
甄别可补救候选集合:冲突仅表头判别、观测原子为期望原子真子集。
核心逻辑:近亲模板常各自缺不同的尾部列,多个候选可同时可补救——竞争裁决
交给补洞后的完整重跑(接受条件要求补洞后恰好唯一命中集合内候选);
观测侧存在期望之外的外来原子时该候选不可补救(不是单纯缺字)。
"""
profile_by_key = {
(str(item.get('profile_code') or ''), int(item.get('version') or 0)): item
for item in profiles if isinstance(item, dict)
}
eligible: dict[tuple[str, int], tuple[ProfileMatchCandidate, dict[str, Any]]] = {}
for candidate in match.candidates:
if sorted(candidate.reason_codes) != ['profile_header_discriminator_conflict']:
continue
key = (candidate.profile_code, candidate.version)
raw = profile_by_key.get(key)
if raw is None:
continue
expected_atoms, observed_atoms, _observed = _candidate_header_atoms(
raw_profile=raw, layout=layout, header_to_field=header_to_field,
)
if not (expected_atoms - observed_atoms) or (observed_atoms - expected_atoms):
continue
eligible[key] = (candidate, raw)
return eligible
def _glyphs_in_header_band(
*,
glyphs: list[dict[str, Any]],
page_width: float,
page_height: float,
primary_table_bbox: list[float] | None,
source: str,
) -> list[dict[str, Any]]:
"""把补洞字形过滤到主表表头带内(归一化坐标,含少量容差)并打来源标记。"""
if not primary_table_bbox or len(primary_table_bbox) != 4:
return []
if page_width <= 0 or page_height <= 0:
return []
x0, y0, x1, y1 = primary_table_bbox
band_height = max(0.001, y1 - y0) * _HEADER_BAND_RATIO
kept: list[dict[str, Any]] = []
for glyph in glyphs:
bbox = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else None
if not bbox:
continue
center_x = (float(bbox.get('x0') or 0) + float(bbox.get('x1') or 0)) / 2 / page_width
center_y = (float(bbox.get('y0') or 0) + float(bbox.get('y1') or 0)) / 2 / page_height
if (
x0 - _BAND_EPSILON <= center_x <= x1 + _BAND_EPSILON
and y0 - _BAND_EPSILON <= center_y <= y0 + band_height + _BAND_EPSILON
):
marked = dict(glyph)
marked['source'] = source
kept.append(marked)
return kept
def _text_to_char_glyphs(text: str, bbox: dict[str, float]) -> list[dict[str, Any]]:
"""
把控件展示值按词分配展开为字形(与 OCR 字形同构,供视觉行重组)。
核心逻辑:词内字符连续;词间与控件尾部预留 > 0.75×字符宽的几何空隙,
保证 positioned_token_spans 的显著间隔分词能恢复出与签名一致的 token
切分(否则相邻控件字形会被并词,如 'ETD'+'ETA' → 'etdeta')。
"""
folded = _fold_diacritics(text)
words = [word for word in folded.split() if word.strip()]
if not words:
return []
bbox_width = max(0.01, float(bbox['x1']) - float(bbox['x0']))
usable_ratio = 0.7
word_gap_ratio = 1.2
total_chars = sum(len(word) for word in words)
char_width = bbox_width * usable_ratio / max(1, total_chars)
out: list[dict[str, Any]] = []
x = float(bbox['x0'])
y0, y1 = float(bbox['y0']), float(bbox['y1'])
for word in words:
for character in word:
out.append({'text': character, 'bbox': {
'x0': x, 'y0': y0, 'x1': x + char_width, 'y1': y1,
}})
x += char_width
x += char_width * word_gap_ratio
return out
def _default_read_asset_bytes(asset_id: int) -> bytes:
"""按 id 加载 FileAsset 后读取字节;read_asset_bytes 接收 ORM 对象而非 id。"""
from app.extensions import db
from app.models import FileAsset
from app.services.file_assets.service import read_asset_bytes
asset = db.session.get(FileAsset, int(asset_id))
if asset is None:
raise LookupError(f'file asset not found: {asset_id}')
return read_asset_bytes(asset)
def _collect_rescue_glyphs(
*,
document: Any,
page: dict[str, Any],
primary_table_bbox: list[float] | None,
page_images_fn: Callable[[bytes], list[Any]] | None,
ocr_lines_fn: Callable[..., list[Any]] | None,
read_asset_fn: Callable[[int], bytes],
) -> tuple[list[dict[str, Any]], str] | None:
"""
按优先级收集表头带补洞字形。
① AcroForm/XFA 控件展示值(确定性);② 整带 RapidOCR(图像兜底)。
Returns:
(字形列表, 来源标记) 或 None(无可用证据)。
"""
page_width = float(page.get('width') or 0)
page_height = float(page.get('height') or 0)
asset_id = int(getattr(document, 'asset_id', 0) or 0)
if read_asset_fn is None:
read_asset_fn = _default_read_asset_bytes
# [STEP 1] AcroForm/XFA 控件文本:确定性坐标与文本,优先于 OCR。
if asset_id > 0:
try:
from app.services.shipping_notice.document_layout.xfa_acroform import (
read_acroform_widgets,
)
content = read_asset_fn(asset_id)
widgets = [
widget for widget in read_acroform_widgets(content)
if int(widget.page_no) == 1 and str(widget.value or '').strip()
]
widget_glyphs: list[dict[str, Any]] = []
for widget in widgets:
nb = widget.normalized_bbox or {}
if not all(key in nb for key in ('x0', 'y0', 'x1', 'y1')):
continue
widget_glyphs.extend(_text_to_char_glyphs(str(widget.value), {
'x0': float(nb['x0']) * page_width,
'y0': float(nb['y0']) * page_height,
'x1': float(nb['x1']) * page_width,
'y1': float(nb['y1']) * page_height,
}))
band = _glyphs_in_header_band(
glyphs=widget_glyphs, page_width=page_width, page_height=page_height,
primary_table_bbox=primary_table_bbox, source='acroform_widget',
)
if band:
return band, 'acroform_widget'
except Exception: # noqa: BLE001 - 控件读取失败时回退 OCR 来源,补救不阻断主链
pass
# [STEP 2] 表头带 RapidOCR:渲染页 1 后 OCR(纯扫描/图像世代兜底)。
if asset_id <= 0:
return None
try:
if page_images_fn is None:
from app.services.shipping_notice.document_layout.native_pdf import (
extract_native_pdf_pages,
)
def page_images_fn(content: bytes) -> list[Any]:
return extract_native_pdf_pages(content, render_images=True)
if ocr_lines_fn is None:
from app.services.shipping_notice.document_layout.ocr_pdf import (
OCR_CONFIDENCE_FLOOR,
extract_ocr_lines,
)
def ocr_lines_fn(*args: Any, **kwargs: Any) -> list[Any]:
kwargs.setdefault('minimum_confidence', OCR_CONFIDENCE_FLOOR)
return extract_ocr_lines(*args, **kwargs)
pdf_pages = page_images_fn(read_asset_fn(asset_id))
first_page = next((item for item in pdf_pages if int(item.page_no) == 1), None)
if first_page is None or first_page.image is None:
return None
ocr_lines = ocr_lines_fn(
first_page.image,
page_width=first_page.width,
page_height=first_page.height,
minimum_confidence=OCR_RESCUE_CONFIDENCE_FLOOR,
)
if not ocr_lines:
return None
from app.services.shipping_notice.order_document_profile_service import (
_ocr_lines_to_page_characters,
)
ocr_glyphs = [
{**glyph, 'text': _fold_diacritics(str(glyph.get('text') or ''))}
for glyph in _ocr_lines_to_page_characters(lines=ocr_lines)
if str(glyph.get('text') or '').strip()
]
band = _glyphs_in_header_band(
glyphs=ocr_glyphs, page_width=page_width, page_height=page_height,
primary_table_bbox=primary_table_bbox, source='ocr_coordinate',
)
if band:
return band, 'ocr_coordinate'
return None
except Exception as exc: # noqa: BLE001 - 兜底来源失败时交回上层维持原判
# [PARAM_TUNING] 2026-10-14 test 事故(SNER-20261014-8EBAB7A1):AttributeError
# 炸穿本层令整个 Unit 技术失败。收口语义保持「静默回退」,但必须留观测痕
# 迹,否则只能靠 Unit error_message 反推。
logger.warning(
'order profile rescue glyphs failed document_id=%s error_type=%s',
int(getattr(document, 'id', 0) or 0),
type(exc).__name__,
)
return None
def rescue_match_with_header_ocr(
*,
match: ProfileMatchResult,
profiles: list[dict[str, Any]],
layout: dict[str, Any],
header_to_field: dict[str, str] | None,
document: Any,
match_fn: Callable[..., ProfileMatchResult] | None = None,
page_images_fn: Callable[[bytes], list[Any]] | None = None,
ocr_lines_fn: Callable[..., list[Any]] | None = None,
read_asset_fn: Callable[[int], bytes] | None = None,
) -> ProfileMatchResult:
"""
对路由失败结果尝试表头带证据补洞;任何不满足都原样返回(fail-closed)。
Args:
match: 常规匹配结果,须为 layout_drift / no_match 才尝试。
profiles: 冻结模板快照列表(与常规匹配同一份)。
layout: 已含原生坐标证据的运行期 Layout;禁止修改原对象。
header_to_field: Schema 表头别名契约(与常规匹配同源)。
document: ShippingOrderDocument;用于定位原始 PDF 资产。
match_fn / page_images_fn / ocr_lines_fn / read_asset_fn: 测试注入点,
默认分别使用真实匹配器、pdfium 渲染、RapidOCR 与资产读取。
Returns:
ProfileMatchResult:补洞成功返回带 identity_rescue_source 标记的唯一命中;
否则原样返回入参 match。
"""
if match.status not in {'layout_drift', 'no_match'} or not match.candidates:
return match
eligible = _eligible_rescue_candidates(
match=match, profiles=profiles, layout=layout, header_to_field=header_to_field,
)
if not eligible:
return match
try:
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
page = pages.get('1') or pages.get(1)
if not isinstance(page, dict):
return match
_, _, probe_observed = _candidate_header_atoms(
raw_profile=next(iter(eligible.values()))[1],
layout=layout,
header_to_field=header_to_field,
)
rescued_glyphs = _collect_rescue_glyphs(
document=document, page=page,
primary_table_bbox=probe_observed.get('primary_table_bbox'),
page_images_fn=page_images_fn, ocr_lines_fn=ocr_lines_fn,
read_asset_fn=read_asset_fn,
)
if not rescued_glyphs:
return match
band_glyphs, rescue_source = rescued_glyphs
page_key = '1'
page_glyphs = dict(evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {})
page_glyphs[page_key] = list(page_glyphs.get(page_key) or []) + band_glyphs
augmented = dict(layout)
augmented_evidence = {**evidence, 'page_glyphs': page_glyphs}
merged_sources = dict(augmented_evidence.get('sources') or {})
merged_page_sources = dict(merged_sources.get('pages') or {})
merged_page_sources[page_key] = f"pdf_coordinate+{rescue_source}"
merged_sources['pages'] = merged_page_sources
augmented_evidence['sources'] = merged_sources
augmented['coordinate_evidence'] = augmented_evidence
re_match_fn = match_fn if match_fn is not None else match_frozen_coordinate_profiles
rescued = re_match_fn(
profiles=profiles, layout=augmented, header_to_field=header_to_field,
)
if rescued.status not in {'unique_match', 'selected_by_score'}:
return match
winner_key = (str(rescued.profile_code or ''), int(rescued.version or 0))
if winner_key not in eligible:
# 补洞改变了竞争格局(唤醒了集合外候选)——维持原判。
return match
marked_candidates = [
item.model_copy(update={'identity_rescue_assisted': (
str(item.profile_code or ''), int(item.version or 0)) == winner_key
})
for item in rescued.candidates
]
return rescued.model_copy(update={
'identity_rescue_source': rescue_source,
'candidates': marked_candidates,
})
except Exception as exc: # noqa: BLE001 - 补救属锦上添花:任何异常(含 AttributeError 等未预期类型错误)都回退原判,不得阻断抽取主链。
logger.warning(
'order profile rescue aborted document_id=%s error_type=%s',
int(getattr(document, 'id', 0) or 0),
type(exc).__name__,
)
return match
@@ -18,7 +18,10 @@ from zipfile import ZIP_DEFLATED, ZipFile
from app.core.errors import NotFoundError, ValidationError
from app.models import ShippingExportArtifact, ShippingNotice
from app.services.shipping_notice.query_service import get_task_for_user, resolve_task_export_download
from app.services.shipping_notice.query_service import (
get_task_visible_to_user,
resolve_task_export_download,
)
MAX_ARCHIVE_TASKS = 100
@@ -28,15 +31,17 @@ def _select_tasks(
user_id: int,
task_refs: list[str] | None,
selection_name: str,
is_admin: bool = False,
require_business_no: bool = False,
) -> tuple[list[ShippingNotice], str]:
"""按显式 task_no 或 business_no 选择当前用户通知,禁止部分越权成功。"""
"""按显式 task_no 或 business_no 选择当前用户可下载通知,禁止部分越权成功。"""
normalized_tasks = list(dict.fromkeys(str(item or '').strip() for item in (task_refs or []) if str(item or '').strip()))
if not normalized_tasks:
raise ValidationError(f'{selection_name} is required', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
tasks = []
for task_no in normalized_tasks:
task = get_task_for_user(task_no, user_id)
# 下载授权与单票导出同一谓词:创建者或管理员(可下载=可见)。
task = get_task_visible_to_user(task_no, user_id, is_admin=is_admin)
# 导出归档是正式 Notice 边界;OT 尚未生成正式单据时不可进入 Artifact 查询。
if not isinstance(task, ShippingNotice) or (
require_business_no and str(getattr(task, 'business_no', '') or '').strip().upper() != task_no.upper()
@@ -90,10 +95,17 @@ def build_export_archive(
user_id: int,
task_nos: list[str] | None = None,
business_nos: list[str] | None = None,
is_admin: bool = False,
) -> tuple[BinaryIO, str, dict]:
"""
生成 ZIP 和 manifest;缺失/损坏票据保留在 manifest,但不阻止其余有效文件下载。
Args:
user_id: 当前下载用户;与 ``is_admin`` 共同构成下载授权谓词口径。
task_nos: 按 SN 技术号选择(与 business_nos 二选一)。
business_nos: 按发货通知单号选择(与 task_nos 二选一)。
is_admin: 是否平台管理员;管理员可打包其可见的正式 Notice。
Returns:
(定位到开头的 ZIP 字节流, 下载文件名, manifest 字典)。
"""
@@ -105,6 +117,7 @@ def build_export_archive(
user_id=user_id,
task_refs=selection_values,
selection_name=selection_name,
is_admin=is_admin,
require_business_no=business_nos is not None,
)
artifacts = _ready_artifacts(tasks)
@@ -115,11 +128,16 @@ def build_export_archive(
included = 0
with ZipFile(stream, mode='w', compression=ZIP_DEFLATED) as archive:
for task in tasks:
# business_no 供端点按票写入访问审计(与单票下载同一 aggregate 口径)。
entry_base = {
'task_no': task.task_no,
'business_no': str(getattr(task, 'business_no', '') or ''),
}
task_artifacts = artifacts.get(int(task.id), []) if task.id is not None else []
if not task_artifacts:
entries.append({'task_no': task.task_no, 'status': 'missing_artifact', 'artifact_no': None, 'file_name': None})
entries.append({**entry_base, 'status': 'missing_artifact', 'artifact_no': None, 'file_name': None})
for artifact in task_artifacts:
entry = {'task_no': task.task_no, 'status': 'missing_file', 'artifact_no': artifact.artifact_no, 'file_name': None}
entry = {**entry_base, 'status': 'missing_file', 'artifact_no': artifact.artifact_no, 'file_name': None}
entry['artifact_no'] = artifact.artifact_no
path = Path(artifact.file_path)
if not path.is_file():
@@ -1277,6 +1277,14 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str,
)
# 行级匹配只持久化当前 LineMatch;OT 不再保存库存匹配聚合列或行结果缓存。
_merge_line_inventory_resolutions(task, match_payload, snapshot_line_id=int(snapshot.lines[orig_idx].id) if snapshot is not None and orig_idx < len(snapshot.lines) else None)
# [BE-料号兜底自动放行] 行事实落库后、聚合重算【前】执行(与 match_inventory 同款钩子):
# 料号总量满足需求的缺口行由系统自动放行,使下方聚合重算把放行行计入满足、
# 行级重匹配可直接落 MATCHED_FULFILLABLE;重入安全性说明见 match_inventory 钩子注释。
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
auto_release_part_fallback_shortages,
)
auto_release_part_fallback_shortages(task)
line_results = list(match_payload.get('line_results') or [])
from app.services.shipping_notice.reservation_service import record_inventory_verification
@@ -1778,6 +1786,17 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
inventory_snapshot_id=active_inventory_file_for_task(task).id if active_inventory_file_for_task(task) else None,
matching_rule_version='stp_line_v2',
)
# [BE-料号兜底自动放行] 行事实落库后、聚合与 match_completed 判定【前】执行:
# 料号总量满足需求的缺口行由系统自动放行(满足即放行,非仅可放行),使随后的
# 聚合重算与满足性判定把放行行计入满足、任务可直接落 MATCHED_FULFILLABLE。
# 重入安全:匹配跑在 AutoProgress Gate 执行器事务内时,submit_auto_progress 按
# 「任务唯一活动 Job + 活动 Attempt 复用」幂等,不会重复入队或自触发;auto fulfill
# Job 重复入队由协调器 eligible+幂等键吸收(与既有匹配路径的多入队行为一致)。
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
auto_release_part_fallback_shortages,
)
auto_release_part_fallback_shortages(task)
# 详情投影只读 task JSON;必须基于已落库的 current 行事实重算整单,
# 否则匹配失败后订单明细仍显示“待确认”,且局部结果可能覆盖既有缺口。
match_status, shortages = _recompute_task_match_aggregate(task)
@@ -716,6 +716,255 @@ def freeze_manual_line_source_selection(
return result, all(bool(item['candidate_inventory_source_codes']) for item in line_projections)
def active_candidate_set_is_manually_pinned(
task: ShippingNotice,
*,
session: Session | None = None,
) -> bool:
"""
判断活动候选集是否含人工选源(「人工指定即定论」的统一判定入口)。
Args:
task: 当前 ShippingOrderTask。
session: 可选 Session。
Returns:
bool: True 表示人工已裁决候选源,自动重路由必须跳过。
"""
sess = session or db.session
active_set = (
sess.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id))
if getattr(task, 'active_inventory_candidate_set_id', None) is not None
else None
)
if active_set is None:
return False
if getattr(active_set, 'frozen_by_id', None) is not None:
return True
return any(
str(getattr(source, 'candidate_origin', '') or '').strip().lower() == 'manual_override'
for source in (active_set.sources or [])
)
def refresh_candidates_from_current_routing(
task: ShippingNotice,
*,
execution_id: int | None = None,
session: Session | None = None,
) -> bool:
"""
任务级:按当前库存源主数据与路由规则重跑裁决并重冻结候选集;返回是否产生新版本候选集。
【AI 触发时机】:仅「重新获取库存(RPA)」的任务级人工重取路径作为前置步骤调用;
禁止在轮询(poll)、自动首投路径调用——刷新是显式人工动作的伴随效果,不是隐式自动行为。
核心逻辑:
[守卫 1] 仅多候选未定源可刷新(task_frozen_inventory_source_codes > 1);源已定单
不得自动改源,换源走 override_line_inventory_source 行级覆写。
[守卫 2] 活动候选集含人工选源(frozen_by_id / candidate_origin='manual_override')
时跳过:人工指定即定论,禁止重路由洗掉人工裁决。
[STEP 1] 记录当前活动 set_id。
[STEP 2] adjudicate_and_apply_inventory_source(execution_id=...) 重裁决 + 幂等冻结
(freeze 服务 input_fingerprint 未变则复用旧集,零副作用;重裁决为 unresolved 时
apply 不落任何事实,活动集保持不变,同样视为无变化)。
[STEP 3] 活动集变化时冻结服务已内置旧版本下游失效(_invalidate_task_candidate_outputs:
匹配事实/准备 Attempt/RPA Attempt 等),此处仅补写任务事件供审计追溯。
Args:
task: 当前 ShippingOrderTask(须已冻结候选集)。
execution_id: 当前 ProcessExecution id;透传冻结服务,避免重冻结撤销活动执行链。
session: 可选 Session。
Returns:
bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。
"""
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
from app.services.shipping_notice.inventory_source_gate import adjudicate_and_apply_inventory_source
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
sess = session or db.session
if len(task_frozen_inventory_source_codes(task)) <= 1:
return False
if active_candidate_set_is_manually_pinned(task, session=sess):
return False
before = get_active_candidate_set(task)
before_set_id = int(before.id) if before is not None else None
adjudicate_and_apply_inventory_source(task, execution_id=execution_id)
sess.flush()
after = get_active_candidate_set(task)
after_set_id = int(after.id) if after is not None else None
if before_set_id == after_set_id:
return False
from app.services.shipping_notice.tool_common import log_task_event
log_task_event(
task,
'inventory_candidates_refreshed',
{
'scope': 'task',
'previous_set_id': before_set_id,
'new_set_id': after_set_id,
'source_codes': task_frozen_inventory_source_codes(task),
},
source='system',
)
return True
def refresh_line_candidates_from_current_routing(
task: ShippingNotice,
*,
line_no: int,
execution_id: int | None = None,
session: Session | None = None,
) -> bool:
"""
行级:按当前库存源主数据与路由规则重评单个订单行的候选源并重冻结候选集;返回是否产生新版本。
【AI 触发时机】:仅「重新获取库存(RPA)」的行级重抓(retry_inventory_preparation 携带
line_scope)作为前置步骤调用;禁止在轮询/自动首投路径调用。
核心逻辑:
[守卫 1] 目标行当前候选 >1(未定源)才重评;单源行已定,改源走行级覆写。
[守卫 2] 活动候选集含人工选源时跳过(与任务级刷新同一条红线:人工指定即定论)。
[STEP 1] 行级规则重评:_task_routing_lines(task) 按 line_no-1 取目标行(越界返回 False),
evaluate_inventory_source_rules(task=task, line=...) 得到规则原始候选,经
get_database_inventory_source 过滤停用源(对齐 _result_to_adjudication 语义);
仅接受 resolved/ambiguous 结论,unresolved 保持旧行为不刷新。
[STEP 2] 以活动集全量行为骨架构建 line_projections:目标行替换为新候选,其余行原样继承
(保留既有行候选,不做整单重路由)。
[STEP 3] freeze_candidates_for_task(candidates_frozen 裁决)幂等冻结;created_new 即新版
候选集(supersede 旧集时内置下游失效),写行级刷新任务事件并返回 True。
Args:
task: 当前 ShippingOrderTask(须已冻结候选集)。
line_no: 目标订单项次(1 基,对应冻结快照 line_no)。
execution_id: 当前 ProcessExecution id;透传冻结服务,避免重冻结撤销活动执行链。
session: 可选 Session。
Returns:
bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。
"""
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
from app.services.shipping_notice.inventory_source_repository import (
get_database_inventory_source,
inventory_sources_runtime_version,
)
from app.services.shipping_notice.inventory_source_rules import (
_task_routing_lines,
compute_routing_fingerprint,
evaluate_inventory_source_rules,
extract_routing_context,
)
sess = session or db.session
active_set = get_active_candidate_set(task)
if active_set is None:
return False
if active_candidate_set_is_manually_pinned(task, session=sess):
return False
existing_lines = {
int(row.line_no): row
for row in (active_set.lines or [])
if getattr(row, 'line_no', None) is not None
}
target = existing_lines.get(int(line_no))
if target is None:
return False
current_codes = [
str(code).strip().upper()
for code in (target.source_codes_json or [])
if str(code or '').strip()
]
if len(current_codes) <= 1:
return False
routing_lines = _task_routing_lines(task)
position = int(line_no) - 1
if position < 0 or position >= len(routing_lines):
return False
line_result = evaluate_inventory_source_rules(task=task, line=routing_lines[position])
line_status = str(getattr(line_result, 'status', '') or '').strip().lower()
if line_status not in {'resolved', 'ambiguous'}:
return False
new_codes: list[str] = []
for raw in (getattr(line_result, 'source_codes', None) or []):
code = str(raw or '').strip().upper()
if code and code not in new_codes and get_database_inventory_source(code) is not None:
new_codes.append(code)
if not new_codes:
return False
line_projections: list[dict[str, Any]] = []
union_codes: list[str] = []
for row_line_no in sorted(existing_lines):
row = existing_lines[row_line_no]
codes = (
new_codes
if row_line_no == int(line_no)
else [
str(code).strip().upper()
for code in (row.source_codes_json or [])
if str(code or '').strip()
]
)
for code in codes:
if code not in union_codes:
union_codes.append(code)
line_projections.append({
'line_no': row_line_no,
'source_line_no': str(getattr(row, 'source_line_no', '') or '') or None,
'part_number': getattr(row, 'part_number', None),
'reservation_id': getattr(row, 'reservation_id', None),
'candidate_inventory_source_codes': codes,
})
if not union_codes:
return False
context = extract_routing_context(task)
adjudication = InventorySourceAdjudication(
status='candidates_frozen',
method='line_refresh_reroute',
source_code=None,
connector_type=None,
warehouse_id=None,
config_version=inventory_sources_runtime_version(),
routing_fingerprint=compute_routing_fingerprint(context),
candidates=[{'source_code': code} for code in union_codes],
evidence=[{
'line_candidates_refresh': {
'line_no': int(line_no),
'previous_codes': current_codes,
'new_codes': new_codes,
},
}],
reason='line_refresh_reroute',
)
freeze_result = freeze_candidates_for_task(
task,
adjudication=adjudication,
line_projections=line_projections,
execution_id=execution_id,
session=sess,
)
if not freeze_result.created_new:
return False
from app.services.shipping_notice.tool_common import log_task_event
log_task_event(
task,
'inventory_candidates_refreshed',
{
'scope': 'line',
'line_no': int(line_no),
'previous_codes': current_codes,
'new_codes': new_codes,
'new_set_id': int(freeze_result.candidate_set_id),
},
source='system',
)
return True
def freeze_wave_notice_routing(
notice: ShippingNotice,
*,
@@ -21,6 +21,7 @@ from app.models import (
ShippingInventoryCandidateSet,
ShippingInventoryCandidateSource,
ShippingInventoryFile,
ShippingNotice,
ShippingOrderTask,
ShippingNoticeLineInventoryMatch,
ShippingTaskInventoryRpaAttempt,
@@ -82,8 +83,35 @@ def _candidate_set_filter(
return list(rows)
def resolve_inventory_fact_task(task: Any) -> Any:
"""
将库存事实读取对象归一为正式 OT。
核心逻辑:候选集/库存 Link 全部挂在 OT 上,而货代上传等入口按 business_no
加载 ShippingNotice——Notice 没有 active_inventory_candidate_set_id 字段,
直接查询会 fail-closed 成「库存源尚未确定」(历史缺陷:RPA 上传被恒拦截,
自动推进的 freight_upload_rpa 门禁也因此秒切人工)。OT 原样返回;Notice 沿
order_task_id 解析,缺绑定或 OT 不存在时原样返回,由上层无候选集语义继续
fail-closed。
Args:
task: ShippingOrderTask 或 ShippingNotice。
Returns:
归一后的 OT(或无法解析时的原对象)。
"""
if isinstance(task, ShippingNotice):
order_task_id = getattr(task, 'order_task_id', None)
if order_task_id is None:
return task
order_task = _session().get(ShippingOrderTask, int(order_task_id))
if order_task is not None:
return order_task
return task
def get_active_candidate_set(
task: ShippingOrderTask,
task: ShippingOrderTask | ShippingNotice,
*,
session: Session | None = None,
) -> ShippingInventoryCandidateSet | None:
@@ -92,7 +120,9 @@ def get_active_candidate_set(
核心逻辑:严格依赖 ShippingOrderTask.active_inventory_candidate_set_id;
指针为空、坏链、跨 Task、非 frozen 均返回 None,由上层映射阻断。
传入 ShippingNotice 时先归一为其 order_task(见 resolve_inventory_fact_task)。
"""
task = resolve_inventory_fact_task(task)
candidate_set_id = getattr(task, 'active_inventory_candidate_set_id', None)
if candidate_set_id is None:
return None
@@ -2,8 +2,10 @@
services/shipping_notice/inventory_routing_engine.py
用途:执行已发布的通用库存源路由规则并生成可解释的 Source 候选。
依赖:库存路由模型、冻结订单 Snapshot、routing_operators。
逻辑:只评估最高优先级命中的规则层;规则仅输出候选或人工复核,不执行 RPA 或 Warehouse 判定。
依赖:库存路由模型、冻结订单 Snapshot、routing_operators、inventory_source_repository。
逻辑:行级评估先做「库存源线索直连」(冻结行 inventory_source_hint 经精确/唯一后缀解析启用源,
命中即 resolved,跳过全部规则层——含预约单号兜底规则;未命中 fail-open 落回规则层);
随后只评估最高优先级命中的规则层;规则仅输出候选或人工复核,不执行 RPA 或 Warehouse 判定。
多候选为建单前正常结果(can_build=True);零候选或 require_manual_review 才阻断建单。
输出附带规则版本与命中规则摘要,供建单前重路由审计与前端展示;可用性过滤由资格服务完成。
"""
@@ -15,6 +17,7 @@ from datetime import datetime
from typing import Any
from app.models import ShippingInventoryRoutingRule, ShippingOrderSnapshot
from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources
from app.services.shipping_notice.routing_operators import matches_operator
@@ -88,6 +91,55 @@ def _matched_rule_summaries(rules: list[ShippingInventoryRoutingRule]) -> tuple[
)
def _resolve_source_from_hint(line_source_hint: str) -> str | None:
"""
库存源线索 → 启用源解析:精确 source_code 相等优先,否则启用源中唯一后缀命中。
无命中或多命中(后缀撞源)返回 None——调用方 fail-open 落回规则层,不以线索阻断流程。
"""
code = str(line_source_hint or '').strip().upper()
if not code:
return None
enabled_codes = [
normalized
for normalized in (
str(item.get('source_code') or '').strip().upper()
for item in list_database_inventory_sources(enabled_only=True)
)
if normalized
]
if code in enabled_codes:
return code
suffix_hits = [item for item in enabled_codes if item.endswith(code)]
return suffix_hits[0] if len(suffix_hits) == 1 else None
def _hint_routing_result(source_code: str) -> InventoryRoutingResult:
"""线索直连结果:resolved 单源,evidence 标明来源供审计追溯。"""
return InventoryRoutingResult(
'resolved',
(source_code,),
(),
{'reason': 'inventory_source_hint', 'raw_source_codes': [source_code]},
matched_rules=(),
)
def _resolve_snapshot_line_source_hint(*, task: Any, line: dict[str, Any]) -> str | None:
"""从冻结 Snapshot 行的强类型线索列读取并解析线索;行缺失或不可解析返回 None。"""
snapshot_id = getattr(task, 'order_snapshot_id', None)
if not snapshot_id:
return None
snapshot = ShippingOrderSnapshot.query.get(int(snapshot_id))
if snapshot is None:
return None
position = int(line.get('_position', 0))
target = next((item for item in snapshot.lines if item.position == position), None)
if target is None:
return None
return _resolve_source_from_hint(str(getattr(target, 'inventory_source_hint', '') or ''))
def _condition_value(condition: Any, *, task: Any, line: dict[str, Any] | None) -> Any:
"""只读取冻结 Snapshot;履约路由不得回读动态 FieldValue。"""
if condition.source_kind != 'order_field':
@@ -232,14 +284,22 @@ def evaluate_inventory_source_rules(
"""
评估已发布规则并返回最高优先级的 Source 候选集合(冻结 Snapshot 路径)。
核心逻辑:行级评估先做库存源线索直连(冻结行 inventory_source_hint 列 → 精确/唯一后缀
解析启用源,命中即 resolved,优先于包括预约单号兜底在内的全部规则层);未命中 fail-open
落回规则层。任务级评估无线索语义,维持原行为。
Args:
task: 已解析的货代任务(须有 order_snapshot_id)。
line: 行级规则的订单行;任务级规则传 None。
line: 行级规则的订单行;任务级规则传 None。须含 `_position`(`_task_routing_lines` 产物)。
now: 测试可注入的评估时间,默认当前 UTC 时间。
Returns:
InventoryRoutingResult: 含 status / source_codes / matched_rules / can_build。
"""
if line is not None:
hint_code = _resolve_snapshot_line_source_hint(task=task, line=line)
if hint_code:
return _hint_routing_result(hint_code)
scope = 'line' if line is not None else 'task'
return _evaluate_with_reader(
scope=scope,
@@ -254,11 +314,15 @@ def evaluate_inventory_source_rules_for_field_values(
line_field_values: dict[str, Any] | None = None,
scope: str | None = None,
now: datetime | None = None,
line_source_hint: str | None = None,
) -> InventoryRoutingResult:
"""
基于 field_id→值映射评估路由(建单前 Draft / 资格服务)。
基于 field_id→值 映射评估路由(建单前 Draft / 资格评估)。
核心逻辑:未传 scope 时,有 line_field_values 则评 line,否则评 task;
核心逻辑:行级评估先做库存源线索直连(调用方从 Draft 行取 `inventory_source_hint` 值
传入;精确/唯一后缀解析启用源,命中即 resolved,优先于全部规则层);未命中 fail-open
落回规则层。任务级评估(line_field_values=None)忽略线索,维持原行为。
未传 scope 时,有 line_field_values 则评 line,否则评 task;
不依赖 ShippingNotice / Snapshot,便于复核草稿阶段投影候选。
Args:
@@ -266,6 +330,7 @@ def evaluate_inventory_source_rules_for_field_values(
line_field_values: Line 字段值;行级规则必填。
scope: 显式规则作用域 ``line`` / ``task``;缺省按是否有行值推断。
now: 可选评估时间。
line_source_hint: Draft 行的库存源线索原始值;任务级评估或不传时忽略。
Returns:
InventoryRoutingResult。
@@ -274,6 +339,10 @@ def evaluate_inventory_source_rules_for_field_values(
resolved_scope = scope or ('line' if line_field_values is not None else 'task')
if resolved_scope not in {'line', 'task'}:
raise ValueError('inventory routing scope must be line or task')
if resolved_scope == 'line':
hint_code = _resolve_source_from_hint(line_source_hint or '')
if hint_code:
return _hint_routing_result(hint_code)
line_values = dict(line_field_values or {}) if resolved_scope == 'line' else None
return _evaluate_with_reader(
scope=resolved_scope,
@@ -277,9 +277,14 @@ def assert_inventory_source_gate(
def task_inventory_identity(task: ShippingOrderTask) -> dict[str, str | None]:
"""返回库存执行身份;固定仓来自配置,动态仓仅来自已验证库存 Link。"""
"""返回库存执行身份;固定仓来自配置,动态仓仅来自已验证库存 Link。
传入 ShippingNotice 时先归一为其 order_task(库存 Link 挂在 OT 上)。
"""
from app.services.shipping_notice.inventory_candidate_projection import resolve_inventory_fact_task
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
task = resolve_inventory_fact_task(task)
source_codes = task_frozen_inventory_source_codes(task)
source_code = source_codes[0] if len(source_codes) == 1 else None
source = get_database_inventory_source(source_code) if source_code else None
@@ -294,13 +299,19 @@ def resolve_inventory_source_warehouse_id(
*,
source: dict[str, Any] | None,
) -> str | None:
"""解析库存执行仓库:固定仓读 Source 配置,动态仓只读有效库存 Link。"""
"""解析库存执行仓库:固定仓读 Source 配置,动态仓只读有效库存 Link。
传入 ShippingNotice 时先归一为其 order_task(库存 Link 挂在 OT 上)。
"""
if not source:
return None
mode = str(source.get('warehouse_resolution_mode') or '').strip().lower()
if mode == 'fixed':
return str(source.get('fixed_warehouse_id') or '').strip().upper() or None
from app.services.shipping_notice.inventory_candidate_projection import resolve_inventory_fact_task
task = resolve_inventory_fact_task(task)
task_id = getattr(task, 'id', None)
source_code = str(source.get('source_code') or '').strip().upper()
if not task_id or not source_code:
@@ -5,6 +5,11 @@ services/shipping_notice/line_inventory_match_persistence.py
依赖:ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、normalize 投影语义。
逻辑:由 fulfillment_workflow.match_inventory 调用;按冻结订单行 snapshot_line_id 落库;
新快照新增行并切换 is_current;不覆盖历史快照事实。
行级 inventory_snapshot_id 按匹配结果自带的 inventory_file_no 归因到「命中文件」;
仅行结果未回填文件号(如 not_found)时才回退任务级锚点快照——多源池下锚点文件
≠命中文件,混用会导致 Excel 仓库列写成锚点仓(历史缺陷:AWSCV 单写成 CMH01)。
匹配器下发的料号兜底总量 part_available_qty(Task 1)随行事实字符串化落列,
供后续投影层与自动放行服务读取。
"""
from __future__ import annotations
@@ -109,12 +114,14 @@ def persist_line_inventory_match_facts(
from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts
snap_id = active_inventory_runtime_facts(task).get('inventory_file_id')
# 匹配器结果可能未回填 inventory_file_no,但当前快照本身已是行匹配的
# 正式文件身份。持久化必须补齐,避免“有快照却无行级下载证据”。
# 任务级锚点快照仅作行结果缺文件号时的回退身份;命中文件归因在行循环内逐行解析。
snapshot_file_no = None
if snap_id is not None:
snapshot = ShippingInventoryFile.query.get(int(snap_id))
snapshot_file_no = str(getattr(snapshot, 'inventory_file_no', '') or '').strip() or None
# 命中文件号 → 文件 ID 缓存;文件号查不到文件时缓存 None,本行回退锚点快照
# (命中证据仍以 matched_file_no 为准,不把锚点伪装成命中文件)。
file_id_by_no: dict[str, int | None] = {}
line_results = [
item for item in list(match_payload.get('line_results') or []) if isinstance(item, dict)
@@ -154,6 +161,23 @@ def persist_line_inventory_match_facts(
continue
snapshot_line_id = int(snapshot_line.id)
# [STEP] 行级文件归因:匹配结果自带 inventory_file_no 时解析命中文件 ID;
# 未回填(如 not_found)或文件号无法解析时回退任务级锚点快照。
# 禁止把锚点文件身份盖到命中了其他源文件的行上(历史缺陷根因)。
line_file_no = str(result.get('inventory_file_no') or '').strip() or None
line_snap_id = snap_id
if line_file_no is not None:
if line_file_no not in file_id_by_no:
hit_file = (
ShippingInventoryFile.query
.filter_by(inventory_file_no=line_file_no)
.first()
)
file_id_by_no[line_file_no] = int(hit_file.id) if hit_file is not None else None
resolved_file_id = file_id_by_no[line_file_no]
if resolved_file_id is not None:
line_snap_id = resolved_file_id
match_result, inventory_status = map_disposition_to_match_codes(
disposition=str(result.get('disposition') or res.get('disposition') or ''),
part_number=result.get('part_number') or res.get('part_number'),
@@ -170,8 +194,8 @@ def persist_line_inventory_match_facts(
else []
)
# [STEP] BE-5:无库存快照时禁止 ready/not_found(不得规范为 0)
if snap_id is None and (
# [STEP] BE-5:本行无任何库存文件身份时禁止 ready/not_found(不得规范为 0)
if line_snap_id is None and (
inventory_status == 'ready'
or match_result in {'matched', 'not_found'}
):
@@ -193,20 +217,20 @@ def persist_line_inventory_match_facts(
)
unit_value = str(unit_raw or '').strip()[:32] or None
# [STEP] 同 OT+行+快照:更新;否则新建并撤销旧 current
# [STEP] 同 OT+行+命中文件:更新;否则新建并撤销旧 current
existing = None
if snap_id is not None:
if line_snap_id is not None:
existing = (
ShippingNoticeLineInventoryMatch.query
.filter_by(
task_id=int(task.id),
snapshot_line_id=snapshot_line_id,
line_no=line_no,
inventory_snapshot_id=int(snap_id),
inventory_snapshot_id=int(line_snap_id),
)
.first()
)
if existing is None and snap_id is None:
if existing is None and line_snap_id is None:
existing = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task.id), snapshot_line_id=snapshot_line_id, is_current=True)
@@ -251,7 +275,7 @@ def persist_line_inventory_match_facts(
'candidate_hit_source_codes': result.get('candidate_hit_source_codes'),
'inventory_file_no': file_no,
'inventory_row_ref': result.get('inventory_row_ref'),
'snapshot_missing': snap_id is None,
'snapshot_missing': line_snap_id is None,
'evidence_ref_plain': evidence_plain if evidence_ref else None,
}
row = ShippingNoticeLineInventoryMatch(
@@ -271,12 +295,18 @@ def persist_line_inventory_match_facts(
else None
),
candidate_line_id=int(candidate_line.id) if candidate_line is not None else None,
inventory_snapshot_id=int(snap_id) if snap_id is not None else None,
inventory_snapshot_id=int(line_snap_id) if line_snap_id is not None else None,
match_result=match_result,
inventory_status=inventory_status,
required_qty=str(required) if required is not None else None,
available_qty=str(available) if available is not None else None,
shortage_qty=str(shortage) if shortage is not None else None,
# 料号兜底总量(Task 1 匹配器下发):字符串化落列;无键/None → NULL,
# BE-5 / not_found 分支不篡改,直接取匹配器原值。
part_available_qty=(
str(result['part_available_qty'])
if result.get('part_available_qty') is not None else None
),
reservation_id=rsv,
part_number=pn,
unit=unit_value,
@@ -296,7 +326,7 @@ def persist_line_inventory_match_facts(
'candidate_line_id': int(candidate_line.id) if candidate_line is not None else None,
'allowed_source_codes_snapshot': list(allowed_source_codes),
'inventory_file_no': file_no,
'inventory_snapshot_id': int(snap_id) if snap_id is not None else None,
'inventory_snapshot_id': int(line_snap_id) if line_snap_id is not None else None,
'inventory_row_ref': result.get('inventory_row_ref'),
'match_result': match_result,
}).encode('utf-8')
@@ -334,7 +364,7 @@ def persist_line_inventory_match_facts(
'candidate_hit_source_codes': result.get('candidate_hit_source_codes'),
'inventory_file_no': file_no,
'inventory_row_ref': result.get('inventory_row_ref'),
'snapshot_missing': snap_id is None,
'snapshot_missing': line_snap_id is None,
'evidence_ref_plain': evidence_plain if evidence_ref else None,
}
existing.match_result = match_result
@@ -342,6 +372,11 @@ def persist_line_inventory_match_facts(
existing.required_qty = str(required) if required is not None else None
existing.available_qty = str(available) if available is not None else None
existing.shortage_qty = str(shortage) if shortage is not None else None
# 更新分支同样以最新匹配结果刷新兜底总量;键缺失 → NULL,不残留旧值。
existing.part_available_qty = (
str(result['part_available_qty'])
if result.get('part_available_qty') is not None else None
)
existing.reservation_id = rsv
existing.part_number = pn
existing.unit = unit_value
@@ -372,7 +407,7 @@ def persist_line_inventory_match_facts(
'candidate_line_id': int(candidate_line.id) if candidate_line is not None else None,
'allowed_source_codes_snapshot': list(allowed_source_codes),
'inventory_file_no': file_no,
'inventory_snapshot_id': int(snap_id) if snap_id is not None else None,
'inventory_snapshot_id': int(line_snap_id) if line_snap_id is not None else None,
'inventory_row_ref': result.get('inventory_row_ref'),
'match_result': match_result,
}).encode('utf-8')
@@ -5,6 +5,8 @@ services/shipping_notice/line_inventory_match_projection.py
依赖:ShippingNoticeLineInventoryMatch、ShippingTaskInventoryRpaAttempt、Config 自动履约开关。
逻辑:由 order_review_fulfillment_decision_service / ui_state._build_stage_context 调用;
ready+not_found→available=0;result_missing 不得转 0;
part_available_qty(料号兜底总量)仅 inventory_status==ready 时透出,否则 None,
不派生「可兜底放行」布尔(自动放行判定在 Task 7 服务内基于行事实现算);
inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮);
line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail;
load_current_match_facts_by_task / inventory_rpa_is_running 在同一 HTTP 请求内 memo,
@@ -562,6 +564,7 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any
'required_qty': row.required_qty,
'available_qty': row.available_qty,
'shortage_qty': row.shortage_qty,
'part_available_qty': getattr(row, 'part_available_qty', None),
'reservation_id': row.reservation_id,
'part_number': row.part_number,
'unit': row.unit,
@@ -661,6 +664,7 @@ def project_line_inventory_view(
'inventory_status': None,
'match_result': None,
'available_qty': None,
'part_available_qty': None,
'shortage_qty': None,
'is_shortage': False,
'display_available': 'pending',
@@ -699,6 +703,12 @@ def project_line_inventory_view(
required_qty=required_qty if required_qty is not None else fact.get('required_qty'),
available_qty=fact.get('available_qty'),
)
# [STEP] 料号兜底口径:仅库存就绪时透出料号总可用量(与 available_qty 同门控);
# 「是否可兜底放行」的判定由自动放行服务基于行事实现算,投影层不下发派生布尔。
part_total = _parse_qty(fact.get('part_available_qty'))
part_available_value = (
str(part_total) if inventory_status == STATUS_READY and part_total is not None else None
)
user_status = project_user_line_status(
inventory_status=inventory_status,
match_result=match_result,
@@ -770,6 +780,7 @@ def project_line_inventory_view(
'inventory_status': inventory_status,
'match_result': match_result,
'available_qty': qty['available_qty'],
'part_available_qty': part_available_value,
'shortage_qty': qty['shortage_qty'],
'is_shortage': bool(qty['is_shortage']),
'display_available': qty['display_available'],
@@ -290,6 +290,8 @@ def project_line_inventory_candidates(
header_field_values=header_ids,
line_field_values=line_ids,
scope='line',
# [线索直连] Draft 行的库存源线索经引擎精确/唯一后缀解析启用源,命中即优先于全部规则层。
line_source_hint=str(line_by_code.get('inventory_source_hint') or '').strip() or None,
)
task_result = evaluate_inventory_source_rules_for_field_values(
header_field_values=header_ids,
@@ -118,7 +118,25 @@ def _order_snapshot_line_ids(notice: ShippingNotice) -> list[str]:
return sorted(set(keys), key=lambda value: int(value))
def editable_scope(order_task: ShippingNotice) -> dict[str, Any]:
def _resolve_scope_notice(task: ShippingNotice | ShippingOrderTask) -> ShippingNotice | None:
"""编辑窗身份归一:主通知原样返回;传入 OT 时按 order_task_id 反查任一同单通知。
产物(Export Artifact)与 Attempt 都挂在通知上——OT 身份直接参与谓词会因
查不到产物而恒判可编辑(用户报告:Excel 已产生仍显示出单工具条)。
"""
task_id = getattr(task, 'id', None)
if isinstance(task, ShippingNotice) or task_id is None:
# 主通知原样返回;未落库的 OT 不可能有通知,视同"Excel 从未生成"。
return task if isinstance(task, ShippingNotice) else None
return (
ShippingNotice.query
.filter(ShippingNotice.order_task_id == int(task_id))
.order_by(ShippingNotice.id.asc())
.first()
)
def editable_scope(order_task: ShippingNotice | ShippingOrderTask) -> dict[str, Any]:
"""
计算确认后订单的编辑窗矩阵(D10 / §3.1)。
@@ -127,20 +145,24 @@ def editable_scope(order_task: ShippingNotice) -> dict[str, Any]:
行未入波次 → 无活动 Attempt(不受首单 Excel 限制)。
Args:
order_task: 正式订单的主 ShippingNotice(含 order_task_id 可回读同订单全部通知)。
order_task: 主 ShippingNotice 或正式 OT(OT 自动按 order_task_id 归一到主通知)。
Returns:
dict: {'header': bool, 'lines': {snapshot_line_id: bool}},同构供 ui_state.edit_window 下发。
"""
notices = _order_notices(order_task)
notice = _resolve_scope_notice(order_task)
if notice is None:
# 尚未产生任何通知(Excel 从未生成):无产物、无活动 Attempt,视为可编辑。
return {'header': True, 'lines': {}}
notices = _order_notices(notice)
order_busy = any(_notice_has_active_attempt(n) for n in notices)
header_has_excel = any(_notice_has_export_artifact(n) for n in notices)
header = (not header_has_excel) and (not order_busy)
wave_notice_map = _wave_line_to_notice_map(_review_case_id_for_notice(order_task))
wave_notice_map = _wave_line_to_notice_map(_review_case_id_for_notice(notice))
lines: dict[str, bool] = {}
for snapshot_line_id in _order_snapshot_line_ids(order_task):
for snapshot_line_id in _order_snapshot_line_ids(notice):
wave_task_id = wave_notice_map.get(snapshot_line_id)
if wave_task_id is None:
# 未入波次行:不受首单 Excel 限制,仅受活动 Attempt 影响。
@@ -311,6 +311,51 @@ def _resolve_automatic_acceptance(raw_order: dict[str, Any]) -> dict[str, str] |
return dict(_AUTOMATIC_ACCEPTANCE_BY_MARKER[marker]) if marker in _AUTOMATIC_ACCEPTANCE_BY_MARKER else None
def _failed_unit_errors_by_document(run_id: int | None) -> dict[int, dict[str, str | None]]:
"""
读取 Run 内 Unit 级失败事实(document_id → 错误码/消息),供收口裁决纠正文档级状态。
核心逻辑:persist 的候选裁决只知道「有没有 pending」,不知道 Unit 是否技术失败;
Unit 全失败的附件没有任何产出裁决,禁止按零 pending 误写 completed
(回归 SNER-20261014-8EBAB7A1:9 Unit 全失败仍整批 completed,批次中心误报通知完成)。
Args:
run_id: ShippingOrderProcessingRun 主键;为空时返回空表(领域单测路径)。
Returns:
document_id → {'error_code', 'error_message'} 映射。
"""
if run_id is None:
return {}
from app.models import ShippingOrderProcessingPlan, ShippingOrderProcessingUnit
rows = (
db.session.query(
ShippingOrderProcessingUnit.document_id,
ShippingOrderProcessingUnit.error_code,
ShippingOrderProcessingUnit.error_message,
)
.join(
ShippingOrderProcessingPlan,
ShippingOrderProcessingPlan.id == ShippingOrderProcessingUnit.plan_id,
)
.filter(
ShippingOrderProcessingPlan.run_id == int(run_id),
ShippingOrderProcessingUnit.status == 'failed',
ShippingOrderProcessingUnit.document_id.isnot(None),
)
.all()
)
return {
int(document_id): {
'error_code': str(error_code or '').strip() or 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED',
'error_message': str(error_message or '').strip() or 'Order extraction unit failed',
}
for document_id, error_code, error_message in rows
if document_id is not None
}
def persist_order_extraction_result(
*,
session: ChatSession,
@@ -794,21 +839,82 @@ def persist_order_extraction_result(
# [STEP 2] 聚合 Document 结果;无法归属到 Intake 的异常项会使本轮全部 Document 保持部分完成。
has_unassigned_pending = any(not item.get('source_intake_no') for item in pending)
# Unit 失败事实优先:Unit 失败且无候选/待处理裁决的附件,识别并未完成,
# 必须落 failed(携带 Unit 错误码),禁止按「零 pending」误写 completed——
# 否则随后的 Run 失败收口会因「已是终态」跳过回填,批次中心误报已完成。
failed_unit_error_by_document = _failed_unit_errors_by_document(run_id)
for document in documents:
keys = document_candidate_keys[int(document.id)]
document.order_extraction_status = (
'partially_completed'
if document_has_pending[int(document.id)] or has_unassigned_pending
else 'completed'
)
unit_failure = failed_unit_error_by_document.get(int(document.id))
if unit_failure and not keys and not document_has_pending[int(document.id)]:
document.order_extraction_status = 'failed'
document.order_extraction_error_code = unit_failure['error_code']
document.order_extraction_error_message = unit_failure['error_message']
else:
document.order_extraction_status = (
'partially_completed'
if document_has_pending[int(document.id)] or has_unassigned_pending
else 'completed'
)
document.order_extraction_error_code = None
document.order_extraction_error_message = None
document.order_extraction_source = extraction_source
document.order_extraction_result_json = {
'request_id': request_id,
'candidate_keys': keys,
'non_shipping_order_indexes': document_non_shipping_indexes[int(document.id)],
}
document.order_extraction_error_code = None
document.order_extraction_error_message = None
# [STEP 2.5] 重识别 Run 终态收口:本 Run 已落库的可复核 Case 必须在此原子激活为
# 文件 Stream 当前版本——Case 创建时按 reparse 延迟激活、约定等 Run 终态切换,但
# 该钩子此前从未接线,导致工作台队列(按 Stream.current_case_id 平铺)看不到任何
# Case,单据永远不可见(回归 SNER-20261014-35E35017 → BB05A18B:9 Case 全部
# stream_id=NULL,工作台空白且停接收解析)。
if run_id is not None:
from app.models import ShippingOrderProcessingRun, ShippingOrderReviewCase
from app.services.shipping_notice.candidate_service import (
is_current_reviewable_candidate,
)
from app.services.shipping_notice.review_stream_service import (
activate_review_case,
ensure_review_stream_for_case,
run_is_reparse_successor_of_case,
)
persisted_run = db.session.get(ShippingOrderProcessingRun, int(run_id))
if persisted_run is not None and persisted_run.reparse_of_run_id is not None:
reparse_cases = ShippingOrderReviewCase.query.filter(
ShippingOrderReviewCase.run_id == int(persisted_run.id),
ShippingOrderReviewCase.status != 'superseded',
ShippingOrderReviewCase.candidate_id.isnot(None),
).all()
for review_case in reparse_cases:
try:
candidate = db.session.get(
ShippingOrderCandidate, int(review_case.candidate_id),
)
if not is_current_reviewable_candidate(candidate):
continue
stream = ensure_review_stream_for_case(case=review_case)
declared_source = None
if stream.current_case_id is not None:
current_case = db.session.get(
ShippingOrderReviewCase, int(stream.current_case_id),
)
if (
current_case is not None
and run_is_reparse_successor_of_case(
run=persisted_run, current_case=current_case,
)
):
declared_source = int(current_case.id)
activate_review_case(
case=review_case, trigger='batch_reparse_succeeded',
declared_source_case_id=declared_source,
)
except ConflictError:
# 已确认/履约中的当前版本不得被草稿覆盖:保留现状态供人工处理。
continue
# [STEP 3] 只对本次 documents 作用域内消失的 Candidate 做版本失效。
# Unit 增量提交仅带当前 PDF,禁止把同 Intake/Run 的兄弟 PDF Candidate
@@ -836,13 +942,32 @@ def persist_order_extraction_result(
duplicate_results_by_intake.get(int(intake.id), []),
)
apply_duplicate_result_to_intake(intake, aggregate)
intake.order_extraction_status = (
'partially_completed'
if pending_by_intake[int(intake.id)] or has_unassigned_pending
else 'completed'
# Intake 聚合文档级终态:全部业务附件 failed → failed;部分失败 → partially_completed;
# 二者都不得被后续「零 pending 即 completed」的收口覆盖。
intake_documents = documents_by_intake.get(int(intake.id)) or []
failed_intake_documents = [
document
for document in intake_documents
if str(document.order_extraction_status or '').strip().lower() == 'failed'
]
business_document_count = sum(
1
for document in intake_documents
if str(document.document_type or '').strip().lower() != 'email_body'
)
intake.order_extraction_error_code = None
intake.order_extraction_error_message = None
if failed_intake_documents and business_document_count > 0 \
and len(failed_intake_documents) >= business_document_count:
intake.order_extraction_status = 'failed'
intake.order_extraction_error_code = failed_intake_documents[0].order_extraction_error_code
intake.order_extraction_error_message = failed_intake_documents[0].order_extraction_error_message
elif failed_intake_documents or pending_by_intake[int(intake.id)] or has_unassigned_pending:
intake.order_extraction_status = 'partially_completed'
intake.order_extraction_error_code = None
intake.order_extraction_error_message = None
else:
intake.order_extraction_status = 'completed'
intake.order_extraction_error_code = None
intake.order_extraction_error_message = None
intake.updated_at = datetime.utcnow()
db.session.flush()
@@ -864,6 +989,15 @@ def persist_order_extraction_result(
.all()
)
if run is not None and current_candidates:
# [STEP] 裸数字启发式冲突的自动解决:字段级裁决已 accepted 的
# supplement_field_conflict 不再阻断建单资格(PO 行收敛/正式值源写入
# 即为裁决)。必须在 OT 创建前执行,否则资格门禁误报字段冲突。
from app.services.shipping_notice.candidate_qualification_service import (
resolve_satisfied_supplement_conflicts,
)
for candidate in current_candidates:
resolve_satisfied_supplement_conflicts(candidate)
# PDF 级复核重识别:Run.user_task_no 已是 Case 对应 OT(可能是兄弟号),
# 禁止再按 index=0 当根号、给其他 Candidate 派生 -C{id}。
marker = (getattr(run, 'input_snapshot_json', None) or {}).get('review_reparse')
@@ -1001,7 +1135,13 @@ def persist_order_extraction_result(
for intake in intakes:
intake.parse_status = 'consumed'
intake.consumed_at = now
intake.order_extraction_status = 'completed'
# consumed 仅代表「邮件解析结果已被抽取收口消费」;文档/Intake 级
# order_extraction_status 若已按 Unit 失败裁决为 failed/partially_completed,
# 不得在此覆盖回 completed——否则 Run 失败收口会因「已是终态」跳过回填。
if str(intake.order_extraction_status or '').strip().lower() not in {
'failed', 'partially_completed',
}:
intake.order_extraction_status = 'completed'
intake.updated_at = now
db.session.commit()
@@ -866,6 +866,7 @@ def _build_snapshot(
)
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
from app.services.shipping_notice.generic_parse_plan import compile_generic_parse_plan
from app.services.shipping_notice.reservation_id import find_bare_numeric_reservation_candidates
table_contract = compile_table_header_contract(dict(schema_version.definition_json or {}))
generic_config = (
@@ -932,6 +933,13 @@ def _build_snapshot(
)
if isinstance(email_supplement, dict):
email_supplement['document_id'] = int(document.id)
# [裸数字兜底] 快照冻结前按当前正文重扫「整格纯数字」表格候选;
# 合并末段结合订单已提取字段值裁决,快照重建保证与 Schema 同源。
email_supplement['reservation_candidates'] = find_bare_numeric_reservation_candidates(
html_tables=html_tables,
content_hash=str(document.content_hash or ''),
)
email_supplement['email_subject'] = str(email.get('subject') or '')
document_snapshot = {
'document_id': document.id,
'document_type': document.document_type,
@@ -49,6 +49,9 @@ from app.services.shipping_notice.document_layout.order_profile_matcher import (
ProfileMatchResult,
match_frozen_coordinate_profiles,
)
from app.services.shipping_notice.document_layout.order_profile_ocr_rescue import (
rescue_match_with_header_ocr,
)
from app.services.shipping_notice.document_layout.order_profile_parse_validation import (
validate_profile_parse_candidate,
)
@@ -1078,6 +1081,16 @@ def _profile_table_candidates(
profiles=coordinate_profiles, layout=layout,
header_to_field=contract.header_to_field,
)
if (
match.status in {'layout_drift', 'no_match'}
and document_model is not None
):
# 表头带证据补洞:仅当存在「仅表头判别冲突 + 观测原子纯缺失」候选时
# 尝试;重跑完整匹配器且恰好唯一命中可补救候选才采纳,否则维持原判。
match = rescue_match_with_header_ocr(
match=match, profiles=coordinate_profiles, layout=layout,
header_to_field=contract.header_to_field, document=document_model,
)
affinity_applied = False
if not match_only:
match = _apply_parse_validation_gate(
@@ -498,7 +498,21 @@ def _email_parent_rows(
if document_id <= 0 or document_id in existing_document_ids:
continue
parse_status = parse_statuses.get(intake_id, '')
parent_status = 'failed' if parse_status == 'parse_failed' else 'processing'
run_status = str(run.status or '').strip().lower()
if run_status in {'queued', 'processing'}:
# 运行中的 Run:EML 父项只区分解析失败与处理中。
parent_status = 'failed' if parse_status == 'parse_failed' else 'processing'
else:
# [STEP] 终态 Run 的 EML 父项必须跟随 Run 结果收敛,禁止停留在「处理中」
# (历史缺陷:全部 Unit 失败后父项仍显示处理中,误导用户批次仍在进行)。
# partially_completed 的用户语义与 review_required 一致(需人工处理)。
parent_status = {
'failed': 'failed',
'cancelled': 'cancelled',
'completed': 'completed',
'review_required': 'review_required',
'partially_completed': 'review_required',
}.get(run_status, 'failed')
rows.append({
'unit_id': -document_id,
'document_id': document_id,
@@ -1901,10 +1901,24 @@ def extract(
live_fingerprint = live_fingerprint or signature.get('dataset_structure_fingerprint')
source = selected.get('definition', {}).get('source_contract') if isinstance(selected.get('definition'), dict) else {}
source = source if isinstance(source, dict) else {}
identity_state = 'matched'
if not source.get('template_packet_checksum') or not source.get('dataset_structure_fingerprint'):
return review('xfa_profile_identity_incomplete')
if source.get('template_packet_checksum') != live_template or source.get('dataset_structure_fingerprint') != live_fingerprint:
return review('xfa_profile_identity_mismatch')
identity_state = 'incomplete'
elif (
source.get('template_packet_checksum') != live_template
or source.get('dataset_structure_fingerprint') != live_fingerprint
):
identity_state = 'mismatch'
# [SOFT GATE] XFA 身份指纹漂移不再硬拦截(回归 SNER-20261014-35E35017:供应商
# 换代必变指纹,硬拦截使 XFA 单据永远空转人工)。视觉 Route 已唯一命中,datasets
# 取值后仍有 validate_xfa_extraction 业务交叉校验兜底;漂移降级为决策留痕
# (xfa_identity_state)+ fallback 码,仅当取值/校验失败时与业务原因码一起转 Review。
decision['xfa_identity_state'] = identity_state
if identity_state != 'matched':
decision['fallback_reason_codes'] = [
*(decision.get('fallback_reason_codes') or []),
f'xfa_profile_identity_{identity_state}',
]
table_id = workflow._profile_visual_main_table_id(selected, document.get('layout_snapshot') or {})
if not table_id:
return review('xfa_visual_main_table_missing')
@@ -1947,7 +1961,11 @@ def extract(
# 审计故障不能篡改已冻结的取值/Review 裁决。
pass
if extraction.status != 'parsed' or extraction.reason_codes:
return review(*(list(extraction.reason_codes or []) or ['xfa_required_field_missing']))
codes = list(extraction.reason_codes or []) or ['xfa_required_field_missing']
if identity_state != 'matched':
# 漂移被软门禁放行后取值仍失败:身份码前置,让复核者看到根因。
codes = [f'xfa_profile_identity_{identity_state}', *codes]
return review(*codes)
validation = validate_xfa_extraction(
raw_profile=selected, dataset_analysis=outcome.dataset_analysis, extraction=extraction, pdf_bytes=pdf_bytes,
)
@@ -1960,7 +1978,10 @@ def extract(
'profile_checksum': str(selected.get('checksum') or ''),
}
if not validation.passed:
return review(*(list(validation.reason_codes or []) or ['xfa_business_validation_failed']))
validation_codes = list(validation.reason_codes or []) or ['xfa_business_validation_failed']
if identity_state != 'matched':
validation_codes = [f'xfa_profile_identity_{identity_state}', *validation_codes]
return review(*validation_codes)
table = {
'profile_id': selected.get('profile_id') or selected.get('id'), 'profile_code': str(selected.get('profile_code') or ''),
'profile_version': int(selected.get('version') or 0), 'profile_checksum': str(selected.get('checksum') or ''),
@@ -15,15 +15,21 @@ from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError
from app.models import (
ShippingCustomer,
ShippingOrderCandidate,
ShippingCustomerShadowResolution,
ShippingOrderExtraction,
ShippingOrderReviewCase,
ShippingOrderTask,
)
from app.services.shipping_notice.candidate_qualification_service import (
resolve_review_case_customer_resolved,
)
from app.services.shipping_notice.customer_resolution_service import confirm_customer_resolution
from app.services.shipping_notice.customer_resolution_service import (
confirm_customer_resolution,
rebind_allowed_for_task,
resolution_for_task,
)
from app.services.shipping_notice.workflow_ledger_service import (
assert_case_is_current_workflow_version,
)
@@ -160,19 +166,45 @@ def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> di
)
)
]
# [STEP 2] 已确认(含改绑)后以确认结果与客户主数据为权威展示:识别候选显示在改绑后会 stale。
confirmed_task = (
db.session.get(ShippingOrderTask, int(case.confirmed_task_id))
if getattr(case, 'confirmed_task_id', None) else None
)
resolution_row = resolution_for_task(confirmed_task) if confirmed_task is not None else None
confirmed_customer_id = (
getattr(resolution_row, 'confirmed_customer_id', None)
if resolution_row is not None and resolution_row.status == 'confirmed'
else (getattr(shadow, 'confirmed_customer_id', None) if shadow is not None else None)
)
confirmed_customer = (
db.session.get(ShippingCustomer, int(confirmed_customer_id))
if confirmed_customer_id else None
)
return {
'resolved': bool(resolved),
'status': status,
'role': 'customer',
'extraction_id': int(extraction.id) if extraction is not None else None,
'raw_name': None,
'customer_id': getattr(shadow, 'confirmed_customer_id', None) or display_match.get('customer_id'),
'standard_name': display_match.get('standard_name'),
'short_code': display_match.get('short_code'),
'customer_id': confirmed_customer_id or display_match.get('customer_id'),
'standard_name': (
confirmed_customer.standard_name if confirmed_customer is not None
else display_match.get('standard_name')
),
'short_code': (
confirmed_customer.short_code if confirmed_customer is not None
else display_match.get('short_code')
),
'candidates': list(display_match.get('candidates') or []),
'input_values': input_values,
'evidence': evidence,
'match': display_match,
# 「修改客户」按钮谓词:仅已确认且无 Export Artifact/活动 Attempt 时可改绑(A 管控)。
'rebind_allowed': (
rebind_allowed_for_task(confirmed_task) if confirmed_task is not None else False
),
}
@@ -304,6 +304,9 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu
is_evidence_gap = reason in _EVIDENCE_GAP_REASONS
if is_evidence_gap and field_evidence_gap_is_non_blocking(candidate, item):
continue
# 已自动解决(正式值源/PO 行收敛写入)的冲突不再进入待裁决面板。
if str(item.get('resolution_status') or '').strip() == 'resolved':
continue
# 只有多个候选值不一致才属于「字段冲突待裁决」。
if len(value_keys) < 2 and not is_evidence_gap and not is_current_open_blocking:
continue
@@ -30,6 +30,9 @@ from app.models import (
ShippingOrderTask,
ShippingTaskInventoryRpaAttempt,
)
from app.services.shipping_notice.line_inventory_match_persistence import (
resolve_review_case_for_task,
)
from app.services.shipping_notice.workflow_ledger_service import (
assert_case_is_current_workflow_version,
)
@@ -317,8 +320,14 @@ def _shortage_release_required_fields(
line_index: int | None,
inventory_snapshot_id: int | None,
inventory_source_code: str | None,
) -> list[dict[str, str]]:
"""按该行快照、库存源解析方案和发货模板计算短缺放行补录字段。"""
) -> tuple[list[dict[str, Any]], str]:
"""按该行快照、库存源解析方案和发货模板计算短缺放行补录字段。
Returns:
(fields, evidence_scope) 元组:fields 为模板库存字段投影(快照唯一值只读,
其余 requires_manual);evidence_scope ∈ {'inventory_snapshot', 'part_fallback'},
'part_fallback' 表示预约键在库存快照 0 行命中、已按料号键重筛带出(审计口径)。
"""
if line_index is None:
raise ConflictError(
'Current line inventory evidence is unavailable',
@@ -371,7 +380,8 @@ def _shortage_release_required_fields(
and str(item.get('source_key') or '').strip().isdigit()
}
labels = {str(row.id): str(row.display_name or '').strip() for row in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all()} if field_ids else {}
return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels)
# 无快照即无库存证据:全部模板库存字段人工补录,证据范围维持快照口径。
return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels), 'inventory_snapshot'
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
match_keys = definition.get('match_keys') if isinstance(definition.get('match_keys'), list) else []
expected = [
@@ -395,6 +405,24 @@ def _shortage_release_required_fields(
dict(row) for row in inventory_lines
if all(_match_text(row.get(inventory_field)) == value for inventory_field, value in expected)
]
evidence_scope = 'inventory_snapshot'
if not candidates:
# [STEP] 料号兜底(2026-10 需求):预约键在库存快照 0 行命中时,按料号键重筛证据行,
# 能唯一取值的字段不再要求人工手填。仅识别 field_code='part_number' 的匹配键;
# 匹配方案不含料号键则维持空候选(全人工补录,fail-closed)。
part_field_ids = {
int(field_id) for field_id, _value in expected
if str(field_id).strip().isdigit()
and str(getattr(db.session.get(ShippingInventoryField, int(field_id)), 'field_code', '') or '') == 'part_number'
}
if part_field_ids:
candidates = [
dict(row) for row in inventory_lines
if all(_match_text(row.get(str(field_id))) == value
for field_id, value in expected if int(field_id) in part_field_ids)
]
if candidates:
evidence_scope = 'part_fallback'
field_ids = {
int(str(item.get('source_key') or '').strip())
for item in mappings
@@ -411,7 +439,7 @@ def _shortage_release_required_fields(
mappings=mappings,
candidates=candidates,
field_labels=labels,
)
), evidence_scope
def _manual_required_release_fields(fields: list[dict[str, Any]]) -> list[dict[str, str]]:
@@ -429,7 +457,7 @@ def _manual_required_release_fields(fields: list[dict[str, Any]]) -> list[dict[s
def _sync_confirmed_task_fulfillment_gates(
*,
case: ShippingOrderReviewCase,
actor_id: int,
actor_id: int | None,
trigger: str = 'inventory_shortage_released',
) -> None:
"""
@@ -924,7 +952,8 @@ def project_review_case_line_decisions(
release_line_index, release_snapshot_id, release_source_code = _release_fact_identity(fact)
if release_line_index is None:
release_line_index = draft_line.get('_line_index')
release_template_fields = _shortage_release_required_fields(
# scope 仅在 decide 落库时写入审计快照;投影契约本期不新增字段。
release_template_fields, _evidence_scope = _shortage_release_required_fields(
task=task,
line_index=release_line_index,
inventory_snapshot_id=release_snapshot_id,
@@ -1076,6 +1105,185 @@ def build_inventory_issue_fallback(
}
def _apply_shortage_line_release(
task: ShippingNotice,
line_index: int,
release_field_values: dict[str, Any],
*,
evidence_scope: str | None = None,
actor_type: str = 'user',
actor_id: int | None = None,
auto_release: bool = False,
case: ShippingOrderReviewCase | None = None,
reason: str | None = None,
) -> ShippingOrderReviewLineDecision:
"""
人工 decide 与缺口自动放行共用的短缺放行执行体:解析证据字段、校验补录、
版本化落库、同步正式 OT 门禁并写审计。
核心逻辑:从 decide_review_line_fulfillment 放行分支原样提取(行为不变)。
证据字段按行事实快照解析(预约键命中 → inventory_snapshot;预约键 0 行命中
按料号键重筛 → part_fallback);落库快照 release_field_values 为「自动带出 +
人工补录」全量字段值字典(导出覆盖唯一来源);落库后立即重算任务履约态并
同步门禁/自动履约入队,与人工放行完全一致。终态/已决定行必须由调用方先跳过,
本执行体不重复校验放行资格。
Args:
task: 正式 OT 聚合根(含 order_snapshot_id;自动放行来自匹配钩子,
人工 decide 来自 case.confirmed_task_id)。
line_index: 目标行号(0-based,与行匹配事实 line_index 同口径)。
release_field_values: 人工补录值(decide)或自动带出全量值(自动放行);
校验后与模板字段合并为全量值字典落库。
evidence_scope: 调用方已解析的证据范围;None 时按行事实重新解析
(人工 decide 路径,由本执行体统一解析避免双重查询语义分叉)。
actor_type: 决定来源('user' 人工 / 'system' 自动放行),写入 decision_source。
actor_id: 操作人(人工为操作用户;自动为触发匹配的用户,可为 None)。
auto_release: True 时在决定与审计快照标记 auto_release(系统自动放行溯源)。
case: 可选;人工 decide 已加载的可写 Case。缺省时按 confirmed_task_id 反查。
reason: 可选人工放行原因;自动放行为 None。
Returns:
新建的 ShippingOrderReviewLineDecision(已 flush、含主键)。
Raises:
ConflictError: Case/草稿行缺失、证据不可解析或人工必填字段缺失。
"""
release_case = case if case is not None else resolve_review_case_for_task(task)
if release_case is None or getattr(release_case, 'id', None) is None:
raise ConflictError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
draft_line_by_index = {
int(row.get('_line_index')): (key, row)
for key, row in _draft_line_map(release_case).items()
if row.get('_line_index') is not None
}
pair = draft_line_by_index.get(int(line_index))
if pair is None:
raise ConflictError('Review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND')
key, draft_line = pair
from app.models import ShippingNoticeLineInventoryMatch
fact = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task.id), line_index=int(line_index), is_current=True)
.first()
if getattr(task, 'id', None) is not None else None
)
release_line_index = getattr(fact, 'line_index', None) if fact is not None else int(line_index)
release_template_fields, resolved_scope = _shortage_release_required_fields(
task=task,
line_index=release_line_index,
inventory_snapshot_id=getattr(fact, 'inventory_snapshot_id', None) if fact is not None else None,
inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else None,
)
release_evidence_scope = str(evidence_scope or resolved_scope or 'inventory_snapshot')
release_required_fields = _manual_required_release_fields(release_template_fields)
release_values = _validate_inventory_shortage_release_fields(
required_fields=release_required_fields,
supplied_values=release_field_values or {},
)
# [STEP] 落库为「自动带出 + 人工补录」全量模板字段值字典:人工提交值覆盖自动带出值
# (校验白名单仅用于必填校验,不再裁剪落库字典)。export.release_overrides_by_source_line
# 只读本字典——若仍落仅人工项,料号兜底/预约命中自动带出的字段在 Excel 证据列将为空。
manual_field_ids = {str(field.get('field_id') or '') for field in release_required_fields}
release_values = {
str(field.get('field_id') or ''): (
release_values[str(field.get('field_id') or '')]
if str(field.get('field_id') or '') in manual_field_ids
else (None if field.get('value') is None else str(field.get('value')))
)
for field in release_template_fields
}
projections = _line_projection_map(release_case)
proj = projections.get(key) or {}
from app.services.shipping_notice.order_review_workbench_projection import (
schema_fields_from_case,
)
schema_fields = schema_fields_from_case(release_case)
req_qty = _parse_qty(_line_required_qty(draft_line, proj, schema_fields=schema_fields))
avail_qty = _parse_qty(proj.get('available_qty'))
current = _active_decision(release_case, key)
# [STEP 1] 停用旧活动决定(放行资格与终态校验由调用方完成)。
if current is not None:
current.is_active = False
current.updated_at = datetime.utcnow()
status = _STATUS_BY_DECISION[DECISION_RELEASE_SHORTAGE]
row = ShippingOrderReviewLineDecision(
review_case_id=int(release_case.id),
draft_line_id=key,
line_index=draft_line.get('_line_index'),
decision_version=_next_version(release_case, key),
decision_code=DECISION_RELEASE_SHORTAGE,
decision_source=actor_type,
line_status=status,
is_active=True,
reason=str(reason or '').strip()[:2000] or None,
required_qty=str(req_qty) if req_qty is not None else None,
available_qty=str(avail_qty) if avail_qty is not None else (
str(proj.get('available_qty') or '').strip() or None
),
reservation_id=_line_reservation_id(draft_line, proj),
part_number=_line_part_number(
draft_line,
proj,
schema_fields=schema_fields,
),
actor_user_id=int(actor_id) if actor_id is not None else None,
snapshot_json={
'decision_code': DECISION_RELEASE_SHORTAGE,
'decision_source': actor_type,
'required_qty': str(req_qty) if req_qty is not None else None,
'available_qty': str(avail_qty) if avail_qty is not None else None,
'draft_line_id': key,
'release_field_values': release_values,
'release_required_fields': release_required_fields,
# 审计口径:放行证据来自预约匹配快照(inventory_snapshot)还是料号兜底重筛(part_fallback)。
'release_evidence_scope': release_evidence_scope,
**({'auto_release': True} if auto_release else {}),
},
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
)
db.session.add(row)
# [STEP 2] 审计 after 投影依赖数据库分配的主键,必须先 flush。
db.session.flush()
# [BE-结案-豁免] 放行是库存充分性 Gate 的受控事实:决定落库后立即重算并触发编排。
_sync_confirmed_task_fulfillment_gates(
case=release_case,
actor_id=actor_id,
trigger='inventory_shortage_released',
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='review_line_fulfillment_decided',
aggregate_type='order_review_case',
aggregate_id=str(release_case.case_no),
action=DECISION_RELEASE_SHORTAGE,
actor_type=actor_type,
actor_id=int(actor_id) if actor_id is not None else None,
review_case_no=str(release_case.case_no),
run_no=str(release_case.run.run_no) if release_case.run is not None else None,
metadata={
'draft_line_id': key,
'decision_code': DECISION_RELEASE_SHORTAGE,
'decision_version': int(row.decision_version),
'line_status': status,
'release_field_count': len(release_values),
**({'auto_release': True} if auto_release else {}),
},
before=_serialize_decision(current) if current is not None else None,
after=_serialize_decision(row),
source='order_review_fulfillment_decision',
)
return row
def decide_review_line_fulfillment(
*,
user_id: int,
@@ -1100,7 +1308,9 @@ def decide_review_line_fulfillment(
draft_line_id: 草稿行键。
decision_code: 决定码。
reason: 关闭/重开必填原因;短缺放行可选(人工放行事实由审计链记录)。
release_field_values: 短缺放行时模板行级库存字段的人工补录值。
release_field_values: 短缺放行时模板行级库存字段的人工补录值;落库快照
release_field_values 为「自动带出 + 人工补录」全量字段值字典(导出覆盖唯一来源),
release_evidence_scope 记录证据范围(inventory_snapshot / part_fallback)。
expected_draft_version: 可选草稿乐观锁。
actor_is_admin: 是否管理员(重开授权)。
@@ -1200,93 +1410,94 @@ def decide_review_line_fulfillment(
details={'draft_line_id': key},
)
release_line_index = getattr(fact, 'line_index', None) if fact is not None else draft_line.get('_line_index')
release_template_fields = _shortage_release_required_fields(
task=task,
line_index=release_line_index,
inventory_snapshot_id=getattr(fact, 'inventory_snapshot_id', None) if fact is not None else None,
inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else None,
) if task is not None else []
release_required_fields = _manual_required_release_fields(release_template_fields)
release_values = _validate_inventory_shortage_release_fields(
required_fields=release_required_fields,
supplied_values=release_field_values or {},
)
else:
release_required_fields = []
release_values = {}
# [STEP 1] 停用旧活动决定
if current is not None:
current.is_active = False
current.updated_at = datetime.utcnow()
status = _STATUS_BY_DECISION.get(code, 'pending_decision')
row = ShippingOrderReviewLineDecision(
review_case_id=int(case.id),
draft_line_id=key,
line_index=draft_line.get('_line_index'),
decision_version=_next_version(case, key),
decision_code=code,
decision_source='user',
line_status=status,
is_active=True,
reason=str(reason or '').strip()[:2000] or None,
required_qty=str(req_qty) if req_qty is not None else None,
available_qty=str(avail_qty) if avail_qty is not None else (
str(proj.get('available_qty') or '').strip() or None
),
reservation_id=_line_reservation_id(draft_line, proj),
part_number=_line_part_number(
draft_line,
proj,
schema_fields=schema_fields,
),
actor_user_id=int(user_id),
snapshot_json={
'decision_code': code,
'decision_source': 'user',
'required_qty': str(req_qty) if req_qty is not None else None,
'available_qty': str(avail_qty) if avail_qty is not None else None,
'draft_line_id': key,
'release_field_values': release_values,
'release_required_fields': release_required_fields,
},
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
)
db.session.add(row)
# [STEP 2] 审计 after 投影依赖数据库分配的主键,必须先 flush。
db.session.flush()
if code in {DECISION_RELEASE_SHORTAGE, DECISION_CLOSE}:
# [BE-结案-豁免] 结案与放行同为库存充分性 Gate 的受控事实:决定落库后立即重算并触发编排。
_sync_confirmed_task_fulfillment_gates(
case=case,
# [STEP] 短缺放行统一走共享执行体:证据字段解析、全量字段落库、停用旧决定、
# 门禁同步与审计均在 _apply_shortage_line_release 内完成(人工与系统自动放行
# 同一条链路,行为不变)。无 task 时上方放行资格校验已拒绝(无事实且无 RPA
# 终态失败豁免),不会到达此处。
row = _apply_shortage_line_release(
task,
release_line_index,
release_field_values or {},
actor_type='user',
actor_id=int(user_id),
trigger='inventory_shortage_released' if code == DECISION_RELEASE_SHORTAGE else 'line_fulfillment_closed',
case=case,
reason=reason,
)
status = _STATUS_BY_DECISION[DECISION_RELEASE_SHORTAGE]
else:
# [STEP 1] 停用旧活动决定
if current is not None:
current.is_active = False
current.updated_at = datetime.utcnow()
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
status = _STATUS_BY_DECISION.get(code, 'pending_decision')
row = ShippingOrderReviewLineDecision(
review_case_id=int(case.id),
draft_line_id=key,
line_index=draft_line.get('_line_index'),
decision_version=_next_version(case, key),
decision_code=code,
decision_source='user',
line_status=status,
is_active=True,
reason=str(reason or '').strip()[:2000] or None,
required_qty=str(req_qty) if req_qty is not None else None,
available_qty=str(avail_qty) if avail_qty is not None else (
str(proj.get('available_qty') or '').strip() or None
),
reservation_id=_line_reservation_id(draft_line, proj),
part_number=_line_part_number(
draft_line,
proj,
schema_fields=schema_fields,
),
actor_user_id=int(user_id),
snapshot_json={
'decision_code': code,
'decision_source': 'user',
'required_qty': str(req_qty) if req_qty is not None else None,
'available_qty': str(avail_qty) if avail_qty is not None else None,
'draft_line_id': key,
'release_field_values': {},
'release_required_fields': [],
'release_evidence_scope': None,
},
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
)
db.session.add(row)
# [STEP 2] 审计 after 投影依赖数据库分配的主键,必须先 flush。
db.session.flush()
if code == DECISION_CLOSE:
# [BE-结案-豁免] 结案是库存充分性 Gate 的受控事实:决定落库后立即重算并触发编排。
_sync_confirmed_task_fulfillment_gates(
case=case,
actor_id=int(user_id),
trigger='line_fulfillment_closed',
)
record_fulfillment_audit(
event_type='review_line_fulfillment_reopened' if code == DECISION_REOPEN else 'review_line_fulfillment_decided',
aggregate_type='order_review_case',
aggregate_id=str(case.case_no),
action=code,
actor_type='user',
actor_id=int(user_id),
review_case_no=str(case.case_no),
run_no=str(case.run.run_no) if case.run is not None else None,
metadata={
'draft_line_id': key,
'decision_code': code,
'decision_version': int(row.decision_version),
'line_status': status,
'release_field_count': len(release_values),
},
before=_serialize_decision(current) if current is not None else None,
after=_serialize_decision(row),
source='order_review_fulfillment_decision',
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='review_line_fulfillment_reopened' if code == DECISION_REOPEN else 'review_line_fulfillment_decided',
aggregate_type='order_review_case',
aggregate_id=str(case.case_no),
action=code,
actor_type='user',
actor_id=int(user_id),
review_case_no=str(case.case_no),
run_no=str(case.run.run_no) if case.run is not None else None,
metadata={
'draft_line_id': key,
'decision_code': code,
'decision_version': int(row.decision_version),
'line_status': status,
'release_field_count': 0,
},
before=_serialize_decision(current) if current is not None else None,
after=_serialize_decision(row),
source='order_review_fulfillment_decision',
)
from app.services.shipping_notice.order_review_resume_service import (
attach_resume_outcome,
@@ -1311,6 +1522,113 @@ def decide_review_line_fulfillment(
return attach_resume_outcome(payload, resume)
def _active_decision_line_indexes(task: ShippingNotice) -> set[int]:
"""读取当前任务全部活动行决定的 line_index(含 release/close/fulfill 等一切决定)。
核心逻辑:自动放行只处理「无任何活动决定」的行——已放行、已结案、已入波次或
已有其他人工决定的行一律跳过,保证幂等且绝不自动撤销既有决定(与
``_released_snapshot_line_ids_for_task`` 同款 Case 反查口径)。
"""
from app.models import ShippingOrderReviewCase
if getattr(task, 'id', None) is None:
return set()
rows = (
ShippingOrderReviewLineDecision.query
.join(
ShippingOrderReviewCase,
ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id,
)
.filter(
ShippingOrderReviewCase.confirmed_task_id == int(task.id),
ShippingOrderReviewLineDecision.is_active.is_(True),
ShippingOrderReviewLineDecision.line_index.isnot(None),
)
.all()
)
return {int(row.line_index) for row in rows}
def auto_release_part_fallback_shortages(
task: ShippingNotice,
*,
actor_id: int | None = None,
) -> list[int]:
"""
匹配落库后按料号兜底自动放行缺口行(用户确认语义:满足即自动放行,非仅可放行)。
核心逻辑:仅处理「ready + 缺口 + 料号总量≥需求 + 无活动决定 + 证据字段全部可
自动取值」的行;任一条件不满足(含证据解析 ConflictError)一律跳过并保持人工
路径,fail-closed 不变。复用 _apply_shortage_line_release,审计/门禁同步/自动
履约入队与人工放行完全一致;幂等由「无活动决定的行才处理」保证,不自动撤销
既有放行。注意:行匹配事实以 snapshot_line_id 为键,行号取自 fact['line_index']。
Args:
task: 正式任务聚合根(OT 或正式 Notice,须含 id 与 order_snapshot_id)。
actor_id: 触发匹配的用户(审计归属);自动决定本身 actor_type='system'。
Returns:
自动放行的 line_index 列表(按行号升序)。
"""
from app.services.shipping_notice.line_inventory_match_projection import (
load_current_match_facts_by_task,
)
task_id = getattr(task, 'id', None)
if task_id is None:
return []
facts = load_current_match_facts_by_task(int(task_id))
if not facts:
return []
decided_indexes = _active_decision_line_indexes(task)
ordered_facts = sorted(
(fact for fact in facts.values() if fact.get('line_index') is not None),
key=lambda fact: int(fact['line_index']),
)
released: list[int] = []
for fact in ordered_facts:
line_index = int(fact['line_index'])
try:
if line_index in decided_indexes:
continue
if not _is_shortage_match_fact(fact):
continue
required = _parse_qty(fact.get('required_qty'))
part_total = _parse_qty(fact.get('part_available_qty'))
if required is None or part_total is None or part_total < required:
# 料号兜底量缺失或不足 → 维持人工待处置(不得任取部分数量放行)。
continue
fields, evidence_scope = _shortage_release_required_fields(
task=task,
line_index=line_index,
inventory_snapshot_id=fact.get('inventory_snapshot_id'),
inventory_source_code=fact.get('inventory_source_code'),
)
if any(bool(field.get('requires_manual')) for field in fields):
# 证据字段无法唯一取值(requires_manual 残留)→ 降级人工放行,补录要求保留。
continue
auto_values = {
str(field.get('field_id') or ''): (
None if field.get('value') is None else str(field.get('value'))
)
for field in fields
}
_apply_shortage_line_release(
task,
line_index,
auto_values,
evidence_scope=evidence_scope,
actor_type='system',
actor_id=actor_id,
auto_release=True,
)
released.append(line_index)
except ConflictError:
# 证据不可解析(无源/模板未发布/无快照/草稿行缺失)→ 维持人工路径,不中断其余行。
continue
return released
def close_remaining_fulfillment(
*,
user_id: int,
@@ -4,6 +4,9 @@
逻辑:优先 PO+MPN;其次同 PO+合法 reservation_id 对齐;仅唯一签名的 PO 可降级广播;
无同 PO 候选时仅对「PO 缺失」行做唯一料号兜底(mpn_fallback);有 PO 且与 PDF
不一致则禁止补充。歧义只写复核原因。同趟单次合并,不互相重入。
主合并结束后另做「裸数字兜底」:仍无预约单号的订单,从正文裸 5/10 位数字
候选里排除已识别字段值/主题标签值/跨单已占用值,唯一候选以低置信度写入
header 默认值,多候选转为复核冲突,绝不覆盖任何已有值。
"""
from __future__ import annotations
@@ -13,7 +16,12 @@ from typing import Any
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value
from app.services.shipping_notice.po_number import normalize_atomic_po_number
from app.services.shipping_notice.reservation_id import validated_reservation_id
from app.services.shipping_notice.reservation_id import (
filter_reservation_heuristic_candidates,
normalize_reservation_id,
reservation_ids_in_labeled_context,
validated_reservation_id,
)
def _values(fields: Any, code: str, codes: dict[str, str]) -> set[str]:
@@ -273,6 +281,269 @@ def _supplement_multi_value_conflict(
}
def _iter_order_observation_values(
order: dict[str, Any], *, include_header_values: bool = True,
) -> list[Any]:
"""收集订单头/行的原始字段 Observation 值;include_header_values=False 时
跳过表头观测(行级补写语义:表头已采纳值允许镜像写入缺失行级)。"""
values: list[Any] = []
field_groups: list[Any] = []
if include_header_values:
field_groups.append(order.get('header_fields'))
for line in order.get('lines') or []:
if isinstance(line, dict):
field_groups.append(line.get('fields'))
for fields in field_groups:
if not isinstance(fields, list):
continue
for field in fields:
if not isinstance(field, dict):
continue
for observation in field.get('observations') or []:
if isinstance(observation, dict) and observation.get('value') not in (None, ''):
values.append(observation.get('value'))
return values
def _heuristic_excluded_values(
order: dict[str, Any],
supplement: dict[str, Any],
*,
include_order_header_values: bool = True,
) -> set[str]:
"""构造裸数字候选的排除集:订单已提取值 + 邮件补充行值 + 邮件主题标签值。
核心逻辑:客户 PO 号本身就是 10 位纯数字,是启发式最大的误判源;因此除了
订单 Observation 原值外,还纳入 Reservation/PO 两种归一变体(千分位、x.0、
前导零),并排除主题里「PO xxx」等带标签数字(Q10 双保险)。
Args:
include_order_header_values: 行级补写语义下传 False——表头已采纳的预约号
正是要镜像写入缺失行级的值,不能出现在排除集里(否则行级永远补不上)。
"""
excluded: set[str] = set()
raw_values = _iter_order_observation_values(
order, include_header_values=include_order_header_values,
)
rows = supplement.get('rows') if isinstance(supplement.get('rows'), list) else []
for row in rows:
if isinstance(row, dict):
raw_values.extend(str(value) for value in row.values() if str(value or '').strip())
for raw in raw_values:
text = str(raw).strip()
if text:
excluded.add(text.upper())
normalized = validated_reservation_id(normalize_reservation_id(raw))
if normalized:
excluded.add(normalized)
excluded.add(normalized.lstrip('0'))
po = normalize_atomic_po_number(raw)
if po:
excluded.add(po.upper())
excluded.add(po.lstrip('0').upper() or po.upper())
excluded.update(
value.upper()
for value in reservation_ids_in_labeled_context(str(supplement.get('email_subject') or ''))
)
return {value for value in excluded if value}
def _inject_reservation_heuristic(
fields: list[dict[str, Any]],
field_id: str,
value: str,
evidence: dict[str, Any],
document_id: int,
) -> None:
"""以裸数字兜底语义写入 reservation Observation:低置信度并携带 basis 标记。
与 _inject 的差异:confidence 固定 0.5(启发式,非权威证据),
email_supplement_evidence 增加 basis='bare_numeric_heuristic' 供复核端标注。
"""
target = next((item for item in fields if isinstance(item, dict) and item.get('field_id') == field_id), None)
observation = {
'value': value, 'document_id': document_id, 'quote': str(evidence.get('raw_value') or value),
'confidence': 0.5, 'email_supplement_evidence': {
'table_index': evidence.get('table_index'), 'row_index': evidence.get('row_index'),
'column_index': evidence.get('column_index'), 'cell_id': evidence.get('cell_id'),
'basis': 'bare_numeric_heuristic',
},
}
if target is None:
fields.append({'field_id': field_id, 'observations': [observation]})
else:
target['observations'] = [observation]
def _order_has_reservation_value(order: dict[str, Any], ids: dict[str, str]) -> bool:
"""判断订单头或任意行已存在预约单号取值(含非法格式原值);存在则兜底绝不写入。
按 Q2 契约「已有值永不覆盖」:即使原值未通过 5/10 位校验(如字母型编号),
也视为已有业务事实,只能走人工纠错,不能被裸数字猜测悄悄替换。
"""
reverse_ids = {v: k for k, v in ids.items()}
if _values(order.get('header_fields'), 'reservation_id', reverse_ids):
return True
for line in order.get('lines') or []:
if isinstance(line, dict) and _values(line.get('fields'), 'reservation_id', reverse_ids):
return True
return False
def _order_po_variants(order: dict[str, Any], ids: dict[str, str]) -> set[str]:
"""本单已提取客户 PO 号的匹配变体集合(原值/归一/去前导零)。"""
reverse_ids = {v: k for k, v in ids.items()}
values = list(_values(order.get('header_fields'), 'customer_po_number', reverse_ids))
for line in order.get('lines') or []:
if isinstance(line, dict):
values.extend(_values(line.get('fields'), 'customer_po_number', reverse_ids))
variants: set[str] = set()
for value in values:
text = str(value).strip()
if not text:
continue
variants.add(text)
po = normalize_atomic_po_number(text)
if po:
variants.update({po, po.lstrip('0')})
variants.add(text.lstrip('0'))
return {variant for variant in variants if variant}
def _apply_reservation_heuristic(
order: dict[str, Any],
supplement: dict[str, Any],
*,
configs: dict[str, dict[str, Any]],
ids: dict[str, str],
schema_version: str,
claimed: set[str],
) -> None:
"""对仍无预约单号的订单执行裸数字兜底裁决(唯一→写入;多候选→冲突)。
核心逻辑:
[STEP 1] Schema 无 reservation_id 字段、候选键缺失或订单已有合法值 → 直接返回;
[STEP 2] 排除集 = 订单已提取值 ∪ 补充行值 ∪ 主题标签值 ∪ 跨单已占用(claimed);
[STEP 3] 唯一候选 → 按 Schema 作用域写入 header 默认值或缺失行,relation 标记
reservation_heuristic 供工作台补充状态展示;
[STEP 4] 多候选 → 复用 supplement_field_conflict 冲突结构(values + 逐候选
email_body 证据源),转现有字段冲突裁决面板,绝不自动挑值。
"""
config = configs.get('reservation_id')
field_id = ids.get('reservation_id')
candidates = supplement.get('reservation_candidates')
if config is None or not field_id or not isinstance(candidates, list) or not candidates:
return
# [分作用域兜底] 「已有值永不覆盖」按字段作用域生效:表头已有预约号→不再重复
# 注入表头;行级缺失→仍执行行级补写(分配邮件一行一个 PO+预约号,明细缺预约
# 号属数据不完整,回归 SNER-20261014-0AB6D98A doc 915 明细预约号空)。
reverse_ids = {v: k for k, v in ids.items()}
header_has_reservation = bool(
_values(order.get('header_fields'), 'reservation_id', reverse_ids),
)
header_reservation_values = set(
_values(order.get('header_fields'), 'reservation_id', reverse_ids),
)
lines_missing_reservation = [
line for line in order.get('lines') or []
if isinstance(line, dict) and isinstance(line.get('fields'), list)
and not _values(line['fields'], 'reservation_id', reverse_ids)
]
scope = str(config.get('scope') or '').strip().lower()
if scope == 'header' and header_has_reservation:
return
if scope != 'header' and not lines_missing_reservation:
return
excluded = _heuristic_excluded_values(order, supplement) | claimed
if lines_missing_reservation and header_has_reservation:
# [镜像语义] 表头已采纳的预约号值从排除集中移除——它正是要写入缺失
# 行级的值;其余订单观测值(尤其 PO)保持排除,防止 PO 误当预约号。
mirror_allow: set[str] = set()
for value in header_reservation_values:
text = str(value).strip().upper()
if text:
mirror_allow.update({text, text.lstrip('0')})
normalized = validated_reservation_id(normalize_reservation_id(text))
if normalized:
mirror_allow.update({normalized, normalized.lstrip('0')})
excluded -= mirror_allow
surviving, status = filter_reservation_heuristic_candidates(candidates, excluded_values=excluded)
if status == 'none':
return
# [PO 行定位收敛] 分配邮件整批表格一行一个 PO+预约号:本单 PO 所在行的预约号
# 即本单预约号。裸数字候选携带原始表坐标(table_index/row_index),与补充解析行
# 同源对齐——对齐行内含本单 PO 即认定该候选为本单预约号。命中唯一 → 按唯一路径
# 写入;命中多个或未命中时维持既有冲突裁决(绝不自动猜值)。
order_po_values = _order_po_variants(order, ids)
supplement_rows = supplement.get('rows') if isinstance(supplement.get('rows'), list) else []
parsed_rows_by_pos = {
(str(row.get('table_index') or 0), str(row.get('row_index') or 0)): row
for row in supplement_rows if isinstance(row, dict)
}
scoped: list[dict[str, Any]] = []
if order_po_values and parsed_rows_by_pos:
for item in surviving:
evidence = item.get('evidence') if isinstance(item.get('evidence'), dict) else {}
pos = (str(evidence.get('table_index') or 0), str(evidence.get('row_index') or 0))
row = parsed_rows_by_pos.get(pos)
if row is None:
continue
row_values = {str(value).strip() for value in row.values() if str(value or '').strip()}
if order_po_values & row_values:
scoped.append(item)
if scoped:
surviving = scoped
status = 'unique' if len(surviving) == 1 else 'multiple'
document_id = int(supplement.get('document_id') or 0)
values = [str(item.get('value') or '') for item in surviving]
marker = {'status': status, 'values': values, 'document_id': document_id or None}
if status == 'unique':
value = validated_reservation_id(values[0])
if not value:
return
evidence = dict(surviving[0].get('evidence') or {})
if str(config.get('scope') or '') == 'header':
header_fields = order.get('header_fields')
if isinstance(header_fields, list):
_inject_reservation_heuristic(header_fields, field_id, value, evidence, document_id)
else:
# 行级写入只补真正缺失的行;带任何原值(含非法格式)的行不覆盖。
reverse_ids = {v: k for k, v in ids.items()}
for line in order.get('lines') or []:
if isinstance(line, dict) and isinstance(line.get('fields'), list):
if not _values(line['fields'], 'reservation_id', reverse_ids):
_inject_reservation_heuristic(line['fields'], field_id, value, evidence, document_id)
claimed.add(value)
marker['status'] = 'applied'
marker['value'] = value
if not str(order.get('_hxops_email_supplement_relation') or '').strip():
order['_hxops_email_supplement_relation'] = 'reservation_heuristic'
else:
pseudo_rows = [
{
'reservation_id': item.get('value'),
'table_index': (item.get('evidence') or {}).get('table_index'),
'row_index': (item.get('evidence') or {}).get('row_index'),
'evidence': {'reservation_id': dict(item.get('evidence') or {})},
}
for item in surviving
]
conflict = _supplement_multi_value_conflict(
field_code='reservation_id',
config=config,
values=set(values),
selected_rows=pseudo_rows,
line_index=-1,
email_document_id=document_id,
schema_version=schema_version,
)
if conflict not in order.setdefault('conflicts', []):
order['conflicts'].append(conflict)
if not str(order.get('_hxops_email_supplement_relation') or '').strip():
order['_hxops_email_supplement_relation'] = 'reservation_heuristic'
order['_hxops_reservation_heuristic'] = marker
def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_intake: dict[int, dict[str, Any]], schema_definition: dict[str, Any]) -> list[dict[str, Any]]:
"""
按冻结 Schema 逐字段合并正文事实,并对歧义订单附加复核冲突。
@@ -487,4 +758,18 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta
})
order['_hxops_email_supplement_relation'] = relation
merged.append(order)
# [STEP] 裸数字兜底:主合并完成后仍无预约单号的订单,按排除规则裁决正文候选。
# 跨单 claimed 防止同一候选同时灌入多个订单;旧 Run 补充快照无候选键时整体跳过。
claimed_reservations: set[str] = set()
for order in merged:
supplement = supplements_by_intake.get(int(order.get('_hxops_intake_id') or 0))
if isinstance(supplement, dict) and isinstance(supplement.get('reservation_candidates'), list):
_apply_reservation_heuristic(
order,
supplement,
configs=configs,
ids=ids,
schema_version=schema_version,
claimed=claimed_reservations,
)
return merged
@@ -478,17 +478,22 @@ def inventory_preparation_primary_action(
"""裁决库存准备 Gate 面向业务用户的主动作。
单源合并(用户拍板):库存失败只保留 2 个按钮 ——
``retry_inventory_preparation``(直接重跑 RPA)与 ``retry_inventory_matching``
(优先复用已有快照并重匹配;无快照时 match_inventory 内部经 ensure_inventory 回退 RPA)。
``retry_inventory_preparation``(显式重跑 RPA)与 ``retry_inventory_matching``
(复用已抓取库存与字段映射并重匹配,不重抓,见 execute_stage_capability_rematch)。
已下线的 ``reload_inventory_result``(只重读)不再独立成主动作,其「复用快照」行为已并入
``retry_inventory_matching``。
边界(STP 多候选,ensure_inventory auto 模式):缺快照停人工待处理、不隐式触发 RPA。
因此获取库存未成功(无行级匹配结果)时,``retry_inventory_matching`` 由阶段能力禁用
(disabled_reason=no_match_result,见 ui_state._stage_capabilities_for_task),
重抓必须走显式的 ``retry_inventory_preparation``;本函数只裁决按钮位次,不禁用按钮。
"""
normalized_status = str(status or '').strip().lower()
normalized_reason = str(blocking_reason_code or '').strip().lower()
if normalized_status == 'waiting_external':
return 'poll_inventory_preparation'
if normalized_reason in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'}:
# [MERGE] 超时/耗尽:优先复用已有快照重匹配,无则回退 RPA(retry_inventory_matching 自含)。
# [MERGE] 超时/耗尽:优先复用已有快照重匹配;无匹配结果时该按钮由阶段能力
# 禁用(no_match_result),显式重抓走侧路 retry_inventory_preparation。
return 'retry_inventory_matching'
if normalized_status in {'blocked_manual', 'blocked_retryable'}:
return 'retry_inventory_preparation'
@@ -938,6 +938,42 @@ def _handle_retry_inventory_preparation(
freeze_mode='manual',
)
db.session.flush()
# [STEP 0B] 人工重取前的候选源刷新(幂等):任务级 retry_inventory_preparation 先按当前
# 主数据/路由规则整单重判候选集;行级重抓(line_scope 非空)仅重评目标行候选。
# 两者均无变化零副作用;有变化则新版候选集随 supersede 自带旧事实失效,再走下方
# 既有失效与重取链——补源场景由此闭环:管理端启用新源后点「重新获取库存(RPA)」
# 即可让新源进入取数与匹配范围,无需重建订单。
# 轮询/自动首投(外层条件已排除)与 Excel 已生成(源锁定,D7 边界)不刷新;
# 已定源(任务级整单/行级目标行候选 ≤1)与人工钉源不刷新(helper 内守卫,改源走
# override_line_inventory_source)。
# 行键失效(line_scope_key/snapshot_line_id 解析不到行)时 _resolve_line_inventory_scope
# 返回 None,按既有降级语义走任务级刷新(升级前行为一致)。
if str(payload.get('action_code') or '').strip() == 'retry_inventory_preparation':
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
if latest_export_artifact(task) is None:
from app.services.shipping_notice.inventory_candidate_freeze_service import (
refresh_candidates_from_current_routing,
refresh_line_candidates_from_current_routing,
)
if line_scope is None:
refresh_candidates_from_current_routing(task, execution_id=int(execution.id))
elif refresh_line_candidates_from_current_routing(
task, line_no=int(line_scope['line_no']), execution_id=int(execution.id),
):
# 刷新产生新候选集后旧 scope 已过期:按同参重解析行作用域,让本次失效与
# RPA 取数直接使用新冻结码;重解析为 None(如行键已失效)则保守沿用旧值。
refreshed_scope = _resolve_line_inventory_scope(
task,
line_scope_key=(
payload.get('line_scope_key')
if payload.get('line_scope_key') is not None
else payload.get('snapshot_line_id')
),
)
if refreshed_scope is not None:
line_scope = refreshed_scope
if payload.get('action_code') in {
'retry_inventory_preparation',
'retry_inventory_from_preparation',
@@ -352,6 +352,13 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None:
continue
current = gate
break
facts_before = (
execution.last_passed_gate_code,
execution.current_gate_code,
execution.primary_next_action_code,
execution.responsible_party,
execution.status,
)
execution.last_passed_gate_code = last_passed
if current is None:
execution.current_gate_code = None
@@ -359,7 +366,16 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None:
execution.responsible_party = None
if execution.status not in {'cancelled', 'failed'}:
execution.status = 'completed'
_sync_order_task_stage_after_gate_refresh(execution)
_sync_order_task_stage_after_gate_refresh(
execution,
facts_changed=facts_before != (
execution.last_passed_gate_code,
execution.current_gate_code,
execution.primary_next_action_code,
execution.responsible_party,
execution.status,
),
)
return
execution.current_gate_code = current.gate_code
execution.primary_next_action_code = current.next_action_code
@@ -376,10 +392,23 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None:
# [OT SYNC] Gate 指针刷新后回写挂接 OT 的 stage/status,避免主卡/批次只读
# 投影停留在技术阶段(如 excel_generating),与当前 Gate 事实分叉。
# 仅已绑定任务时同步;建单前执行(无 task_id)自然跳过。延迟导入避免循环依赖。
_sync_order_task_stage_after_gate_refresh(execution)
_sync_order_task_stage_after_gate_refresh(
execution,
facts_changed=facts_before != (
execution.last_passed_gate_code,
execution.current_gate_code,
execution.primary_next_action_code,
execution.responsible_party,
execution.status,
),
)
def _sync_order_task_stage_after_gate_refresh(execution: ShippingProcessExecution) -> None:
def _sync_order_task_stage_after_gate_refresh(
execution: ShippingProcessExecution,
*,
facts_changed: bool = False,
) -> None:
"""Gate 指针刷新后回写挂接 OT 的 stage/status(completed 与阻断两个出口共用)。"""
if getattr(execution, 'task_id', None) is None:
return
@@ -397,10 +426,38 @@ def _sync_order_task_stage_after_gate_refresh(execution: ShippingProcessExecutio
if task is not None else None
)
if notice is not None:
version_before = int(getattr(task, 'progress_version', 0) or 0)
sync_order_task_stage_for_notice(notice, order_task=task)
# 库存缺口/文件就绪等 Gate 事实变化但映射后 stage/status 未变时,仍须推进
# progress_version:工作台以该版本变化触发 [REFRESH_ON_CHANGE] 重拉任务详情,
# 版本冻结会让行级可用数量/缺口停留在上一次快照。
if (
facts_changed
and task is not None
and int(getattr(task, 'progress_version', 0) or 0) == version_before
):
_bump_order_task_progress_version(task)
elif task is not None:
# Notice 生成前只维护 OT 自身阶段;不能调用 Notice 专属映射。
task.stage = task.stage or 'notification_preparation'
# 无 Notice 绑定(通知准备/库存匹配常态)时上方 Notice 映射不存在,Gate 每次真实
# 推进都必须经中央写入口递增 progress_version,否则统一投影版本冻结,
# 前端轮询只更新右卡门禁、任务详情表格永不刷新。
if facts_changed:
_bump_order_task_progress_version(task)
def _bump_order_task_progress_version(task: ShippingOrderTask) -> None:
"""Gate 事实已变化但 stage/status 无值可变时,经中央写入口强制递增进度版本。"""
from app.services.shipping_notice.order_task_service import sync_order_task_processing_state
sync_order_task_processing_state(
task,
bump_progress=True,
force_progress_bump=True,
reason_code='gate_facts_advanced',
source='process_gate_service',
)
def ensure_execution_for_workflow_version(
@@ -812,6 +812,11 @@ def apply_user_projection_fields(
return 'waiting_human'
if unverified_upload_terminal:
return 'waiting_human'
if gate_status in {'queued', 'running', 'waiting_external'}:
# Gate/Execution 在途 = 系统处理中:Notice 生成前 OT.status 会停留在建单前
# 的 waiting_review,不得据此把 RPA 自动推进误报成待人工——前端把
# waiting_human 视为终态并停止投影轮询,回调完成将永远无法被感知。
return 'running'
# 1) 终态短路:old_status completed/cancelled/failed
if old_status == 'completed':
return 'completed'
@@ -120,6 +120,7 @@ REVIEW_WORKBENCH_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
'review_field_changed',
'review_field_updated',
'review_customer_confirmed',
'review_customer_rebound',
'review_duplicate_resolved',
'review_conflict_resolved',
'review_qualification_evaluated',
@@ -1564,13 +1564,22 @@ def _enrich_task_center_fields(
data["created_by"] = task.user_id
if viewer_user_id is not None:
data["can_handle"] = task_can_handle(task, int(viewer_user_id), is_admin=is_admin)
# 下载能力与导出端点同一谓词;SUMMARY/DETAIL 均下发,供抽屉/批量勾选消费。
data["can_download_export"] = can_download_task_export(
task, user_id=int(viewer_user_id), is_admin=is_admin,
)
data["recent_event"] = _latest_task_event_summary(task)
data["artifact_summary"] = _artifact_summary_for_task(task)
data['notice_line_summary'] = _notice_line_summary_for_task(task)
# [STEP] 懒导入避免与 ui_state ↔ query_service 循环依赖。
from app.services.shipping_notice.ui_state import build_task_ui_state
ui_state = build_task_ui_state(task, include_stage_context=include_stage_context)
ui_state = build_task_ui_state(
task,
include_stage_context=include_stage_context,
viewer_user_id=viewer_user_id,
viewer_is_admin=is_admin,
)
data["ui_state"] = ui_state
# [PERF] 优先复用 ui_state.process_gate(build_task_ui_state 已查 Execution);
# 无 Gate 时回退 position/user_mode,避免再跑一次 resolve_task_ui_state。
@@ -1730,12 +1739,15 @@ def list_tasks_page_for_user(
page: int = 1,
page_size: int = 20,
lifecycle_status: str | None = None,
is_admin: bool = False,
) -> dict[str, Any]:
"""
分页列出当前用户可见的发货任务摘要。
工作台任务量增长后必须由数据库分页,不能先拉取固定上限再在浏览器切页;
`items` 仅表示当前页,`total` 用于计算稳定的页码与空页回退。
``is_admin`` 只影响 SUMMARY 的能力字段(can_handle / can_download_export),
不扩大列表可见范围(仍为本人 + 无主 Notice)。
"""
normalized_page = max(1, int(page))
normalized_page_size = max(1, min(int(page_size), 100))
@@ -1795,7 +1807,7 @@ def list_tasks_page_for_user(
rows = [row for row in rows if row is not None]
return {
"items": [
serialize_task_summary(item, viewer_user_id=user_id)
serialize_task_summary(item, viewer_user_id=user_id, is_admin=is_admin)
for item in rows
],
"page": normalized_page,
@@ -1849,6 +1861,35 @@ def get_task_visible_to_user(
return task
def can_download_task_export(
task: ShippingOrderTask | ShippingNotice | None,
*,
user_id: int,
is_admin: bool = False,
) -> bool:
"""
导出下载的唯一授权谓词:创建者或平台管理员(与导出端点同一口径)。
核心逻辑:单票/批量 Excel 下载端点与 UI 的 download_excel 动作、
can_download_export 字段都必须消费本谓词,禁止各处另行推导归属;
管理员放开下载(可下载=可见)后,每次下载仍须写入 record_access_audit。
无主任务(user_id IS NULL)仅管理员可下载。
Args:
task: 已加载的任务实体(可为 None)。
user_id: 当前查看/下载用户。
is_admin: 是否平台管理员。
Returns:
当前用户是否允许下载该任务的正式 Excel。
"""
if task is None:
return False
if is_admin:
return True
return task.user_id is not None and int(task.user_id) == int(user_id)
def list_freight_notice_groups_for_task(
task: ShippingNotice,
*,
@@ -29,12 +29,20 @@ from app.services.shipping_notice.audit_service import append_shipping_audit_eve
def _read_receipt_callback_file(file_path: str) -> bytes:
"""只读取收料专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。"""
"""只读取收料专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。
路径契约为「drop 根内文件名」:Worker(Windows RPA 主机)与后端(Linux 容器)分属
两机,各自看到的根路径不同(C:\\HxopsRpaTest\\... vs /mnt/hxops-rpa-*-data/...),
Worker 只上报文件名,后端用自身挂载的 drop 根拼接定位;携带本机绝对路径的历史
载荷亦按末段文件名解析(2026-10-08 修复跨机成功回调全程 400 的事故)。
"""
configured_root = str(current_app.config.get('FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR') or '').strip()
if not configured_root:
raise ValidationError('receipt callback file root is unavailable', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
root = Path(configured_root).resolve()
path = Path(file_path).resolve()
# 容忍历史载荷携带 Windows 绝对路径:先归一分隔符再取末段文件名(防遍历,单一分段)。
name = Path(str(file_path).replace('\\', '/')).name
path = (root / name).resolve()
try:
path.relative_to(root)
except ValueError as exc:
@@ -2,9 +2,12 @@
services/shipping_notice/reservation_id.py
用途:提取、标准化并校验发货通知与库存中的 Reservation ID。
依赖:正则表达式与标准 `typing` 工具。
依赖:正则表达式与标准 `typing` 工具;裸数字兜底扫描惰性依赖版面 HTML 网格解析。
逻辑:由 notice_lines、inventory_snapshot、match、extract、EML 补充解析等多个模块复用;
归一结果恒为 5/10 位纯数字(可剥括号备注、@ 前缀、短数字行序后缀如 35354-1)。
另提供「裸数字兜底」:正文数据表无表头且常规证据缺失时,扫描「整格恰好为
5/10 位纯数字」的 HTML 表格单元格候选(供 order_supplement_merge 在合并
末段做唯一/多候选裁决;自由文本不扫描)。
"""
from __future__ import annotations
@@ -30,6 +33,16 @@ PR_NUMBER_LINE_RE = re.compile(
r"PR\s*Number\s*[::]?\s*([^\n\r]+)",
re.IGNORECASE,
)
# [裸数字兜底] 紧跟业务标签的数字串(PO/订单/发票/数量)不是预约单号;捕获组为数字本体。
# 保留前导词边界防止命中复合词内部;尾部不加边界、由「必须跟数字」门控,
# 使 PO12345 / PO# 12345 / Purchase Order: 12345 等写法都被覆盖,而 podium 等词不受影响。
# 仅用于邮件主题等上下文的标签排除;正文候选已收紧为「整格纯数字」,不再做自由文本扫描。
LABELED_NON_RESERVATION_RE = re.compile(
r"(?i)(?:\bp\.?\s*o\.?|\bpurchase\s+orders?|\borders?|\binvoices?|\binv\.?|\bqty\.?|\bquantity)"
r"(?:\s*(?:number|no\.?|#))?\s*[:#]?\s*(\d{3,})"
)
# 候选数量上限:转发/引用链可能携带大量历史数字,防止 supplement 快照被刷爆。
MAX_HEURISTIC_RESERVATION_CANDIDATES = 20
def normalize_reservation_id(value: Any) -> str:
@@ -151,3 +164,123 @@ def validated_reservation_id(value: Any, *, numeric_only: bool = False) -> str:
"""提取并返回合法 Reservation ID;候选不满足契约时返回空字符串。"""
candidate = extract_reservation_id(value)
return candidate if is_valid_reservation_id(candidate, numeric_only=numeric_only) else ""
def reservation_ids_in_labeled_context(text: str) -> set[str]:
"""返回文本中紧跟业务标签(PO/订单/发票/数量)的数字串,供裸数字候选排除。
AI 触发时机:合并末段判断裸数字候选前,先排除邮件主题等上下文里
「PO xxx」「Invoice xxx」这类带标签的数字,即使它们未被提取为字段。
Args:
text: 任意原文(邮件主题、正文段落等)。
Returns:
set[str]: 标签后紧跟的数字串原文(未归一);无命中返回空集合。
"""
return {
match.group(1)
for match in LABELED_NON_RESERVATION_RE.finditer(str(text or ""))
}
def _iter_heuristic_cell_texts(html_tables: list[str] | None, content_hash: str):
"""惰性产出 HTML 表格单元格文本及其证据定位;解析失败的表安全跳过。
逻辑:版面网格的 cell_id 是 DOM 级可追溯证据,优先于行号猜测;
惰性导入 html_table 避免给本工具模块增加常驻依赖。
"""
if not html_tables:
return
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
for table_index, html in enumerate(html_tables):
try:
grid = parse_html_grid(
str(html or ''), table_id=f'reservation-heuristic:{content_hash}:{table_index}',
)
except Exception:
continue
for row_index, row in enumerate(grid.rows):
for column, slot in enumerate(row):
if slot is None or not str(slot.text or '').strip():
continue
yield str(slot.text), {
'table_index': table_index,
'row_index': row_index,
'column_index': column,
'cell_id': slot.cell_id,
}
def _heuristic_cell_is_bare_number(cell_text: str) -> bool:
"""判断表格单元格是否「整格恰好为 5/10 位纯数字」(2026-10-15 收紧规则)。
前后带任何字符都不取:地址邮编(``Secaucus, NJ 07094``)、带字母前后的
编号(``T00410``)、带备注的值(``39739 (A)``)一律排除,只留独立数值格。
"""
return bool(RESERVATION_ID_NUMERIC_RE.fullmatch(str(cell_text or '').strip()))
def find_bare_numeric_reservation_candidates(
*,
html_tables: list[str] | None = None,
content_hash: str = "",
) -> list[dict[str, Any]]:
"""扫描正文 HTML 表格中「整格恰好为 5/10 位纯数字」的预约单号候选。
AI 触发时机:EML 正文数据表没有表头、常规表头契约解析不出预约单号时,
在补充事实里预置候选列表;真正「是否采纳」由 order_supplement_merge 在
合并末段结合已提取字段值裁决,本函数绝不直接写入订单。
核心逻辑:只认表格(2026-10-15 收紧)——自由文本(签名、地址、引用链)
一律不扫描,杜绝邮编等噪声;单元格整格纯数字才算候选(PO 号同为 10 位
纯数字会入选,由合并端按已提取字段值/主题标签排除);同值只保留首个证据;
总数截断到 MAX_HEURISTIC_RESERVATION_CANDIDATES。
Args:
html_tables: 正文顶层 HTML 表格片段列表;为空时返回空列表(无表格不兜底)。
content_hash: 正文 Document 内容哈希,用于稳定 cell_id。
Returns:
list[dict]: ``[{value, evidence}]``;evidence 含 table_index/row_index/
column_index/cell_id/raw_value(DOM 级可追溯)。
"""
candidates: list[dict[str, Any]] = []
seen: set[str] = set()
for cell_text, base_evidence in _iter_heuristic_cell_texts(html_tables, content_hash):
if not _heuristic_cell_is_bare_number(cell_text):
continue
value = str(cell_text).strip()
if value in seen or len(candidates) >= MAX_HEURISTIC_RESERVATION_CANDIDATES:
continue
seen.add(value)
candidates.append({'value': value, 'evidence': {**base_evidence, 'raw_value': value}})
return candidates
def filter_reservation_heuristic_candidates(
candidates: list[dict[str, Any]],
*,
excluded_values: set[str],
) -> tuple[list[dict[str, Any]], str]:
"""按「已识别字段值/跨单已占用」排除后裁决候选状态。
Args:
candidates: ``find_bare_numeric_reservation_candidates`` 的产物。
excluded_values: 需排除的值集合(比较前统一 strip+大写)。
Returns:
``(surviving, status)``:status 为 ``unique``(恰好一个,可自动采纳)、
``ambiguous``(多个,转人工裁决)或 ``none``(无候选)。
"""
excluded = {str(value).strip().upper() for value in excluded_values if str(value).strip()}
surviving = [
item for item in (candidates or [])
if str(item.get('value') or '').strip().upper() not in excluded
]
if not surviving:
return [], 'none'
if len(surviving) == 1:
return surviving, 'unique'
return surviving, 'ambiguous'
@@ -17,6 +17,7 @@ from app import db
from app.core.errors import ConflictError
from app.models import (
ShippingOrderDocument,
ShippingOrderProcessingRun,
ShippingOrderReviewCase,
ShippingOrderReviewCaseEvent,
ShippingOrderReviewStream,
@@ -30,6 +31,33 @@ ReviewStreamTrigger = Literal[
]
def run_is_reparse_successor_of_case(
*,
run: ShippingOrderProcessingRun,
current_case: ShippingOrderReviewCase,
max_hops: int = 10,
) -> bool:
"""
判定 Run 是否为某文件当前 Case 所属 Run 的重解析后继(沿 reparse_of_run_id 有界上溯)。
核心逻辑:批次重解析(reparse_order_extraction_run)不写 review_reparse 快照
marker,activate_review_case 的替代来源证明需要调用方提供;本函数即该证明——
上溯有界跳数内命中 current_case.run_id 即认定同文件版本替代关系成立。
"""
current_run_id = int(current_case.run_id)
cursor = run
for _ in range(max(1, int(max_hops))):
ancestor_id = getattr(cursor, 'reparse_of_run_id', None)
if ancestor_id is None:
return False
if int(ancestor_id) == current_run_id:
return True
cursor = db.session.get(ShippingOrderProcessingRun, int(ancestor_id))
if cursor is None:
return False
return False
def _document_content_identity(document_id: int) -> str:
"""计算 Stream 的稳定文件身份;当前业务按 Document 严格隔离,哈希仅供审计说明。"""
document = db.session.get(ShippingOrderDocument, int(document_id))
@@ -91,12 +119,19 @@ def activate_review_case(
*,
case: ShippingOrderReviewCase,
trigger: ReviewStreamTrigger,
declared_source_case_id: int | None = None,
) -> ShippingOrderReviewStream:
"""
将一个成功可复核的 Case 原子切换为其文件 Stream 的当前版本。
AI 触发时机:初次 PDF 完成时或重解析成功且新 Case 已完整落库时调用;失败、等待布局和
仅创建后继 Run 时禁止调用。确认/履约中的当前版本不可被草稿覆盖,冲突必须显式暴露。
Args:
declared_source_case_id: 调用方已证明的版本替代来源 Case id(如按 Run 谱系
验证过的前代 Case)。快照 marker 缺失时(批次重解析不写
review_reparse.source_case_no)以它补全替代关系证明;快照 marker
优先,两者皆缺时维持保守冲突语义。
"""
stream = ensure_review_stream_for_case(case=case)
stream = ShippingOrderReviewStream.query.filter_by(id=int(stream.id)).with_for_update().one()
@@ -111,6 +146,9 @@ def activate_review_case(
return stream
if trigger != 'initial_extraction' and current is not None:
declared_source_id = _declared_reparse_source_case_id(incoming)
if declared_source_id is None and declared_source_case_id is not None:
# 调用方已按 Run 谱系证明替代来源(批次重解析不写快照 marker 的口径)。
declared_source_id = int(declared_source_case_id)
if declared_source_id is None or declared_source_id != int(current.id):
# [CONCURRENCY] 晚到分支只能进入冲突,绝不能覆盖已切换的另一文件版本。
stream.state = 'conflict'
@@ -513,7 +513,7 @@ def _check_rpa_worker_ready_for_capability(
required_capability: 必选 Worker 能力;空字符串表示不校验能力。
extra_reasons: 调用方预检附加原因(凭据/队列等)。
worker_predicate: 可选过滤(如仅收料 Worker);不匹配的心跳不进入列表。
require_sentinel: 是否要求共享哨兵(收料为 False)。
require_sentinel: 是否要求共享哨兵(库存/收料同口径均 True)。
Returns:
RpaWorkerReadiness。
@@ -4263,14 +4263,17 @@ def project_conversation_processing_summary(
if case.run_id is not None
)
# 订单抽取失败且尚无 Candidate/Case/OT 时,仍需最新 Run 身份供重解析;
# 仅 load id/run_no,不触碰 Plan/Unit。
# 仅 load id/run_no/status/error_code,不触碰 Plan/Unit。status/error_code
# 供摘要把「抽取收口 completed 但最新 Run 失败」的文档纠正为失败裁决。
latest_run_by_intake_id: dict[int, Any] = {}
if intake_ids:
for intake_id, run_id, run_no in (
for intake_id, run_id, run_no, run_status, run_error_code in (
db.session.query(
ShippingOrderProcessingRunIntake.intake_id,
ShippingOrderProcessingRun.id,
ShippingOrderProcessingRun.run_no,
ShippingOrderProcessingRun.status,
ShippingOrderProcessingRun.error_code,
)
.join(
ShippingOrderProcessingRun,
@@ -4287,7 +4290,12 @@ def project_conversation_processing_summary(
key = int(intake_id)
if key in latest_run_by_intake_id:
continue
latest_run_by_intake_id[key] = {'id': int(run_id), 'run_no': str(run_no or '').strip()}
latest_run_by_intake_id[key] = {
'id': int(run_id),
'run_no': str(run_no or '').strip(),
'status': str(run_status or '').strip().lower(),
'error_code': str(run_error_code or '').strip() or None,
}
run_ids.add(int(run_id))
runs_by_id = {
int(run.id): run
@@ -4455,7 +4463,31 @@ def project_conversation_processing_summary(
if raw in {'review_required', 'waiting_review', 'pending_review', 'waiting_human'}:
return 'waiting_human', 'waiting_review' if stage == 'candidate_creating' else stage, 'waiting_review'
if raw in {'completed', 'uploaded'}:
return 'completed', 'completed', None
# 文档级 completed 只代表「抽取收口完成」,不是业务终态:通知完成必须
# 以正式 OT/Notice/上传核验为前提,禁止把收口语义译成通知完成
# (回归 SNER-20261014-8EBAB7A1:9 Unit 全失败仍整批 completed,
# 批次中心据此误报 9/9 已完成 + 通知完成)。
if task is not None:
return 'completed', 'completed', None
if case is not None and case_status == 'non_order':
# 非订单处置是唯一无 OT 的合法业务完成出口。
return 'completed', 'completed', None
latest_intake_run = latest_run_by_intake_id.get(int(document.intake_id)) or {}
latest_run_status = str(latest_intake_run.get('status') or '').strip().lower()
if latest_run_status == 'failed':
# 收口 completed 但最新 Run 失败(含历史脏数据):按失败裁决并提供重解析。
return (
'failed',
stage,
str(latest_intake_run.get('error_code') or '') or 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED',
)
if latest_run_status == 'review_required' and task is None and case is None:
# 收口 completed 但最新 Run 需人工且未物化 Case/OT(如 XFA 身份门禁
# 在命中后拒绝、候选从未创建):停「需处理」并下发重解析入口,
# 禁止落到处理中(回归 SNER-20261014-E27D657F)。
return ('waiting_human', stage or 'candidate_creating', 'run_review_required')
# 无 OT/无处置的收口完成与全量视图同判词:停接收解析(处理中)。
return 'running', stage, None
if raw in {'cancelled', 'archived'}:
return raw, raw, None
return 'running', stage, None
@@ -4499,9 +4531,23 @@ def project_conversation_processing_summary(
stage = 'candidate_creating'
case_status = str(getattr(case, 'status', None) or '').strip().lower()
terminal_case = case_status in {'confirmed', 'non_order', 'superseded', 'reparse_pending'}
extraction_failed = str(document.order_extraction_status or '').strip().lower() in {
'failed', 'parse_failed', 'technical_retrying',
}
# 抽取需人工事实除文档级状态外,还认「无 OT/无 Case 且最新 Run 失败或需人工」:
# 历史/并发脏数据可能把 Unit 全失败的附件写成 completed(抽取收口语义);
# Run 收口 review_required 但未物化 Case/OT(XFA 门禁拒绝)同理,
# 此时仍必须下发重解析入口,与 _status 的裁决同源。
latest_intake_run_status = str(
(latest_run_by_intake_id.get(int(document.intake_id)) or {}).get('status') or ''
).strip().lower()
extraction_failed = (
str(document.order_extraction_status or '').strip().lower() in {
'failed', 'parse_failed', 'technical_retrying',
}
or (
task is None
and case is None
and latest_intake_run_status in {'failed', 'review_required'}
)
)
task_no = str(task.task_no).strip() if task is not None else None
available_actions: list[str] = []
primary_action: dict[str, Any] | None = None
@@ -8,6 +8,7 @@ services/shipping_notice/stp_line_inventory_match.py
__source_code(源已在选源/载入 Excel 时确定);多文件命中为冲突;唯一命中且数量充足则冻结
resolved 源与行证据;多源可履约行暂停 Excel(step_payload 标记);人工指定源后
forced_match_source_code 过滤库存行再匹配;结果写入 step_payload / line_results_json。
行结果另含料号兜底总量 part_available_qty(允许源内、忽略预约号与单位的二次汇总)。
"""
from __future__ import annotations
@@ -77,6 +78,37 @@ def _inventory_row_qty(row: dict[str, Any]) -> Decimal:
return Decimal('0')
def _part_total_available_qty(
buckets: dict[tuple[str, str, str, str], dict[str, Any]],
*,
part: str,
allowed_source_codes: list[str],
has_candidate_scope: bool,
) -> Decimal | None:
"""
按料号(忽略预约号、不限单位)在该行允许源范围内汇总库存总可用量(料号兜底口径)。
Args:
buckets: (reservation, part, unit, source) 聚合桶;unit 维度不参与过滤。
part: 归一化料号;空串返回 None。
allowed_source_codes: 该行冻结的候选源;仅 has_candidate_scope 时约束。
has_candidate_scope: 行是否携带候选源范围事实。
Returns:
料号总可用量(Decimal);缺料号返回 None。跨源不合并(multi_file_conflict 语义)。
"""
if not part:
return None
total = Decimal('0')
for key, bucket in buckets.items():
if key[1] != part:
continue
if has_candidate_scope and bucket['source_code'] and bucket['source_code'] not in allowed_source_codes:
continue
total += bucket['available_qty']
return total
def snapshot_header_reservation_id(snapshot: ShippingOrderSnapshot | None) -> str | None:
"""
从冻结 Snapshot 读取 Header 级 reservation_id。
@@ -275,6 +307,9 @@ def match_order_lines_across_candidates(
核心逻辑:匹配键是 Reservation + Part(单位可选);库存源在选源/载入 Excel 时已确定,
库存行缺 ``__source_code`` 仍参与聚合。仅当行上显式带源码时,才用候选源范围过滤/判冲突。
料号兜底:仅 not_found(预约不匹配)/ok/shortage 行额外下发
``part_available_qty``(行允许源内、忽略预约号、不限单位的料号总可用量);
缺料号、invalid(超出候选范围)、multi_file_conflict、缺预约行不写该键,由下游按缺失→None 处理。
Args:
order_lines: 含 part_number / reservation_id / quantity(或 qty)/ uom 的订单行。
@@ -348,6 +383,13 @@ def match_order_lines_across_candidates(
else True
)
]
# [STEP] 料号兜底总量:行允许源内、忽略预约号、不限单位,供预约不匹配/缺口行自动放行判断。
part_total = _part_total_available_qty(
buckets,
part=part,
allowed_source_codes=allowed_source_codes,
has_candidate_scope=has_candidate_scope,
)
if not effective or not part:
disposition = 'not_found'
@@ -408,6 +450,7 @@ def match_order_lines_across_candidates(
'required_qty': float(required),
'available_qty': 0.0,
'shortage_qty': float(required),
'part_available_qty': float(part_total) if part_total is not None else None,
'line_status': 'shortage',
'disposition': disposition,
'resolved_inventory_source_code': None,
@@ -431,6 +474,7 @@ def match_order_lines_across_candidates(
'required_qty': float(required),
'available_qty': float(available),
'shortage_qty': 0.0,
'part_available_qty': float(part_total) if part_total is not None else None,
'line_status': 'ok',
'disposition': disposition,
'resolved_inventory_source_code': resolved_source,
@@ -453,6 +497,7 @@ def match_order_lines_across_candidates(
'required_qty': float(required),
'available_qty': float(available),
'shortage_qty': float(max(required - available, Decimal('0'))),
'part_available_qty': float(part_total) if part_total is not None else None,
'line_status': 'partial' if available > 0 else 'shortage',
'disposition': disposition,
'resolved_inventory_source_code': resolved_source,
@@ -16,6 +16,7 @@ services/shipping_notice/ui_state.py
+ 当前 Match 投影诚实反映最近一轮(Notice 经 order_task_id→OT),
行级拆 selected_source_code(CandidateSet 取数目标)与 source_code(Match 正式源);
短缺行复用放行模板字段;匹配成功无短缺下发 can_fulfill_complete_line;
prep 行直透投影 part_available_qty(料号兜底总量,仅库存就绪时非空)供前端「可用数量」列;
下发 source_options 与 capabilities(阶段能力,供右卡点击 stageCapabilityBypass);
用户动作统一由 Gate 授权;build_task_ui_state 同请求内复用一次 Gate 摘要;
project_notice_available_actions 供货代上传聚合行内菜单轻量消费。
@@ -60,7 +61,11 @@ from app.services.shipping_notice.lifecycle_projection import (
LIFECYCLE_STAGES,
project_lifecycle,
)
from app.services.shipping_notice.query_service import resolve_task_export_download, serialize_task_summary
from app.services.shipping_notice.query_service import (
can_download_task_export,
resolve_task_export_download,
serialize_task_summary,
)
from app.services.shipping_notice.state_machine import (
UserMode,
)
@@ -950,7 +955,8 @@ def _build_stage_context(
release_line_index, release_snapshot_id, release_source_code = _release_fact_identity(fact)
if release_line_index is None and getattr(snapshot_line, 'position', None) is not None:
release_line_index = int(snapshot_line.position)
release_template_fields = _shortage_release_required_fields(
# scope 仅在 decide 落库时写入审计快照;prep 行投影契约本期不新增字段。
release_template_fields, _evidence_scope = _shortage_release_required_fields(
task=order_task,
line_index=release_line_index,
inventory_snapshot_id=release_snapshot_id,
@@ -976,6 +982,7 @@ def _build_stage_context(
'required_qty': required_qty,
'available_qty': inv_view.get('available_qty'),
'shortage_qty': inv_view.get('shortage_qty'),
'part_available_qty': inv_view.get('part_available_qty'),
'source_code': source_code,
'selected_source_code': selected_source_code,
'status': inv_view.get('user_line_status'),
@@ -1155,10 +1162,19 @@ def _build_stage_context(
}
def _build_edit_window(task: ShippingNotice) -> dict[str, Any]:
"""二期编辑窗(D10)谓词:header/lines 可编辑矩阵,工作台以此隐藏/禁用出单入口。"""
from app.services.shipping_notice import order_edit_window_service as order_edit_window
return order_edit_window.editable_scope(task)
def build_task_ui_state(
task: ShippingNotice,
*,
include_stage_context: bool = False,
viewer_user_id: int | None = None,
viewer_is_admin: bool = False,
) -> dict[str, Any]:
"""
构建单票任务 UI State。
@@ -1167,6 +1183,14 @@ def build_task_ui_state(
禁止 Chat、通知卡与任务中心分别推导状态;
可点击用户动作只由 Gate 与已验证 Artifact 授权产生。
Gate 摘要只查一次,再派生 position/user_mode,禁止再走 resolve_task_ui_state 二次查库。
Args:
task: 源任务实体。
include_stage_context: 是否附带 stage_context(工作面只读事实)。
viewer_user_id: 当前查看者;给定时时 download_excel 动作按导出统一谓词
(can_download_task_export:创建者或管理员)门禁下发;为 None 时维持
聊天链路旧口径(仅按 Artifact 授权,聊天会话与创建者同源)。
viewer_is_admin: 查看者是否平台管理员(配合 viewer_user_id 使用)。
"""
from app.services.shipping_notice.state_machine import (
_review_status_fallback_ui_state,
@@ -1207,7 +1231,12 @@ def build_task_ui_state(
# [AUTHORITY] Gate 负责当前可写恢复动作;Excel 下载是已产出文件的只读动作,
# 两者不能相互覆盖。即使当前 Gate 阻断并清空旧动作,也只在
# Artifact 已通过 resolve_task_export_download 校验时补入下载授权。
if resolve_task_export_download(task) is not None:
# 下载动作与导出端点消费同一谓词:viewer 已知时按创建者/管理员门禁,
# 避免非创建者"看得到点不动";viewer 未知(聊天链路)维持 Artifact 口径。
if resolve_task_export_download(task) is not None and (
viewer_user_id is None
or can_download_task_export(task, user_id=int(viewer_user_id), is_admin=viewer_is_admin)
):
download_action = _unified_action({
'id': 'download_excel',
'label': '下载 Excel',
@@ -1247,6 +1276,10 @@ def build_task_ui_state(
)
if include_stage_context else None
)
edit_window = (
_build_edit_window(task)
if include_stage_context else None
)
reason = None
if isinstance(process_gate, dict) and process_gate.get("blocking_reason_code"):
reason = {
@@ -1268,6 +1301,9 @@ def build_task_ui_state(
"actions": actions,
# 仅正式详情按需返回的工作面只读事实;不产生状态、权限或动作。
**({'stage_context': stage_context} if stage_context is not None else {}),
# 二期编辑窗门控矩阵(无 Export Artifact 且无活动 Attempt 才可编辑);
# 波次出单工具条与字段编辑守卫的数据源,禁止再次静默丢失。
**({'edit_window': edit_window} if edit_window is not None else {}),
"reason": reason,
# OT 与 Notice 字段不完全同构:禁止硬读 Notice 专属列。
"lifecycle_status": getattr(task, "lifecycle_status", None) or getattr(task, "status", None),
Loaded 100 of 337 files, more files were not shown because too many files have changed in this diff. Show more