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
HTEWJ\26070045 f0ac888d60 Merge branch 'dev' into order-delivery-reply
# Conflicts:
#	backend/app/services/schedule/job_options.py
#	frontend/src/locales/th/admin.json
#	frontend/src/locales/zh-TW/admin.json
2026-09-30 08:45:11 +08: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
HTEWJ\26070045 821bd0a62c Merge branch 'dev' into order-delivery-reply
# Conflicts:
#	backend/app/models/user.py
#	docs/demand.md
#	docs/funclist.md
#	frontend/src/features/auth/stores/auth.store.ts
#            dev existing problems
2026-09-29 16:38:05 +08:00
HTEWJ\26070045 e87dca85a3 test(admin): 移除已随 dev 下线的权限申请审批用例 2026-09-29 15:09:58 +08:00
HTEWJ\26070045 42d8b70250 Merge branch 'dev' into order-delivery-reply
# Conflicts:
#	backend/app/__init__.py
#	backend/app/services/admin/permission_service.py
#	frontend/src/features/user/views/UserProfilePage.vue
#	frontend/src/locales/en/admin.json
#	frontend/src/locales/th/admin.json
#	frontend/src/locales/zh-CN/admin.json
#	frontend/src/locales/zh-TW/admin.json
2026-09-29 15:08:04 +08:00
sophie 863e009b59 feat(training): 原型图 2026-09-29 09:19:33 +08:00
HTEWJ\26070045 298fadf1c8 Merge branch 'dev' into order-delivery-reply
# Conflicts:
#backend/app/core/config/settings.py
2026-09-23 12:01:15 +08:00
HTEWJ\26070045 36868f875c chore(order-delivery-reply): 前端页面调整、细节修改、优化逻辑等 2026-09-23 10:31:34 +08:00
HTEWJ\26070045 7fb36b301c Merge branch 'dev' into order-delivery-reply
# Conflicts:
#	frontend/src/locales/en/admin.json
#	frontend/src/locales/th/admin.json
#	frontend/src/locales/zh-TW/admin.json
2026-09-22 11:57:14 +08:00
HTEWJ\26070045 616034a4cd Merge branch 'dev' into order-delivery-reply
# Conflicts:
#	.env.shared
#	backend/app/api/chat.py
#	backend/app/core/config/settings.py
#	backend/app/models/user.py
#	backend/app/services/admin/permission_service.py
#	docs/demand.md
#	frontend/src/app/router/routes/workspace.routes.ts
#	frontend/src/features/admin/modules/users/components/UserFormModal.vue
#	frontend/src/features/admin/modules/users/composables/useUsersAdmin.ts
#	frontend/src/features/admin/types/user.types.ts
#	frontend/src/features/auth/stores/auth.store.ts
#	frontend/src/features/user/views/UserProfilePage.vue
#	frontend/src/locales/en/admin.json
#	frontend/src/locales/en/errors.json
#	frontend/src/locales/th/admin.json
#	frontend/src/locales/th/errors.json
#	frontend/src/locales/zh-CN/admin.json
#	frontend/src/locales/zh-CN/errors.json
#	frontend/src/locales/zh-TW/admin.json
#	frontend/src/locales/zh-TW/errors.json
#	frontend/src/shared/utils/auth.ts
2026-09-22 10:37:59 +08:00
HTEWJ\26070045 3de24fd373 style(order-delivery-reply): 页面样式调整 2026-09-21 17:29:54 +08:00
super 8d14b8a100 Merge branch 'dev' into super 2026-09-21 17:07:47 +08:00
HTEWJ\26070045 49f6a0f222 feat(order-delivery-reply): 新增订单交期回复工作台 2026-09-21 15:40:15 +08:00
380 changed files with 41231 additions and 7151 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,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' }
+18 -1
View File
@@ -122,6 +122,21 @@ 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()
except Exception as exc: # pragma: no cover - 表未就绪时容忍
logger.warning('Failed to ensure order-delivery-reply schedule: %s', exc)
try:
from app.services.order_delivery_reply.app_seed import ensure_builtin_order_delivery_agent
ensure_builtin_order_delivery_agent()
except Exception as exc: # pragma: no cover - 表未就绪时容忍
logger.warning('Failed to ensure order-delivery-reply agent: %s', exc)
try:
from app.services.lean_training_schedule_seed import ensure_default_lean_training_schedule
ensure_default_lean_training_schedule()
@@ -129,7 +144,9 @@ def create_app(config_name='default'):
logger.warning('Failed to ensure lean-training schedule: %s', exc)
else:
logger.info('Skip startup schedule seeding: schedule_tasks table is not ready')
# 固资快照同步已迁至独立进程 workers/worker_fixed_assets.py,Web 不再起线程。
# 固资快照同步已迁至独立进程 workers/worker_fixed_assets.py,Web 不再起线程;
# 排程执行同样由独立 worker 进程(workers/worker_scheduler.py,生产 hxops-schedule-worker 容器)
# 负责(dev Wave 4),Web 进程不再兜底扫描。
# AUTO_UPLOAD 显式开启时启动级校验货代上传 RPA(仅告警,不阻断启动)。
try:
from app.services.shipping_notice.rpa_worker_heartbeat import (
+4
View File
@@ -49,6 +49,8 @@ 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
@@ -80,5 +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')
+3
View File
@@ -39,6 +39,7 @@ def chat_completions():
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
conversation_id = data.get('conversation_id')
shipping_task_id = str(data.get('task_id') or '').strip()
shipping_batch_no = str(data.get('batch_no') or '').strip()
kb_type = data.get('kb_type', '企业知识库')
files = data.get('files')
request_id = uuid.uuid4().hex[:12]
@@ -174,6 +175,7 @@ def chat_completions():
normalized_files=normalized_files,
adapter_hints=_build_chat_adapter_hints(
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
),
shipping_task_id=shipping_task_id,
kb_type=kb_type,
@@ -214,6 +216,7 @@ def chat_completions():
user_role=user_proxy.role,
adapter_hints=_build_chat_adapter_hints(
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
),
),
)
+5 -3
View File
@@ -10,19 +10,21 @@ from __future__ import annotations
from .shared import * # noqa: F403
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None) -> dict | None:
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_batch_no: str | None = None) -> dict | None:
"""
构建聊天入口分发给领域 adapter 的提示字典。
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task 提示,
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示,
统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。
"""
task_id = str(shipping_task_id or '').strip()
if not task_id:
batch_no = str(shipping_batch_no or '').strip()
if not task_id and not batch_no:
return None
return {
'shipping_notice': {
'task_id': task_id or None,
'batch_no': batch_no or None,
}
}
@@ -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():
+320
View File
@@ -0,0 +1,320 @@
"""
backend/app/api/order_delivery_reply.py
用途:订单交期回复工作台 API——列表筛选分页、单行详情、最近同步时间、保存交期批次、单行通知、
联合回复保存与批量通知、手动全量同步。
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError/NotFoundError/ValidationError、
services/order_delivery_reply(query_service 查询、reply_service 保存批次、
notify_service 通知锁定、sync_service 同步状态)。
逻辑:读取只打本地快照,不触碰 ERP;保存批次只写批次与 save 审计,不通知不锁定;
通知与锁定在 notify_service 中同事务完成(企微成功才锁定)。
权限要求 access 或 manage(manage 隐含 access),键常量与技术文档 §7.2 一致;写接口要求 manage。
鉴权:GET 系列要求 `order_delivery_reply.access` 或 `order_delivery_reply.manage`;
保存批次 / 单行通知 / 联合回复 / 批量通知 / 手动同步要求 `order_delivery_reply.manage`;
部门批量发放仅 admin 角色。两键 admin 默认开(User._role_default_feature_permissions)。
"""
from __future__ import annotations
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
from app.core.response import ok
from app.extensions import db
from app.models import User
from app.services.order_delivery_reply import notify_service, query_service, reply_service
from app.services.order_delivery_reply.sync_service import OrderDeliverySyncService
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:
"""
把后端 naive-UTC 时间转为北京时间的展示字符串(YYYY-MM-DD HH:MM:SS)。
用途:sync_runs / notified_at 等以 utcnow 落库,直接 isoformat 会把 UTC 当本地时间误导用户。
约束:仅用于展示序列化,不改变库内存储;无法解析时原样返回。
"""
from datetime import timezone
from zoneinfo import ZoneInfo
if value is None:
return None
try:
local = value.replace(tzinfo=timezone.utc).astimezone(ZoneInfo("Asia/Shanghai"))
return local.strftime("%Y-%m-%d %H:%M:%S")
except (AttributeError, ValueError):
return value.isoformat() if hasattr(value, "isoformat") else str(value)
# 功能权限键(与 docs/features/order-delivery-reply/technical-design.md §7.2 对齐)。
PERMISSION_MANAGE = "order_delivery_reply.manage"
PERMISSION_ACCESS = "order_delivery_reply.access"
def _require_user():
"""返回当前登录用户;未认证抛 UnauthorizedError。"""
user = get_current_user()
if not user:
raise UnauthorizedError()
return user
def _has_order_delivery_permission(user, key: str) -> bool:
"""
判定功能权限:统一走 User.has_feature_permission(角色默认 + 显式勾选合并)。
核心逻辑:admin 角色两键默认开(User._role_default_feature_permissions);
普通用户按用户管理表单勾选;每次请求只看勾选,不拿部门当门禁(技术文档 §7.2)。
"""
return user.has_feature_permission(key)
def _require_access():
"""
确保当前用户可访问订单交期回复(查看)。
Raises:
UnauthorizedError: 未登录。
ForbiddenError: 已登录但既无 manage 也无 access(manage 命中视为有 access)。
"""
user = _require_user()
if not (_has_order_delivery_permission(user, PERMISSION_MANAGE) or _has_order_delivery_permission(user, PERMISSION_ACCESS)):
raise ForbiddenError(
"Order delivery reply access required",
code="ORDER_DELIVERY_REPLY.FORBIDDEN",
)
return user
def _require_manage():
"""
确保当前用户可写订单交期回复(保存批次 / 通知 / 手动同步)。
Raises:
UnauthorizedError: 未登录。
ForbiddenError: 已登录但无 manage(仅有 access 的业务用户只读)。
"""
user = _require_user()
if not _has_order_delivery_permission(user, PERMISSION_MANAGE):
raise ForbiddenError(
"Order delivery reply manage permission required",
code="ORDER_DELIVERY_REPLY.MANAGE_FORBIDDEN",
)
return user
@order_delivery_reply_bp.get("/lines")
def list_lines():
"""
订单行列表(筛选 + 分页)。
用途与触发时机:工作台首屏与筛选刷新;全选仅作用于本页返回的 items。
参数与输出约束:查询参数 keyword/order_date/status/page/page_size——keyword 为合并搜索
(订单单号/客户订单/客户编号/客户简称/公司全名/产品编号/品名/客户产品编号
命中任一即返回);status ∈ 空(全部) | replied(已回复) | not_fully_replied(未完全回复);
返回统一 envelope,data.items 为行序列化(含批次、状态、未交数量)。
"""
_require_access()
data = query_service.list_lines(request.args.to_dict(flat=True))
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):
"""
单行详情:快照 + 批次 + 状态 + 审计事件。
参数与输出约束:order_no/line_no 为行唯一键;不存在或已标 erp_missing(已不在同步范围)
的行一律按不存在处理返回 404,不在工作台展示。
"""
_require_access()
payload = query_service.get_line(order_no, line_no)
if payload is None:
raise NotFoundError(
"Order delivery line not found",
code="ORDER_DELIVERY_REPLY.LINE_NOT_FOUND",
)
return ok(payload, request_id=getattr(g, "request_id", None))
@order_delivery_reply_bp.put("/lines/<order_no>/<int:line_no>/batches")
def save_line_batches(order_no: str, line_no: int):
"""
保存单行交期批次(未锁定行整表替换)。
用途与触发时机:单行弹窗「回复交期/修改回复」提交;联合回复保存逐行复用同一服务入口。
参数与输出约束:body {"batches": [{planned_date, qty, remark?}]};交期必填 YYYY-MM-DD、
数量 > 0、备注 ≤ 200、批次 1..20 条且交期不重复;各批次合计必须等于订单数量,
不等返回 422 BATCH_QTY_TOTAL_MISMATCH(2026-09-23 由「超额仅提醒」修订)。
已锁定行返回 409 LINE_LOCKED;erp_missing 行按 404。
"""
user = _require_manage()
payload = request.get_json(silent=True) or {}
data = reply_service.save_batches(order_no, line_no, payload.get("batches"), user.id)
return ok(data, request_id=getattr(g, "request_id", None))
@order_delivery_reply_bp.post("/lines/<order_no>/<int:line_no>/notify")
def notify_line(order_no: str, line_no: int):
"""
单行发送通知业务部门(企微),成功后行级锁定。
用途与触发时机:生管在行内点「发送通知业务部门」(该行已有批次且未锁定时可用)。
参数与输出约束:无 body;无批次 422(请先回复交期)、已锁定 409、业务员对不上
User.employee_id 或企微发送失败 503(该行不锁定);成功返回
locked=true 与交期回复人员(生管工号+姓名)、通知时间、trace_id。
"""
user = _require_manage()
data = notify_service.notify_line(order_no, line_no, user)
return ok(data, request_id=getattr(g, "request_id", None))
@order_delivery_reply_bp.post("/batch-reply")
def batch_reply():
"""
联合回复交期:对勾选多行逐行保存批次(只保存,不通知、不锁定)。
用途与触发时机:勾选多行 →「+ 联合回复交期」→ 按行填批次 → 保存回复(R-REPLY-02)。
参数与输出约束:body {"items": [{order_no, line_no, batches: [{planned_date, qty, remark?}]}]},
单次 ≤ 200 行;每行各批次合计必须等于订单数量(不等该行失败,2026-09-23 修订);
单行失败不回滚其它行,响应按行给 ok/error;
全部行保存成功 success 才为 true 语义由 data.succeeded/failed 表达。
"""
user = _require_manage()
payload = request.get_json(silent=True) or {}
data = reply_service.batch_reply(payload.get("items"), user.id)
return ok(data, request_id=getattr(g, "request_id", None))
@order_delivery_reply_bp.post("/notify-batch")
def notify_batch():
"""
批量通知:对勾选中「已有批次且未锁定」的行逐行发送企微通知并锁定。
用途与触发时机:勾选多行 → 工具栏「批量通知」(R-NOTIFY-02);与联合回复是两个独立操作。
参数与输出约束:body {"lines": [{order_no, line_no}]},单次 ≤ 200 行;
无批次或已锁定的勾选行 skipped(带 reason)不计成败;
单行失败不回滚其它行;返回 succeeded/failed/skipped 与逐行结果。
"""
user = _require_manage()
payload = request.get_json(silent=True) or {}
data = notify_service.notify_batch(payload.get("lines"), user)
return ok(data, request_id=getattr(g, "request_id", None))
@order_delivery_reply_bp.get("/sync/latest")
def latest_sync():
"""
最近一次同步运行记录,供页面展示同步时间与结果。
参数与输出约束:无参数;从未同步过时 data 为 null(前端展示「尚未同步」),
失败时返回 failed 状态与错误摘要,前端明示同步失败并保留上次快照口径。
"""
_require_access()
run = OrderDeliverySyncService.latest_run()
if run is None:
return ok(None, request_id=getattr(g, "request_id", None))
return ok(
{
"id": run.id,
"trigger": run.trigger,
"status": run.status,
"started_at": _utc_to_shanghai(run.started_at),
"finished_at": _utc_to_shanghai(run.finished_at),
"line_count": run.line_count,
"error_message": run.error_message,
},
request_id=getattr(g, "request_id", None),
)
@order_delivery_reply_bp.post("/sync")
def run_sync():
"""
手动触发一次 ERP 全量同步(范围与 07:00 排程完全一致)。
用途与触发时机:生管在工作台点「手动刷新」(需求 §15);同步互斥——排程正在跑时
返回 skipped,不并发执行。
参数与输出约束:无 body;同步在本请求内同步执行(一期口径,行量在万级内可控),
返回 {run_id, status: success|skipped, line_count};失败原样抛 AppError
(上次快照保留,页面明示失败原因)。
"""
_require_manage()
data = OrderDeliverySyncService.run_sync(trigger="manual")
return ok(data, request_id=getattr(g, "request_id", None))
@order_delivery_reply_bp.post("/admin/permissions/grant-by-department")
def grant_permissions_by_department():
"""
按部门批量发放订单交期回复功能权限(可选能力,仅 admin)。
用途与触发时机:用户量大时管理员选部门一次性把勾选写到当时该部门成员账号上(需求 §3)。
参数与输出约束:body {"department": "<部门名>", "permission": "manage" | "access"};
这是一次性发放——调岗后权限不随部门字段变化自动增减,需再勾或再跑一次;
只做授予(置 true),不撤销;返回 {"department", "permission", "granted"}。
部门无成员时 granted=0,不视为错误。
"""
user = _require_user()
if getattr(user, "role", None) != "admin":
raise ForbiddenError(
"Admin privilege required for department permission grant",
code="ORDER_DELIVERY_REPLY.ADMIN_REQUIRED",
)
payload = request.get_json(silent=True) or {}
department = str(payload.get("department") or "").strip()
permission = str(payload.get("permission") or "").strip()
if not department:
raise ValidationError("department 必填", code="ORDER_DELIVERY_REPLY.GRANT_DEPARTMENT_REQUIRED")
if permission not in (PERMISSION_MANAGE, PERMISSION_ACCESS):
raise ValidationError("permission 须为 manage 或 access", code="ORDER_DELIVERY_REPLY.GRANT_PERMISSION_INVALID")
members = User.query.filter(User.department == department).all()
granted = 0
for member in members:
# [STEP] 经 set_feature_permissions 归一化:只持久化与角色默认不同的覆盖项。
raw = dict(member.feature_permissions) if isinstance(member.feature_permissions, dict) else {}
raw[permission] = True
member.set_feature_permissions(raw)
granted += 1
db.session.commit()
return ok(
{"department": department, "permission": permission, "granted": granted},
request_id=getattr(g, "request_id", None),
)
+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'],
+9 -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,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 不同,动态解析保证卡片均可定位「员工培训-精益管理」);
@@ -553,6 +553,13 @@ class Config:
SCHEDULE_WORKER_ENABLED = os.getenv('SCHEDULE_WORKER_ENABLED', 'true').lower() == 'true'
SCHEDULE_WORKER_POLL_SECONDS = float(os.getenv('SCHEDULE_WORKER_POLL_SECONDS', '30') or '30')
SCHEDULE_JOB_RUNNING_TIMEOUT_SECONDS = float(os.getenv('SCHEDULE_JOB_RUNNING_TIMEOUT_SECONDS', '7200') or '7200')
# Web 进程内排程兜底扫描:仅本地开发(ENV_NAME=dev,无 schedule-worker 容器)默认开启;
# test/prod 由 hxops-schedule-worker 容器负责(run.py 固定走 DevelopmentConfig,不能按配置类判定)。
_scanner_env_raw = str(os.getenv('SCHEDULE_WEB_SCANNER_ENABLED') or '').strip().lower()
if _scanner_env_raw:
SCHEDULE_WEB_SCANNER_ENABLED = _scanner_env_raw in ('1', 'true', 'yes', 'on')
else:
SCHEDULE_WEB_SCANNER_ENABLED = _normalize_env_name(os.getenv('ENV_NAME') or ACTIVE_ENV_NAME) == 'dev'
# Cron 表达式按此时区解读(如 0 12 * * * 表示该时区 12:00);入库 next_run_at 仍为 UTC。
SCHEDULE_TIMEZONE = (os.getenv('SCHEDULE_TIMEZONE') or 'Asia/Shanghai').strip()
SRM_SQLSERVER_HOST = os.getenv('SRM_SQLSERVER_HOST', '')
@@ -778,6 +785,7 @@ class TestingConfig(Config):
WTF_CSRF_ENABLED = False
SQLALCHEMY_ENGINE_OPTIONS = {}
SCHEDULE_WORKER_ENABLED = False
SCHEDULE_WEB_SCANNER_ENABLED = False
FIXED_ASSETS_SYNC_ENABLED = False
FIXED_ASSETS_EXPORT_TO_DOCS = False
ENV_NAME = 'dev'
@@ -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',
+27 -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,21 @@ 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,
OrderDeliveryErpLine,
OrderDeliveryLineState,
OrderDeliverySyncRun,
)
from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit
__all__ = [
@@ -427,6 +442,12 @@ __all__ = [
'ContractPaymentAlert',
'ContractPaymentAlertBatch',
'ContractPaymentSyncState',
'EquipmentAcceptanceOrder',
'EquipmentAcceptanceNode',
'EquipmentAcceptanceOperator',
'EquipmentAcceptanceSetting',
'EquipmentAcceptanceSendFile',
'EquipmentAcceptanceSendRecord',
'TransferRun',
'TransferSourceJob',
'TransferMatching',
@@ -440,4 +461,9 @@ __all__ = [
'IntegrationInterfaceDefinition',
'IntegrationBinding',
'IntegrationCall',
'OrderDeliveryErpLine',
'OrderDeliveryBatch',
'OrderDeliveryLineState',
'OrderDeliveryAuditEvent',
'OrderDeliverySyncRun',
]
+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)
+146
View File
@@ -0,0 +1,146 @@
"""
backend/app/models/order_delivery_reply.py
用途:订单交期回复域模型,保存 ERP 订单行快照、交期批次、行级锁定状态、审计与同步运行记录。
依赖:models.base.Base、users。
逻辑:同步服务只写 erp_lines 的 ERP 快照列;保存回复只写 batches;通知成功路径才写
line_states.locked;audit_events 记录保存/通知/锁定/同步;sync_runs 记录每次同步。
工作台所有读取只打本地库,禁止回写 ERP。
"""
from __future__ import annotations
from datetime import date, datetime
from decimal import Decimal
from typing import Any, Optional
from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Index, JSON, Numeric, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class OrderDeliveryErpLine(Base):
"""ERP 销售订单行快照(订单单号+项次唯一);仅同步服务写入 ERP 列,不覆盖批次与锁定。"""
__tablename__ = "order_delivery_erp_lines"
__table_args__ = (
UniqueConstraint("order_no", "line_no", name="uq_order_delivery_erp_lines_order_line"),
Index("ix_order_delivery_erp_lines_order_date", "order_date"),
Index("ix_order_delivery_erp_lines_customer_no", "customer_no"),
Index("ix_order_delivery_erp_lines_salesperson", "salesperson_code"),
Index("ix_order_delivery_erp_lines_slip_code", "slip_code"),
)
id: Mapped[int] = mapped_column(primary_key=True)
order_no: Mapped[str] = mapped_column(String(64), nullable=False)
line_no: Mapped[int] = mapped_column(nullable=False)
order_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
customer_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
customer_short_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
customer_full_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
# salesperson_code 对 HXOPS User.employee_id,供企微收件人映射;列表展示 salesperson_name。
salesperson_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
salesperson_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
dept_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
dept_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
customer_po: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
part_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
part_name: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
spec: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
customer_part_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
agreed_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 4), nullable=True)
delivered_qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 4), nullable=True)
# 单别取 oea01 连字符前段(8301-1605280014 → 8301);一期只落库预留,不展示不过滤。
slip_code: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
# 本轮同步未命中但已有批次或锁定的行不删除,置 true 后默认列表不展示。
erp_missing: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False, index=True)
last_synced_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
class OrderDeliveryBatch(Base):
"""订单行的交期批次(计划交期+数量+备注);未锁定行保存时整表替换。仅保存回复路径写入。"""
__tablename__ = "order_delivery_batches"
__table_args__ = (
UniqueConstraint("line_id", "seq", name="uq_order_delivery_batches_line_seq"),
Index("ix_order_delivery_batches_line", "line_id"),
)
id: Mapped[int] = mapped_column(primary_key=True)
line_id: Mapped[int] = mapped_column(
ForeignKey("order_delivery_erp_lines.id", ondelete="CASCADE"), nullable=False
)
seq: Mapped[int] = mapped_column(nullable=False)
planned_date: Mapped[date] = mapped_column(Date, nullable=False)
qty: Mapped[Decimal] = mapped_column(Numeric(18, 4), nullable=False)
# 备注 ≤ 200 字符,由 API 层校验。
remark: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
class OrderDeliveryLineState(Base):
"""订单行锁定状态(一行一态);仅通知成功路径写入 locked=true,与通知同一事务。"""
__tablename__ = "order_delivery_line_states"
__table_args__ = (
UniqueConstraint("line_id", name="uq_order_delivery_line_states_line"),
)
id: Mapped[int] = mapped_column(primary_key=True)
line_id: Mapped[int] = mapped_column(
ForeignKey("order_delivery_erp_lines.id", ondelete="CASCADE"), nullable=False
)
locked: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
# 交期回复人员 = 最近一次发送成功的生管;存快照工号+姓名便于审计回溯。
notified_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
notified_employee_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
notified_user_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
notified_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
class OrderDeliveryAuditEvent(Base):
"""订单交期回复审计:保存批次、发送通知、锁定、同步、出货提醒、未回复提醒六类动作。"""
__tablename__ = "order_delivery_audit_events"
__table_args__ = (
Index("ix_order_delivery_audit_events_line", "line_id"),
Index("ix_order_delivery_audit_events_action", "action", "created_at"),
)
id: Mapped[int] = mapped_column(primary_key=True)
# sync 事件无具体行时 line_id 为空。
line_id: Mapped[Optional[int]] = mapped_column(
ForeignKey("order_delivery_erp_lines.id", ondelete="CASCADE"), nullable=True
)
order_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
line_no: Mapped[Optional[int]] = mapped_column(nullable=True)
# save | notify | lock | sync | ship_remind(出货提醒,payload.ok=true 参与去重)| unreplied_remind(未回复再提醒)
action: Mapped[str] = mapped_column(String(32), nullable=False)
operator_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
payload_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class OrderDeliverySyncRun(Base):
"""订单交期同步运行记录;同步作业每次运行写一行,失败保留上次快照。"""
__tablename__ = "order_delivery_sync_runs"
__table_args__ = (
Index("ix_order_delivery_sync_runs_started", "started_at"),
)
id: Mapped[int] = mapped_column(primary_key=True)
trigger: Mapped[str] = mapped_column(String(16), nullable=False) # scheduled | manual
status: Mapped[str] = mapped_column(String(16), nullable=False) # running | success | failed
started_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
line_count: Mapped[int] = mapped_column(default=0, nullable=False)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
@@ -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)
+5
View File
@@ -100,6 +100,11 @@ class User(Base):
'shipping_notice.xfa_split_rule_preview': admin,
'shipping_notice.xfa_split_rule_publish': admin,
'maintenance.ledger_write': admin,
# 合同付款预警已改走 Agent 授权(agent_code=contract_payment),不再占用功能权限键。
# 订单交期回复:manage=生管可写(保存/通知/同步),access=业务只读;
# manage 命中视为有 access(判定见 api/order_delivery_reply.py)。
'order_delivery_reply.manage': admin,
'order_delivery_reply.access': admin,
}
def is_platform_admin(self) -> bool:
@@ -228,10 +228,10 @@ def _section_type_for_line(line: str) -> str | None:
def _extract_repeated_section_answers(lines: list[str]) -> dict[str, list[str]]:
"""提取 PDF 后半段按小节重复出现的填空标准答案,避免把答案行当作新题目。"""
"""提取 PDF 后半段按小节重复出现的填空/判断标准答案,避免把答案行当作新题目。"""
occurrences: dict[str, int] = {}
active_type: str | None = None
answers: dict[str, list[str]] = {'fill': []}
answers: dict[str, list[str]] = {'fill': [], 'boolean': []}
in_answer_sheet = False
for line in lines:
if _is_answer_section_heading(line):
@@ -241,17 +241,34 @@ def _extract_repeated_section_answers(lines: list[str]) -> dict[str, list[str]]:
section_type = _section_type_for_line(line)
if section_type:
occurrences[section_type] = occurrences.get(section_type, 0) + 1
if occurrences[section_type] > 1:
in_answer_sheet = True
active_type = section_type if occurrences[section_type] > 1 or in_answer_sheet else None
repeated = occurrences[section_type] > 1
in_answer_sheet = in_answer_sheet or repeated
active_type = section_type if (repeated or in_answer_sheet) else None
# 小节标题行自带答案内容(如「二、判断题:1-2、√ ×」):去掉标题前缀后按判断答案表解析
if in_answer_sheet and section_type == 'boolean':
remainder = _BOOLEAN_SECTION_PATTERN.sub('', _normalize_spaces(line), count=1)
remainder = remainder.lstrip('一二三四五六七八九十、..::\t (()) ')
if remainder and not _QUESTION_START_PATTERN.match(remainder):
for raw_token in _BOOLEAN_TOKEN_PATTERN.findall(remainder):
answer = _normalize_answer_token(raw_token)
if answer:
answers['boolean'].append(answer)
continue
if not in_answer_sheet or active_type != 'fill':
if not in_answer_sheet or active_type not in {'fill', 'boolean'}:
continue
match = _QUESTION_START_PATTERN.match(line)
if match:
value = _normalize_spaces(match.group(2))
if value:
answers['fill'].append(value)
if not match:
continue
value = _normalize_spaces(match.group(2))
if not value:
continue
if active_type == 'fill':
answers['fill'].append(value)
elif ' ' not in value:
# 判断答案行只接受整行单 token(如「1、√」);带空格的多题答案表交由题号映射解析
answer = _normalize_answer_token(value)
if answer:
answers['boolean'].append(answer)
return answers
@@ -320,11 +337,12 @@ def _split_question_blocks(lines: list[str]) -> list[tuple[int, str, str | None]
continue
if current_section_type == 'answer_sheet' or (current_section_type and current_section_type.startswith('answer_')):
continue
if _is_answer_sheet_line(line):
continue
# 题干匹配必须先于答案表过滤:行内答案题干(如「1. 题干… 答案:C 解析:…」)整行含「答案」,
# 若先走答案表过滤会被整体丢弃导致整卷解析为空(2026-09-29 修复,原顺序该分支为死代码)。
question_match = _QUESTION_START_PATTERN.match(line)
if question_match:
if _is_answer_sheet_line(line) and '答案' not in line:
# 疑似答案表行(如「1.B 2.A 3.正确」)即使形如题干也不生成题目
continue
if current_no is not None and current_lines:
blocks.append((current_no, ' '.join(current_lines).strip(), current_section_type))
@@ -480,6 +498,7 @@ def parse_training_question_bank_text(text: str) -> dict[str, Any]:
question_bank: list[dict[str, Any]] = []
skipped_questions: list[int] = []
fill_answer_index = 0
boolean_answer_index = 0
# [STEP 1] 先按题号切块,再对每一块做题型、答案和解析判定,避免跨题串行污染。
answer_sequence_index = 0
@@ -497,6 +516,17 @@ def parse_training_question_bank_text(text: str) -> dict[str, Any]:
mapped_answer=answer_map.get(question_no, ''),
ordered_answer=ordered_answer,
)
if section_type == 'boolean':
# 分节重复答案区(如「二、判断题 1、√」「二、判断题:1-2、√ ×」)提取到的判断答案
# 作为兜底候选补入;内联/题号映射/整卷顺序命中时仍优先。
repeated_answer = (
repeated_section_answers['boolean'][boolean_answer_index]
if boolean_answer_index < len(repeated_section_answers['boolean'])
else ''
)
boolean_answer_index += 1
if repeated_answer and repeated_answer not in answer_candidates:
answer_candidates.append(repeated_answer)
if section_type == 'boolean':
for answer in answer_candidates:
question_payload = _build_boolean_question(
+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}
@@ -0,0 +1,13 @@
"""
backend/app/services/order_delivery_reply/__init__.py
用途:订单交期回复域服务包入口;聚合导出同步服务与 SQL 常量。
依赖:本包 sql / sync_service。
逻辑:API 层(app/api/order_delivery_reply.py)与排程种子经此包调用同步;scripts/order_delivery_query.py
复用 ORDER_DELIVERY_SQL 保持取数口径一致。
"""
from app.services.order_delivery_reply.sql import ORDER_DELIVERY_SQL
from app.services.order_delivery_reply.sync_service import OrderDeliverySyncService
__all__ = ["ORDER_DELIVERY_SQL", "OrderDeliverySyncService"]
@@ -0,0 +1,57 @@
"""
backend/app/services/order_delivery_reply/app_seed.py
用途:把「订单交期回复」注册为应用管理中的内置 iframe 应用(不接 Dify)。
依赖:models.Agent;启动时由 app/__init__.py 幂等调用。
逻辑:按 agent_code 幂等创建一条 runtime_provider='iframe' 的 Agent 记录,
iframe_url 指向前端免布局嵌入路由 /apps/order-delivery-reply;
在聊天壳内整页渲染工作台操作页。应用的可见性走 Agent 权限
(admin 自动可见,普通用户在用户管理授权);页面与 API 仍由
order_delivery_reply.access/manage 功能权限守卫,两层各司其职。
管理员可在应用管理中修改名称/描述/图标/排序,但不应把
runtime_provider 改回 dify(本应用没有 Dify 绑定)。
"""
from __future__ import annotations
from datetime import datetime
from app import db
from app.models import Agent
ORDER_DELIVERY_AGENT_CODE = 'order_delivery_reply'
ORDER_DELIVERY_IFRAME_URL = '/apps/order-delivery-reply'
def ensure_builtin_order_delivery_agent(*, commit: bool = True):
"""
幂等创建订单交期回复内置应用(iframe 型,非 Dify)。
Args:
commit: 是否提交;测试或外层事务可传 False。
Returns:
新建的 Agent;已存在时返回 None。
"""
existing = Agent.query.filter_by(agent_code=ORDER_DELIVERY_AGENT_CODE).first()
if existing:
return None
agent = Agent(
name='订单交期回复',
description='查单 → 填交期 → 通知业务员;ERP 订单交期回复工作台',
agent_code=ORDER_DELIVERY_AGENT_CODE,
runtime_provider='iframe',
conversation_mode='embedded',
iframe_url=ORDER_DELIVERY_IFRAME_URL,
dify_app_id=None,
dify_api_key=None,
is_active=True,
category='业务应用',
sort_order=0,
created_at=datetime.utcnow(),
)
db.session.add(agent)
if commit:
db.session.commit()
else:
db.session.flush()
return agent
@@ -0,0 +1,281 @@
"""
backend/app/services/order_delivery_reply/notify_service.py
用途:订单交期回复的通知与锁定——按行通知订单业务员(企微)、成功后行级锁定并留痕。
依赖:wecom_notify.send_wecom_event_message(平台统一 textcard,本域只传业务参数)、
models/order_delivery_reply、models.User(employee_id → wecom_userid 映射)、extensions.db。
逻辑:发送成功与 locked=true 在同一事务提交(禁止「已通知未锁定」);失败不锁定;
收件人是订单业务员(oea14 → User.employee_id),与操作人(生管)无关;
交期回复人员 = 最近一次发送成功的生管工号+姓名(R-NOTIFY-03)。
批量通知(第 5 步)逐行复用本模块,单行失败不回滚其它行。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from sqlalchemy import select
from app.core.errors import (
ConflictError,
NotFoundError,
ServiceUnavailableError,
ValidationError,
)
from app.extensions import db
from app.models import User
from app.models.order_delivery_reply import (
OrderDeliveryAuditEvent,
OrderDeliveryBatch,
OrderDeliveryErpLine,
OrderDeliveryLineState,
)
from app.services.integrations.wecom.notify import send_wecom_event_message
# 企微事件开关名;与 settings.WECOM_NOTIFY_EVENTS 默认值条目一致(同 contract_payment_warning 命名风格)。
WECOM_EVENT_TYPE = "order_delivery_reply_notify"
# 工作台跳转路由(前端第 8 步落地,带上该行查询参数直开行)。
JUMP_PATH = "/apps/order-delivery-reply" # 免布局嵌入路由:企微内打开不带工作台侧栏
def _load_line(order_no: str, line_no: int) -> OrderDeliveryErpLine:
"""按行唯一键取未 erp_missing 的快照行;不存在/不在同步范围抛 404。"""
line = db.session.scalar(
select(OrderDeliveryErpLine).where(
OrderDeliveryErpLine.order_no == order_no,
OrderDeliveryErpLine.line_no == line_no,
OrderDeliveryErpLine.erp_missing.is_(False),
)
)
if not line:
raise NotFoundError(
"Order delivery line not found",
code="ORDER_DELIVERY_REPLY.LINE_NOT_FOUND",
)
return line
def _load_state(line_id: int) -> OrderDeliveryLineState | None:
return db.session.scalar(
select(OrderDeliveryLineState).where(OrderDeliveryLineState.line_id == line_id)
)
def _resolve_recipient(line: OrderDeliveryErpLine) -> User:
"""
订单业务员 → HXOPS 用户:salesperson_code(oea14) 对 User.employee_id。
Returns:
对应 User。
Raises:
ServiceUnavailableError: 对不上或账号未绑企微——该行通知失败、不锁定(需求 §13)。
"""
recipient = db.session.scalar(
select(User).where(User.employee_id == (line.salesperson_code or "").strip())
)
if recipient is None or not (recipient.wecom_userid or "").strip():
raise ServiceUnavailableError(
f"业务员工号 {line.salesperson_code} 未关联 HXOPS 用户或未绑定企微,无法通知",
code="ORDER_DELIVERY_REPLY.SALESPERSON_UNMAPPED",
)
return recipient
def _send_line_notification(line: OrderDeliveryErpLine, recipient: User) -> dict[str, Any]:
"""
调平台既有 send_wecom_event_message 发送单行通知(textcard 壳、按钮、回执全用现成实现)。
参数与输出约束:content 按需求 §13 固定文案;jump_params 带该行唯一键供企微直达;
返回 {ok, trace_id, ...},成败以函数返回为准(回执只留痕不改状态)。
"""
return send_wecom_event_message(
event_type=WECOM_EVENT_TYPE,
user=recipient,
title="订单交期回复",
content=f"您有订单号:项次{line.order_no}:{line.line_no}的订单需要填写/确认/查看交期。",
jump_path=JUMP_PATH,
jump_params={"order_no": line.order_no, "line_no": line.line_no},
)
def notify_line(order_no: str, line_no: int, operator: User) -> dict[str, Any]:
"""
单行通知 + 锁定 + 审计(行内「发送通知业务部门」入口)。
用途与触发时机:生管在行内点「发送通知业务部门」;AI/排程不触发。
批量通知逐行复用本函数,外层保证单行失败不影响其它行。
核心逻辑:[STEP 1] 行存在校验;无批次 → 422(请先回复交期);已锁定 → 409;
[STEP 2] 解析收件人(订单业务员),对不上 → 该行失败不锁定;
[STEP 3] 发企微;发送失败 → 该行失败不锁定(503 NOTIFY_FAILED);
[STEP 4] 发送成功后同一事务写 locked + 交期回复人员快照 + notify/lock 审计并提交。
Args:
order_no / line_no: 行唯一键。
operator: 操作的生管(HXOPS 用户);交期回复人员取其工号+姓名。
Returns:
{"order_no", "line_no", "locked": true, "notified_user_name", "notified_at"}。
"""
# [STEP 1] 前置校验:无批次不能通知;已锁定不能重复通知。
line = _load_line(order_no, line_no)
state = _load_state(line.id)
if state and state.locked:
raise ConflictError(
"该订单行已通知锁定,无需重复通知",
code="ORDER_DELIVERY_REPLY.LINE_LOCKED",
)
batch_count = len(
db.session.scalars(
select(OrderDeliveryBatch.id).where(OrderDeliveryBatch.line_id == line.id)
).all()
)
if batch_count == 0:
raise ValidationError("请先回复交期再发送通知", code="ORDER_DELIVERY_REPLY.BATCHES_REQUIRED")
# [STEP 2] 收件人 = 订单业务员,与操作权限无关。
recipient = _resolve_recipient(line)
# [STEP 3] 先发送:成败以 send_wecom_event_message 返回为准;失败不写任何锁定状态。
result = _send_line_notification(line, recipient)
if not result.get("ok"):
raise ServiceUnavailableError(
"企微通知发送失败,该行未锁定",
code="ORDER_DELIVERY_REPLY.NOTIFY_FAILED",
details={"trace_id": result.get("trace_id"), "reason": result.get("reason")},
)
# [STEP 4] 发送成功 → 同一事务锁定 + 快照 + 审计;提交失败会整体回滚(宁可不锁定,禁止已通知未锁定)。
notified_at = datetime.utcnow()
if state is None:
state = OrderDeliveryLineState(line_id=line.id)
db.session.add(state)
state.locked = True
state.notified_user_id = operator.id
state.notified_employee_id = (operator.employee_id or "").strip() or None
state.notified_user_name = operator.real_name
state.notified_at = notified_at
db.session.add_all(
[
OrderDeliveryAuditEvent(
line_id=line.id,
order_no=line.order_no,
line_no=line.line_no,
action="notify",
operator_user_id=operator.id,
payload_json={
"recipient_employee_id": line.salesperson_code,
"recipient_wecom_userid": recipient.wecom_userid,
"trace_id": result.get("trace_id"),
"notified_at": notified_at.isoformat(),
},
),
OrderDeliveryAuditEvent(
line_id=line.id,
order_no=line.order_no,
line_no=line.line_no,
action="lock",
operator_user_id=operator.id,
payload_json={
"notified_employee_id": state.notified_employee_id,
"notified_user_name": state.notified_user_name,
"notified_at": notified_at.isoformat(),
},
),
]
)
db.session.commit()
return {
"order_no": line.order_no,
"line_no": line.line_no,
"locked": True,
"notified_employee_id": state.notified_employee_id,
"notified_user_name": state.notified_user_name,
"notified_at": notified_at.isoformat(),
"wecom_trace_id": result.get("trace_id"),
}
def notify_batch(raw_lines: list, operator: User) -> dict[str, Any]:
"""
批量通知:对勾选行逐行发送通知并锁定(无批次或已锁定的行跳过)。
用途与触发时机:工作台勾选多行后点工具栏「批量通知」(R-NOTIFY-02);
与「联合回复交期」是两个独立操作,本函数不做任何批次保存。
核心逻辑:[STEP 1] 校验请求结构(非空数组、每项含 order_no/line_no,上限 200);
[STEP 2] 逐行:无批次 → skipped;已锁定 → skipped;其余调 notify_line;
单行失败不回滚其它行(notify_line 每行独立事务),失败行带原因返回;
[STEP 3] 汇总 succeeded / failed / skipped 与各行结果。
Args:
raw_lines: [{"order_no", "line_no"}]。
operator: 操作的生管(HXOPS 用户)。
Returns:
{"succeeded": N, "failed": N, "skipped": N,
"items": [{order_no, line_no, ok, skipped?, reason?, data?}]}。
"""
from app.core.errors import AppError
if not isinstance(raw_lines, list) or not raw_lines:
raise ValidationError("lines 必须为非空数组", code="ORDER_DELIVERY_REPLY.NOTIFY_BATCH_EMPTY")
if len(raw_lines) > 200:
raise ValidationError("单次批量通知行数超过上限 200", code="ORDER_DELIVERY_REPLY.NOTIFY_BATCH_EMPTY")
def _key(item: dict) -> tuple[str, int] | None:
try:
order_no = str(item.get("order_no") or "").strip()
line_no = int(item.get("line_no"))
return (order_no, line_no) if order_no else None
except (TypeError, ValueError):
return None
results: list[dict[str, Any]] = []
for item in raw_lines:
if not isinstance(item, dict):
results.append({"ok": False, "error": "行格式不合法"})
continue
key = _key(item)
if key is None:
results.append({"ok": False, "error": "行唯一键缺失或格式不合法"})
continue
order_no, line_no = key
# [STEP 2] 跳过语义:无批次(不能通知)/ 已锁定(无需重复通知)不计入成败。
line = db.session.scalar(
select(OrderDeliveryErpLine).where(
OrderDeliveryErpLine.order_no == order_no,
OrderDeliveryErpLine.line_no == line_no,
OrderDeliveryErpLine.erp_missing.is_(False),
)
)
if line is None:
results.append({"order_no": order_no, "line_no": line_no, "ok": False, "error": "订单行不存在"})
continue
state = _load_state(line.id)
if state and state.locked:
results.append({"order_no": order_no, "line_no": line_no, "ok": True, "skipped": True, "reason": "already_locked"})
continue
has_batch = db.session.scalar(
select(OrderDeliveryBatch.id).where(OrderDeliveryBatch.line_id == line.id).limit(1)
)
if has_batch is None:
results.append({"order_no": order_no, "line_no": line_no, "ok": True, "skipped": True, "reason": "no_batches"})
continue
try:
data = notify_line(order_no, line_no, operator)
results.append({"order_no": order_no, "line_no": line_no, "ok": True, "data": data})
except AppError as exc:
# 单行失败不回滚其它行:notify_line 内部已按行提交或未写入。
db.session.rollback()
results.append({"order_no": order_no, "line_no": line_no, "ok": False, "error": exc.message})
return {
"succeeded": sum(1 for r in results if r.get("ok") and not r.get("skipped")),
"failed": sum(1 for r in results if not r.get("ok")),
"skipped": sum(1 for r in results if r.get("skipped")),
"items": results,
}
@@ -0,0 +1,410 @@
"""
backend/app/services/order_delivery_reply/query_service.py
用途:订单交期回复工作台只读查询——列表筛选分页、单行详情、状态推导与序列化。
依赖:models/order_delivery_reply(快照/批次/状态)、extensions.db。
逻辑:所有读取只打本地快照;行状态为读时推导(无批次=未回复,有批次未锁定=部分回复,
已锁定=已回复),筛选「已回复/未完全回复」据此下推到 SQL;erp_missing 行一律不返回。
本服务不做任何写操作,也不访问 ERP。
"""
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
from app.models.order_delivery_reply import (
OrderDeliveryAuditEvent,
OrderDeliveryBatch,
OrderDeliveryErpLine,
OrderDeliveryLineState,
)
# 状态筛选合法值:空/None = 全部。
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 注释。"""
from datetime import timezone
from zoneinfo import ZoneInfo
if value is None:
return None
try:
return value.replace(tzinfo=timezone.utc).astimezone(ZoneInfo("Asia/Shanghai")).strftime("%Y-%m-%d %H:%M:%S")
except (AttributeError, ValueError):
return value.isoformat() if hasattr(value, "isoformat") else str(value)
def _dec_str(value: Decimal | None) -> str | None:
"""
Numeric 序列化为去尾零的十进制字符串(80.0000 → "80",7.5000 → "7.5")。
用途:数量/未交数量展示;Postgres Numeric 保留列 scale,直接 str() 会带多余尾零。
约束:仅用于展示序列化,不改变库内精度。
"""
if value is None:
return None
text = format(value, "f")
if "." in text:
text = text.rstrip("0").rstrip(".")
return text or "0"
def _has_batch_subquery():
"""该订单行是否已存在交期批次的 EXISTS 子查询(状态推导用)。"""
return select(OrderDeliveryBatch.line_id).where(OrderDeliveryBatch.line_id == OrderDeliveryErpLine.id).exists()
def _locked_subquery():
"""该订单行是否已通知锁定的 EXISTS 子查询(状态推导用)。"""
return (
select(OrderDeliveryLineState.line_id)
.where(
OrderDeliveryLineState.line_id == OrderDeliveryErpLine.id,
OrderDeliveryLineState.locked.is_(True),
)
.exists()
)
def _reply_person_subquery(like: str):
"""该订单行的交期回复人员(姓名/工号,存于行状态快照)命中关键词的 EXISTS 子查询。"""
return (
select(OrderDeliveryLineState.line_id)
.where(
OrderDeliveryLineState.line_id == OrderDeliveryErpLine.id,
or_(
OrderDeliveryLineState.notified_user_name.ilike(like),
OrderDeliveryLineState.notified_employee_id.ilike(like),
),
)
.exists()
)
def _base_query() -> Select:
"""列表基础查询:只取未标 erp_missing 的已同步行(默认列表不展示已不在同步范围的行)。"""
return select(OrderDeliveryErpLine).where(OrderDeliveryErpLine.erp_missing.is_(False))
def _apply_filters(stmt: Select, params: dict[str, Any]) -> Select:
"""
应用列表筛选(AND 语义)与状态筛选下推。
核心逻辑:keyword 关键词合并搜索——订单单号/客户订单/客户编号/客户简称/公司全名/
产品编号/品名/客户产品编号/业务员(姓名、工号)/交期回复人员(姓名、工号,
2026-09-23 增补,按行状态快照 EXISTS)命中任一字段即返回(OR,工作台单搜索框口径);
order_date 精确单日;status=replied → 已锁定,
status=not_fully_replied → 未锁定(未回复∪部分回复)。
"""
keyword = str(params.get("keyword") or "").strip()
if keyword:
like = f"%{keyword}%"
stmt = stmt.where(
or_(
OrderDeliveryErpLine.order_no.ilike(like),
OrderDeliveryErpLine.customer_po.ilike(like),
OrderDeliveryErpLine.customer_no.ilike(like),
OrderDeliveryErpLine.customer_short_name.ilike(like),
OrderDeliveryErpLine.customer_full_name.ilike(like),
OrderDeliveryErpLine.part_no.ilike(like),
OrderDeliveryErpLine.part_name.ilike(like),
OrderDeliveryErpLine.customer_part_no.ilike(like),
OrderDeliveryErpLine.salesperson_name.ilike(like),
OrderDeliveryErpLine.salesperson_code.ilike(like),
_reply_person_subquery(like),
)
)
order_date_raw = params.get("order_date")
if order_date_raw:
parsed = _parse_date(order_date_raw)
if parsed is None:
from app.core.errors import ValidationError
raise ValidationError("订单日期格式须为 YYYY-MM-DD")
stmt = stmt.where(OrderDeliveryErpLine.order_date == parsed)
status = (params.get("status") or "").strip()
if status and status not in STATUS_FILTER_VALUES:
from app.core.errors import ValidationError
raise ValidationError(f"不支持的状态筛选:{status}")
if status == "replied":
stmt = stmt.where(_locked_subquery())
elif status == "not_fully_replied":
# 未完全回复 = 未回复 ∪ 部分回复,统一口径为「尚未通知锁定」。
stmt = stmt.where(~_locked_subquery())
return stmt
def _parse_date(raw: Any) -> date | None:
"""解析 YYYY-MM-DD 单日;非法返回 None(由调用方决定是否报错)。"""
if isinstance(raw, date) and not isinstance(raw, datetime):
return raw
try:
return date.fromisoformat(str(raw))
except (TypeError, ValueError):
return None
def _serialize_line(
line: OrderDeliveryErpLine,
batches: list[OrderDeliveryBatch],
state: OrderDeliveryLineState | None,
) -> dict[str, Any]:
"""
序列化一行工作台列表/详情数据。
核心逻辑:行状态读时推导(见模块 docstring);未交数量 = 数量 − 已交数量(None 当 0),
只做展示派生,不落库;不输出 slip_code(一期列表不出单别列)。
"""
locked = bool(state and state.locked)
if locked:
status = "replied"
elif batches:
status = "partial_replied"
else:
status = "not_replied"
qty = line.qty or Decimal(0)
delivered = line.delivered_qty or Decimal(0)
return {
"id": line.id,
"order_no": line.order_no,
"line_no": line.line_no,
"order_date": line.order_date.isoformat() if line.order_date else None,
"customer_no": line.customer_no,
"customer_short_name": line.customer_short_name,
"customer_full_name": line.customer_full_name,
"salesperson_code": line.salesperson_code,
"salesperson_name": line.salesperson_name,
"dept_code": line.dept_code,
"dept_name": line.dept_name,
"customer_po": line.customer_po,
"part_no": line.part_no,
"part_name": line.part_name,
"spec": line.spec,
"customer_part_no": line.customer_part_no,
"agreed_date": line.agreed_date.isoformat() if line.agreed_date else None,
"unit": line.unit,
"qty": _dec_str(line.qty),
"delivered_qty": _dec_str(line.delivered_qty),
"undelivered_qty": _dec_str(qty - delivered),
"status": status,
"locked": locked,
"batches": [
{
"seq": batch.seq,
"planned_date": batch.planned_date.isoformat() if batch.planned_date else None,
"qty": _dec_str(batch.qty),
"remark": batch.remark,
}
for batch in batches
],
"notified_employee_id": state.notified_employee_id if state else None,
"notified_user_name": state.notified_user_name if state else None,
"notified_at": _utc_to_shanghai(state.notified_at if state else None),
}
def list_lines(params: dict[str, Any]) -> dict[str, Any]:
"""
订单行列表查询(筛选 + 分页 + 默认排序)。
用途与触发时机:GET /api/order-delivery-reply/lines 的服务层实现;工作台首屏与筛选刷新。
核心逻辑:[STEP 1] 组装基础查询(排除 erp_missing)并应用筛选;
[STEP 2] count 总数后按默认排序分页取本页行;
[STEP 3] 批量预取本页行的批次与锁定状态,避免 N+1,再逐行序列化。
Args:
params: keyword / order_date / status / page / page_size。
Returns:
{"items": [...], "page", "page_size", "total"};items 含批次与状态(见 _serialize_line)。
"""
stmt = _apply_filters(_base_query(), params)
total = db.session.scalar(select(func.count()).select_from(stmt.subquery()))
try:
page = max(int(params.get("page") or 1), 1)
page_size = min(max(int(params.get("page_size") or DEFAULT_PAGE_SIZE), 1), MAX_PAGE_SIZE)
except (TypeError, ValueError):
from app.core.errors import ValidationError
raise ValidationError("分页参数须为整数")
stmt = stmt.order_by(
OrderDeliveryErpLine.order_date.asc(),
OrderDeliveryErpLine.customer_no.asc(),
OrderDeliveryErpLine.order_no.asc(),
OrderDeliveryErpLine.line_no.asc(),
OrderDeliveryErpLine.part_no.asc(),
).limit(page_size).offset((page - 1) * page_size)
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
items = [
_serialize_line(line, batches_by_line.get(line.id, []), states_by_line.get(line.id))
for line in lines
]
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:
"""
单行详情:快照 + 批次 + 锁定状态 + 该行审计事件。
Args:
order_no / line_no: 行唯一键;erp_missing 行按不存在处理(返回 None → API 404)。
Returns:
序列化 dict;不存在或已不在同步范围返回 None。
"""
line = db.session.scalar(
_base_query().where(
OrderDeliveryErpLine.order_no == order_no,
OrderDeliveryErpLine.line_no == line_no,
)
)
if not line:
return None
batches = list(
db.session.scalars(
select(OrderDeliveryBatch).where(OrderDeliveryBatch.line_id == line.id).order_by(OrderDeliveryBatch.seq)
).all()
)
state = db.session.scalar(select(OrderDeliveryLineState).where(OrderDeliveryLineState.line_id == line.id))
payload = _serialize_line(line, batches, state)
payload["audit_events"] = [
{
"action": event.action,
"operator_user_id": event.operator_user_id,
"payload_json": event.payload_json,
"created_at": _utc_to_shanghai(event.created_at),
}
for event in db.session.scalars(
select(OrderDeliveryAuditEvent)
.where(OrderDeliveryAuditEvent.line_id == line.id)
.order_by(OrderDeliveryAuditEvent.created_at.desc())
).all()
]
return payload
@@ -0,0 +1,362 @@
"""
backend/app/services/order_delivery_reply/reminder_service.py
用途:订单交期回复的定时提醒扫描——已回复行按回复交期提前 N 天提醒业务员出货;
未回复行超过 N 天再次提醒生管。由排程 order-delivery-remind(日批)调用。
依赖:models/order_delivery_reply(快照/批次/锁定/审计)、models.User(工号 → 企微映射)、
wecom_notify.send_wecom_event_message、services/schedule/timezone_util(北京时区业务日)。
逻辑:[出货提醒] 已锁定(已回复)行的批次 planned_date 落在 [今天, 今天+N] 时,按业务员聚合
发一条企微;同一 (行, 交期) 只提醒一次(audit_events action=ship_remind 去重),发送失败
不落成功记录,次日扫描自动补发。
[未回复提醒] 未锁定行的订单日期(order_date,取 ERP oea02)距今 ≥ N 天时再次提醒生管
(收件人 = 任务参数 unreplied_remind_user_ids,留空回退任务通知人),同一行每 N 天最多
提醒一次(action=unreplied_remind 去重),多行聚合成一条通知避免刷屏。
提醒只读业务数据 + 写审计,绝不改动批次/锁定状态。
(2026-09-23 修订:超期锚点由快照首次入库 created_at 改为订单日期,按业务确认以订单日期计超期。)
"""
from __future__ import annotations
from datetime import datetime, timedelta
from typing import Any
from sqlalchemy import select
from zoneinfo import ZoneInfo
from app.extensions import db
from app.models import User
from app.models.order_delivery_reply import (
OrderDeliveryAuditEvent,
OrderDeliveryBatch,
OrderDeliveryErpLine,
OrderDeliveryLineState,
)
from app.services.integrations.wecom.notify import send_wecom_event_message
# 企微事件开关名:与行级通知共用同一事件(WECOM_NOTIFY_EVENTS 已包含,无需新增配置)。
WECOM_EVENT_TYPE = "order_delivery_reply_notify"
JUMP_PATH = "/apps/order-delivery-reply" # 免布局嵌入路由:企微内打开不带工作台侧栏
# 通知正文最多列出的订单条数;超出的折叠为「…等 N 笔」,避免超出企微卡片描述上限。
MAX_LISTED_ORDERS = 8
# 审计动作名(models.order_delivery_reply.OrderDeliveryAuditEvent.action,String(32))。
ACTION_SHIP_REMIND = "ship_remind"
ACTION_UNREPLIED_REMIND = "unreplied_remind"
def _business_today():
"""北京时间业务日(约定交货日/回复交期都是业务日期,不能拿 UTC 日期比较)。"""
return datetime.now(ZoneInfo("Asia/Shanghai")).date()
def _resolve_salesperson_user(salesperson_code: str | None) -> User | None:
"""订单业务员工号 → HXOPS 用户(须已绑企微);对不上返回 None,由调用方记录失败。"""
code = (salesperson_code or "").strip()
if not code:
return None
user = db.session.scalar(select(User).where(User.employee_id == code))
if user is None or not (user.wecom_userid or "").strip():
return None
return user
def _audit_reminded_keys(action: str, since_days: int) -> dict[int, set[str]]:
"""
读取历史上「发送成功」的已提醒 (line_id → planned_date 集合),供去重。
核心逻辑:只认 payload.ok=true 的审计——发送失败不算已提醒,次日扫描自动补发;
Args:
action: ship_remind(payload 带 planned_date 与 ok)。
since_days: 只回看最近 N 天的审计(窗口远大于提醒周期,足够去重且避免全表扫描)。
"""
since = datetime.utcnow() - timedelta(days=since_days)
events = db.session.scalars(
select(OrderDeliveryAuditEvent).where(
OrderDeliveryAuditEvent.action == action,
OrderDeliveryAuditEvent.created_at >= since,
)
).all()
reminded: dict[int, set[str]] = {}
for event in events:
payload = event.payload_json if isinstance(event.payload_json, dict) else {}
if payload.get("ok") is not True:
continue
key = str(payload.get("planned_date") or "")
reminded.setdefault(event.line_id or 0, set()).add(key)
return reminded
def _last_successful_unreplied_remind_at(since_days: int) -> dict[int, datetime]:
"""
每行最近一次「发送成功」的未回复提醒时间(控制 N 天一次的再次提醒节奏)。
核心逻辑:只统计 payload.ok=true 的事件;窗口外的旧事件等价于「从未提醒」
(超过 N 天本来就该再次提醒),因此按窗口过滤不改变节奏语义。
"""
since = datetime.utcnow() - timedelta(days=since_days)
events = db.session.scalars(
select(OrderDeliveryAuditEvent).where(
OrderDeliveryAuditEvent.action == ACTION_UNREPLIED_REMIND,
OrderDeliveryAuditEvent.created_at >= since,
)
).all()
last_by_line: dict[int, datetime] = {}
for event in events:
payload = event.payload_json if isinstance(event.payload_json, dict) else {}
if payload.get("ok") is not True or event.line_id is None or event.created_at is None:
continue
line_id = int(event.line_id)
if line_id not in last_by_line or event.created_at > last_by_line[line_id]:
last_by_line[line_id] = event.created_at
return last_by_line
def _truncate_orders(entries: list[str]) -> str:
"""订单清单截断:最多列 MAX_LISTED_ORDERS 条,其余折叠为「…等 N 笔」。"""
if len(entries) <= MAX_LISTED_ORDERS:
return "\n".join(entries)
listed = "\n".join(entries[:MAX_LISTED_ORDERS])
return f"{listed}\n…等共 {len(entries)} 笔"
def _send_remind_card(user: User, content: str, jump_params: dict[str, Any] | None = None) -> dict[str, Any]:
"""发提醒卡片;返回 {ok, trace_id?/reason?},成败以 send_wecom_event_message 返回为准。"""
result = send_wecom_event_message(
event_type=WECOM_EVENT_TYPE,
user=user,
title="订单交期回复",
content=content,
jump_path=JUMP_PATH,
jump_params=jump_params,
)
return {"ok": bool(result.get("ok")), "trace_id": result.get("trace_id"), "reason": result.get("reason")}
def run_ship_reminders(advance_days: int) -> dict[str, Any]:
"""
出货提醒:已回复(已锁定)行中,回复交期距今 ≤ advance_days 天的,提醒对应业务员出货。
核心逻辑:[STEP 1] 业务窗口 [today, today+advance_days];查已锁定且未标 erp_missing 的
行批次候选;[STEP 2] 按 (line_id, planned_date) 去重(历史 ship_remind 审计);
[STEP 3] 按业务员聚合发一条企微(一条多单,避免逐单刷屏),发送失败不计成功;
[STEP 4] 逐行写 ship_remind 审计(含 trace/成败),供下次去重与追溯。
Returns:
{"advance_days", "candidate_lines", "notified_salespersons", "notified_lines",
"failed_salespersons", "skipped_unmapped"}。
"""
today = _business_today()
window_end = today + timedelta(days=max(0, int(advance_days)))
candidates: dict[int, list[dict[str, Any]]] = {}
rows = db.session.execute(
select(OrderDeliveryBatch, OrderDeliveryErpLine)
.join(OrderDeliveryErpLine, OrderDeliveryErpLine.id == OrderDeliveryBatch.line_id)
.join(OrderDeliveryLineState, OrderDeliveryLineState.line_id == OrderDeliveryErpLine.id)
.where(
OrderDeliveryErpLine.erp_missing.is_(False),
OrderDeliveryLineState.locked.is_(True),
OrderDeliveryBatch.planned_date >= today,
OrderDeliveryBatch.planned_date <= window_end,
)
.order_by(OrderDeliveryBatch.planned_date.asc())
).all()
for batch, line in rows:
candidates.setdefault(line.id, []).append(
{
"planned_date": batch.planned_date,
"qty": batch.qty,
"line": line,
}
)
if not candidates:
return {"advance_days": advance_days, "candidate_lines": 0, "notified_salespersons": 0,
"notified_lines": 0, "failed_salespersons": 0, "skipped_unmapped": 0}
# [STEP 2] 去重:同 (行, 回复交期) 只提醒一次;回看窗口取 3 倍提前天数(至少 30 天)。
reminded = _audit_reminded_keys(ACTION_SHIP_REMIND, since_days=max(30, int(advance_days) * 3))
# 按业务员聚合并过滤已提醒的 (行, 交期)。
by_salesperson: dict[str, dict[str, Any]] = {}
notified_lines = 0
for line_id, entries in candidates.items():
fresh = [e for e in entries if e["planned_date"].isoformat() not in reminded.get(line_id, set())]
if not fresh:
continue
line = fresh[0]["line"]
code = (line.salesperson_code or "").strip()
bucket = by_salesperson.setdefault(
code, {"entries": [], "line_ids": set()},
)
for entry in fresh:
bucket["entries"].append(entry)
bucket["line_ids"].add(line_id)
notified_persons = 0
failed_persons = 0
skipped_unmapped = 0
for code, bucket in by_salesperson.items():
user = _resolve_salesperson_user(code)
if user is None:
# 业务员未映射企微:记失败审计(不带 trace),次日扫描同样会重试。
skipped_unmapped += 1
for entry in bucket["entries"]:
db.session.add(OrderDeliveryAuditEvent(
line_id=entry["line"].id,
order_no=entry["line"].order_no,
line_no=entry["line"].line_no,
action=ACTION_SHIP_REMIND,
payload_json={
"kind": "ship",
"planned_date": entry["planned_date"].isoformat(),
"ok": False,
"reason": "salesperson_unmapped",
"salesperson_code": code,
},
))
db.session.commit()
continue
lines_text = _truncate_orders([
f"{entry['line'].order_no}:{entry['line'].line_no} 交期 {entry['planned_date'].isoformat()}"
for entry in bucket["entries"]
])
content = (
f"您有 {len(bucket['entries'])} 笔订单将在 {advance_days} 天内交货,请及时安排出货:\n{lines_text}"
)
# 卡片带 status=replied:业务员点开直达「已回复」视图(出货提醒行必然已回复锁定)。
result = _send_remind_card(user, content, jump_params={"status": "replied"})
if result["ok"]:
notified_persons += 1
notified_lines += len(bucket["line_ids"])
else:
failed_persons += 1
for entry in bucket["entries"]:
db.session.add(OrderDeliveryAuditEvent(
line_id=entry["line"].id,
order_no=entry["line"].order_no,
line_no=entry["line"].line_no,
action=ACTION_SHIP_REMIND,
payload_json={
"kind": "ship",
"planned_date": entry["planned_date"].isoformat(),
"ok": result["ok"],
"reason": result.get("reason"),
"recipient_employee_id": code,
"recipient_wecom_userid": user.wecom_userid,
"trace_id": result.get("trace_id"),
},
))
db.session.commit()
return {
"advance_days": advance_days,
"candidate_lines": len(candidates),
"notified_salespersons": notified_persons,
"notified_lines": notified_lines,
"failed_salespersons": failed_persons,
"skipped_unmapped": skipped_unmapped,
}
def run_unreplied_reminders(unreplied_days: int, notify_user_ids: list[int]) -> dict[str, Any]:
"""
未回复再提醒:订单日期距今超 N 天仍未回复的订单行,聚合提醒生管(收件人 = 排程任务通知人配置)。
核心逻辑:[STEP 1] 候选 = 未锁定且未标 erp_missing、订单日期(order_date)距今
≥ unreplied_days 的行(订单日期为空不参与提醒);
[STEP 2] 同行距上次提醒 ≥ unreplied_days 才再次提醒
(audit action=unreplied_remind 的 max(created_at) 控制,未提醒过则立即提醒);
[STEP 3] 汇总为一
条企微发给每个配置的生管收件人;无收件人时跳过并如实返回。
Returns:
{"unreplied_days", "due_lines", "notified_recipients", "failed_recipients", "skipped_no_recipient"}。
"""
today = _business_today()
threshold_date = today - timedelta(days=max(0, int(unreplied_days)))
locked_subq = (
select(OrderDeliveryLineState.line_id)
.where(OrderDeliveryLineState.line_id == OrderDeliveryErpLine.id,
OrderDeliveryLineState.locked.is_(True))
.exists()
)
due_lines = list(
db.session.scalars(
select(OrderDeliveryErpLine)
.where(
OrderDeliveryErpLine.erp_missing.is_(False),
~locked_subq,
# 超期锚点 = ERP 订单日期(oea02,2026-09-23 由 created_at 改来,按业务确认口径):
# 订单日期距今 ≥ N 天仍未锁定即入选;订单日期为空无法判定,不参与提醒。
OrderDeliveryErpLine.order_date.is_not(None),
OrderDeliveryErpLine.order_date <= threshold_date,
)
.order_by(OrderDeliveryErpLine.order_date.asc())
).all()
)
if not due_lines:
return {"unreplied_days": unreplied_days, "due_lines": 0, "notified_recipients": 0,
"failed_recipients": 0, "skipped_no_recipient": False}
# [STEP 2] 同一行 N 天内不重复提醒(只看发送成功的记录;失败不算已提醒)。
last_reminded = _last_successful_unreplied_remind_at(since_days=max(30, int(unreplied_days) * 3))
pending_lines = [
line for line in due_lines
if line.id not in last_reminded
or (datetime.utcnow() - last_reminded[line.id]) >= timedelta(days=max(1, int(unreplied_days)))
]
if not pending_lines:
return {"unreplied_days": unreplied_days, "due_lines": len(due_lines), "notified_recipients": 0,
"failed_recipients": 0, "skipped_no_recipient": False}
recipient_ids = [int(uid) for uid in (notify_user_ids or []) if uid]
if not recipient_ids:
return {"unreplied_days": unreplied_days, "due_lines": len(due_lines), "notified_recipients": 0,
"failed_recipients": 0, "skipped_no_recipient": True}
recipients = [u for u in User.query.filter(User.id.in_(recipient_ids)).all() if (u.wecom_userid or "").strip()]
if not recipients:
return {"unreplied_days": unreplied_days, "due_lines": len(due_lines), "notified_recipients": 0,
"failed_recipients": 0, "skipped_no_recipient": True}
lines_text = _truncate_orders([
f"{line.order_no}:{line.line_no} 客户 {line.customer_no or '—'} 下单 {line.order_date.isoformat() if line.order_date else '—'}"
for line in pending_lines
])
content = (
f"有 {len(pending_lines)} 笔订单交期已超过 {unreplied_days} 天未回复,请及时查看并回复交期:\n{lines_text}"
)
notified = 0
failed = 0
for user in recipients:
result = _send_remind_card(user, content, jump_params={"status": "not_fully_replied"})
if result["ok"]:
notified += 1
else:
failed += 1
# 提醒节奏按「发送时间」记(成功失败都记,失败下次扫描重试不叠加节奏)。
for line in pending_lines:
db.session.add(OrderDeliveryAuditEvent(
line_id=line.id,
order_no=line.order_no,
line_no=line.line_no,
action=ACTION_UNREPLIED_REMIND,
payload_json={
"kind": "unreplied",
"unreplied_days": unreplied_days,
"ok": result["ok"],
"reason": result.get("reason"),
"recipient_user_id": user.id,
"trace_id": result.get("trace_id"),
},
))
db.session.commit()
return {
"unreplied_days": unreplied_days,
"due_lines": len(pending_lines),
"notified_recipients": notified,
"failed_recipients": failed,
"skipped_no_recipient": False,
}
@@ -0,0 +1,270 @@
"""
backend/app/services/order_delivery_reply/reply_service.py
用途:订单交期回复的写路径——单行/联合保存交期批次(未锁定行整表替换)。
依赖:models/order_delivery_reply(快照/批次/状态/审计)、extensions.db、core.errors。
逻辑:保存与通知是两步(需求 §5):本服务只写批次与 save 审计,不通知、不锁定;
已锁定行拒绝写入(409);批次校验(交期必填、数量>0、备注≤200、各批次合计必须
等于订单数量——2026-09-23 由「超额仅提醒」修订,BATCH_QTY_TOTAL_MISMATCH)在此层完成。
后续通知/锁定在 notify_service 中与企微发送同事务实现,禁止在本文件锁定。
"""
from __future__ import annotations
from datetime import date, datetime
from decimal import Decimal, InvalidOperation
from typing import Any
from sqlalchemy import select
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.extensions import db
from app.models.order_delivery_reply import (
OrderDeliveryAuditEvent,
OrderDeliveryBatch,
OrderDeliveryErpLine,
OrderDeliveryLineState,
)
# 批次数量上限:单行允许维护的批次条数(需求 §10「1..N 批」,N 收敛为 20 防误操作)。
MAX_BATCH_COUNT = 20
REMARK_MAX_LENGTH = 200
def _parse_batches(raw_batches: Any) -> list[dict[str, Any]]:
"""
校验并规范化请求中的批次列表。
用途与触发时机:单行保存与联合回复保存共用;在触碰数据库之前先做全量校验。
核心逻辑:必须为非空 list(1..MAX_BATCH_COUNT 条);每条交期必填且为合法日期、
数量 > 0、备注 ≤ 200;同一次提交内不允许重复交期(重复即录入错误)。
Args:
raw_batches: 请求 body 中的 batches 数组,元素 {planned_date, qty, remark?}。
Returns:
规范化后的 [{planned_date: date, qty: Decimal, remark: str|None}],按提交顺序。
Raises:
ValidationError: 结构、日期、数量、备注长度、重复交期不合法。
"""
if not isinstance(raw_batches, list) or not raw_batches:
raise ValidationError("batches 必须为非空数组", code="ORDER_DELIVERY_REPLY.BATCHES_REQUIRED")
if len(raw_batches) > MAX_BATCH_COUNT:
raise ValidationError(f"单行批次数量超过上限 {MAX_BATCH_COUNT}", code="ORDER_DELIVERY_REPLY.BATCH_COUNT_EXCEEDED")
normalized: list[dict[str, Any]] = []
seen_dates: set[date] = set()
for idx, item in enumerate(raw_batches, start=1):
if not isinstance(item, dict):
raise ValidationError(f"第 {idx} 条批次格式不合法", code="ORDER_DELIVERY_REPLY.BATCH_INVALID")
planned_raw = item.get("planned_date")
try:
planned_date = date.fromisoformat(str(planned_raw))
except (TypeError, ValueError):
raise ValidationError(
f"第 {idx} 条批次交期必填且须为 YYYY-MM-DD",
code="ORDER_DELIVERY_REPLY.BATCH_INVALID",
)
if planned_date in seen_dates:
raise ValidationError(
f"第 {idx} 条批次交期 {planned_date} 重复",
code="ORDER_DELIVERY_REPLY.BATCH_INVALID",
)
seen_dates.add(planned_date)
qty_raw = item.get("qty")
try:
qty = Decimal(str(qty_raw))
except (TypeError, InvalidOperation):
raise ValidationError(f"第 {idx} 条批次数量不合法", code="ORDER_DELIVERY_REPLY.BATCH_INVALID")
if qty <= 0:
raise ValidationError(f"第 {idx} 条批次数量必须大于 0", code="ORDER_DELIVERY_REPLY.BATCH_INVALID")
remark = item.get("remark")
if remark is not None:
remark = str(remark).strip() or None
if len(remark) > REMARK_MAX_LENGTH:
raise ValidationError(
f"第 {idx} 条批次备注超过 {REMARK_MAX_LENGTH} 字符",
code="ORDER_DELIVERY_REPLY.BATCH_INVALID",
)
normalized.append({"planned_date": planned_date, "qty": qty, "remark": remark})
return normalized
def get_line_for_write(order_no: str, line_no: int) -> tuple[OrderDeliveryErpLine, OrderDeliveryLineState | None]:
"""
取可写的订单行与其锁定状态(写路径统一入口)。
Args:
order_no / line_no: 行唯一键。
Returns:
(行, 状态或None)。
Raises:
NotFoundError: 行不存在或已标 erp_missing(直链按不存在处理)。
ConflictError: 行已通知锁定,禁止再改批次。
"""
line = db.session.scalar(
select(OrderDeliveryErpLine).where(
OrderDeliveryErpLine.order_no == order_no,
OrderDeliveryErpLine.line_no == line_no,
OrderDeliveryErpLine.erp_missing.is_(False),
)
)
if not line:
raise NotFoundError(
"Order delivery line not found",
code="ORDER_DELIVERY_REPLY.LINE_NOT_FOUND",
)
state = db.session.scalar(
select(OrderDeliveryLineState).where(OrderDeliveryLineState.line_id == line.id)
)
if state and state.locked:
raise ConflictError(
"该订单行交期已通知锁定,不能修改批次",
code="ORDER_DELIVERY_REPLY.LINE_LOCKED",
)
return line, state
def save_batches(order_no: str, line_no: int, raw_batches: Any, operator_user_id: int | None) -> dict[str, Any]:
"""
保存一行交期批次(未锁定行整表替换:删旧批 → 写新批 → 记审计)。
用途与触发时机:单行「回复交期/修改回复」与联合回复保存逐行复用本入口;
AI/排程不触发本函数(无自动回复语义)。
核心逻辑:[STEP 1] 校验批次结构(_parse_batches);
[STEP 2] get_line_for_write 确认行存在且未锁定;数量守恒校验:各批次合计必须
等于订单数量(2026-09-23 由「超额仅提醒」修订),不等抛 422 BATCH_QTY_TOTAL_MISMATCH;
[STEP 3] 事务内删除旧批次、按序号写入新批次;
[STEP 4] 写 action=save 审计(含批次快照)。
保存后行仍为部分回复;通知与锁定走 notify 路径,本函数不触碰 line_states。
Args:
order_no / line_no: 行唯一键。
raw_batches: [{planned_date, qty, remark?}]。
operator_user_id: 保存人(HXOPS 用户 id),审计用。
Returns:
{"order_no", "line_no", "batches": [...], "total_qty"} 序列化结果。
"""
normalized = _parse_batches(raw_batches)
line, _state = get_line_for_write(order_no, line_no)
# [STEP 2] 数量守恒:各批次合计必须等于订单数量(保存口径 2026-09-23 修订,原允许超额仅提醒);
# 校验在任何写操作之前,失败时不落批次也不落审计。
total_qty = sum((batch["qty"] for batch in normalized), Decimal(0))
order_qty = line.qty if line.qty is not None else Decimal(0)
if total_qty != order_qty:
raise ValidationError(
f"各批次数量合计({total_qty})必须等于订单数量({order_qty}),请调整后重新保存",
code="ORDER_DELIVERY_REPLY.BATCH_QTY_TOTAL_MISMATCH",
)
# [STEP 3] 整表替换:未锁定行的旧批次全部作废,以本次提交为准。
db.session.query(OrderDeliveryBatch).filter(OrderDeliveryBatch.line_id == line.id).delete()
for seq, batch in enumerate(normalized, start=1):
db.session.add(
OrderDeliveryBatch(
line_id=line.id,
seq=seq,
planned_date=batch["planned_date"],
qty=batch["qty"],
remark=batch["remark"],
created_by=operator_user_id,
)
)
db.session.add(
OrderDeliveryAuditEvent(
line_id=line.id,
order_no=line.order_no,
line_no=line.line_no,
action="save",
operator_user_id=operator_user_id,
payload_json={
"batch_count": len(normalized),
"total_qty": str(total_qty),
"batches": [
{
"seq": seq,
"planned_date": batch["planned_date"].isoformat(),
"qty": str(batch["qty"]),
"remark": batch["remark"],
}
for seq, batch in enumerate(normalized, start=1)
],
"saved_at": datetime.utcnow().isoformat(),
},
)
)
db.session.commit()
return {
"order_no": line.order_no,
"line_no": line.line_no,
"batches": [
{
"seq": seq,
"planned_date": batch["planned_date"].isoformat(),
"qty": str(batch["qty"]),
"remark": batch["remark"],
}
for seq, batch in enumerate(normalized, start=1)
],
"total_qty": str(total_qty),
}
def batch_reply(raw_items: Any, operator_user_id: int | None) -> dict[str, Any]:
"""
联合回复:对勾选的多行逐行保存批次(只保存,不通知、不锁定)。
用途与触发时机:工作台勾选多行后点「+ 联合回复交期」并逐行填批次提交(R-REPLY-02)。
核心逻辑:[STEP 1] 校验请求结构(非空数组、每项含 order_no/line_no/batches);
[STEP 2] 逐行调用 save_batches;单行失败不回滚已成功的行(草稿语义,
部分保存优于整体失败),失败行带错误信息返回由前端标红重试;
[STEP 3] 汇总 succeeded/failed 与各行结果。
Args:
raw_items: [{"order_no", "line_no", "batches": [{planned_date, qty, remark?}]}]。
operator_user_id: 保存人。
Returns:
{"succeeded": N, "failed": N, "items": [{order_no, line_no, ok, error?, data?}]}。
"""
from app.core.errors import AppError
if not isinstance(raw_items, list) or not raw_items:
raise ValidationError("items 必须为非空数组", code="ORDER_DELIVERY_REPLY.BATCH_REPLY_EMPTY")
if len(raw_items) > 200:
raise ValidationError("单次联合回复行数超过上限 200", code="ORDER_DELIVERY_REPLY.BATCH_REPLY_EMPTY")
results: list[dict[str, Any]] = []
for item in raw_items:
if not isinstance(item, dict) or not item.get("order_no") or item.get("line_no") is None:
results.append({"ok": False, "error": "行唯一键缺失(order_no/line_no)"})
continue
order_no = str(item["order_no"]).strip()
try:
line_no = int(item["line_no"])
except (TypeError, ValueError):
results.append({"order_no": order_no, "ok": False, "error": "line_no 须为整数"})
continue
try:
data = save_batches(order_no, line_no, item.get("batches"), operator_user_id)
results.append({"order_no": order_no, "line_no": line_no, "ok": True, "data": data})
except AppError as exc:
# [STEP 2] 单行失败只记结果,不回滚其它行(save_batches 每行独立事务)。
db.session.rollback()
results.append(
{"order_no": order_no, "line_no": line_no, "ok": False, "error": exc.message}
)
return {
"succeeded": sum(1 for r in results if r.get("ok")),
"failed": sum(1 for r in results if not r.get("ok")),
"items": results,
}
@@ -0,0 +1,50 @@
"""订单交期回复默认排程种子:每天 07:00(Asia/Shanghai)ERP 全量同步 + 07:10 每日提醒。"""
from __future__ import annotations
from datetime import datetime
from app import db
from app.models import ScheduleTask, User
from app.services.schedule.timezone_util import compute_next_run_at
_DEFAULTS = (
('SCH-ORDER-DELIVERY-SYNC', 'order-delivery-sync', '订单交期回复 ERP 同步(日批 07:00)', '0 7 * * *'),
# 提醒排在同步之后:扫描的是当天刚同步的最新快照。
('SCH-ORDER-DELIVERY-REMIND', 'order-delivery-remind', '订单交期回复 提醒(日批 07:10)', '10 7 * * *'),
)
def ensure_default_order_delivery_schedules(*, commit: bool = True):
"""
幂等创建订单交期回复每日同步默认排程。
Args:
commit: 是否提交新建排程;测试或外层事务可传 False。
Returns:
新建的 ScheduleTask 列表;无用户时返回空列表。
"""
owner = db.session.query(User).filter(User.role == 'admin').order_by(User.id.asc()).first() or db.session.query(User).order_by(User.id.asc()).first()
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,50 @@
"""
backend/app/services/order_delivery_reply/sql.py
用途:订单交期回复 ERP(鼎捷 topprod)取数 SQL 唯一权威定义;同步服务与原型脚本共用。
依赖:无(纯常量);连接约定见 services/text2sql.py(ERP_DB_DSN / ERP_DB_USER / ERP_DB_PASSWORD)。
逻辑:一期同步全部「已审核 oeaconf='Y' + 已核准 oea49='1' + 未结案 oeb70≠Y」合格订单行,
不按单别过滤;后期单别白名单在此基础上追加 IN 条件。业务约束:仅只读 SELECT,
禁止改写为 INSERT/UPDATE/DELETE。
"""
# 基础 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,
b.oeb03 AS line_no,
a.oea02 AS order_date,
a.oea03 AS customer_no,
d.occ02 AS customer_short_name,
d.occ18 AS customer_full_name,
a.oea14 AS salesperson_code,
e.gen02 AS salesperson_name,
a.oea15 AS dept_code,
f.gem02 AS dept_name,
a.oea10 AS customer_po,
b.oeb04 AS part_no,
b.oeb06 AS part_name,
c.ima021 AS spec,
b.oeb11 AS customer_part_no,
b.oeb15 AS agreed_date,
b.oeb05 AS unit,
b.oeb12 AS qty,
NVL(b.oeb24, 0) AS delivered_qty
FROM HXJM.OEA_FILE a
INNER JOIN HXJM.OEB_FILE b ON a.oea01 = b.oeb01
LEFT JOIN HXJM.IMA_FILE c ON b.oeb04 = c.ima01 AND b.oeb06 = c.ima02
LEFT JOIN HXJM.OCC_FILE d ON a.oea03 = d.occ01
LEFT JOIN HXJM.GEN_FILE e ON a.oea14 = e.gen01
LEFT JOIN HXJM.GEM_FILE f ON a.oea15 = f.gem01
WHERE a.oeaconf = 'Y'
AND a.oea49 = '1'
AND NVL(b.oeb70, 'N') = 'N'
AND NVL(b.oeb24, 0) = 0
"""
@@ -0,0 +1,357 @@
"""
backend/app/services/order_delivery_reply/sync_service.py
用途:订单交期回复 ERP 全量同步服务(07:00 排程与手动刷新共用);只读 ERP、upsert 本地快照。
依赖:services/order_delivery_reply/sql(取数口径)、services/text2sql(Oracle thick 模式初始化)、
models/order_delivery_reply(本地表)、extensions.db。
逻辑:按 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
import logging
import os
import threading
from datetime import date, datetime
from typing import Any
from sqlalchemy import select, update
from app.extensions import db
from app.models.order_delivery_reply import (
OrderDeliveryAuditEvent,
OrderDeliveryErpLine,
OrderDeliverySyncRun,
)
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",
"customer_no",
"customer_short_name",
"customer_full_name",
"salesperson_code",
"salesperson_name",
"dept_code",
"dept_name",
"customer_po",
"part_no",
"part_name",
"spec",
"customer_part_no",
"agreed_date",
"unit",
"qty",
"delivered_qty",
"slip_code",
)
_FETCH_SIZE = 500
_thick_init_lock = threading.Lock()
_thick_initialized = False
def _ensure_thick_client(oracledb) -> None:
"""按 ORACLE_CLIENT_LIB_DIR(或 backend/oracle_client 约定)初始化 thick 模式;幂等且失败不掩埋。"""
global _thick_initialized
with _thick_init_lock:
if _thick_initialized or not getattr(oracledb, "is_thin_mode", lambda: True)():
_thick_initialized = True
return
candidates = []
env_dir = (os.getenv("ORACLE_CLIENT_LIB_DIR") or "").strip()
if env_dir:
candidates.append(os.path.normpath(env_dir))
backend_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
candidates.append(os.path.join(backend_dir, "oracle_client"))
marker = {"oci.dll", "libclntsh.so", "libclntsh.dylib"}
lib_dir = None
for root in candidates:
if not root or not os.path.isdir(root):
continue
if marker & {n.lower() for n in os.listdir(root)}:
lib_dir = root
break
sub = [d for d in os.listdir(root) if d.startswith("instantclient_") and os.path.isdir(os.path.join(root, d))]
if sub:
lib_dir = os.path.join(root, sub[0])
break
if lib_dir:
os.environ["PATH"] = lib_dir + os.pathsep + os.environ.get("PATH", "")
if hasattr(os, "add_dll_directory"):
os.add_dll_directory(lib_dir)
oracledb.init_oracle_client(lib_dir=lib_dir)
else:
oracledb.init_oracle_client()
_thick_initialized = True
# 进程内互斥:同一 worker 同时只跑一个同步(多 worker 由 sync_runs running 行兜底,一期单机足够)。
_sync_lock = threading.Lock()
def _extract_slip_code(order_no: str | None) -> str | None:
"""从订单单号取连字符前的单别(8301-1605280014 → 8301);无连字符返回整号前缀。"""
if not order_no:
return None
return order_no.split("-", 1)[0]
class OrderDeliverySyncService:
"""ERP → 本地 Postgres 的订单行全量同步;所有方法不回写 ERP。"""
@staticmethod
def _connect():
"""
建立 ERP Oracle 连接(凭据复用合同付款预警的 CONTRACT_PAYMENT_ERP_* 配置)。
核心逻辑:账号/密码优先专用键 ERP_DB_USER / ERP_DB_PASSWORD(或 ERP_USERNAME/ERP_PASSWORD),
缺省回退 .env.shared 已有的 CONTRACT_PAYMENT_ERP_USERNAME / CONTRACT_PAYMENT_ERP_PASSWORD
(hxjm 账号,与合同付款预警同一连接口径,技术文档 §3.1);DSN 用 ERP_DB_DSN。
thin 优先,失败时按 Text2SQL 既有路径切 thick(本地 Instant Client)。
Returns:
oracledb.Connection;凭据缺失时抛 RuntimeError 提示配置来源。
"""
import oracledb
user = (
os.getenv("ERP_DB_USER")
or os.getenv("ERP_USERNAME")
or os.getenv("CONTRACT_PAYMENT_ERP_USERNAME")
or "EXT_VIEW_USER"
)
password = (
os.getenv("ERP_DB_PASSWORD")
or os.getenv("ERP_PASSWORD")
or os.getenv("CONTRACT_PAYMENT_ERP_PASSWORD")
)
dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod")
if not password:
raise RuntimeError(
"ERP 口令未配置:请设置 ERP_DB_PASSWORD,或复用 .env.shared 的 "
"CONTRACT_PAYMENT_ERP_PASSWORD(与合同付款预警同一 topprod 连接)"
)
try:
return oracledb.connect(user=user, password=password, dsn=dsn)
except oracledb.DatabaseError:
# thin 模式连不上(topprod 为 11g 必走 thick):用 ORACLE_CLIENT_LIB_DIR 自初始化,
# 不再依赖 services/text2sql——worker 进程 sys.path 差异曾致
# "No module named app.services.text2sql"(2026-09-22 排程同步失败根因)。
_ensure_thick_client(oracledb)
return oracledb.connect(user=user, password=password, dsn=dsn)
@classmethod
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}{date_clause} ORDER BY a.oea01) "
f"WHERE order_no > :last_order_no AND ROWNUM <= {_FETCH_SIZE}"
)
binds["last_order_no"] = last_order_no
cursor.execute(page_sql, binds)
else:
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()]
@classmethod
def _upsert_page(cls, rows: list[dict[str, Any]], synced_at: datetime) -> set[tuple[str, int]]:
"""
upsert 一页快照行:只更新 ERP 列白名单并复位 erp_missing,绝不覆盖批次/锁定。
Returns:
本页命中的 (order_no, line_no) 集合,供整轮结束后标记 erp_missing。
"""
from sqlalchemy.dialects.postgresql import insert
hit_keys: set[tuple[str, int]] = set()
for raw in rows:
order_no = str(raw["order_no"] or "").strip()
if not order_no or raw["line_no"] is None:
continue
line_no = int(raw["line_no"])
values = {
"order_no": order_no,
"line_no": line_no,
"slip_code": _extract_slip_code(order_no),
"erp_missing": False,
"last_synced_at": synced_at,
}
for col in ERP_LINE_COLUMNS:
if col == "slip_code":
continue
value = raw.get(col)
if isinstance(value, datetime):
value = value.date()
values[col] = value
stmt = insert(OrderDeliveryErpLine).values(**values)
stmt = stmt.on_conflict_do_update(
constraint="uq_order_delivery_erp_lines_order_line",
set_={**{col: stmt.excluded[col] for col in ERP_LINE_COLUMNS},
"erp_missing": False,
"last_synced_at": synced_at},
)
db.session.execute(stmt)
hit_keys.add((order_no, line_no))
return hit_keys
@classmethod
def run_sync(cls, trigger: str = "manual") -> dict[str, Any]:
"""
执行一次全量同步(排程传 'scheduled',手动传 'manual')。
用途与触发时机:07:00 定时任务与生管手动刷新共用入口;AI/脚本也可直调验证取数。
核心逻辑:[STEP 1] 抢互斥锁并写 running 状态的 sync_runs;
[STEP 2] 按 oea01 分页拉 ERP 合格行,逐页 upsert(仅 ERP 列白名单);
[STEP 3] 本轮未命中的本地行统一置 erp_missing=true(不删除,默认列表不展示);
[STEP 4] 写审计与终态 sync_runs;任何异常保留上次快照、记 failed。
Args:
trigger: 'scheduled' | 'manual'。
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}
synced_at = datetime.utcnow()
run = OrderDeliverySyncRun(trigger=trigger, status="running", started_at=synced_at)
db.session.add(run)
db.session.commit()
hit_keys: set[tuple[str, int]] = set()
try:
with cls._connect() as conn:
with conn.cursor() as cursor:
last_order_no: str | None = None
while True:
page = cls._fetch_page(cursor, last_order_no, date_from)
if not page:
break
hit_keys |= cls._upsert_page(page, synced_at)
db.session.commit()
last_order_no = str(page[-1]["order_no"])
# [STEP 3] 未命中行标记 erp_missing:已有批次/锁定的行保留可追,纯快照行同样不再展示。
missing_ids = [
row_id
for row_id, order_no, line_no, _missing in db.session.execute(
select(
OrderDeliveryErpLine.id,
OrderDeliveryErpLine.order_no,
OrderDeliveryErpLine.line_no,
OrderDeliveryErpLine.erp_missing,
)
).all()
if (order_no, line_no) not in hit_keys
]
if missing_ids:
db.session.execute(
update(OrderDeliveryErpLine)
.where(OrderDeliveryErpLine.id.in_(missing_ids))
.values(erp_missing=True)
)
run.status = "success"
run.line_count = len(hit_keys)
run.finished_at = datetime.utcnow()
db.session.add(
OrderDeliveryAuditEvent(
action="sync",
payload_json={"trigger": trigger, "line_count": len(hit_keys), "missing_count": len(missing_ids)},
)
)
db.session.commit()
logger.info("order-delivery-reply sync done: trigger=%s lines=%s missing=%s", trigger, len(hit_keys), len(missing_ids))
return {"run_id": run.id, "status": "success", "line_count": len(hit_keys)}
except Exception as exc: # noqa: BLE001 — 同步失败必须落库留痕并保留上次快照
db.session.rollback()
run.status = "failed"
run.error_message = str(exc)[:4000]
run.finished_at = datetime.utcnow()
db.session.add(run)
db.session.commit()
logger.exception("order-delivery-reply sync failed (trigger=%s)", trigger)
raise
finally:
_sync_lock.release()
@staticmethod
def latest_run() -> OrderDeliverySyncRun | None:
"""最近一次同步运行记录,供页面展示同步时间与结果。"""
return (
db.session.execute(
select(OrderDeliverySyncRun).order_by(OrderDeliverySyncRun.started_at.desc()).limit(1)
)
.scalar_one_or_none()
)
@@ -19,6 +19,9 @@ KNOWN_FEATURE_KEYS: tuple[str, ...] = (
'shipping_notice.xfa_split_rule_preview',
'shipping_notice.xfa_split_rule_publish',
'maintenance.ledger_write',
# 订单交期回复(2026-09-29 合并登记):manage 命中视为有 access,两键须一并授予。
'order_delivery_reply.manage',
'order_delivery_reply.access',
)
FEATURE_CATALOG: tuple[dict[str, Any], ...] = (
@@ -64,6 +67,18 @@ FEATURE_CATALOG: tuple[dict[str, Any], ...] = (
'name': '台账与维修维护',
'hint': '维护设备台账与维修记录',
},
{
'key': 'order_delivery_reply.manage',
'bind': 'agent_code:order_delivery_reply',
'name': '订单交期回复管理',
'hint': '生管回复交期、发送通知并手动同步',
},
{
'key': 'order_delivery_reply.access',
'bind': 'agent_code:order_delivery_reply',
'name': '订单交期回复查看',
'hint': '业务只读查看已同步订单与回复结果',
},
)
# 现网 users.role 枚举对应的标准权限组。admin/user/hr 为内置;rd/shipping 可后续增删应用。
@@ -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}
]
@@ -3,24 +3,57 @@ backend/app/services/schedule/file_asset_cleanup_job.py
用途:排程平台 Job —— 清理过期未引用的临时文件资产。
依赖:file_assets.cleanup。
逻辑:platform_api_path=file-asset-cleanup 时由 job_registry 调用。
逻辑:platform_api_path=file-asset-cleanup 时由 job_registry 调用;
包装 cleanup_expired_temporary_assets 的统计字典为平台标准七元组
(total/success/failed/skipped/details/errors/step_logs),对齐其它平台 Job 契约。
"""
from __future__ import annotations
from typing import Any
from app.models import ScheduleRun, ScheduleTask
from app.services.file_assets.cleanup import cleanup_expired_temporary_assets
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
def run_file_asset_cleanup_schedule(task: Any, run: Any) -> dict[str, Any]:
def run_file_asset_cleanup_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行临时文件资产 TTL 清理。
执行临时文件资产 TTL 清理并返回平台标准审计七元组。
统计口径:total=scanned(本批扫描数)、success=deleted(物理删除数)、
failed=errors(删除失败数)、skipped=expired 未删除部分。
Args:
task: ScheduleTask。
task: ScheduleTask(job_params.limit 可调单批上限,缺省 200)。
run: ScheduleRun。
Returns:
清理统计。
(total, success, failed, skipped, details, errors, step_logs)。
"""
_ = task, run
return cleanup_expired_temporary_assets(limit=200)
_ = run
params = task.job_params if isinstance(task.job_params, dict) else {}
try:
limit = int(params.get("limit") or 200)
except (TypeError, ValueError):
limit = 200
stats = cleanup_expired_temporary_assets(limit=limit)
scanned = int(stats.get("scanned") or 0)
deleted = int(stats.get("deleted") or 0)
errors_count = int(stats.get("errors") or 0)
expired = int(stats.get("expired") or 0)
skipped = max(0, expired - deleted)
errors: list[str] = []
if errors_count:
errors.append(f"临时文件资产清理有 {errors_count} 个对象删除失败,详见 step_logs 统计")
step_logs: list[dict[str, Any]] = [
{
"step": "file_asset_cleanup",
"status": "success" if errors_count == 0 else "partial",
"detail": stats,
}
]
return (scanned, deleted, errors_count, skipped, [stats], errors, step_logs)
@@ -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 跳过,不记失败。
@@ -64,6 +64,21 @@ def _shipping_receipt_sources_options() -> list[dict[str, Any]]:
} for source, _config in rows]
def _hxops_users_options() -> list[dict[str, Any]]:
"""全部启用用户(value=users.id);订单交期回复未回复提醒收件人等场景用。"""
from app.models import User
users = User.query.filter(User.status == "active").order_by(User.real_name.asc(), User.id.asc()).all()
return [
{
"label": f"{u.real_name or u.username}({u.employee_id or '-'})",
"value": u.id,
"description": u.department or None,
}
for u in users
]
def _users_options() -> list[dict[str, Any]]:
"""启用中的用户列表(value=user.id),供排程通知人类参数选择。"""
from app.models import User
@@ -88,6 +103,7 @@ _OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = {
"agent_apps": _agent_apps_options,
"shipping_inventory_sources": _shipping_inventory_sources_options,
"shipping_receipt_sources": _shipping_receipt_sources_options,
"hxops_users": _hxops_users_options,
"users": _users_options,
}
+124 -11
View File
@@ -156,12 +156,106 @@ 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(
key="contract-payment-sync", label="合同付款 OA 同步", handler=run_contract_payment_sync_schedule,
description="同步 OA 合同归档、验收归档和厂商预付款请款作业。", category="contract_payment",
))
from app.services.schedule.order_delivery_reply_job import run_order_delivery_sync_schedule
from app.services.schedule.order_delivery_remind_job import (
DEFAULT_SHIP_ADVANCE_DAYS,
DEFAULT_SHIP_REMIND_ENABLED,
DEFAULT_UNREPLIED_DAYS,
DEFAULT_UNREPLIED_REMIND_ENABLED,
run_order_delivery_remind_schedule,
)
register_platform_job(PlatformJobDefinition(
key="order-delivery-sync", label="订单交期回复 ERP 同步", handler=run_order_delivery_sync_schedule,
description=(
"每天 07:00 全量同步已审核、已核准、未结案的 ERP 销售订单行快照;"
"同步成功后按任务参数「同步完成提醒收件人」提醒生管查看回复(未配置时回退本任务通知人)。"
),
category="order_delivery_reply",
params_schema=(
{
"key": "sync_remind_user_ids",
"type": "multi_select",
"label": "同步完成提醒收件人(生管)",
"required": False,
"default": [],
"options_source": "hxops_users",
"help": "同步完成提醒的生管收件人,可从全部启用用户中搜索选择;"
"与本任务「通知人」(运行结果通知)互相独立;留空时回退通知人名单以兼容旧配置。",
},
),
defaults={"sync_remind_user_ids": []},
))
register_platform_job(PlatformJobDefinition(
key="order-delivery-remind", label="订单交期回复 提醒", handler=run_order_delivery_remind_schedule,
description=(
"每天扫描:已回复行按回复交期提前 N 天企微提醒对应业务员出货;"
"超 N 天未回复的行再次企微提醒生管(收件人取任务参数「未回复提醒收件人」,"
"未配置时回退本任务通知人)。两类提醒可通过任务参数独立启停。"
),
category="order_delivery_reply",
params_schema=(
{
"key": "ship_remind_enabled",
"type": "boolean",
"label": "启用出货提醒",
"required": False,
"default": DEFAULT_SHIP_REMIND_ENABLED,
"help": "关闭后不再按回复交期提前提醒业务员出货;未回复提醒不受影响。",
},
{
"key": "ship_remind_advance_days",
"type": "number",
"label": "出货提醒提前天数",
"required": False,
"default": DEFAULT_SHIP_ADVANCE_DAYS,
"help": "已回复订单的回复交期距今 ≤ 该天数时,企微提醒对应业务员安排出货。取值 0-3650。",
},
{
"key": "unreplied_remind_enabled",
"type": "boolean",
"label": "启用未回复提醒",
"required": False,
"default": DEFAULT_UNREPLIED_REMIND_ENABLED,
"help": "关闭后不再对超期未回复的订单行再次提醒生管;出货提醒不受影响。",
},
{
"key": "unreplied_remind_days",
"type": "number",
"label": "未回复再次提醒天数",
"required": False,
"default": DEFAULT_UNREPLIED_DAYS,
"help": "订单日期距今超过该天数仍未回复交期时再次提醒生管;同一行每达到该天数最多提醒一次。取值 0-3650。",
},
{
"key": "unreplied_remind_user_ids",
"type": "multi_select",
"label": "未回复提醒收件人(生管)",
"required": False,
"default": [],
"options_source": "hxops_users",
"help": "超期未回复提醒的生管收件人,可从全部启用用户中搜索选择;"
"与本任务「通知人」(运行结果通知)互相独立;留空时回退通知人名单以兼容旧配置。",
},
),
defaults={
"ship_remind_enabled": DEFAULT_SHIP_REMIND_ENABLED,
"ship_remind_advance_days": DEFAULT_SHIP_ADVANCE_DAYS,
"unreplied_remind_enabled": DEFAULT_UNREPLIED_REMIND_ENABLED,
"unreplied_remind_days": DEFAULT_UNREPLIED_DAYS,
"unreplied_remind_user_ids": [],
},
))
register_platform_job(PlatformJobDefinition(
key="lean-training-reminder", label="精益管理培训逾期提醒", handler=run_lean_training_reminder_schedule,
description="周日截止后,于周一、周三、周五向未完成员工推送精益培训提醒。", category="training",
@@ -178,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",
@@ -476,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=(
@@ -501,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},
))
@@ -0,0 +1,148 @@
"""
backend/app/services/schedule/order_delivery_remind_job.py
用途:将订单交期回复的每日提醒适配到平台排程(ScheduleTask platform_job,job key
order-delivery-remind,默认日批 07:10 在同步之后执行)。
依赖:services/order_delivery_reply/reminder_service(出货提醒 + 未回复再提醒)、
ScheduleTask/ScheduleRun。
逻辑:从 task.job_params 读取配置(管理端排程表单「任务参数」可改,均有默认值):
ship_remind_enabled / unreplied_remind_enabled 布尔开关独立启停两类提醒;
ship_remind_advance_days 默认 3、unreplied_remind_days 默认 3。
未回复提醒收件人优先取 job_params 的 unreplied_remind_user_ids(管理端「未回复提醒收件人」
多选参数,与平台运行结果通知的「通知人」互相独立);未配置时回退任务 notify_user_ids_json
兼容旧配置。天数统一钳制在 0-3650,防止表单误填巨大值导致 today+timedelta 溢出
(OverflowError: date value out of range,2026-09-22 出货提醒扫描事故根因)。
两个扫描互相独立:单个扫描抛错回滚后继续另一个,最终把错误计入 errors
(failed_count>0 时平台排程标 partial_failed/failed,不影响数据快照);
开关关闭的一侧直接跳过(summary 记 skipped=disabled),不影响另一侧。
"""
from __future__ import annotations
from typing import Any, Callable
from app.models import ScheduleRun, ScheduleTask
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
# 配置键与默认值:与 job_registry 中 order-delivery-remind 的 params_schema 一致。
SHIP_REMIND_ENABLED_KEY = "ship_remind_enabled"
UNREPLIED_REMIND_ENABLED_KEY = "unreplied_remind_enabled"
SHIP_REMIND_ADVANCE_DAYS_KEY = "ship_remind_advance_days"
UNREPLIED_REMIND_DAYS_KEY = "unreplied_remind_days"
DEFAULT_SHIP_REMIND_ENABLED = True
DEFAULT_UNREPLIED_REMIND_ENABLED = True
DEFAULT_UNREPLIED_USER_IDS_KEY = "unreplied_remind_user_ids"
DEFAULT_SHIP_ADVANCE_DAYS = 3
DEFAULT_UNREPLIED_DAYS = 3
# 天数上限(约 10 年):date + timedelta 超过 9999 年会抛 OverflowError: date value out of range。
MAX_REMIND_DAYS = 3650
def _read_days(task: ScheduleTask, key: str, default: int) -> int:
"""读取 job_params 中的天数配置;非法值回退默认,并钳制到 [0, MAX_REMIND_DAYS]。
上限原因:today + timedelta(days=N) 在 N 巨大时溢出抛
OverflowError: date value out of range(2026-09-22 出货提醒扫描失败根因)。
"""
params = task.job_params if isinstance(task.job_params, dict) else {}
try:
value = int(params.get(key, default))
except (TypeError, ValueError):
return default
return min(max(value, 0), MAX_REMIND_DAYS)
def _read_unreplied_recipients(task: ScheduleTask) -> list[int]:
"""读取未回复提醒的生管收件人:优先任务参数多选名单,留空回退任务通知人(旧配置兼容)。"""
params = task.job_params if isinstance(task.job_params, dict) else {}
raw = params.get(DEFAULT_UNREPLIED_USER_IDS_KEY)
ids = [int(uid) for uid in raw if uid] if isinstance(raw, list) else []
if ids:
return ids
if task.notify_enabled:
return [int(uid) for uid in (task.notify_user_ids_json or []) if uid]
return []
def _read_bool(task: ScheduleTask, key: str, default: bool) -> bool:
"""读取 job_params 中的开关配置;非法值回退默认(参数类型已由契约层校验)。"""
params = task.job_params if isinstance(task.job_params, dict) else {}
value = params.get(key, default)
return value if isinstance(value, bool) else default
def _run_scan(errors: list[str], label: str, scan: Callable[[], dict[str, Any]]) -> dict[str, Any]:
"""执行单个扫描:异常回滚后记入 errors(failed+1),不吞掉另一侧扫描。"""
from app.extensions import db
try:
return scan()
except Exception as exc: # noqa: BLE001 — 扫描失败计入运行结果,由排程页展示
db.session.rollback()
errors.append(f"{label}扫描失败: {exc}")
return {"error": str(exc)}
def run_order_delivery_remind_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行每日提醒扫描:已回复行提前 N 天提醒业务员出货;超 N 天未回复行再次提醒生管。
两类提醒由 job_params 的布尔开关独立启停(ship_remind_enabled / unreplied_remind_enabled);
关闭的一侧跳过并在 summary 标记 skipped=disabled,不影响另一侧。
Args:
task: 当前排程任务定义(job_params 带天数/开关配置,notify_user_ids_json 带生管收件人)。
run: 当前排程执行记录。
Returns:
通用排程审计七元组;total/success/failed 按两侧扫描的发送对象计数汇总。
"""
from app.services.order_delivery_reply.reminder_service import (
run_ship_reminders,
run_unreplied_reminders,
)
ship_enabled = _read_bool(task, SHIP_REMIND_ENABLED_KEY, DEFAULT_SHIP_REMIND_ENABLED)
unreplied_enabled = _read_bool(task, UNREPLIED_REMIND_ENABLED_KEY, DEFAULT_UNREPLIED_REMIND_ENABLED)
advance_days = _read_days(task, SHIP_REMIND_ADVANCE_DAYS_KEY, DEFAULT_SHIP_ADVANCE_DAYS)
unreplied_days = _read_days(task, UNREPLIED_REMIND_DAYS_KEY, DEFAULT_UNREPLIED_DAYS)
errors: list[str] = []
if ship_enabled:
ship_result = _run_scan(errors, "出货提醒", lambda: run_ship_reminders(advance_days))
if ship_result.get("skipped_unmapped"):
errors.append(
f"出货提醒有 {ship_result['skipped_unmapped']} 名业务员工号未映射 HXOPS 企微用户,未送达"
)
else:
ship_result = {"skipped": "disabled", "advance_days": advance_days}
unreplied_recipients = _read_unreplied_recipients(task)
if unreplied_enabled:
unreplied_result = _run_scan(errors, "未回复提醒", lambda: run_unreplied_reminders(unreplied_days, unreplied_recipients))
if unreplied_result.get("skipped_no_recipient"):
errors.append("存在超期未回复订单,但未配置「未回复提醒收件人」(且任务通知人未配置或开关关闭),未发送提醒")
else:
unreplied_result = {"skipped": "disabled", "unreplied_days": unreplied_days}
# 统计口径:出货提醒按业务员(人)、未回复提醒按收件人生管(人);扫描异常各计 1 笔失败。
success = int(ship_result.get("notified_salespersons") or 0) + int(unreplied_result.get("notified_recipients") or 0)
failed = (
int(ship_result.get("failed_salespersons") or 0)
+ int(unreplied_result.get("failed_recipients") or 0)
+ sum(1 for result in (ship_result, unreplied_result) if result.get("error"))
)
skipped = int(ship_result.get("skipped_unmapped") or 0)
total = success + failed + skipped
summary = {
"ship_remind": ship_result,
"unreplied_remind": unreplied_result,
"ship_remind_enabled": ship_enabled,
"unreplied_remind_enabled": unreplied_enabled,
"advance_days": advance_days,
"unreplied_days": unreplied_days,
"unreplied_recipients": unreplied_recipients,
}
step_logs = [{"step": "order_delivery_remind", "status": "success" if failed == 0 else "partial", "detail": summary}]
return (total, success, failed, skipped, [summary], errors, step_logs)
@@ -0,0 +1,113 @@
"""
backend/app/services/schedule/order_delivery_reply_job.py
用途:将订单交期回复 ERP 全量同步适配到平台排程(ScheduleTask platform_job)。
依赖:services/order_delivery_reply/sync_service(同步本体)、notify_service(企微事件类型与跳转路径)、
wecom_notify.send_wecom_event_message、ScheduleTask/ScheduleRun。
逻辑:排程 worker 每天 07:00(Asia/Shanghai)触发 handler,内部以 trigger='scheduled'
复用与手动刷新完全相同的 run_sync;同步成功后按任务参数 sync_remind_user_ids
(管理端「同步完成提醒收件人」多选,与运行结果通知的「通知人」互相独立;
留空回退 notify_user_ids_json 兼容旧配置)给生管发提醒,
并把 domain_notification_managed 写入 run 摘要,抑制通用「排程执行结果」通知避免重复;
通知失败不改变同步结果(同步已成功落库,仅记录失败原因)。
同步失败向上抛出,由平台排程标记本次运行失败并保留上次快照(sync_runs 已各自留痕)。
"""
from __future__ import annotations
from typing import Any
from app.models import ScheduleRun, ScheduleTask, User
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
SYNC_REMIND_USER_IDS_KEY = "sync_remind_user_ids"
def _read_sync_remind_recipients(task: ScheduleTask) -> list[int]:
"""同步完成提醒收件人:优先任务参数 sync_remind_user_ids,留空回退任务通知人(旧配置兼容)。"""
params = task.job_params if isinstance(task.job_params, dict) else {}
raw = params.get(SYNC_REMIND_USER_IDS_KEY)
ids = [int(uid) for uid in raw if uid] if isinstance(raw, list) else []
if ids:
return ids
if task.notify_enabled:
return [int(uid) for uid in (task.notify_user_ids_json or []) if uid]
return []
def _notify_production_after_sync(task: ScheduleTask, line_count: int) -> list[dict[str, Any]]:
"""
同步成功后提醒生管查看订单交期回复(收件人 = 任务参数 sync_remind_user_ids,回退通知人)。
Args:
task: 触发本次同步的排程任务。
line_count: 本次同步的订单行数量,用于通知文案。
Returns:
逐人发送结果列表 [{user_id, ok, reason?}];未配置收件人时返回空列表。
"""
from app.services.order_delivery_reply.notify_service import (
WECOM_EVENT_TYPE,
JUMP_PATH,
)
from app.services.integrations.wecom.notify import send_wecom_event_message
user_ids = _read_sync_remind_recipients(task)
if not user_ids:
return []
users = User.query.filter(User.id.in_(user_ids)).all()
results: list[dict[str, Any]] = []
for user in users:
result = send_wecom_event_message(
event_type=WECOM_EVENT_TYPE,
user=user,
title="订单交期回复",
content=f"今日订单交期数据已同步完成(共 {line_count} 行),请及时查看并回复交期。",
jump_path=JUMP_PATH,
# 卡片带 status=not_fully_replied:生管点开直达「未完全回复」视图(待回复行)。
jump_params={"status": "not_fully_replied"},
)
entry: dict[str, Any] = {"user_id": user.id, "ok": bool(result.get("ok"))}
if not entry["ok"]:
entry["reason"] = result.get("reason")
results.append(entry)
return results
def run_order_delivery_sync_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行订单交期回复 ERP 全量同步(已审核 + 已核准 + 未结案订单行)并提醒生管。
Args:
task: 当前排程任务定义。
run: 当前排程执行记录。
Returns:
通用排程审计七元组;同步异常原样抛出,交由平台排程记录失败运行。
"""
from app.extensions import db
from app.services.order_delivery_reply.sync_service import OrderDeliverySyncService
summary = OrderDeliverySyncService.run_sync(trigger="scheduled")
count = int(summary.get("line_count") or 0)
# [STEP 2] 域内已自行通知生管:写入标记,抑制通用「排程执行结果」企微通知避免双重打扰。
# 直调(run=None,脚本/测试)时跳过 run 摘要写入。
if run is not None:
run.response_summary_json = {"domain_notification_managed": True}
db.session.commit()
notify_results = _notify_production_after_sync(task, count)
failed_notify = [item for item in notify_results if not item["ok"]]
step_logs = [
{
"step": "order_delivery_sync",
"status": "success",
"detail": {**summary, "production_notify": notify_results},
}
]
errors: list[str] = [
f"生管通知发送失败 user_id={item['user_id']} reason={item.get('reason')}" for item in failed_notify
]
return (count, count, 0, 0, [summary], errors, step_logs)
@@ -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'
@@ -0,0 +1,63 @@
"""
backend/app/services/schedule/web_scanner.py
用途:Web 进程内的排程扫描兜底线程——让开发环境(只跑 run.py,没有独立 schedule-worker
容器)也能按 cron 触发到期排程(如订单交期回复每天 07:00 的 ERP 全量同步)。
依赖:app.jobs.runner.run_forever、app.jobs.store.claim_next(schedule 队列)、JobContext。
逻辑:create_app 启动时按 SCHEDULE_WEB_SCANNER_ENABLED 决定是否拉起守护线程;线程内
推送 app context 后复用与 workers/worker_scheduler.py 完全相同的消费路径
(claim_next('schedule') → prepare_schedule_queue 扫描到期任务 → handler 执行)。
多进程并发安全由 enqueue_due_schedule_runs 的 FOR UPDATE SKIP LOCKED 与
schedule_runs 活动 run 去重保证,与独立 worker 并存不会重复执行。
生产环境默认关闭(compose 已有 hxops-schedule-worker 专职容器),可用环境变量覆盖。
"""
from __future__ import annotations
import threading
_web_scanner_started = False
_web_scanner_lock = threading.Lock()
def start_web_schedule_scanner(app) -> None:
"""
按配置在 Web 进程内启动排程扫描守护线程(幂等;重复调用直接返回)。
用途与触发时机:create_app 启动阶段调用;AI/请求路径不触发。
开发环境默认开启(SCHEDULE_WEB_SCANNER_ENABLED 缺省 true),
生产环境默认关闭(缺省 false,由 hxops-schedule-worker 容器负责)。
核心逻辑:[STEP 1] 读 SCHEDULE_WEB_SCANNER_ENABLED,关闭则不打扰;
[STEP 2] 进程内单例锁后起 daemon 线程,线程内推送 app context、
导入 handlers、复用 run_forever(queues=['schedule']) 主循环。
"""
global _web_scanner_started
enabled = bool(app.config.get("SCHEDULE_WEB_SCANNER_ENABLED", False))
if not enabled:
app.logger.info("Web schedule scanner disabled by SCHEDULE_WEB_SCANNER_ENABLED=false")
return
with _web_scanner_lock:
if _web_scanner_started:
return
def _loop(app_ref=app):
with app_ref.app_context():
import app.jobs.handlers # noqa: F401 — 触发 @register_handler
from app.jobs.context import JobContext
from app.jobs.runner import run_forever
ctx = JobContext(
config=dict(app_ref.config),
logger=app_ref.logger,
extras={"queues": ["schedule"]},
)
app_ref.logger.info("Web schedule scanner starting (queues=['schedule'])")
run_forever(ctx)
thread = threading.Thread(target=_loop, name="web-schedule-scanner", daemon=True)
thread.start()
_web_scanner_started = True
app.logger.info("Web schedule scanner started")
@@ -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 ''),
Loaded 100 of 380 files, more files were not shown because too many files have changed in this diff. Show more