fix(audit-20261019): T1-T9 审计修复、存储归属与审计日志列宽
- T1 资金/库存/报价/自采 P1(BIZ-1/2/3/4/10/13/14) - T2 主系统反向事件墓碑/改派/孤儿处理(BIZ-6/8/9) - T3 选分公司 ticket、trust proxy、角色权限收口(SEC-2/3/4) - T4 缺列/RLS/tenant 名单/FK/迁移执行器(DATA-1..8) - T5 401 登出/分页/映射口径/blob/ZIP 中文名(FE-1..4/BIZ-15) - T6 测试脚本目标守卫/config fail-fast/容器配置(OPS-2..8) - T7 前后端测试与 lint 门禁清零 - T8 应付卡片按关联订单日(口径 A) - T9 存储对象全链路归属校验、敏感列禁写、审计 target_id 超长修复
This commit is contained in:
+6
-2
@@ -6,7 +6,6 @@ node_modules
|
||||
!DESIGN_SYSTEM.md
|
||||
.env
|
||||
.env.*
|
||||
!.env.production
|
||||
dist
|
||||
server/dist
|
||||
server/node_modules
|
||||
@@ -19,7 +18,12 @@ server/.env
|
||||
*.log
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
deploy
|
||||
# OPS-5(Dockerfile.web 构建):采用 §AC-T6.4.1 方案 B —— 只排除 deploy 下其它内容,
|
||||
# 显式放行 Dockerfile.web 需要的两个文件(父目录 deploy 本身不在排除列表,故 `!` 例外生效;
|
||||
# 保留原路径可避免 docs/ 里的 deploy/... 行号引用失效、避免配置双份漂移)。
|
||||
deploy/*
|
||||
!deploy/nginx.frontend.conf
|
||||
!deploy/web-entrypoint.sh
|
||||
scripts
|
||||
outputs
|
||||
skills
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# Gitea push config (do not commit token to public repos)
|
||||
# Copy to .env.gitea and fill in your values
|
||||
# 运行环境(必须显式:development|test|production)
|
||||
NODE_ENV=development
|
||||
GITEA_URL=https://git.xdjchuanhui.com
|
||||
GITEA_USER=jxc
|
||||
GITEA_PASS=CHANGE_ME_GITEA_PASSWORD
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
APP_PORT=8080
|
||||
# 运行环境(必须显式:development|test|production)
|
||||
NODE_ENV=production
|
||||
# OPS-3:production 必须显式白名单(逗号分隔,不允许 *);否则 API 拒绝启动
|
||||
CORS_ORIGINS=https://your-supplier.example.com
|
||||
POSTGRES_USER=supplier
|
||||
POSTGRES_PASSWORD=CHANGE_ME_STRONG_PASSWORD
|
||||
POSTGRES_DB=supplier_delivery
|
||||
|
||||
+4
-2
@@ -1,4 +1,6 @@
|
||||
# 三端分离部署配置(局域网示例)
|
||||
# 运行环境(必须显式:development|test|production)
|
||||
NODE_ENV=production
|
||||
# 复制为 .env.split 后修改 IP 为实际局域网地址
|
||||
|
||||
# 前端 Nginx
|
||||
@@ -8,8 +10,8 @@ WEB_PORT=8080
|
||||
API_PORT=3001
|
||||
# 浏览器访问的后端地址(必须是局域网内其他设备也能访问的 IP)
|
||||
API_PUBLIC_URL=http://192.168.0.100:3001
|
||||
# 允许的前端来源,* 表示局域网调试方便;生产可改为 http://192.168.0.100:8080
|
||||
CORS_ORIGINS=*
|
||||
# 允许的前端来源(显式白名单;production 下 * 会被 fail-fast 拒绝)
|
||||
CORS_ORIGINS=http://192.168.0.100:8080
|
||||
|
||||
# 数据库(独立容器,仅 API 内网访问)
|
||||
POSTGRES_USER=supplier
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# 腾讯云 API 密钥(CAM 子账号,最小权限)
|
||||
# 运行环境(必须显式:development|test|production)
|
||||
NODE_ENV=development
|
||||
# 复制为 .env.tencent 并填写,勿提交 Git
|
||||
TENCENT_SECRET_ID=AKIDxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
TENCENT_SECRET_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# 开发团队 · 本机项目说明(AGENTS.local.md)
|
||||
|
||||
> 叠加层:与同目录 `AGENTS.md` 一起生效,本文件只补充"在这台机器上怎么开发与验证"。
|
||||
> 全局团队协议(角色/流程/工具)由 `$DSH_HOME/AGENTS.md` 自动注入,不在此重复。
|
||||
|
||||
## 项目
|
||||
|
||||
- 记录中的工作区路径:`/home/ubuntu/harness/suppler/SupplierSystem`(= 本机 `~/harness/suppler/SupplierSystem`,同一份文件)
|
||||
- 形态:AI 生鲜配送主系统的**供应商系统**二次开发分支(同机开发、共用 PostgreSQL 集群与 COS 桶)
|
||||
- **隔离标识(改代码时最容易踩错的地方,勿改回主系统取值)**:
|
||||
|
||||
| 维度 | 主系统 | 本系统(正确值) | 落点 |
|
||||
|---|---|---|---|
|
||||
| 数据库 / 角色 | `canteen_delivery` / `canteen` | `supplier_delivery` / `supplier` | `server/.env` |
|
||||
| Web 端口 | 3015 | `3021` | `webpack.config.js` |
|
||||
| API 端口 | 3001 | `3022` | `server/.env` `PORT` |
|
||||
| 上传统目录 | `server/uploads` | `server/uploads-supplier` | `STORAGE_DIR` |
|
||||
| COS 前缀 | 无 | `supplier-system/` | `S3_KEY_PREFIX` |
|
||||
|
||||
## 验证命令(在 `~/harness/suppler/SupplierSystem` 下执行)
|
||||
|
||||
| 目的 | 命令 |
|
||||
|---|---|
|
||||
| 类型检查 | `npm run typecheck` |
|
||||
| 前端单测 | `npm run test:unit`(`vitest run`) |
|
||||
| 后端单测 | `npm --prefix server test` |
|
||||
| 流程/页面脚本 | `npm run test:api` / `npm run test:pages` / `npm run test:miniprogram` / `npm run test:customer-mp` |
|
||||
| 全量 | `npm run test:all` |
|
||||
| Lint | `npm run lint`(仓库容忍上限 250 warnings) |
|
||||
|
||||
不必每次全量,但:**改了后端逻辑必须跑 `npm --prefix server test`**;改了前端逻辑跑 `npm run test:unit`。
|
||||
交付时贴出真实命令与输出。
|
||||
|
||||
## 团队分工落点
|
||||
|
||||
- `analyst`:把需求落成验收清单,标注每条怎么验证(含"隔离标识没被改回主系统"这一条)。
|
||||
- `dev`:最小改动;改完自测(自测不算验证)。
|
||||
- `verifier`:逐条对照验收清单;**优先检查上面那张隔离表**,再看权限、金额/库存计算、事务边界。
|
||||
- `tester`:补边界与回归用例,新增测试放既有 `tests/` 或 `server/tests/`,风格保持一致。
|
||||
|
||||
## 红线
|
||||
|
||||
未经用户当轮直接命令,**不得部署上线**(生产范围与细则见本目录 `AGENTS.md` 顶部)。
|
||||
@@ -34,7 +34,11 @@ services:
|
||||
- '${APP_PORT:-8080}:3001'
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
# T6/T3 协作:容器内必须监听 0.0.0.0(默认回环只适合同机 nginx)
|
||||
HOST: 0.0.0.0
|
||||
PORT: 3001
|
||||
# OPS-3 配套:production 必须显式白名单(缺失/* 会拒绝启动)
|
||||
CORS_ORIGINS: ${CORS_ORIGINS:?set CORS_ORIGINS in .env.production}
|
||||
DATABASE_URL: postgresql://${POSTGRES_USER:-supplier}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:-supplier_delivery}
|
||||
ADMIN_DATABASE_URL: postgresql://${POSTGRES_USER:-supplier}:${POSTGRES_PASSWORD}@postgres:5432/postgres
|
||||
JWT_SECRET: ${JWT_SECRET:?set JWT_SECRET in .env.production}
|
||||
@@ -61,6 +65,12 @@ services:
|
||||
ARK_MODEL: ${ARK_MODEL:-}
|
||||
volumes:
|
||||
- supplier_uploads_prod:/app/uploads
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'node -e "fetch(''http://127.0.0.1:3001/api/health'').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"']
|
||||
interval: 15s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 40s
|
||||
|
||||
volumes:
|
||||
supplier_pgdata_prod:
|
||||
|
||||
@@ -40,12 +40,14 @@ services:
|
||||
- '${API_PORT:-3001}:3001'
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
# T6/T3 协作:容器内必须监听 0.0.0.0
|
||||
HOST: 0.0.0.0
|
||||
SERVE_STATIC: 'false'
|
||||
PORT: 3001
|
||||
DATABASE_URL: postgresql://${POSTGRES_USER:-supplier}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:-supplier_delivery}
|
||||
ADMIN_DATABASE_URL: postgresql://${POSTGRES_USER:-supplier}:${POSTGRES_PASSWORD}@postgres:5432/postgres
|
||||
JWT_SECRET: ${JWT_SECRET:?set JWT_SECRET}
|
||||
CORS_ORIGINS: ${CORS_ORIGINS:-*}
|
||||
CORS_ORIGINS: ${CORS_ORIGINS:?set CORS_ORIGINS (explicit origin, not *)}
|
||||
STORAGE_DIR: /app/uploads
|
||||
# 容器内路径由**本系统专用卷** supplier_uploads 兜底(与主系统不同容器/不同卷);
|
||||
# 一旦启用对象存储,S3_KEY_PREFIX 必须非空 —— 留空即写进主系统的桶根。
|
||||
@@ -69,6 +71,12 @@ services:
|
||||
ARK_MODEL: ${ARK_MODEL:-}
|
||||
volumes:
|
||||
- supplier_uploads:/app/uploads
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'node -e "fetch(''http://127.0.0.1:3001/api/health'').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"']
|
||||
interval: 15s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 40s
|
||||
networks:
|
||||
- db-net
|
||||
- app-net
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# customer_sku_remarks 租户隔离口径(D9-B,2026-10-19)
|
||||
|
||||
## 结论
|
||||
|
||||
`customer_sku_remarks` **有意关闭 RLS**(public / legacy_public / tenant_br001 / tenant_template 与 tenant_br002 对齐)。
|
||||
|
||||
## 原因
|
||||
|
||||
- 该表**没有 `branch_code` 列**,无法用 `branch_code = current_setting('app.branch_code')` 表达分公司隔离;
|
||||
历史 RLS 开启但 0 条 policy ⇒ 除 br002(RLS 关)外的 schema 读 0 行、写被拒(BR001 功能坏)。
|
||||
- 本系统租户隔离的主机制是 **每租户独立 schema**(`tenant_<branch>`,连接时设置 `search_path`);
|
||||
表级 RLS 只用于"含 branch_code 且可能跨分支共享 schema"的表(`apply_tenant_core_rls` 名单)。
|
||||
- 方案 A(加 branch_code + 回填 + 改写入/网关)影响面大且需客户端传 branch_code;方案 C(按 customer_code EXISTS)
|
||||
对"新客户 code 尚不存在"的 INSERT 仍过不了 WITH CHECK。用户批准 **B:对齐关闭**。
|
||||
|
||||
## 迁移
|
||||
|
||||
- `migrations/20261060_customer_sku_remarks_disable_rls.sql`:对所有 `relrowsecurity=true` 的
|
||||
`customer_sku_remarks` 执行 `DISABLE ROW LEVEL SECURITY`(DO 块、幂等)。
|
||||
- 只读校验:`pg_class.relrowsecurity = false`(全部 schema);`pg_policies` 中该表 0 条。
|
||||
|
||||
## 写入/读取路径
|
||||
|
||||
`customerSkuRemarkService`(写)与 `/api/data` 网关(读写)。隔离依赖请求租户上下文切换 `search_path`;
|
||||
跨租户误读不会因 RLS 被拦,代码层不得在无租户上下文时直读该表。
|
||||
@@ -0,0 +1,54 @@
|
||||
# 存储对象旧 key(无 `<branch>/` 前缀)迁移说明
|
||||
|
||||
- 日期:2026-10-19
|
||||
- 范围:`server/src/services/storageObjectOwnership.ts`、`server/src/services/accessPolicy.ts`
|
||||
- 关联:T9 存储归属(SEC-5 / T9F-5)
|
||||
|
||||
## 背景
|
||||
|
||||
历史对象 key 有两种形状:
|
||||
|
||||
1. **新 key(推荐)**:`<branchCode>/<folder>/<file>`,例如 `BR001/free-cost/x.jpg`;
|
||||
2. **旧 key(无前缀)**:例如 `free-cost/x.jpg`、`sku-direct/2026-...jpg`、`inspection-photos/...`,
|
||||
以及更早的裸文件名 `1700000000000-abc.jpg`。
|
||||
|
||||
T9F-5 之前,`buildSignedStoragePathForCtx` 对旧 key 只要拿到任意 `branchCode` 就**同步签发**
|
||||
可读 URL,属于 fail-open:跨租户旧对象只要知道对象名就能被签出。
|
||||
|
||||
## 现在的规则(2026-10-19 起)
|
||||
|
||||
- `buildSignedStoragePathForCtx(ctx, bucket, key)`:
|
||||
- `<branch>/...`:前缀必须等于当前 branch,否则 403;
|
||||
- `archive/<branch>/...`:只允许本 branch 的归档下载(跨分支 403);
|
||||
- **无前缀旧 key**:**不再同步签发**,一律 403;
|
||||
- `super_admin`:设计上的跨租户运维口,保留签发能力。
|
||||
- 需要读取本分支旧 key 的入口,改用 `buildSignedStoragePathForCtxChecked(ctx, bucket, key)`:
|
||||
先 `assertStorageKeyOwned` 做异步 DB 归属反查(本分支 RLS 上下文 + 业务表 LIKE),
|
||||
通过后才签发 —— 即“签发前异步反查”,不是同步放行。
|
||||
- 列表/装饰等展示路径使用 `tryBuildSignedStoragePathForCtx`:旧 key 未迁移时返回 `null`
|
||||
(调用方给空 URL),**不 500**、不泄露。
|
||||
- `/api/data` 的 insert/update 禁止写存储 key 列(`accessPolicy.ts` 的
|
||||
`SENSITIVE_STORAGE_WRITE_COLUMNS`,含嵌套 JSON 字段递归命中),super_admin 也必须走业务接口。
|
||||
|
||||
## 需要迁移的对象
|
||||
|
||||
以下命名空间中的**无前缀**对象需要按 `<branchCode>/` 前缀重命名(或重新上传):
|
||||
|
||||
| 旧前缀 | 逻辑桶 | 说明 |
|
||||
|--------|--------|------|
|
||||
| `inspection-photos/`、裸文件名 | inspection-photos | 验收照片 |
|
||||
| `processing-inspection-photos/` | processing-inspection-photos | 加工验收照片 |
|
||||
| `delivery-photos/`、`delivery-loading/` | delivery-photos | 分拣/核货/送达照片 |
|
||||
| `sku-direct/` | delivery-photos | 自采直送照片 |
|
||||
| `supplier-invoices/`、`free-cost/`、`free-cost-invoice/`、`free-cost-payment/` | invoices | 发票/成本凭证/付款凭证 |
|
||||
| `quality-reports/` | quality-reports | 质检/批次报告 |
|
||||
|
||||
迁移原则:
|
||||
|
||||
1. 对象重命名后,同步更新业务表里的引用列(`inspections.inspection_photos`、
|
||||
`picking_items.outbound_photos/loading_photos`、`purchase_orders.direct_delivery_photos`、
|
||||
`invoices.invoice_url`、`cost_details.voucher_url`、`fixed_costs.voucher_urls`、
|
||||
`free_cost_*` 的 `storage_path`、`quality_reports/inventory_batch_reports.file_paths` 等);
|
||||
2. 迁移前后都要跑一遍 `assertStorageKeyOwned` 抽样核对;
|
||||
3. 归档包(`archive/<branch>/<YYYY-MM>.tar.gz`)不是业务源 key,不参与本次迁移,也**禁止**
|
||||
作为 finalize 的源对象(`assertStorageKeyOwned` 与 finalize 均对 `archive/*` 403)。
|
||||
@@ -0,0 +1,51 @@
|
||||
# 租户核心 FK 收口(DATA-7,2026-10-19)
|
||||
|
||||
## 迁移
|
||||
|
||||
`migrations/20261062_tenant_core_foreign_keys_drift.sql`
|
||||
|
||||
- `public.ensure_tenant_core_foreign_keys(p_schema)` 扩展为 **22 条**:原有 3 条
|
||||
(order_items→orders、order_item_fulfillments→order_items、picking_items→picking_tasks,保持原约束名)
|
||||
+ 新增 19 条,子表/列/父表/列/`ON DELETE` 与 `tenant_br001` 的 `pg_get_constraintdef` 完全一致。
|
||||
- 全部 `ADD CONSTRAINT ... NOT VALID`(不阻塞、不删数据);幂等(`pg_constraint` NOT EXISTS 判断)。
|
||||
- 迁移对 `tenant_template` + 所有已注册 active/pending 租户执行该函数。
|
||||
|
||||
## VALIDATE 策略(D11)
|
||||
|
||||
迁移末尾对**本次涉及的 NOT VALID** 约束逐条查孤儿:
|
||||
|
||||
- 孤儿数 = 0 ⇒ `ALTER TABLE ... VALIDATE CONSTRAINT`(滚动验证,发生在同一迁移事务内);
|
||||
- 孤儿数 > 0 ⇒ 保持 `NOT VALID` 并 `RAISE NOTICE` 记 orphan 计数,**不删数据**。
|
||||
|
||||
本地(2026-10-19)迁移后:所有租户 FK 计数 = 22/22/22/22/22/22,`tenant_br001` vs `tenant_br002`
|
||||
按"子表+列→父表+列+删除动作"差集为空;仍有 2 条保持 `NOT VALID`:
|
||||
|
||||
| schema | 约束 | 子表→父表 | orphan |
|
||||
|---|---|---|---|
|
||||
| tenant_br002 | tenant_core_fulfillments_item_fk | order_item_fulfillments→order_items | 14 |
|
||||
| tenant_br005 | tenant_core_fulfillments_item_fk | order_item_fulfillments→order_items | 6 |
|
||||
|
||||
这些历史孤儿需人工清理后再滚动执行:
|
||||
|
||||
```sql
|
||||
SELECT c.id, c.order_item_id
|
||||
FROM tenant_br002.order_item_fulfillments c
|
||||
WHERE c.order_item_id IS NOT NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM tenant_br002.order_items p WHERE p.id = c.order_item_id);
|
||||
-- 清理后:
|
||||
ALTER TABLE tenant_br002.order_item_fulfillments VALIDATE CONSTRAINT tenant_core_fulfillments_item_fk;
|
||||
```
|
||||
|
||||
## 查询
|
||||
|
||||
```sql
|
||||
-- 计数
|
||||
select n.nspname, count(*) from pg_constraint c
|
||||
join pg_class r on r.oid=c.conrelid join pg_namespace n on n.oid=r.relnamespace
|
||||
where c.contype='f' and n.nspname like 'tenant%' group by 1 order by 1;
|
||||
|
||||
-- 未验证
|
||||
select n.nspname, c.conname from pg_constraint c
|
||||
join pg_class r on r.oid=c.conrelid join pg_namespace n on n.oid=r.relnamespace
|
||||
where c.contype='f' and not c.convalidated and n.nspname like 'tenant%';
|
||||
```
|
||||
@@ -61,8 +61,8 @@ CREATE POLICY anon_all_customer_alias_stats ON customer_alias_stats FOR ALL USIN
|
||||
CREATE POLICY anon_all_alias_recognition_logs ON alias_recognition_logs FOR ALL USING (true);
|
||||
|
||||
-- 创建索引
|
||||
CREATE INDEX idx_customer_image_aliases_customer ON customer_image_aliases(customer_code);
|
||||
CREATE INDEX idx_customer_image_aliases_sku ON customer_image_aliases(sku_code);
|
||||
CREATE INDEX idx_customer_image_aliases_ocr ON customer_image_aliases USING gin(to_tsvector('chinese', ocr_text));
|
||||
CREATE INDEX idx_customer_alias_stats_customer ON customer_alias_stats(customer_code);
|
||||
CREATE INDEX idx_alias_recognition_logs_customer ON alias_recognition_logs(customer_code);
|
||||
CREATE INDEX IF NOT EXISTS idx_customer_image_aliases_customer ON customer_image_aliases(customer_code);
|
||||
CREATE INDEX IF NOT EXISTS idx_customer_image_aliases_sku ON customer_image_aliases(sku_code);
|
||||
CREATE INDEX IF NOT EXISTS idx_customer_image_aliases_ocr ON customer_image_aliases USING gin(to_tsvector('chinese', ocr_text));
|
||||
CREATE INDEX IF NOT EXISTS idx_customer_alias_stats_customer ON customer_alias_stats(customer_code);
|
||||
CREATE INDEX IF NOT EXISTS idx_alias_recognition_logs_customer ON alias_recognition_logs(customer_code);
|
||||
|
||||
@@ -122,7 +122,7 @@ BEGIN
|
||||
END IF;
|
||||
|
||||
EXECUTE format(
|
||||
'CREATE TABLE %I.%I (LIKE %I.%I INCLUDING ALL)',
|
||||
'CREATE TABLE IF NOT EXISTS %I.%I (LIKE %I.%I INCLUDING ALL)',
|
||||
p_target_schema, p_table, p_source_schema, p_table
|
||||
);
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ BEGIN
|
||||
IF to_regclass(format('%I.processing_demand_items', sch)) IS NULL
|
||||
AND to_regclass(format('%I.processing_tasks', sch)) IS NOT NULL THEN
|
||||
EXECUTE format(
|
||||
'CREATE TABLE %I.processing_demand_items (
|
||||
'CREATE TABLE IF NOT EXISTS %I.processing_demand_items (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
task_id UUID NOT NULL REFERENCES %I.processing_tasks(id) ON DELETE CASCADE,
|
||||
order_item_id UUID NOT NULL,
|
||||
@@ -64,7 +64,7 @@ BEGIN
|
||||
IF to_regclass(format('%I.processing_demand_picks', sch)) IS NULL
|
||||
AND to_regclass(format('%I.processing_tasks', sch)) IS NOT NULL THEN
|
||||
EXECUTE format(
|
||||
'CREATE TABLE %I.processing_demand_picks (
|
||||
'CREATE TABLE IF NOT EXISTS %I.processing_demand_picks (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
task_id UUID NOT NULL REFERENCES %I.processing_tasks(id) ON DELETE CASCADE,
|
||||
sku_code VARCHAR(50) NOT NULL,
|
||||
|
||||
@@ -16,5 +16,5 @@ CREATE TABLE IF NOT EXISTS order_image_vectors (
|
||||
);
|
||||
|
||||
-- 索引
|
||||
CREATE INDEX idx_order_image_vectors_hash ON order_image_vectors(customer_code, image_hash);
|
||||
CREATE INDEX idx_order_image_vectors_customer ON order_image_vectors(customer_code);
|
||||
CREATE INDEX IF NOT EXISTS idx_order_image_vectors_hash ON order_image_vectors(customer_code, image_hash);
|
||||
CREATE INDEX IF NOT EXISTS idx_order_image_vectors_customer ON order_image_vectors(customer_code);
|
||||
@@ -14,7 +14,7 @@ BEGIN
|
||||
LOOP
|
||||
IF to_regclass(format('%I.order_image_vectors', sch)) IS NULL THEN
|
||||
EXECUTE format($sql$
|
||||
CREATE TABLE %I.order_image_vectors (
|
||||
CREATE TABLE IF NOT EXISTS %I.order_image_vectors (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
customer_code VARCHAR(50) NOT NULL,
|
||||
image_hash VARCHAR(64) NOT NULL,
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
-- 主系统**反向事件墓碑**(2026-10-19,T2 / BIZ-6)
|
||||
--
|
||||
-- 背景:反向事件(preparations.reallocated / preparations.item_removed / order.cancelled)
|
||||
-- **可能先于 E1 到达**(E1 受主系统"发送供应商"三档闸门,E2/E3/E4 恒推)。旧实现遇到未知
|
||||
-- prep_id / 未知订单只返回 ignored;等 E1 之后到达时,已被删/已改派的备货行会被**重新建回来**。
|
||||
--
|
||||
-- 口径:未知业务键落一条**持久墓碑**,导入侧命中墓碑即跳过(不建单/不建行)。
|
||||
-- · kind = 'prep':business_key = prep_id(小写);kind = 'order':business_key = main_order_code;
|
||||
-- · 唯一键 (branch_code, kind, business_key) ⇒ 重复投递 ON CONFLICT DO NOTHING(幂等);
|
||||
-- · 可清理:应用侧 `purgeReverseTombstones(days)`(不接定时任务);
|
||||
-- · 本表是**平台台账**(public,与 main_system_order_imports 同域),
|
||||
-- **不是**租户业务表 ⇒ 不加入 public.tenant_business_tables()。
|
||||
-- 迁移幂等:CREATE TABLE IF NOT EXISTS + DO 块补唯一约束。
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.main_system_reverse_tombstones (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
branch_code varchar(64) NOT NULL,
|
||||
-- 'prep' = 备货行 prep_id;'order' = 主系统订单号 main_order_code
|
||||
kind varchar(16) NOT NULL,
|
||||
business_key text NOT NULL,
|
||||
reason text,
|
||||
-- 原始事件载荷/定位线索(排障用;可为空)
|
||||
payload jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT main_system_reverse_tombstones_kind_check CHECK (kind IN ('prep', 'order'))
|
||||
);
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint
|
||||
WHERE conname = 'main_system_reverse_tombstones_branch_kind_key_key'
|
||||
AND conrelid = 'public.main_system_reverse_tombstones'::regclass
|
||||
) THEN
|
||||
ALTER TABLE public.main_system_reverse_tombstones
|
||||
ADD CONSTRAINT main_system_reverse_tombstones_branch_kind_key_key
|
||||
UNIQUE (branch_code, kind, business_key);
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- 清理(按 created_at)与导入侧按 key 批量查询都走索引
|
||||
CREATE INDEX IF NOT EXISTS idx_main_system_reverse_tombstones_created
|
||||
ON public.main_system_reverse_tombstones (created_at);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_main_system_reverse_tombstones_lookup
|
||||
ON public.main_system_reverse_tombstones (branch_code, kind, business_key);
|
||||
|
||||
COMMENT ON TABLE public.main_system_reverse_tombstones IS
|
||||
'主系统反向事件墓碑:未知 prep_id/main_order_code 先落此表,E1 导入命中即跳过(BIZ-6,2026-10-19)';
|
||||
@@ -0,0 +1,33 @@
|
||||
-- T4 / DATA-1(2026-10-19,用户批准方案 B):customer_sku_remarks 统一关闭 RLS。
|
||||
--
|
||||
-- 背景:该表**没有 branch_code 列**,RLS 无法表达"分公司隔离";但 public / legacy_public /
|
||||
-- tenant_br001 / tenant_template 开了 RLS 且 0 条 policy ⇒ BR001 经 /api/data 网关读 0 行、
|
||||
-- INSERT 被拒(功能坏),而 tenant_br002(关 RLS)正常。
|
||||
--
|
||||
-- 决策(D9-B):对齐 br002,对**所有已开启 RLS 的 schema** 执行 DISABLE ROW LEVEL SECURITY;
|
||||
-- 隔离依赖 schema(每个租户独立 schema,连接 `search_path` 由租户上下文设置),
|
||||
-- 与"含 branch_code 的表才上租户 RLS"策略一致。详见
|
||||
-- docs/design/20261019-customer-sku-remarks-rls.md。
|
||||
--
|
||||
-- 幂等:只对 relrowsecurity=true 的 schema 执行;重复运行 no-op。
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
r RECORD;
|
||||
BEGIN
|
||||
FOR r IN
|
||||
SELECT n.nspname AS schema_name
|
||||
FROM pg_class c
|
||||
JOIN pg_namespace n ON n.oid = c.relnamespace
|
||||
WHERE c.relname = 'customer_sku_remarks'
|
||||
AND c.relkind = 'r'
|
||||
AND c.relrowsecurity = true
|
||||
ORDER BY n.nspname
|
||||
LOOP
|
||||
EXECUTE format('ALTER TABLE %I.customer_sku_remarks DISABLE ROW LEVEL SECURITY', r.schema_name);
|
||||
RAISE NOTICE 'customer_sku_remarks RLS disabled on % (D9-B: no branch_code, isolation by schema)', r.schema_name;
|
||||
END LOOP;
|
||||
END $$;
|
||||
|
||||
COMMENT ON TABLE public.customer_sku_remarks IS
|
||||
'客户商品备注:无 branch_code,租户隔离依赖 schema(RLS 有意关闭,见 docs/design/20261019-customer-sku-remarks-rls.md)';
|
||||
@@ -0,0 +1,212 @@
|
||||
-- T4 / DATA-5(2026-10-19 T4):tenant_business_tables() 名单漂移 + 双向守卫。
|
||||
--
|
||||
-- 现状(迁移前):名单 119 项 —— 缺 main_system_sku_mappings(20261018 之前)、
|
||||
-- 且含两张幽灵表:quote_sheet_change_requests(已被 20261020 主动 DROP)、
|
||||
-- supplier_price_agreements(全库不存在、本仓库无代码引用)。
|
||||
-- 20261018 之后名单已补 msm,但仍残留两个幽灵名 ⇒ 新建分公司克隆会去找不存在的表。
|
||||
--
|
||||
-- 本迁移:
|
||||
-- ① 重发名单:117 项 = 模板当前 117 张表(补 msm、删两个幽灵名);
|
||||
-- ② 重定义 assert_tenant_template_matches_business_tables() 为**双向**守卫:
|
||||
-- 模板 ⊆ 名单(旧) + 名单 ⊆ 模板(新,新装库漏登记/多登记都中断迁移);
|
||||
-- ③ 末尾先 ensure_tenant_schemas_match_template() 给已有租户补表,再跑断言。
|
||||
-- 幂等:CREATE OR REPLACE + 迁移末尾 ensure/assert 均幂等;不改文件名/顺序。
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.tenant_business_tables()
|
||||
RETURNS TEXT[]
|
||||
LANGUAGE sql
|
||||
IMMUTABLE
|
||||
AS $$
|
||||
SELECT ARRAY[
|
||||
'main_system_sku_mappings',
|
||||
'after_sale_returns',
|
||||
'after_sales',
|
||||
'ai_prompt_overrides',
|
||||
'ai_prompt_revisions',
|
||||
'ai_prompt_templates',
|
||||
'alias_recognition_logs',
|
||||
'allocation_tasks',
|
||||
'assistant_conversations',
|
||||
'assistant_messages',
|
||||
'assistant_turns',
|
||||
'bid_awards',
|
||||
'bid_invitations',
|
||||
'bid_prices',
|
||||
'bid_quotes',
|
||||
'bid_round_items',
|
||||
'bid_rounds',
|
||||
'categories',
|
||||
'cost_adjustments',
|
||||
'cost_details',
|
||||
'customer_alias_stats',
|
||||
'customer_delivery_assignments',
|
||||
'customer_portal_users',
|
||||
'customer_processing_aliases',
|
||||
'customer_quote_sheet_customers',
|
||||
'customer_quote_sheet_items',
|
||||
'customer_quote_sheets',
|
||||
'customer_quote_versions',
|
||||
'customer_recipients',
|
||||
'customer_sku_aliases',
|
||||
'customer_sku_remarks',
|
||||
'customer_skus',
|
||||
'customer_statements',
|
||||
'customers',
|
||||
'delivery_location_history',
|
||||
'delivery_person_locations',
|
||||
'delivery_person_users',
|
||||
'delivery_persons',
|
||||
'delivery_schedules',
|
||||
'delivery_signatures',
|
||||
'delivery_tasks',
|
||||
'exception_tickets',
|
||||
'fixed_costs',
|
||||
'free_cost_invoice_links',
|
||||
'free_cost_invoices',
|
||||
'free_cost_payment_vouchers',
|
||||
'import_mapping_memories',
|
||||
'inspection_loss_confirmations',
|
||||
'inspection_photo_archive_entries',
|
||||
'inspection_photo_archives',
|
||||
'inspection_returns',
|
||||
'inspection_review_logs',
|
||||
'inspections',
|
||||
'inventory',
|
||||
'inventory_batch_report_matches',
|
||||
'inventory_batch_reports',
|
||||
'inventory_logs',
|
||||
'inventory_reservations',
|
||||
'invoice_statement_links',
|
||||
'invoices',
|
||||
'market_compare_exclusions',
|
||||
'market_external_catalog',
|
||||
'market_price_history',
|
||||
'market_price_indices',
|
||||
'market_prices',
|
||||
'market_sku_external_bindings',
|
||||
'notifications',
|
||||
'operation_logs',
|
||||
'order_allocation_batches',
|
||||
'order_item_fulfillments',
|
||||
'order_item_returns',
|
||||
'order_items',
|
||||
'orders',
|
||||
'parse_session_items',
|
||||
'parse_sessions',
|
||||
'picking_assign_rules',
|
||||
'picking_containers',
|
||||
'picking_items',
|
||||
'picking_scan_logs',
|
||||
'picking_tasks',
|
||||
'price_invert_events',
|
||||
'print_jobs',
|
||||
'processing_demand_items',
|
||||
'processing_demand_picks',
|
||||
'processing_logs',
|
||||
'processing_tasks',
|
||||
'product_catalog',
|
||||
'product_substitutions',
|
||||
'purchase_orders',
|
||||
'purchaser_users',
|
||||
'quality_report_prep_links',
|
||||
'quality_reports',
|
||||
'quote_price_proposals',
|
||||
'seasonal_recommendations',
|
||||
'self_purchase_stock_inbounds',
|
||||
'sign_records',
|
||||
'sku_direct_delivery_customers',
|
||||
'sku_suppliers',
|
||||
'skus',
|
||||
'smart_classification_rules',
|
||||
'statement_disputes',
|
||||
'statement_lines',
|
||||
'statement_payments',
|
||||
'supplier_categories',
|
||||
'supplier_prep_amend_requests',
|
||||
'supplier_preparations',
|
||||
'supplier_rating_snapshots',
|
||||
'supplier_statements',
|
||||
'supplier_users',
|
||||
'suppliers',
|
||||
'system_configs',
|
||||
'unit_conversions',
|
||||
'user_preferences',
|
||||
'voice_recognition_logs',
|
||||
'warehouse_locations',
|
||||
'warehouses',
|
||||
'weigh_devices'
|
||||
]
|
||||
$$;
|
||||
|
||||
COMMENT ON FUNCTION public.tenant_business_tables() IS
|
||||
'租户 schema 业务表名单(117 张,= tenant_template 表集合;新增/删除表必须同步本函数,末尾双向断言会中断迁移)。';
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.assert_tenant_template_matches_business_tables()
|
||||
RETURNS void
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
DECLARE
|
||||
v_leftover text;
|
||||
v_missing_on_template text;
|
||||
BEGIN
|
||||
-- 新库/未初始化模板:不阻断
|
||||
IF to_regclass('tenant_template.orders') IS NULL
|
||||
AND to_regclass('tenant_template.product_catalog') IS NULL THEN
|
||||
RAISE NOTICE 'tenant_template 不存在或为空,跳过 tenant_business_tables() 校验';
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
-- ① 模板 ⊆ 名单(旧方向):模板有表但名单没登记 ⇒ 新建分公司会缺表
|
||||
SELECT string_agg(c.relname, ', ' ORDER BY c.relname)
|
||||
INTO v_leftover
|
||||
FROM pg_class c
|
||||
JOIN pg_namespace n ON n.oid = c.relnamespace
|
||||
WHERE c.relkind = 'r'
|
||||
AND n.nspname = 'tenant_template'
|
||||
AND NOT (c.relname = ANY (public.tenant_business_tables()));
|
||||
|
||||
IF v_leftover IS NOT NULL THEN
|
||||
RAISE EXCEPTION
|
||||
'tenant_template 仍有未列入 tenant_business_tables() 的表: %(新增表未同步名单 → 新建分公司会缺表)',
|
||||
v_leftover;
|
||||
END IF;
|
||||
|
||||
-- ② 名单 ⊆ 模板(新方向):名单里有、模板却没有 ⇒ 幽灵项/漏建表,克隆会失败
|
||||
SELECT string_agg(t, ', ' ORDER BY t)
|
||||
INTO v_missing_on_template
|
||||
FROM unnest(public.tenant_business_tables()) AS t
|
||||
WHERE to_regclass(format('tenant_template.%I', t)) IS NULL;
|
||||
|
||||
IF v_missing_on_template IS NOT NULL THEN
|
||||
RAISE EXCEPTION
|
||||
'tenant_business_tables() 含 tenant_template 不存在的表: %(幽灵项或漏建模板表)',
|
||||
v_missing_on_template;
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
|
||||
COMMENT ON FUNCTION public.assert_tenant_template_matches_business_tables() IS
|
||||
'双向守卫:tenant_template 表集合必须与 tenant_business_tables() 完全一致(任一方向漏/多都中断迁移)。见 docs/design/20260915-tenant-table-list-guard.md';
|
||||
|
||||
-- 兼容显式命名(AC-T4.3.3):反向守卫也可单独调用
|
||||
CREATE OR REPLACE FUNCTION public.assert_business_tables_match_tenant_template()
|
||||
RETURNS void
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
BEGIN
|
||||
PERFORM public.assert_tenant_template_matches_business_tables();
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- 给已有租户补模板表(msm 已存在则为 no-op),再跑双向断言。
|
||||
-- DO 块形式:与其它迁移一致,便于幂等重放/集中报错(函数本身幂等)。
|
||||
-- P1(T4 红队复攻,2026-10-19):顺序必须是 **先双向 assert、后 ensure**!
|
||||
-- 若先 ensure:ensure 会把"名单有、template 缺、public 有"的平台表克隆进 template,
|
||||
-- 随后的反向断言看到 template 已含该表 ⇒ 多登记/幽灵项被漏检(红线)。
|
||||
DO $$
|
||||
BEGIN
|
||||
PERFORM public.assert_tenant_template_matches_business_tables();
|
||||
PERFORM public.ensure_tenant_schemas_match_template();
|
||||
-- ensure 后再断言一次:确保补表后仍严格一致(补表不应引入漂移)
|
||||
PERFORM public.assert_tenant_template_matches_business_tables();
|
||||
END $$;
|
||||
@@ -0,0 +1,204 @@
|
||||
-- T4 / DATA-7(2026-10-19 T4):租户核心 FK 漂移收口(br002 3 条 vs br001/template 22 条)。
|
||||
--
|
||||
-- 现状:tenant_br002 只有 3 条核心 FK(order_items/order_item_fulfillments/picking_items 也可能缺),
|
||||
-- br001/template 已有 22 条;其它租户同样漂移。缺 FK 会让删父行留孤儿(Postgres 不拦)。
|
||||
--
|
||||
-- 本迁移:
|
||||
-- ① CREATE OR REPLACE public.ensure_tenant_core_foreign_keys(p_schema):
|
||||
-- 原有 3 条 + 新增 19 条(以 tenant_br001 的 pg_get_constraintdef 为准,子表/父表/列/ON DELETE 完全一致);
|
||||
-- 全部先 ADD CONSTRAINT ... NOT VALID(不阻塞、不删数据);
|
||||
-- ② 对 tenant_template + 所有已注册 active/pending 租户 PERFORM 该函数;
|
||||
-- ③ 条件 VALIDATE:对本次涉及的 NOT VALID FK 先查孤儿数;=0 才 VALIDATE,>0 保持 NOT VALID 并 RAISE NOTICE
|
||||
-- 输出 orphan 计数(不删数据,留人工清理后滚动 VALIDATE)。
|
||||
-- 幂等:NOT EXISTS(pg_constraint) 后 ADD;VALIDATE 对已 validated 的约束是 no-op(按 convalidated 过滤)。
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.ensure_tenant_core_foreign_keys(p_schema TEXT)
|
||||
RETURNS VOID
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
DECLARE
|
||||
child_oid oid;
|
||||
parent_oid oid;
|
||||
child_att smallint;
|
||||
parent_att smallint;
|
||||
v_child text;
|
||||
v_child_col text;
|
||||
v_parent text;
|
||||
v_parent_col text;
|
||||
v_on_delete text;
|
||||
v_conname text;
|
||||
BEGIN
|
||||
IF p_schema IS NULL OR NOT (
|
||||
p_schema = 'tenant_template'
|
||||
OR (
|
||||
p_schema ~ '^tenant_[a-z0-9_-]{2,30}$'
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM public.tenant_schema_registry r
|
||||
WHERE r.schema_name = p_schema AND r.status IN ('active', 'pending')
|
||||
)
|
||||
)
|
||||
) THEN
|
||||
RAISE EXCEPTION 'invalid or unregistered tenant schema: %', p_schema;
|
||||
END IF;
|
||||
|
||||
-- 原有 3 条核心 FK(保持原约束名与语义)
|
||||
child_oid := to_regclass(format('%I.order_items', p_schema));
|
||||
parent_oid := to_regclass(format('%I.orders', p_schema));
|
||||
IF child_oid IS NOT NULL AND parent_oid IS NOT NULL THEN
|
||||
SELECT attnum::smallint INTO child_att FROM pg_attribute
|
||||
WHERE attrelid = child_oid AND attname = 'order_code' AND NOT attisdropped;
|
||||
SELECT attnum::smallint INTO parent_att FROM pg_attribute
|
||||
WHERE attrelid = parent_oid AND attname = 'order_code' AND NOT attisdropped;
|
||||
IF child_att IS NOT NULL AND parent_att IS NOT NULL AND NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint c
|
||||
WHERE c.contype = 'f' AND c.conrelid = child_oid AND c.confrelid = parent_oid
|
||||
AND c.conkey = ARRAY[child_att]::smallint[] AND c.confkey = ARRAY[parent_att]::smallint[]
|
||||
) THEN
|
||||
EXECUTE format(
|
||||
'ALTER TABLE %I.order_items ADD CONSTRAINT tenant_core_order_items_order_fk
|
||||
FOREIGN KEY (order_code) REFERENCES %I.orders(order_code)
|
||||
ON DELETE CASCADE NOT VALID', p_schema, p_schema);
|
||||
END IF;
|
||||
END IF;
|
||||
|
||||
child_oid := to_regclass(format('%I.order_item_fulfillments', p_schema));
|
||||
parent_oid := to_regclass(format('%I.order_items', p_schema));
|
||||
child_att := NULL; parent_att := NULL;
|
||||
IF child_oid IS NOT NULL AND parent_oid IS NOT NULL THEN
|
||||
SELECT attnum::smallint INTO child_att FROM pg_attribute
|
||||
WHERE attrelid = child_oid AND attname = 'order_item_id' AND NOT attisdropped;
|
||||
SELECT attnum::smallint INTO parent_att FROM pg_attribute
|
||||
WHERE attrelid = parent_oid AND attname = 'id' AND NOT attisdropped;
|
||||
IF child_att IS NOT NULL AND parent_att IS NOT NULL AND NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint c
|
||||
WHERE c.contype = 'f' AND c.conrelid = child_oid AND c.confrelid = parent_oid
|
||||
AND c.conkey = ARRAY[child_att]::smallint[] AND c.confkey = ARRAY[parent_att]::smallint[]
|
||||
) THEN
|
||||
EXECUTE format(
|
||||
'ALTER TABLE %I.order_item_fulfillments ADD CONSTRAINT tenant_core_fulfillments_item_fk
|
||||
FOREIGN KEY (order_item_id) REFERENCES %I.order_items(id)
|
||||
ON DELETE CASCADE NOT VALID', p_schema, p_schema);
|
||||
END IF;
|
||||
END IF;
|
||||
|
||||
child_oid := to_regclass(format('%I.picking_items', p_schema));
|
||||
parent_oid := to_regclass(format('%I.picking_tasks', p_schema));
|
||||
child_att := NULL; parent_att := NULL;
|
||||
IF child_oid IS NOT NULL AND parent_oid IS NOT NULL THEN
|
||||
SELECT attnum::smallint INTO child_att FROM pg_attribute
|
||||
WHERE attrelid = child_oid AND attname = 'pick_code' AND NOT attisdropped;
|
||||
SELECT attnum::smallint INTO parent_att FROM pg_attribute
|
||||
WHERE attrelid = parent_oid AND attname = 'pick_code' AND NOT attisdropped;
|
||||
IF child_att IS NOT NULL AND parent_att IS NOT NULL AND NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint c
|
||||
WHERE c.contype = 'f' AND c.conrelid = child_oid AND c.confrelid = parent_oid
|
||||
AND c.conkey = ARRAY[child_att]::smallint[] AND c.confkey = ARRAY[parent_att]::smallint[]
|
||||
) THEN
|
||||
EXECUTE format(
|
||||
'ALTER TABLE %I.picking_items ADD CONSTRAINT tenant_core_picking_items_task_fk
|
||||
FOREIGN KEY (pick_code) REFERENCES %I.picking_tasks(pick_code)
|
||||
ON DELETE CASCADE NOT VALID', p_schema, p_schema);
|
||||
END IF;
|
||||
END IF;
|
||||
|
||||
-- 新增 19 条(与 tenant_br001 定义一致:子表/列/父表/列/ON DELETE)
|
||||
FOR v_child, v_child_col, v_parent, v_parent_col, v_on_delete IN
|
||||
SELECT * FROM (VALUES
|
||||
('after_sale_returns','after_sale_id','after_sales','id','CASCADE'),
|
||||
('assistant_messages','conversation_id','assistant_conversations','id','CASCADE'),
|
||||
('assistant_turns','conversation_id','assistant_conversations','id','CASCADE'),
|
||||
('bid_awards','quote_id','bid_quotes','id','SET NULL'),
|
||||
('bid_awards','round_id','bid_rounds','id','CASCADE'),
|
||||
('bid_invitations','round_id','bid_rounds','id','CASCADE'),
|
||||
('bid_quotes','invitation_id','bid_invitations','id','SET NULL'),
|
||||
('bid_quotes','round_id','bid_rounds','id','CASCADE'),
|
||||
('bid_round_items','round_id','bid_rounds','id','CASCADE'),
|
||||
('free_cost_invoice_links','cost_detail_id','cost_details','id','CASCADE'),
|
||||
('free_cost_invoice_links','invoice_id','free_cost_invoices','id','CASCADE'),
|
||||
('inspection_photo_archive_entries','archive_id','inspection_photo_archives','id','CASCADE'),
|
||||
('invoice_statement_links','invoice_id','invoices','id','CASCADE'),
|
||||
('parse_session_items','parse_session_id','parse_sessions','id','CASCADE'),
|
||||
('processing_demand_items','task_id','processing_tasks','id','CASCADE'),
|
||||
('processing_demand_picks','task_id','processing_tasks','id','CASCADE'),
|
||||
('quality_report_prep_links','preparation_id','supplier_preparations','id','CASCADE'),
|
||||
('quality_report_prep_links','quality_report_id','quality_reports','id','CASCADE'),
|
||||
('self_purchase_stock_inbounds','sku_code','skus','sku_code',NULL)
|
||||
) AS t(child, child_col, parent, parent_col, on_delete)
|
||||
LOOP
|
||||
child_oid := to_regclass(format('%I.%I', p_schema, v_child));
|
||||
parent_oid := to_regclass(format('%I.%I', p_schema, v_parent));
|
||||
CONTINUE WHEN child_oid IS NULL OR parent_oid IS NULL;
|
||||
SELECT attnum::smallint INTO child_att FROM pg_attribute
|
||||
WHERE attrelid = child_oid AND attname = v_child_col AND NOT attisdropped;
|
||||
SELECT attnum::smallint INTO parent_att FROM pg_attribute
|
||||
WHERE attrelid = parent_oid AND attname = v_parent_col AND NOT attisdropped;
|
||||
CONTINUE WHEN child_att IS NULL OR parent_att IS NULL;
|
||||
CONTINUE WHEN EXISTS (
|
||||
SELECT 1 FROM pg_constraint c
|
||||
WHERE c.contype = 'f' AND c.conrelid = child_oid AND c.confrelid = parent_oid
|
||||
AND c.conkey = ARRAY[child_att]::smallint[] AND c.confkey = ARRAY[parent_att]::smallint[]
|
||||
);
|
||||
v_conname := format('tenant_core_%s_%s_fk', v_child, v_child_col);
|
||||
EXECUTE format(
|
||||
'ALTER TABLE %I.%I ADD CONSTRAINT %I FOREIGN KEY (%I) REFERENCES %I.%I(%I)%s NOT VALID',
|
||||
p_schema, v_child, v_conname, v_child_col,
|
||||
p_schema, v_parent, v_parent_col,
|
||||
CASE WHEN v_on_delete IS NULL THEN '' ELSE ' ON DELETE ' || v_on_delete END
|
||||
);
|
||||
END LOOP;
|
||||
END;
|
||||
$$;
|
||||
|
||||
COMMENT ON FUNCTION public.ensure_tenant_core_foreign_keys(TEXT) IS
|
||||
'确保同一 tenant schema 内 22 条核心 FK(原有 3 + 新增 19,均 NOT VALID);历史数据须巡检清零后逐约束 VALIDATE(本迁移末尾对孤儿=0 的约束自动 VALIDATE)。';
|
||||
|
||||
-- 应用到模板 + 所有已注册租户
|
||||
DO $$
|
||||
DECLARE
|
||||
r RECORD;
|
||||
BEGIN
|
||||
PERFORM public.ensure_tenant_core_foreign_keys('tenant_template');
|
||||
FOR r IN SELECT schema_name FROM public.tenant_schema_registry WHERE status IN ('active','pending') ORDER BY schema_name
|
||||
LOOP
|
||||
PERFORM public.ensure_tenant_core_foreign_keys(r.schema_name);
|
||||
END LOOP;
|
||||
END $$;
|
||||
|
||||
-- 条件 VALIDATE:孤儿=0 才 VALIDATE;有孤儿保持 NOT VALID 并输出清单(不删数据)
|
||||
DO $$
|
||||
DECLARE
|
||||
r RECORD;
|
||||
n bigint;
|
||||
sch text;
|
||||
BEGIN
|
||||
FOR sch IN
|
||||
SELECT n.nspname FROM pg_namespace n
|
||||
WHERE n.nspname = 'tenant_template' OR n.nspname IN (
|
||||
SELECT schema_name FROM public.tenant_schema_registry WHERE status IN ('active','pending')
|
||||
)
|
||||
LOOP
|
||||
FOR r IN
|
||||
SELECT c.conname, c.conrelid::regclass AS child, c.confrelid::regclass AS parent,
|
||||
a.attname AS child_col, pa.attname AS parent_col
|
||||
FROM pg_constraint c
|
||||
JOIN pg_class cl ON cl.oid = c.conrelid
|
||||
JOIN pg_namespace n ON n.oid = cl.relnamespace
|
||||
JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1]
|
||||
JOIN pg_attribute pa ON pa.attrelid = c.confrelid AND pa.attnum = c.confkey[1]
|
||||
WHERE n.nspname = sch
|
||||
AND c.contype = 'f'
|
||||
AND NOT c.convalidated
|
||||
AND array_length(c.conkey, 1) = 1
|
||||
LOOP
|
||||
EXECUTE format(
|
||||
'SELECT count(*) FROM %s c WHERE c.%I IS NOT NULL AND NOT EXISTS (SELECT 1 FROM %s p WHERE p.%I = c.%I)',
|
||||
r.child, r.child_col, r.parent, r.parent_col, r.child_col
|
||||
) INTO n;
|
||||
IF n = 0 THEN
|
||||
EXECUTE format('ALTER TABLE %s VALIDATE CONSTRAINT %I', r.child, r.conname);
|
||||
ELSE
|
||||
RAISE NOTICE 'FK % on %.% NOT VALIDATED: % orphan rows (fix data before rolling VALIDATE)', r.conname, sch, r.child, n;
|
||||
END IF;
|
||||
END LOOP;
|
||||
END LOOP;
|
||||
END $$;
|
||||
@@ -0,0 +1,105 @@
|
||||
-- T4 / DATA-8(2026-10-19 T4,D12 两批)RLS 覆盖第 1 批:高频 30 张。
|
||||
--
|
||||
-- 现状:tenant_br001/br002/template 各有 60 张"含 branch_code 但未开 RLS"的表;
|
||||
-- 目标:最终这两类表 = 0 张,每张 1 条 tenant_isolation_<tbl> policy(FORCE RLS,与既有 15 张同形)。
|
||||
-- 本批:15 张既有 + 30 张(累计 45);
|
||||
-- 逐表 ENABLE/FORCE RLS + DROP POLICY IF EXISTS + CREATE POLICY(幂等);
|
||||
-- ensure_all_tenant_core_rls() 遍历全部 tenant_* schema;clone 路径复用本函数 ⇒ 新租户自动覆盖。
|
||||
--
|
||||
-- 风险:FORCE RLS 对表 owner 生效;无 app.branch_code 的短借连接会读 0 行。两批之间跑全量;
|
||||
-- 若某表出现 permission denied/0 行异常 → 回退该表并记录豁免(不得硬上)。
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.apply_tenant_core_rls(p_schema text)
|
||||
RETURNS void
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
DECLARE
|
||||
tbl text;
|
||||
policy_name text;
|
||||
core_tables text[] := ARRAY[
|
||||
'orders',
|
||||
'order_items',
|
||||
'customers',
|
||||
'customer_skus',
|
||||
'cost_details',
|
||||
'customer_statements',
|
||||
'inspections',
|
||||
'delivery_tasks',
|
||||
'purchase_orders',
|
||||
'supplier_preparations',
|
||||
'inventory',
|
||||
'inventory_reservations',
|
||||
'picking_items',
|
||||
'picking_tasks',
|
||||
'inventory_logs',
|
||||
'after_sale_returns',
|
||||
'after_sales',
|
||||
'categories',
|
||||
'cost_adjustments',
|
||||
'customer_delivery_assignments',
|
||||
'customer_quote_sheets',
|
||||
'customer_quote_versions',
|
||||
'delivery_persons',
|
||||
'delivery_schedules',
|
||||
'delivery_signatures',
|
||||
'exception_tickets',
|
||||
'fixed_costs',
|
||||
'free_cost_invoices',
|
||||
'free_cost_payment_vouchers',
|
||||
'inspection_loss_confirmations',
|
||||
'inspection_photo_archives',
|
||||
'inspection_returns',
|
||||
'inspection_review_logs',
|
||||
'inventory_batch_reports',
|
||||
'invoice_statement_links',
|
||||
'invoices',
|
||||
'operation_logs',
|
||||
'order_allocation_batches',
|
||||
'order_item_returns',
|
||||
'picking_assign_rules',
|
||||
'picking_containers',
|
||||
'picking_scan_logs',
|
||||
'processing_tasks',
|
||||
'product_catalog',
|
||||
'skus'
|
||||
];
|
||||
BEGIN
|
||||
IF p_schema IS NULL OR p_schema NOT LIKE 'tenant_%' THEN
|
||||
RETURN;
|
||||
END IF;
|
||||
IF to_regnamespace(p_schema) IS NULL THEN
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
FOREACH tbl IN ARRAY core_tables
|
||||
LOOP
|
||||
IF to_regclass(format('%I.%I', p_schema, tbl)) IS NULL THEN
|
||||
CONTINUE;
|
||||
END IF;
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_schema = p_schema AND table_name = tbl AND column_name = 'branch_code'
|
||||
) THEN
|
||||
CONTINUE;
|
||||
END IF;
|
||||
EXECUTE format('ALTER TABLE %I.%I ENABLE ROW LEVEL SECURITY', p_schema, tbl);
|
||||
EXECUTE format('ALTER TABLE %I.%I FORCE ROW LEVEL SECURITY', p_schema, tbl);
|
||||
policy_name := 'tenant_isolation_' || tbl;
|
||||
EXECUTE format('DROP POLICY IF EXISTS %I ON %I.%I', policy_name, p_schema, tbl);
|
||||
EXECUTE format(
|
||||
'CREATE POLICY %I ON %I.%I FOR ALL
|
||||
USING (branch_code::text = current_setting(''app.branch_code'', true))
|
||||
WITH CHECK (branch_code::text = current_setting(''app.branch_code'', true))',
|
||||
policy_name, p_schema, tbl
|
||||
);
|
||||
END LOOP;
|
||||
|
||||
IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'canteen_app_rls') THEN
|
||||
EXECUTE format('GRANT USAGE ON SCHEMA %I TO canteen_app_rls', p_schema);
|
||||
EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA %I TO canteen_app_rls', p_schema);
|
||||
EXECUTE format('GRANT USAGE, SELECT, UPDATE ON ALL SEQUENCES IN SCHEMA %I TO canteen_app_rls', p_schema);
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
|
||||
SELECT public.ensure_all_tenant_core_rls();
|
||||
@@ -0,0 +1,135 @@
|
||||
-- T4 / DATA-8(2026-10-19 T4,D12 两批)RLS 覆盖第 2 批:其余 30 张。
|
||||
--
|
||||
-- 现状:tenant_br001/br002/template 各有 60 张"含 branch_code 但未开 RLS"的表;
|
||||
-- 目标:最终这两类表 = 0 张,每张 1 条 tenant_isolation_<tbl> policy(FORCE RLS,与既有 15 张同形)。
|
||||
-- 本批:15 张既有 + 60 张(累计 75);
|
||||
-- 逐表 ENABLE/FORCE RLS + DROP POLICY IF EXISTS + CREATE POLICY(幂等);
|
||||
-- ensure_all_tenant_core_rls() 遍历全部 tenant_* schema;clone 路径复用本函数 ⇒ 新租户自动覆盖。
|
||||
--
|
||||
-- 风险:FORCE RLS 对表 owner 生效;无 app.branch_code 的短借连接会读 0 行。两批之间跑全量;
|
||||
-- 若某表出现 permission denied/0 行异常 → 回退该表并记录豁免(不得硬上)。
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.apply_tenant_core_rls(p_schema text)
|
||||
RETURNS void
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
DECLARE
|
||||
tbl text;
|
||||
policy_name text;
|
||||
core_tables text[] := ARRAY[
|
||||
'orders',
|
||||
'order_items',
|
||||
'customers',
|
||||
'customer_skus',
|
||||
'cost_details',
|
||||
'customer_statements',
|
||||
'inspections',
|
||||
'delivery_tasks',
|
||||
'purchase_orders',
|
||||
'supplier_preparations',
|
||||
'inventory',
|
||||
'inventory_reservations',
|
||||
'picking_items',
|
||||
'picking_tasks',
|
||||
'inventory_logs',
|
||||
'after_sale_returns',
|
||||
'after_sales',
|
||||
'categories',
|
||||
'cost_adjustments',
|
||||
'customer_delivery_assignments',
|
||||
'customer_quote_sheets',
|
||||
'customer_quote_versions',
|
||||
'delivery_persons',
|
||||
'delivery_schedules',
|
||||
'delivery_signatures',
|
||||
'exception_tickets',
|
||||
'fixed_costs',
|
||||
'free_cost_invoices',
|
||||
'free_cost_payment_vouchers',
|
||||
'inspection_loss_confirmations',
|
||||
'inspection_photo_archives',
|
||||
'inspection_returns',
|
||||
'inspection_review_logs',
|
||||
'inventory_batch_reports',
|
||||
'invoice_statement_links',
|
||||
'invoices',
|
||||
'operation_logs',
|
||||
'order_allocation_batches',
|
||||
'order_item_returns',
|
||||
'picking_assign_rules',
|
||||
'picking_containers',
|
||||
'picking_scan_logs',
|
||||
'processing_tasks',
|
||||
'product_catalog',
|
||||
'skus',
|
||||
'ai_prompt_overrides',
|
||||
'assistant_conversations',
|
||||
'assistant_turns',
|
||||
'import_mapping_memories',
|
||||
'market_compare_exclusions',
|
||||
'market_external_catalog',
|
||||
'market_price_history',
|
||||
'market_price_indices',
|
||||
'market_prices',
|
||||
'market_sku_external_bindings',
|
||||
'parse_sessions',
|
||||
'price_invert_events',
|
||||
'print_jobs',
|
||||
'product_substitutions',
|
||||
'quality_reports',
|
||||
'quote_price_proposals',
|
||||
'seasonal_recommendations',
|
||||
'self_purchase_stock_inbounds',
|
||||
'smart_classification_rules',
|
||||
'statement_disputes',
|
||||
'statement_lines',
|
||||
'statement_payments',
|
||||
'supplier_prep_amend_requests',
|
||||
'supplier_rating_snapshots',
|
||||
'supplier_statements',
|
||||
'suppliers',
|
||||
'system_configs',
|
||||
'user_preferences',
|
||||
'warehouses',
|
||||
'weigh_devices'
|
||||
];
|
||||
BEGIN
|
||||
IF p_schema IS NULL OR p_schema NOT LIKE 'tenant_%' THEN
|
||||
RETURN;
|
||||
END IF;
|
||||
IF to_regnamespace(p_schema) IS NULL THEN
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
FOREACH tbl IN ARRAY core_tables
|
||||
LOOP
|
||||
IF to_regclass(format('%I.%I', p_schema, tbl)) IS NULL THEN
|
||||
CONTINUE;
|
||||
END IF;
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_schema = p_schema AND table_name = tbl AND column_name = 'branch_code'
|
||||
) THEN
|
||||
CONTINUE;
|
||||
END IF;
|
||||
EXECUTE format('ALTER TABLE %I.%I ENABLE ROW LEVEL SECURITY', p_schema, tbl);
|
||||
EXECUTE format('ALTER TABLE %I.%I FORCE ROW LEVEL SECURITY', p_schema, tbl);
|
||||
policy_name := 'tenant_isolation_' || tbl;
|
||||
EXECUTE format('DROP POLICY IF EXISTS %I ON %I.%I', policy_name, p_schema, tbl);
|
||||
EXECUTE format(
|
||||
'CREATE POLICY %I ON %I.%I FOR ALL
|
||||
USING (branch_code::text = current_setting(''app.branch_code'', true))
|
||||
WITH CHECK (branch_code::text = current_setting(''app.branch_code'', true))',
|
||||
policy_name, p_schema, tbl
|
||||
);
|
||||
END LOOP;
|
||||
|
||||
IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'canteen_app_rls') THEN
|
||||
EXECUTE format('GRANT USAGE ON SCHEMA %I TO canteen_app_rls', p_schema);
|
||||
EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA %I TO canteen_app_rls', p_schema);
|
||||
EXECUTE format('GRANT USAGE, SELECT, UPDATE ON ALL SEQUENCES IN SCHEMA %I TO canteen_app_rls', p_schema);
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
|
||||
SELECT public.ensure_all_tenant_core_rls();
|
||||
Generated
+1
-1
@@ -16,7 +16,7 @@
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-router-dom": "^6.8.0",
|
||||
"xlsx": "^0.18.5"
|
||||
"xlsx": "0.18.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.23.5",
|
||||
|
||||
+2
-1
@@ -43,6 +43,7 @@
|
||||
"test:unit": "vitest run",
|
||||
"test:all": "npm run test:unit && npm --prefix server test && node server/scripts/test-functionality.js && node server/scripts/test-page-flows.js"
|
||||
},
|
||||
"//xlsx": "CVE-2023-30533 / CVE-2024-22363:xlsx 0.18.5 是 npm 官方最后版本(修复版只在 SheetJS CDN)。D15 决策=固定版本+限制:仅解析本系统/受信来源生成的文件,不启用未受信模板/宏解析;替换 exceljs 需全量回归导入导出,另案评估。",
|
||||
"dependencies": {
|
||||
"@emotion/is-prop-valid": "^1.4.0",
|
||||
"framer-motion": "^11.16.1",
|
||||
@@ -52,7 +53,7 @@
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-router-dom": "^6.8.0",
|
||||
"xlsx": "^0.18.5"
|
||||
"xlsx": "0.18.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.23.5",
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
tests/bidDesignatedDirectAward.test.ts
|
||||
tests/bidHistoryPickAward.test.ts
|
||||
tests/completedPickingEditable.test.ts
|
||||
tests/completeSettleFromReceived.test.ts
|
||||
tests/deliveryLoadingQtyEdit.test.ts
|
||||
tests/historicalOrderFinalize.test.ts
|
||||
tests/homePathConsistency.test.ts
|
||||
tests/independentInbound.test.ts
|
||||
tests/inventoryVoidBatchUi.test.ts
|
||||
tests/marketAiPriceQuoteService.test.ts
|
||||
tests/mobileBadgeCounts.test.ts
|
||||
tests/nonJinInboundQty.test.ts
|
||||
tests/orderAutoAdvanceBackfill.test.ts
|
||||
tests/pickingCompleteKeepPlanQty.test.ts
|
||||
tests/prepBeforeInspection.test.ts
|
||||
tests/processingDemandPickAmend.test.ts
|
||||
tests/purchaseAssignDefault.test.ts
|
||||
tests/purchaseManagementCostHint.test.ts
|
||||
tests/selfPurchaseActualQtySingleWriter.test.ts
|
||||
tests/skuDirectCostsQtyTimesUnitCost.test.ts
|
||||
tests/stockInbound.test.ts
|
||||
tests/warehouseProcessingDemandSheet.test.ts
|
||||
tests/weighInspectionMergeSimilar.test.ts
|
||||
tests/weighInspectionNearToday.test.ts
|
||||
tests/workflowContext.test.ts
|
||||
tests/zeroCostClearsPlanPrice.test.ts
|
||||
@@ -0,0 +1,26 @@
|
||||
tests/bidDesignatedDirectAward.test.ts
|
||||
tests/bidHistoryPickAward.test.ts
|
||||
tests/completedPickingEditable.test.ts
|
||||
tests/completeSettleFromReceived.test.ts
|
||||
tests/deliveryLoadingQtyEdit.test.ts
|
||||
tests/historicalOrderFinalize.test.ts
|
||||
tests/homePathConsistency.test.ts
|
||||
tests/independentInbound.test.ts
|
||||
tests/inventoryVoidBatchUi.test.ts
|
||||
tests/marketAiPriceQuoteService.test.ts
|
||||
tests/mobileBadgeCounts.test.ts
|
||||
tests/nonJinInboundQty.test.ts
|
||||
tests/orderAutoAdvanceBackfill.test.ts
|
||||
tests/pickingCompleteKeepPlanQty.test.ts
|
||||
tests/prepBeforeInspection.test.ts
|
||||
tests/processingDemandPickAmend.test.ts
|
||||
tests/purchaseAssignDefault.test.ts
|
||||
tests/purchaseManagementCostHint.test.ts
|
||||
tests/selfPurchaseActualQtySingleWriter.test.ts
|
||||
tests/skuDirectCostsQtyTimesUnitCost.test.ts
|
||||
tests/stockInbound.test.ts
|
||||
tests/warehouseProcessingDemandSheet.test.ts
|
||||
tests/weighInspectionMergeSimilar.test.ts
|
||||
tests/weighInspectionNearToday.test.ts
|
||||
tests/workflowContext.test.ts
|
||||
tests/zeroCostClearsPlanPrice.test.ts
|
||||
@@ -0,0 +1,26 @@
|
||||
tests/bidDesignatedDirectAward.test.ts
|
||||
tests/bidHistoryPickAward.test.ts
|
||||
tests/completedPickingEditable.test.ts
|
||||
tests/completeSettleFromReceived.test.ts
|
||||
tests/deliveryLoadingQtyEdit.test.ts
|
||||
tests/historicalOrderFinalize.test.ts
|
||||
tests/homePathConsistency.test.ts
|
||||
tests/independentInbound.test.ts
|
||||
tests/inventoryVoidBatchUi.test.ts
|
||||
tests/marketAiPriceQuoteService.test.ts
|
||||
tests/mobileBadgeCounts.test.ts
|
||||
tests/nonJinInboundQty.test.ts
|
||||
tests/orderAutoAdvanceBackfill.test.ts
|
||||
tests/pickingCompleteKeepPlanQty.test.ts
|
||||
tests/prepBeforeInspection.test.ts
|
||||
tests/processingDemandPickAmend.test.ts
|
||||
tests/purchaseAssignDefault.test.ts
|
||||
tests/purchaseManagementCostHint.test.ts
|
||||
tests/selfPurchaseActualQtySingleWriter.test.ts
|
||||
tests/skuDirectCostsQtyTimesUnitCost.test.ts
|
||||
tests/stockInbound.test.ts
|
||||
tests/warehouseProcessingDemandSheet.test.ts
|
||||
tests/weighInspectionMergeSimilar.test.ts
|
||||
tests/weighInspectionNearToday.test.ts
|
||||
tests/workflowContext.test.ts
|
||||
tests/zeroCostClearsPlanPrice.test.ts
|
||||
@@ -0,0 +1,26 @@
|
||||
tests/bidDesignatedDirectAward.test.ts
|
||||
tests/bidHistoryPickAward.test.ts
|
||||
tests/completedPickingEditable.test.ts
|
||||
tests/completeSettleFromReceived.test.ts
|
||||
tests/deliveryLoadingQtyEdit.test.ts
|
||||
tests/historicalOrderFinalize.test.ts
|
||||
tests/homePathConsistency.test.ts
|
||||
tests/independentInbound.test.ts
|
||||
tests/inventoryVoidBatchUi.test.ts
|
||||
tests/marketAiPriceQuoteService.test.ts
|
||||
tests/mobileBadgeCounts.test.ts
|
||||
tests/nonJinInboundQty.test.ts
|
||||
tests/orderAutoAdvanceBackfill.test.ts
|
||||
tests/pickingCompleteKeepPlanQty.test.ts
|
||||
tests/prepBeforeInspection.test.ts
|
||||
tests/processingDemandPickAmend.test.ts
|
||||
tests/purchaseAssignDefault.test.ts
|
||||
tests/purchaseManagementCostHint.test.ts
|
||||
tests/selfPurchaseActualQtySingleWriter.test.ts
|
||||
tests/skuDirectCostsQtyTimesUnitCost.test.ts
|
||||
tests/stockInbound.test.ts
|
||||
tests/warehouseProcessingDemandSheet.test.ts
|
||||
tests/weighInspectionMergeSimilar.test.ts
|
||||
tests/weighInspectionNearToday.test.ts
|
||||
tests/workflowContext.test.ts
|
||||
tests/zeroCostClearsPlanPrice.test.ts
|
||||
@@ -0,0 +1,26 @@
|
||||
tests/bidDesignatedDirectAward.test.ts
|
||||
tests/bidHistoryPickAward.test.ts
|
||||
tests/completedPickingEditable.test.ts
|
||||
tests/completeSettleFromReceived.test.ts
|
||||
tests/deliveryLoadingQtyEdit.test.ts
|
||||
tests/historicalOrderFinalize.test.ts
|
||||
tests/homePathConsistency.test.ts
|
||||
tests/independentInbound.test.ts
|
||||
tests/inventoryVoidBatchUi.test.ts
|
||||
tests/marketAiPriceQuoteService.test.ts
|
||||
tests/mobileBadgeCounts.test.ts
|
||||
tests/nonJinInboundQty.test.ts
|
||||
tests/orderAutoAdvanceBackfill.test.ts
|
||||
tests/pickingCompleteKeepPlanQty.test.ts
|
||||
tests/prepBeforeInspection.test.ts
|
||||
tests/processingDemandPickAmend.test.ts
|
||||
tests/purchaseAssignDefault.test.ts
|
||||
tests/purchaseManagementCostHint.test.ts
|
||||
tests/selfPurchaseActualQtySingleWriter.test.ts
|
||||
tests/skuDirectCostsQtyTimesUnitCost.test.ts
|
||||
tests/stockInbound.test.ts
|
||||
tests/warehouseProcessingDemandSheet.test.ts
|
||||
tests/weighInspectionMergeSimilar.test.ts
|
||||
tests/weighInspectionNearToday.test.ts
|
||||
tests/workflowContext.test.ts
|
||||
tests/zeroCostClearsPlanPrice.test.ts
|
||||
@@ -0,0 +1,26 @@
|
||||
tests/bidDesignatedDirectAward.test.ts
|
||||
tests/bidHistoryPickAward.test.ts
|
||||
tests/completedPickingEditable.test.ts
|
||||
tests/completeSettleFromReceived.test.ts
|
||||
tests/deliveryLoadingQtyEdit.test.ts
|
||||
tests/historicalOrderFinalize.test.ts
|
||||
tests/homePathConsistency.test.ts
|
||||
tests/independentInbound.test.ts
|
||||
tests/inventoryVoidBatchUi.test.ts
|
||||
tests/marketAiPriceQuoteService.test.ts
|
||||
tests/mobileBadgeCounts.test.ts
|
||||
tests/nonJinInboundQty.test.ts
|
||||
tests/orderAutoAdvanceBackfill.test.ts
|
||||
tests/pickingCompleteKeepPlanQty.test.ts
|
||||
tests/prepBeforeInspection.test.ts
|
||||
tests/processingDemandPickAmend.test.ts
|
||||
tests/purchaseAssignDefault.test.ts
|
||||
tests/purchaseManagementCostHint.test.ts
|
||||
tests/selfPurchaseActualQtySingleWriter.test.ts
|
||||
tests/skuDirectCostsQtyTimesUnitCost.test.ts
|
||||
tests/stockInbound.test.ts
|
||||
tests/warehouseProcessingDemandSheet.test.ts
|
||||
tests/weighInspectionMergeSimilar.test.ts
|
||||
tests/weighInspectionNearToday.test.ts
|
||||
tests/workflowContext.test.ts
|
||||
tests/zeroCostClearsPlanPrice.test.ts
|
||||
@@ -0,0 +1,26 @@
|
||||
tests/bidDesignatedDirectAward.test.ts
|
||||
tests/bidHistoryPickAward.test.ts
|
||||
tests/completedPickingEditable.test.ts
|
||||
tests/completeSettleFromReceived.test.ts
|
||||
tests/deliveryLoadingQtyEdit.test.ts
|
||||
tests/historicalOrderFinalize.test.ts
|
||||
tests/homePathConsistency.test.ts
|
||||
tests/independentInbound.test.ts
|
||||
tests/inventoryVoidBatchUi.test.ts
|
||||
tests/marketAiPriceQuoteService.test.ts
|
||||
tests/mobileBadgeCounts.test.ts
|
||||
tests/nonJinInboundQty.test.ts
|
||||
tests/orderAutoAdvanceBackfill.test.ts
|
||||
tests/pickingCompleteKeepPlanQty.test.ts
|
||||
tests/prepBeforeInspection.test.ts
|
||||
tests/processingDemandPickAmend.test.ts
|
||||
tests/purchaseAssignDefault.test.ts
|
||||
tests/purchaseManagementCostHint.test.ts
|
||||
tests/selfPurchaseActualQtySingleWriter.test.ts
|
||||
tests/skuDirectCostsQtyTimesUnitCost.test.ts
|
||||
tests/stockInbound.test.ts
|
||||
tests/warehouseProcessingDemandSheet.test.ts
|
||||
tests/weighInspectionMergeSimilar.test.ts
|
||||
tests/weighInspectionNearToday.test.ts
|
||||
tests/workflowContext.test.ts
|
||||
tests/zeroCostClearsPlanPrice.test.ts
|
||||
@@ -0,0 +1,26 @@
|
||||
tests/bidDesignatedDirectAward.test.ts
|
||||
tests/bidHistoryPickAward.test.ts
|
||||
tests/completedPickingEditable.test.ts
|
||||
tests/completeSettleFromReceived.test.ts
|
||||
tests/deliveryLoadingQtyEdit.test.ts
|
||||
tests/historicalOrderFinalize.test.ts
|
||||
tests/homePathConsistency.test.ts
|
||||
tests/independentInbound.test.ts
|
||||
tests/inventoryVoidBatchUi.test.ts
|
||||
tests/marketAiPriceQuoteService.test.ts
|
||||
tests/mobileBadgeCounts.test.ts
|
||||
tests/nonJinInboundQty.test.ts
|
||||
tests/orderAutoAdvanceBackfill.test.ts
|
||||
tests/pickingCompleteKeepPlanQty.test.ts
|
||||
tests/prepBeforeInspection.test.ts
|
||||
tests/processingDemandPickAmend.test.ts
|
||||
tests/purchaseAssignDefault.test.ts
|
||||
tests/purchaseManagementCostHint.test.ts
|
||||
tests/selfPurchaseActualQtySingleWriter.test.ts
|
||||
tests/skuDirectCostsQtyTimesUnitCost.test.ts
|
||||
tests/stockInbound.test.ts
|
||||
tests/warehouseProcessingDemandSheet.test.ts
|
||||
tests/weighInspectionMergeSimilar.test.ts
|
||||
tests/weighInspectionNearToday.test.ts
|
||||
tests/workflowContext.test.ts
|
||||
tests/zeroCostClearsPlanPrice.test.ts
|
||||
@@ -0,0 +1,26 @@
|
||||
tests/bidDesignatedDirectAward.test.ts
|
||||
tests/bidHistoryPickAward.test.ts
|
||||
tests/completedPickingEditable.test.ts
|
||||
tests/completeSettleFromReceived.test.ts
|
||||
tests/deliveryLoadingQtyEdit.test.ts
|
||||
tests/historicalOrderFinalize.test.ts
|
||||
tests/homePathConsistency.test.ts
|
||||
tests/independentInbound.test.ts
|
||||
tests/inventoryVoidBatchUi.test.ts
|
||||
tests/marketAiPriceQuoteService.test.ts
|
||||
tests/mobileBadgeCounts.test.ts
|
||||
tests/nonJinInboundQty.test.ts
|
||||
tests/orderAutoAdvanceBackfill.test.ts
|
||||
tests/pickingCompleteKeepPlanQty.test.ts
|
||||
tests/prepBeforeInspection.test.ts
|
||||
tests/processingDemandPickAmend.test.ts
|
||||
tests/purchaseAssignDefault.test.ts
|
||||
tests/purchaseManagementCostHint.test.ts
|
||||
tests/selfPurchaseActualQtySingleWriter.test.ts
|
||||
tests/skuDirectCostsQtyTimesUnitCost.test.ts
|
||||
tests/stockInbound.test.ts
|
||||
tests/warehouseProcessingDemandSheet.test.ts
|
||||
tests/weighInspectionMergeSimilar.test.ts
|
||||
tests/weighInspectionNearToday.test.ts
|
||||
tests/workflowContext.test.ts
|
||||
tests/zeroCostClearsPlanPrice.test.ts
|
||||
@@ -0,0 +1,26 @@
|
||||
tests/bidDesignatedDirectAward.test.ts
|
||||
tests/bidHistoryPickAward.test.ts
|
||||
tests/completedPickingEditable.test.ts
|
||||
tests/completeSettleFromReceived.test.ts
|
||||
tests/deliveryLoadingQtyEdit.test.ts
|
||||
tests/historicalOrderFinalize.test.ts
|
||||
tests/homePathConsistency.test.ts
|
||||
tests/independentInbound.test.ts
|
||||
tests/inventoryVoidBatchUi.test.ts
|
||||
tests/marketAiPriceQuoteService.test.ts
|
||||
tests/mobileBadgeCounts.test.ts
|
||||
tests/nonJinInboundQty.test.ts
|
||||
tests/orderAutoAdvanceBackfill.test.ts
|
||||
tests/pickingCompleteKeepPlanQty.test.ts
|
||||
tests/prepBeforeInspection.test.ts
|
||||
tests/processingDemandPickAmend.test.ts
|
||||
tests/purchaseAssignDefault.test.ts
|
||||
tests/purchaseManagementCostHint.test.ts
|
||||
tests/selfPurchaseActualQtySingleWriter.test.ts
|
||||
tests/skuDirectCostsQtyTimesUnitCost.test.ts
|
||||
tests/stockInbound.test.ts
|
||||
tests/warehouseProcessingDemandSheet.test.ts
|
||||
tests/weighInspectionMergeSimilar.test.ts
|
||||
tests/weighInspectionNearToday.test.ts
|
||||
tests/workflowContext.test.ts
|
||||
tests/zeroCostClearsPlanPrice.test.ts
|
||||
@@ -0,0 +1,94 @@
|
||||
# 整合后核查报告(另一会话 WIP 并入 HEAD 之后)
|
||||
|
||||
- 核查对象:`29fbf49`(把另一会话 77 项工作区改动原样并入)之后的 `HEAD`
|
||||
- 核查时间:2026-10-15 · 本地库 `supplier_delivery` · 租户 `tenant_br002`
|
||||
- 一句话结论:**整合后代码是正确可用的**——编译、全量测试、以及散客录单/配送守卫的真库端到端都通过,未发现因整合产生的功能回归;发现的是 **4 处"文档/数据面不一致"**(都是他们的回滚没收到边),不在产品代码逻辑里。
|
||||
|
||||
---
|
||||
|
||||
## 1. 编译与全量测试(对齐已知基线)
|
||||
|
||||
| 检查 | 结果 | 基线 | 判定 |
|
||||
| ---- | ---- | ---- | ---- |
|
||||
| 前端 `npx tsc --noEmit` | 0 错误 | 0 | ✅ |
|
||||
| 后端 `server npx tsc --noEmit` | 0 错误 | 0 | ✅ |
|
||||
| 后端 `vitest run` | **26 文件 / 33 用例失败**,447 文件 3066 用例 | 26 / 33 | ✅ 逐项一致 |
|
||||
| 前端 `vitest run` | **3 文件 / 6 用例失败**,171 文件 912 用例 | 3 / 6 | ✅ 同名同项 |
|
||||
| 设计门禁 `run-all.sh --verify` | 通过 8 / 未通过 1 / 未执行 1 | 同 | ✅ 与基线一致 |
|
||||
|
||||
- 后端失败文件与基线清单(`/tmp/head-files.txt`)**差集为空**:没有新增失败。
|
||||
- 反向差集有 1 项:基线上失败的 `tests/stockCoverZeroReason.test.ts` **现在通过**了——被他们「库存抵扣为 0 的原因可见」顺带修好。
|
||||
- 前端失败三文件与基线同名:`skuCostThirdBucket.contract.test.ts`、`PickingManagement.outboundPhotoPreview.test.ts`、`SystemConfig.allowZeroCost.test.ts`。
|
||||
- 证据日志:[server-vitest.log](./server-vitest.log)、[fe-vitest.log](./fe-vitest.log)、[server-failed-files.txt](./server-failed-files.txt)
|
||||
|
||||
## 2. 两批代码的交汇点(逐处核对,互补无冲突)
|
||||
|
||||
| 交汇点 | 我的改动 | 他们的改动 | 判定 |
|
||||
| ------ | -------- | ---------- | ---- |
|
||||
| `deliveryTaskQueryService.ts` | `nonRetailOrderSql('o')` 6 处(排散客) | `salesVisibleOrderSql('o')` 6 处(只排独立进货) | ✅ 逐条相邻并存;两个判据定义域不重叠,散客不会被误排、独立进货双重排除无害 |
|
||||
| `stockCoverBatchPlanService.ts`(**最高风险**) | P0「多行单只抵第一行」:逐行传 `deferSkipInboundLines: true`,整单补行移出循环 | 恢复整单惰性补行 + 行级 `NOT EXISTS inventory_logs` 守卫 + 不再整单 `return` | ✅ 逐行路径**整段跳过**该函数(`if (!input.deferSkipInboundLines)`),他们的补行只在循环后那一次整单调用里生效,方向一致 |
|
||||
| `orderAllocationService.ts` | `applyStockCoverForOrder` 返回 `zeroReasons` | 消费 `coverResult.zeroReasons` 生成抵 0 原因 | ✅ 签名吻合,非破坏性 |
|
||||
| `orderManageItemsService.ts` | 散客录单走新建单路径 | 零价闸门新增 `allowUnpriced` 旁路(第二道门也同认) | ✅ 只影响「主系统追加 + 已存在单」,新建散客单不受影响 |
|
||||
| `orderWorkflowFulfillmentService.ts` | 散客早退守卫 | 补建候选加 `salesVisibleOrderSql` | ✅ 两处不同函数,互不覆盖 |
|
||||
| `CustomerOrder.tsx` | `retailMode` 5 处 | 回滚「独立进货」选项去重(不再按编码查重) | ✅ 与散客模式零交集 |
|
||||
| `scheduledJobs.ts`(新增 60s 退货跟随定时器) | —— | 调用既有 `followMainSystemPrepChanges(branchCode)` | ✅ 作用域与原来一致(按备货单驱动),散客单无备货 ⇒ 不会被扫到 |
|
||||
| 删除项的悬空引用 | —— | 删 4 篇 doc + 迁移 `20261044` + 脚本 + 契约测试 | ⚠️ 1 处悬空(见 §4.1),其余无引用 |
|
||||
|
||||
## 3. 真库端到端(整合后的 HEAD,本地 BR002)
|
||||
|
||||
一次性脚本(`TST_INT_` 前缀)走**真实服务 + 真实库**,跑完已删除脚本并彻底清理。实测输出:
|
||||
|
||||
```
|
||||
【① 散客录单】ORD_WEB_20261015_BR002_0002
|
||||
covered_qty=3 / status=30
|
||||
逐行抵扣:抄手皮 需求1/抵1;苹果 需求2/抵2 ← 两行都抵满,多行单回归风险实测排除
|
||||
分拣行=0 配送任务=0 采购单=0 备货单=0 预留=4
|
||||
【② 确认扣除并完结】status=90 deducted=true types=retail_out
|
||||
流水:苹果/IN20261015C4KTAE retail_out 30→28;抄手皮/IN202610154AZ1ZD retail_out 5→4
|
||||
Σ扣减=3 ✅ 确认后仍无分拣/配送/采购 ✅
|
||||
【③ 配送守卫】ensureDeliveryTaskForOrder 对散客单与既有独立进货单
|
||||
(ORD_WEB_20261014_BR002_0001, status 90)均空返回、调用前后 delivery_tasks 都是 0 ✅
|
||||
【清理】删除 14 行(orders 1 / order_items 2 / inventory_logs 2 /
|
||||
inventory_reservations 4 / cost_details 2 / order_item_fulfillments 2 / sign_records 1);
|
||||
库存回补 avail 28→30、4→5;按 order_code/related_order_code 扫全部租户表残留 = 0 行 ✅
|
||||
```
|
||||
|
||||
顺带确认了一条库存语义(此前没钉死):`inventory.quantity` 是**入库批次量**(出库不改),活余额是 **`available_qty`**,`inventory_logs.before_qty/after_qty` 记的是 `available_qty`——本次 `retail_out` 与既有 `picking_out` 完全同口径。
|
||||
|
||||
## 4. 发现的整合瑕疵(**未动手**,按仓库「范围外只报告」规则等你裁)
|
||||
|
||||
### 4.1 文档与代码漂移(他们的回滚没收到边)
|
||||
`src/pages/picking/PickingManagement.tsx:130` 仍写着 `设计:docs/design/20261014-分拣标签纸张尺寸预设选择.md`,而该文件已被删除;**但这个功能并没有被回滚**——`LABEL_PAPER_PRESETS` 在第 504 / 1807 / 2800 行都还在用(打印弹窗仍渲染预设下拉)。也就是说:**纸张尺寸预设功能活着,文档与 README 索引行被删了**。
|
||||
- 二选一收口:① 从 `2347068` 恢复该 doc + README 行(代码还在,恢复文档更小风险);② 把该功能也一并撤掉。
|
||||
|
||||
### 4.2 一处口径回退,请确认是否有意
|
||||
`src/utils/pickingLabelPrint.ts` 的默认纸型由 **80×60 回到 50×30**。原 doc 记录的是你 2026-10-14 的裁决「80×60 先设置为这个」(实物签尺寸,只影响没存过设置的浏览器)。若这不是你要改的,这就是一次**默认值回退**;若是有意的,忽略本条。
|
||||
|
||||
### 4.3 我的迁移注释指向已删文件
|
||||
`migrations/20261046_retail_customer.sql:8` 的注释引用了 `20261044_independent_inbound_customer.sql`(已被删)。**仅影响可读性**:该迁移刻意不重写 `clone_tenant_schema()`,运行逻辑不依赖被删文件。
|
||||
|
||||
### 4.4 我自己那篇 doc 的论断已过期(因我这次提交而成立)
|
||||
`docs/design/20261014-抵扣部分不计订单成本.md:46` 写着「该脚本已不存在,但**那是一次未提交的工作区改动**(并发会话的 WIP),不在本提交范围内……别按本文断言它已被删除」。删除已随 `29fbf49` 提交,这句话现在会误导后来人,建议改写为「已随 `29fbf49` 提交删除」。
|
||||
|
||||
### 4.5 部署库数据面与回滚后的代码不一致(**下次按 HEAD 部署前端时才会显形**)
|
||||
- 部署库 br001/br002 里 `20261044` 建的「独立进货」客户行**仍在**(`__INDEPENDENT_INBOUND__`,status 10)。
|
||||
- 回滚后的前端是**无条件内建注入**同名选项(去重逻辑被移除)⇒ 下次按 HEAD 部署前端后,录单页客户下拉会出现**两条「独立进货」**(一条读库、一条内建,code 相同)。
|
||||
- 当前部署的前端含去重逻辑,所以**现在没有问题**;按你已选的范围(只上我三个前端提交,从 `2347068` 构建)也不会触发。
|
||||
- 收口二选一:① 加一个幂等清理迁移删掉存量行;② 恢复内建去重。
|
||||
- 附带更正一条我先前的说法:部署库 `clone_tenant_schema()` 实测**既不建独立进货、也不建散客** ⇒ 新租户不会再长出这行,残留在存量租户。散客侧不受影响(`ensureRetailCustomer` 运行时幂等建行)。
|
||||
|
||||
## 5. 我方过程瑕疵(如实交代)
|
||||
|
||||
1. 侦查中我说过「本地租户库是空的(br001/br002 都 0 行)」——**误判**。本地库有数据(br002 `customers=3 / orders=4`),0 行是**未设 `app.branch_code` 被 RLS 过滤**造成的。已在 §3 用真跑数据更正。
|
||||
2. 第一版真跑脚本的清理步骤:我把异常 `catch {}` 吞掉、又用 `current_schema()` 取表清单,导致它自称「删除行(无)/ 残留 0」是**假 0**(实际一行没删、库存也没回补)。已改用本地超管 `canteen` 逐表删除 14 行、回补 `available_qty` 到 30/5,并重新逐表证明残留 = 0。这是我的失误,与仓库代码无关。
|
||||
|
||||
## 6. 变更清单(本次核查)
|
||||
|
||||
| 文件 | 新增/修改/删除 | 意图 | 是否越权 |
|
||||
| ---- | -------------- | ---- | -------- |
|
||||
| `server/scripts/tmp-tst-int-audit.ts` | 新增后**已删除** | 一次性真跑脚本(跑完即删,未提交) | 授权内(核查用) |
|
||||
| `review-20261015/integration-audit/整合后核查报告.md` | 新增 | 本报告 | 授权内(产出) |
|
||||
| `review-20261015/integration-audit/{server,fe}-vitest.log`、`server-failed-files.txt` | 新增 | 测试证据 | 授权内(产出) |
|
||||
| 仓库代码/迁移/文档 | **零改动** | —— | —— |
|
||||
|
||||
核对命令:`git rev-parse --short HEAD`(应 `29fbf49`)、`git status --porcelain`(应只有未跟踪的 `review-20261015/`)。
|
||||
+9
-2
@@ -1,10 +1,17 @@
|
||||
# 供应商系统(二次开发)默认 API 端口;Web 开发服见根 webpack.config.js(3021)
|
||||
PORT=3022
|
||||
# 必须显式设置:development | test | production(缺失/非法会拒绝启动,见 src/config.ts)
|
||||
NODE_ENV=development
|
||||
# API 监听地址:默认 127.0.0.1(同机 nginx 反代);容器内需 HOST=0.0.0.0
|
||||
HOST=127.0.0.1
|
||||
# Trust proxy:默认 loopback(只信同机一跳);直连/多级代理场景按需显式配置
|
||||
#TRUST_PROXY=loopback
|
||||
# 使用 127.0.0.1 而非 localhost,避免 Windows 下 IPv6 连接需要密码
|
||||
# 独立库:与主系统(canteen_delivery)完全隔离,setup 会按此 URL 建角色与库
|
||||
DATABASE_URL=postgresql://supplier:change-me@127.0.0.1:5432/supplier_delivery
|
||||
# 引导用超管连接:仅 `npm run setup` 建角色/建库时使用,应用运行不使用
|
||||
ADMIN_DATABASE_URL=postgresql://canteen:canteen123@127.0.0.1:5432/postgres
|
||||
# 引导用管理员连接:仅 `npm run setup` 建角色/建库时使用,应用运行不使用。
|
||||
# 需 CREATEDB/CREATEROLE;**不要复用主系统超管(canteen)**,真实口令不要提交。
|
||||
ADMIN_DATABASE_URL=postgresql://postgres:CHANGE_ME@127.0.0.1:5432/postgres
|
||||
JWT_SECRET=change-me-dev-secret-not-for-production
|
||||
# 本地默认开启与生产一致的租户/RLS约束;缺少 RLS 角色时拒绝启动
|
||||
RLS_REQUIRED=1
|
||||
|
||||
Generated
-6
@@ -19,7 +19,6 @@
|
||||
"helmet": "^8.2.0",
|
||||
"ioredis": "^5.11.1",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"meoo-app-name": "file:..",
|
||||
"multer": "^2.2.0",
|
||||
"pg": "^8.13.0",
|
||||
"pinyin-pro": "^3.28.1",
|
||||
@@ -42,7 +41,6 @@
|
||||
}
|
||||
},
|
||||
"..": {
|
||||
"name": "meoo-app-name",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"@emotion/is-prop-valid": "^1.4.0",
|
||||
@@ -3950,10 +3948,6 @@
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/meoo-app-name": {
|
||||
"resolved": "..",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/merge-descriptors": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",
|
||||
|
||||
+2
-2
@@ -24,7 +24,8 @@
|
||||
"audit:stock-claimable": "tsx --env-file=.env scripts/audit-stock-claimable.ts",
|
||||
"diag:supplier-statement-caliber": "tsx --env-file=.env scripts/diag-supplier-statement-payable-caliber.ts",
|
||||
"diag:secret-scan": "tsx --env-file=.env scripts/diag-audit-secret-scan.ts",
|
||||
"repair:supplier-statement-amounts": "tsx --env-file=.env scripts/repair-supplier-statement-amount-columns.ts"
|
||||
"repair:supplier-statement-amounts": "tsx --env-file=.env scripts/repair-supplier-statement-amount-columns.ts",
|
||||
"reconcile:order-header-totals": "tsx --env-file=.env scripts/reconcile-order-header-totals.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "^3.758.0",
|
||||
@@ -38,7 +39,6 @@
|
||||
"helmet": "^8.2.0",
|
||||
"ioredis": "^5.11.1",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"meoo-app-name": "file:..",
|
||||
"multer": "^2.2.0",
|
||||
"pg": "^8.13.0",
|
||||
"pinyin-pro": "^3.28.1",
|
||||
|
||||
@@ -31,8 +31,19 @@ NODE
|
||||
export SKIP_DEMO_SEED="${SKIP_DEMO_SEED:-1}"
|
||||
export SKIP_E2E_SEED="${SKIP_E2E_SEED:-1}"
|
||||
|
||||
echo "[entrypoint] running migrations..."
|
||||
node dist/migrate.js
|
||||
# OPS-6:迁移可开关(默认 1 保持现状);0 = 跳过(多副本部署时只让一个实例跑迁移)
|
||||
RUN_MIGRATIONS="${RUN_MIGRATIONS:-1}"
|
||||
if [ "$RUN_MIGRATIONS" = "1" ]; then
|
||||
echo "[entrypoint] running migrations..."
|
||||
if ! node dist/migrate.js; then
|
||||
echo "[entrypoint] ERROR: 数据库迁移失败,API 不会启动。" >&2
|
||||
echo "[entrypoint] 请先备份数据库(pg_dump)并检查 migrations/ 与 schema_migrations 后重试;" >&2
|
||||
echo "[entrypoint] 本脚本不自动备份/自动回滚(避免给出假的安全感)。" >&2
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
echo "[entrypoint] skip migrations (RUN_MIGRATIONS=$RUN_MIGRATIONS)"
|
||||
fi
|
||||
|
||||
echo "[entrypoint] starting API..."
|
||||
exec "$@"
|
||||
|
||||
@@ -8,7 +8,14 @@ import { createRequire } from 'module';
|
||||
const require = createRequire(import.meta.url);
|
||||
const { currentCycleCode } = require('./test-helpers.js');
|
||||
|
||||
const BASE = (process.env.API_BASE || 'https://www.xdjchuanhui.com/api').replace(/\/$/, '');
|
||||
const { guardTestTarget } = require('./test-target-guard.js');
|
||||
const explicitApiBase = String(process.env.API_BASE || '').trim();
|
||||
if (!explicitApiBase) {
|
||||
console.error('未设置 API_BASE:本机请用 http://127.0.0.1:3022/api;远程需同时设置 ALLOW_REMOTE=1');
|
||||
process.exit(1);
|
||||
}
|
||||
// OPS-2:无默认远程地址;非本机必须 ALLOW_REMOTE=1 且 TTY 确认
|
||||
const BASE = guardTestTarget({ base: explicitApiBase, explicit: true, label: 'API_BASE' });
|
||||
const OPERATING_BRANCH = process.env.OPERATING_BRANCH || 'BR002';
|
||||
|
||||
const ADMIN_PASSWORDS = ['Superadmin@123', 'SuperAdmin@123', 'E2eTest@123'];
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* **订单头金额一次性对账**(2026-10-19 BIZ-16)。
|
||||
*
|
||||
* 背景:`orders.total_amount` 是冗余汇总,行被删/退货红冲后本应重算,但历史上只有
|
||||
* 缺货删行 / 退货跟随 / 售后取消履约三条路径调 `recalcOrderHeaderTotals`;
|
||||
* 其余路径会留下"头与明细不一致"的存量行
|
||||
* (审计样本 `ORD_API_20261018_BR002_0001`:头 253.00 / 未退货明细 249.00,差 ¥4)。
|
||||
*
|
||||
* 口径:**完全复用**既有重算口径(金额 = 未退货行 `amount` 之和;重量 = `sumWeightInJin`),
|
||||
* 明细金额一律不动 ⇒ 不改财务口径。
|
||||
*
|
||||
* 用法(在 `SupplierSystem/server` 下):
|
||||
* npm run reconcile:order-header-totals -- --branch BR002 # dry-run:只报告
|
||||
* npm run reconcile:order-header-totals -- --branch BR002 --apply # 写回
|
||||
* npm run reconcile:order-header-totals -- --branch BR002 --limit 1000
|
||||
*
|
||||
* 退出码:0 = 完成(dry-run 发现不一致也算完成);1 = apply 后仍不一致。
|
||||
*
|
||||
* ⚠️ **写操作只允许本地库**(仓库硬规则:本地脚本不得写线上);脚本会对
|
||||
* `DATABASE_URL` 做主机白名单校验。
|
||||
*/
|
||||
import { reconcileOrderHeaderTotals } from '../src/services/orderHeaderReconcileService';
|
||||
import { pool } from '../src/db';
|
||||
|
||||
type Args = { branch: string; apply: boolean; limit: number };
|
||||
|
||||
function parseArgs(argv: string[]): Args {
|
||||
const out: Args = { branch: '', apply: false, limit: 500 };
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
const arg = String(argv[i] || '');
|
||||
if (arg === '--branch' && argv[i + 1]) out.branch = String(argv[(i += 1)]).toUpperCase();
|
||||
else if (arg.startsWith('--branch=')) out.branch = arg.slice('--branch='.length).toUpperCase();
|
||||
else if (arg === '--apply') out.apply = true;
|
||||
else if (arg === '--limit' && argv[i + 1]) out.limit = Number(argv[(i += 1)]);
|
||||
else if (arg.startsWith('--limit=')) out.limit = Number(arg.slice('--limit='.length));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 硬闸门:绝不连非本地库(本脚本 `--apply` 会写库) */
|
||||
function assertLocalDatabase(url: string) {
|
||||
const host = (() => {
|
||||
try {
|
||||
return new URL(url).hostname;
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
})();
|
||||
if (!['127.0.0.1', 'localhost', '::1'].includes(host)) {
|
||||
throw new Error(`拒绝运行:DATABASE_URL 指向非本地库 (${host || 'unknown'})`);
|
||||
}
|
||||
}
|
||||
|
||||
const money = (n: number) => (Math.round((Number(n) || 0) * 100) / 100).toFixed(2);
|
||||
|
||||
async function main() {
|
||||
const url = String(process.env.DATABASE_URL || '');
|
||||
if (!url) {
|
||||
throw new Error('缺少 DATABASE_URL(用 `npm run reconcile:order-header-totals` 会带 --env-file=.env)');
|
||||
}
|
||||
assertLocalDatabase(url);
|
||||
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
if (!args.branch) {
|
||||
console.error(
|
||||
'用法:npm run reconcile:order-header-totals -- --branch BR002 [--apply] [--limit 500]'
|
||||
);
|
||||
process.exitCode = 2;
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await reconcileOrderHeaderTotals({
|
||||
branchCode: args.branch,
|
||||
apply: args.apply,
|
||||
limit: Number.isFinite(args.limit) ? args.limit : 500,
|
||||
});
|
||||
|
||||
console.log(
|
||||
`[reconcile] 分公司 ${result.branchCode}(${result.apply ? 'APPLY 写回' : 'DRY-RUN 只报告'},` +
|
||||
`扫描上限 ${result.limit}):发现不一致 ${result.mismatchCount} 单,修后仍不一致 ${result.remaining} 单`
|
||||
);
|
||||
for (const mismatch of result.mismatches) {
|
||||
console.log(
|
||||
` · ${mismatch.orderCode}:头 ${money(mismatch.headerAmount)} / 明细 ${money(mismatch.itemAmount)}` +
|
||||
`(差 ${mismatch.diff > 0 ? '+' : ''}${money(mismatch.diff)})`
|
||||
);
|
||||
}
|
||||
for (const fixed of result.fixed) {
|
||||
console.log(
|
||||
` ✔ ${fixed.orderCode}:头 ${money(fixed.beforeAmount)} → ${money(fixed.afterAmount)},` +
|
||||
`重量 → ${fixed.afterWeight} 斤`
|
||||
);
|
||||
}
|
||||
if (!args.apply && result.mismatchCount > 0) {
|
||||
console.log('[reconcile] dry-run 未改库;确认后用 `--apply` 写回。');
|
||||
}
|
||||
console.log(`[reconcile] JSON:${JSON.stringify(result)}`);
|
||||
|
||||
if (args.apply && result.remaining > 0) {
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
.catch((error) => {
|
||||
console.error('[reconcile] 失败:', error instanceof Error ? error.message : error);
|
||||
process.exitCode = 1;
|
||||
})
|
||||
.finally(async () => {
|
||||
// 只用到一个连接池(src/db):脚本跑完主动收口,避免 tsx 挂住
|
||||
await pool.end().catch(() => undefined);
|
||||
});
|
||||
@@ -5,7 +5,16 @@
|
||||
|
||||
const { currentCycleCode } = require('./test-helpers.js');
|
||||
|
||||
const BASE = process.env.API_BASE || 'http://127.0.0.1:3001/api';
|
||||
const { guardTestTarget } = require('./test-target-guard.js');
|
||||
|
||||
// OPS-2:默认打本系统 API(3022),且非本机目标必须 API_BASE + ALLOW_REMOTE=1(TTY 确认)
|
||||
const DEFAULT_TEST_API_BASE = 'http://127.0.0.1:3022/api';
|
||||
const explicitApiBase = String(process.env.API_BASE || '').trim();
|
||||
const BASE = guardTestTarget({
|
||||
base: explicitApiBase || DEFAULT_TEST_API_BASE,
|
||||
explicit: Boolean(explicitApiBase),
|
||||
label: 'API_BASE',
|
||||
});
|
||||
const isLocalApi = BASE.includes('127.0.0.1') || BASE.includes('localhost');
|
||||
const OPERATING_BRANCH = process.env.E2E_TEST_BRANCH || process.env.OPERATING_BRANCH || 'BR002';
|
||||
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 小程序全流程 API 探针(生产/本地均可)
|
||||
* 用法: node server/scripts/test-miniprogram-flow.mjs
|
||||
* 环境: API_BASE 默认 https://www.xdjchuanhui.com/api
|
||||
* 小程序全流程 API 探针(**无默认目标**,必须显式指定)
|
||||
* 用法: API_BASE=http://127.0.0.1:3022/api node server/scripts/test-miniprogram-flow.mjs
|
||||
* 远程: API_BASE=https://... ALLOW_REMOTE=1(非 TTY 拒绝)
|
||||
*/
|
||||
const BASE = (process.env.API_BASE || 'https://www.xdjchuanhui.com/api').replace(/\/$/, '');
|
||||
import { createRequire } from 'module';
|
||||
const require = createRequire(import.meta.url);
|
||||
const { guardTestTarget } = require('./test-target-guard.js');
|
||||
|
||||
const explicitApiBase = String(process.env.API_BASE || '').trim();
|
||||
if (!explicitApiBase) {
|
||||
console.error('未设置 API_BASE:本机请用 http://127.0.0.1:3022/api;远程需同时设置 ALLOW_REMOTE=1');
|
||||
process.exit(1);
|
||||
}
|
||||
const BASE = guardTestTarget({ base: explicitApiBase, explicit: true, label: 'API_BASE' });
|
||||
|
||||
const PASSWORDS = [
|
||||
process.env.MP_TEST_PASSWORD,
|
||||
|
||||
@@ -5,7 +5,16 @@
|
||||
|
||||
const { currentCycleCode } = require('./test-helpers.js');
|
||||
|
||||
const BASE = process.env.API_BASE || 'http://127.0.0.1:3001/api';
|
||||
const { guardTestTarget } = require('./test-target-guard.js');
|
||||
|
||||
// OPS-2:默认打本系统 API(3022);非本机目标必须 API_BASE + ALLOW_REMOTE=1(TTY 确认)
|
||||
const DEFAULT_TEST_API_BASE = 'http://127.0.0.1:3022/api';
|
||||
const explicitApiBase = String(process.env.API_BASE || '').trim();
|
||||
const BASE = guardTestTarget({
|
||||
base: explicitApiBase || DEFAULT_TEST_API_BASE,
|
||||
explicit: Boolean(explicitApiBase),
|
||||
label: 'API_BASE',
|
||||
});
|
||||
const results = [];
|
||||
|
||||
function pass(name, detail = '') {
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 测试脚本目标环境硬守卫(OPS-2,2026-10-19)。
|
||||
*
|
||||
* 背景:`test-functionality.js` / `test-page-flows.js` 旧默认 `http://127.0.0.1:3001/api`
|
||||
* (主系统 API),两个小程序探针默认 `https://www.xdjchuanhui.com/api`(生产)——
|
||||
* 本机跑一次测试就可能把生产数据打一遍。
|
||||
*
|
||||
* 规则:
|
||||
* · 默认只允许本机(127.0.0.1 / localhost / ::1),默认端口 3022;
|
||||
* · 目标非本机时必须 **显式** API_BASE + ALLOW_REMOTE=1,否则 exit 1;
|
||||
* · ALLOW_REMOTE=1 也要 3 秒倒计时确认;非交互(stdin 非 TTY)直接硬失败。
|
||||
*/
|
||||
|
||||
function isLoopbackTarget(base) {
|
||||
try {
|
||||
const host = new URL(base).hostname.replace(/^\[|\]$/g, '').toLowerCase();
|
||||
return host === '127.0.0.1' || host === 'localhost' || host === '::1';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function sleepBlocking(ms) {
|
||||
// 无依赖阻塞等待(用于 TTY 下 3 秒倒计时);非 TTY 不会走到这里
|
||||
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ base: string, explicit?: boolean, label?: string }} options
|
||||
* @returns {string} 归一后的 base(无尾斜杠)
|
||||
*/
|
||||
function guardTestTarget(options) {
|
||||
const raw = String(options.base || '').trim();
|
||||
const base = raw.replace(/\/+$/, '');
|
||||
console.log(`[test] target: ${base}`);
|
||||
if (!base) {
|
||||
console.error('[test] 未设置目标地址:本机默认 http://127.0.0.1:3022/api');
|
||||
process.exit(1);
|
||||
}
|
||||
if (isLoopbackTarget(base)) {
|
||||
/**
|
||||
* O-12.10:本机 3001 是**主系统** API(AI 生鲜配送),不是本系统 3022。
|
||||
* 旧守卫把任何 127.0.0.1 都当"安全本地" ⇒ 默认就可能把主系统数据打一遍。
|
||||
* 需要显式 ALLOW_MAIN_SYSTEM=1 才放行(并在 TTY 下提示)。
|
||||
*/
|
||||
let port = '';
|
||||
try {
|
||||
const parsed = new URL(base);
|
||||
port = parsed.port || (parsed.protocol === 'https:' ? '443' : '80');
|
||||
} catch {
|
||||
/* isLoopbackTarget 已解析过,理论上不会到这里 */
|
||||
}
|
||||
if (port === '3001' && process.env.ALLOW_MAIN_SYSTEM !== '1') {
|
||||
console.error('检测到目标为本机 3001(主系统 API),已拒绝;如确需测试主系统请设置 ALLOW_MAIN_SYSTEM=1');
|
||||
process.exit(1);
|
||||
}
|
||||
return base;
|
||||
}
|
||||
if (!options.explicit || process.env.ALLOW_REMOTE !== '1') {
|
||||
console.error('拒绝访问非本地目标,如确需请设置 ALLOW_REMOTE=1');
|
||||
process.exit(1);
|
||||
}
|
||||
if (!process.stdin.isTTY) {
|
||||
console.error('[test] 非交互环境禁止访问非本地目标(即使 ALLOW_REMOTE=1)');
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`[test] 目标非本地(${options.label || 'remote'}):${base};3 秒后继续,Ctrl+C 取消...`);
|
||||
sleepBlocking(3000);
|
||||
return base;
|
||||
}
|
||||
|
||||
module.exports = { guardTestTarget, isLoopbackTarget };
|
||||
+162
-4
@@ -3,18 +3,148 @@ import { loadEnv } from './env';
|
||||
|
||||
loadEnv();
|
||||
|
||||
const isProduction = process.env.NODE_ENV === 'production';
|
||||
|
||||
// 供应商系统(二次开发):独立库,勿改回 canteen_delivery
|
||||
const DEV_DATABASE_URL = 'postgresql://supplier:change-me@localhost:5432/supplier_delivery';
|
||||
|
||||
const VALID_NODE_ENVS = ['development', 'test', 'production'] as const;
|
||||
export type NodeEnv = (typeof VALID_NODE_ENVS)[number];
|
||||
|
||||
export interface ConfigValidationResult {
|
||||
nodeEnv: NodeEnv;
|
||||
production: boolean;
|
||||
/** 非生产使用默认值时的显式告警(不得静默降级) */
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动配置 fail-fast(OPS-3,2026-10-19)。
|
||||
*
|
||||
* 纯函数(只读传入 env、不连 DB),便于单测:
|
||||
* · `NODE_ENV` 必须显式且只能是 development|test|production(缺失/非法 ⇒ 抛错);
|
||||
* · production 下 `DATABASE_URL` / `CORS_ORIGINS` / `STORAGE_DIR` /(s3 时)`S3_KEY_PREFIX`
|
||||
* 必须显式,且 `DATABASE_URL` 不得回退到开发默认、`STORAGE_DIR` 不得指向主系统 server/uploads;
|
||||
* · 非 production 允许开发默认,但返回 warnings(调用方打印,不得静默)。
|
||||
*/
|
||||
export function validateConfig(env: NodeJS.ProcessEnv = process.env): ConfigValidationResult {
|
||||
const rawNodeEnv = String(env.NODE_ENV ?? '').trim();
|
||||
const problems: string[] = [];
|
||||
if (!rawNodeEnv) {
|
||||
problems.push('NODE_ENV 缺失(必须显式设置为 development|test|production)');
|
||||
} else if (!(VALID_NODE_ENVS as readonly string[]).includes(rawNodeEnv)) {
|
||||
problems.push(`NODE_ENV 非法:${rawNodeEnv}(应为 development|test|production)`);
|
||||
}
|
||||
if (problems.length) throw new Error(`环境变量校验失败:\n- ${problems.join('\n- ')}`);
|
||||
const nodeEnv = rawNodeEnv as NodeEnv;
|
||||
/**
|
||||
* B-12.2:把归一后的 NODE_ENV 写回 process.env。
|
||||
* `NODE_ENV=' production'`(引号值 dotenv 不 trim)时,校验按 production,但运行时
|
||||
* index.ts 的 isDev/isProduction/RLS 判断读原始值 ⇒ 会按 development 放行 CSP/RLS_FAIL_OPEN。
|
||||
* 只在传入真实 process.env 时回写,纯函数单测传对象不污染全局。
|
||||
*/
|
||||
if (env === process.env) process.env.NODE_ENV = nodeEnv;
|
||||
const production = nodeEnv === 'production';
|
||||
const warnings: string[] = [];
|
||||
|
||||
const databaseUrl = String(env.DATABASE_URL ?? '').trim();
|
||||
const corsOrigins = String(env.CORS_ORIGINS ?? '').trim();
|
||||
const storageDir = String(env.STORAGE_DIR ?? '').trim();
|
||||
const storageProvider = String(env.STORAGE_PROVIDER ?? 'local').trim().toLowerCase();
|
||||
// B-12.1:与运行时完全相同的归一化(trim + 去首尾斜杠),否则 '/' 会被判非空却落成空前缀
|
||||
const s3KeyPrefix = String(env.S3_KEY_PREFIX ?? '').trim().replace(/^\/+|\/+$/g, '');
|
||||
const defaultStorageDir = path.join(__dirname, '..', 'uploads');
|
||||
|
||||
if (production) {
|
||||
if (!databaseUrl) problems.push('production 必须显式设置 DATABASE_URL');
|
||||
else if (databaseUrl === DEV_DATABASE_URL) {
|
||||
problems.push('production 的 DATABASE_URL 不得使用开发默认值(必须显式配置独立库)');
|
||||
} else {
|
||||
/**
|
||||
* O-12.2(隔离红线):旧校验只拦精确的 dev 回退值,`.../canteen_delivery`、`canteen` 角色、
|
||||
* `?sslmode=` 等变体仍会连到主系统库/角色。这里解析 URL 后显式拒绝主系统库名与角色。
|
||||
*/
|
||||
try {
|
||||
const parsed = new URL(databaseUrl);
|
||||
/**
|
||||
* O-12.2 编码绕过(2026-10-19 verifier FAIL):`%5F`/`%63` 等编码在 pg-connection-string
|
||||
* 里会被解码成 `canteen_delivery`/`canteen`,旧校验不 decode 就放行。这里先 decode 再比较;
|
||||
* 解码异常/含路径分隔符(`%2F` 变体)一律 fail-closed 拒绝。
|
||||
*/
|
||||
const decodedPath = decodeURIComponent(parsed.pathname).replace(/^\/+/, '').replace(/\/+$/, '');
|
||||
const dbName = decodedPath.toLowerCase();
|
||||
const role = decodeURIComponent(parsed.username || '').toLowerCase();
|
||||
if (dbName.includes('/') || dbName.includes('\\')) {
|
||||
problems.push('production 的 DATABASE_URL 库名不得包含路径分隔符(编码变体按不可信处理)');
|
||||
}
|
||||
if (dbName === 'canteen_delivery') {
|
||||
problems.push('production 的 DATABASE_URL 不得指向主系统库 canteen_delivery(本系统必须 supplier_delivery)');
|
||||
}
|
||||
if (role === 'canteen') {
|
||||
problems.push('production 的 DATABASE_URL 不得使用主系统角色 canteen(本系统必须 supplier)');
|
||||
}
|
||||
} catch {
|
||||
problems.push('production 的 DATABASE_URL 不是合法的连接串(无法解析/解码失败)');
|
||||
}
|
||||
}
|
||||
if (!corsOrigins || corsOrigins === '*') {
|
||||
problems.push('production 必须显式设置 CORS_ORIGINS 白名单(不能为空或 *,禁止反射任意源)');
|
||||
}
|
||||
if (!storageDir) {
|
||||
problems.push('production 必须显式设置 STORAGE_DIR');
|
||||
} else {
|
||||
const normalized = path.resolve(storageDir).replace(/\\/g, '/').replace(/\/+$/, '');
|
||||
const mainSystemUploads = path.resolve(defaultStorageDir).replace(/\\/g, '/').replace(/\/+$/, '');
|
||||
if (normalized === mainSystemUploads || /(^|\/)server\/uploads$/.test(normalized)) {
|
||||
problems.push('production 的 STORAGE_DIR 不得指向主系统上传目录 server/uploads');
|
||||
}
|
||||
}
|
||||
if (storageProvider === 's3' && !s3KeyPrefix) {
|
||||
problems.push('production 且 STORAGE_PROVIDER=s3 时必须设置 S3_KEY_PREFIX(否则写进主系统桶根)');
|
||||
}
|
||||
} else {
|
||||
if (!databaseUrl) warnings.push('DATABASE_URL 未设置,使用开发默认值(仅限非生产)');
|
||||
if (!storageDir) warnings.push(`STORAGE_DIR 未设置,使用默认值 ${defaultStorageDir}(仅限非生产)`);
|
||||
if (!corsOrigins || corsOrigins === '*') {
|
||||
warnings.push('CORS_ORIGINS 未设置或为 *,开发环境允许任意来源(仅限非生产)');
|
||||
}
|
||||
if (storageProvider === 's3' && !s3KeyPrefix) {
|
||||
warnings.push('STORAGE_PROVIDER=s3 但 S3_KEY_PREFIX 为空(非生产不阻断,生产会拒绝启动)');
|
||||
}
|
||||
}
|
||||
|
||||
if (problems.length) {
|
||||
throw new Error(`环境变量校验失败(NODE_ENV=${nodeEnv}):\n- ${problems.join('\n- ')}`);
|
||||
}
|
||||
return { nodeEnv, production, warnings };
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印非生产默认值告警(NODE_ENV=test 不打印:测试进程由 vitest 固定为 test,
|
||||
* 本地 .env 缺 CORS_ORIGINS 等属正常,打印会污染其它用例对 console.warn 的断言,如 storageIsolation)。
|
||||
* 返回实际打印的告警,便于测试;校验本身不受影响。
|
||||
*/
|
||||
export function emitConfigWarnings(result: ConfigValidationResult): string[] {
|
||||
if (result.nodeEnv === 'test') return [];
|
||||
for (const warning of result.warnings) {
|
||||
console.warn(`[config] ${warning}`);
|
||||
}
|
||||
return result.warnings;
|
||||
}
|
||||
|
||||
// 模块加载即执行(fail-fast):缺失/非法配置直接拒绝启动
|
||||
const configValidation = validateConfig();
|
||||
emitConfigWarnings(configValidation);
|
||||
// O-12.15:必须在 validateConfig 归一/回写 NODE_ENV 之后派生,否则 `NODE_ENV=' production'`
|
||||
// 时 serveStatic 会按 development 算成 false(all-in-one 前端不被服务)。
|
||||
const isProduction = configValidation.production;
|
||||
|
||||
// A10: 任意环境必须显式配置 JWT_SECRET,禁止弱默认回退
|
||||
const jwtSecret = String(process.env.JWT_SECRET || '').trim();
|
||||
if (!jwtSecret) {
|
||||
throw new Error('必须设置环境变量 JWT_SECRET(开发/生产均不可使用隐式默认密钥)');
|
||||
}
|
||||
const databaseUrl = process.env.DATABASE_URL || DEV_DATABASE_URL;
|
||||
const storageProvider = (process.env.STORAGE_PROVIDER || 'local').toLowerCase() === 's3' ? 's3' as const : 'local' as const;
|
||||
const storageProvider =
|
||||
String(process.env.STORAGE_PROVIDER || 'local').trim().toLowerCase() === 's3' ? ('s3' as const) : ('local' as const);
|
||||
const s3InternalOnly = process.env.S3_INTERNAL_ONLY === 'true';
|
||||
|
||||
function resolveS3Region() {
|
||||
@@ -45,8 +175,35 @@ function parseCorsOrigins(raw?: string): boolean | string[] {
|
||||
return trimmed.split(',').map((item) => item.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Trust proxy(SEC-3,2026-10-19):默认 **loopback**(只信同机 nginx/webpack 一跳),
|
||||
* 绝不默认 `true`/`1` —— 无条件信任会让直连客户端用 `X-Forwarded-For` 伪造 `req.ip`,
|
||||
* 从而绕开按 IP 的登录限流/审计。
|
||||
*
|
||||
* 支持:`false`(不信任任何代理)/`loopback`/`linklocal`/`uniquelocal`/数字跳数/
|
||||
* 逗号分隔的 IP|CIDR 列表(外部 LB 场景显式配置)。
|
||||
*/
|
||||
function parseTrustProxy(raw?: string): false | true | number | string | string[] {
|
||||
const trimmed = String(raw ?? '').trim();
|
||||
if (!trimmed) return 'loopback';
|
||||
const lower = trimmed.toLowerCase();
|
||||
if (lower === 'false' || lower === '0' || lower === 'off') return false;
|
||||
if (lower === 'true') return true; // 仅显式配置才允许全信任
|
||||
if (/^\d+$/.test(trimmed)) return Number(trimmed);
|
||||
if (lower === 'loopback' || lower === 'linklocal' || lower === 'uniquelocal') return lower;
|
||||
const list = trimmed.split(',').map((item) => item.trim()).filter(Boolean);
|
||||
if (list.length === 1) return list[0];
|
||||
return list;
|
||||
}
|
||||
|
||||
export const config = {
|
||||
port: Number(process.env.PORT || 3022),
|
||||
/**
|
||||
* 监听地址:默认回环(防止绕过同机 nginx 直连 API)。
|
||||
* 容器/特殊部署用 `HOST=0.0.0.0` 显式覆盖(compose 由 T6 负责)。
|
||||
*/
|
||||
host: process.env.HOST || '127.0.0.1',
|
||||
trustProxy: parseTrustProxy(process.env.TRUST_PROXY),
|
||||
databaseUrl,
|
||||
jwtSecret,
|
||||
jwtExpiresIn: process.env.JWT_EXPIRES_IN || '8h',
|
||||
@@ -61,7 +218,8 @@ export const config = {
|
||||
bucket: process.env.S3_BUCKET || '',
|
||||
accessKeyId: process.env.S3_ACCESS_KEY_ID || '',
|
||||
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY || '',
|
||||
keyPrefix: (process.env.S3_KEY_PREFIX || '').replace(/^\/+|\/+$/g, ''),
|
||||
// B-12.1:与校验一致(trim + 去首尾斜杠),避免带空白的值在校验/运行时含义不同
|
||||
keyPrefix: String(process.env.S3_KEY_PREFIX || '').trim().replace(/^\/+|\/+$/g, ''),
|
||||
publicBaseUrl: s3InternalOnly ? '' : (process.env.S3_PUBLIC_BASE_URL || '').replace(/\/+$/, ''),
|
||||
// APK 必须走已备案的 COS 自定义域名(默认域名禁止公网分发 APK);仅 weigh-apk 桶使用,不影响图片
|
||||
weighApkPublicBaseUrl: (process.env.WEIGH_APK_PUBLIC_BASE_URL || '').replace(/\/+$/, ''),
|
||||
|
||||
+52
-6
@@ -2,7 +2,7 @@ import express from 'express';
|
||||
import cors from 'cors';
|
||||
import helmet from 'helmet';
|
||||
import rateLimit, { ipKeyGenerator } from 'express-rate-limit';
|
||||
import { authMiddleware } from './middleware/auth';
|
||||
import { authMiddleware, AuthRequest } from './middleware/auth';
|
||||
import { getDistributedLockStats } from './services/distributedLock';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
@@ -35,6 +35,7 @@ import { tenantDbMiddleware } from './middleware/tenantDbMiddleware';
|
||||
import { operationAuditMiddleware } from './middleware/operationAuditMiddleware';
|
||||
import { startScheduledJobs } from './services/scheduledJobs';
|
||||
import { ensureRoleDefinitionsSchema } from './services/roleDefinitionService';
|
||||
import { loadTenantContext } from './services/tenantScope';
|
||||
import { syncPermissionCatalog } from './services/permissionCatalogService';
|
||||
import { initRedisConnection, isRedisConfigured, pingRedis } from './services/redisClient';
|
||||
import { listHotCacheTables } from './services/queryCacheService';
|
||||
@@ -49,7 +50,13 @@ if (config.storage.provider === 'local') {
|
||||
|
||||
export function createApp() {
|
||||
const app = express();
|
||||
app.set('trust proxy', 1);
|
||||
/**
|
||||
* SEC-3(2026-10-19):不再无条件 `trust proxy = 1`。
|
||||
* 取值由 `TRUST_PROXY` 决定(默认 `loopback`,只信同机代理);无条件信任会让直连请求
|
||||
* 用 `X-Forwarded-For` 伪造 `req.ip` ⇒ 登录限流/审计 IP 可被绕过。
|
||||
* 限流键 `loginKeyGenerator` 本身仍只用 `req.ip`(由 `loginAuditIpHardening.test.ts` 钉住,勿回退)。
|
||||
*/
|
||||
app.set('trust proxy', config.trustProxy);
|
||||
// 开发环境放宽 CSP,生产环境严格限制
|
||||
const isDev = process.env.NODE_ENV !== 'production';
|
||||
app.use(
|
||||
@@ -139,8 +146,21 @@ app.get('/api/health', (_req, res) => {
|
||||
res.json({ status: 'ok', time: new Date().toISOString() });
|
||||
});
|
||||
|
||||
// M3:完整诊断(原 /api/health 载荷)挪到**需登录令牌**的端点。
|
||||
app.get('/api/health/details', authMiddleware, async (_req, res) => {
|
||||
// M3:完整诊断(原 /api/health 载荷)挪到**需登录令牌 + 超管/运维**的端点。
|
||||
// SEC-6(2026-10-19 T9):普通登录用户不得读内部拓扑(桶名/endpoint/热点表/在线连接数/锁统计)。
|
||||
app.get('/api/health/details', authMiddleware, async (req: AuthRequest, res) => {
|
||||
// SEC-6:mobile/受限 token 即使角色是 super_admin/ops 也不得读完整拓扑
|
||||
if (req.tokenScope === 'mobile') {
|
||||
return res.status(403).json({ error: 'forbidden', error_description: '移动端受限令牌不可访问完整诊断' });
|
||||
}
|
||||
const ctx = await loadTenantContext(req.userId);
|
||||
const allowed =
|
||||
Boolean(ctx?.isSuperAdmin) ||
|
||||
Boolean(ctx?.roles?.includes('super_admin')) ||
|
||||
Boolean(ctx?.roles?.includes('ops'));
|
||||
if (!ctx || !allowed) {
|
||||
return res.status(403).json({ error: 'forbidden', error_description: '仅超管/运维可查看完整诊断' });
|
||||
}
|
||||
res.json({
|
||||
status: 'ok',
|
||||
time: new Date().toISOString(),
|
||||
@@ -181,6 +201,31 @@ app.use('/api/modules', modulesRoutes);
|
||||
app.use('/api/catalog', tenantDbMiddleware, catalogRoutes);
|
||||
app.use('/api/roles', rolesRoutes);
|
||||
|
||||
// SEC-8(2026-10-19 T9):/api 未命中路由统一 JSON 404(不再回 Express 默认 HTML)
|
||||
app.use('/api', (_req, res) => {
|
||||
res.status(404).json({ data: null, error: { message: '接口不存在', code: 'not_found' } });
|
||||
});
|
||||
|
||||
// SEC-8(2026-10-19 T9):全局错误兜底 —— 统一 JSON,不把堆栈/内部细节返回客户端。
|
||||
// 放在所有路由之后、静态资源/监听之前;4xx 业务错误仍由各路由自行返回。
|
||||
app.use((err: any, req: express.Request, res: express.Response, _next: express.NextFunction) => {
|
||||
const status = Number(err?.status || err?.statusCode || 500);
|
||||
const code = status >= 500 ? 'internal_error' : String(err?.code || 'request_failed');
|
||||
const message =
|
||||
status >= 500 ? '服务器内部错误,请稍后重试' : String(err?.message || '请求失败');
|
||||
console.error(`[express-error] ${req.method} ${req.originalUrl} status=${status}`, err);
|
||||
// 已开始输出(SSE/流式):直接返回会让连接悬挂;销毁连接让客户端立即感知失败
|
||||
if (res.headersSent) {
|
||||
try {
|
||||
res.destroy();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
return;
|
||||
}
|
||||
res.status(status).json({ data: null, error: { message, code } });
|
||||
});
|
||||
|
||||
const isProduction = process.env.NODE_ENV === 'production';
|
||||
if (isProduction && config.serveStatic) {
|
||||
const staticDir = path.join(__dirname, '..', '..', 'dist');
|
||||
@@ -216,14 +261,15 @@ if (require.main === module) {
|
||||
}
|
||||
}
|
||||
|
||||
app.listen(config.port, '0.0.0.0', () => {
|
||||
app.listen(config.port, config.host, () => {
|
||||
const isProduction = process.env.NODE_ENV === 'production';
|
||||
const mode = isProduction
|
||||
? config.serveStatic
|
||||
? 'production(all-in-one)'
|
||||
: 'production(api-only)'
|
||||
: 'development';
|
||||
console.log(`API server running on 0.0.0.0:${config.port} (${mode})`);
|
||||
// SEC-3:打印**实际**监听地址(默认 127.0.0.1,容器用 HOST=0.0.0.0 覆盖)
|
||||
console.log(`API server running on ${config.host}:${config.port} (${mode})`);
|
||||
// 显眼地打出去连的是哪个主系统:本地开发是 127.0.0.1:3001,上线后是线上地址。
|
||||
// 这一行是为了防「以为在连本地、其实指着生产」——看到不像本地的地址就停下来确认。
|
||||
// 注意:登录已与主系统解耦(一律本地账号),这里只影响拉取/回写,与能否登录无关。
|
||||
|
||||
+36
-21
@@ -51,7 +51,18 @@ function normalizeMigrationSql(sql: string) {
|
||||
.replace(/::app_role/g, '');
|
||||
}
|
||||
|
||||
async function applySqlFile(filePath: string) {
|
||||
/**
|
||||
* 只对**可证明幂等**的「对象已存在」SQLSTATE 容错(DATA-6,2026-10-19):
|
||||
* 42710 duplicate_object / 42P07 duplicate_table / 42701 duplicate_column / 42723 duplicate_function。
|
||||
*
|
||||
* 硬规则:
|
||||
* · 不再用 /already exists/i 文本判断(未知 code 的同一文本必须失败);
|
||||
* · 白名单命中 ⇒ warning 后继续下一个文件,但**绝不**写 schema_migrations(下次仍会重跑);
|
||||
* · 23505/23503/42P01 等及未知错误 ⇒ 失败并抛出,同样不登记。
|
||||
*/
|
||||
const IDEMPOTENT_OBJECT_EXISTS_SQLSTATES = new Set(['42710', '42P07', '42701', '42723']);
|
||||
|
||||
export async function applySqlFile(filePath: string) {
|
||||
const filename = path.basename(filePath);
|
||||
const exists = await pool.query('SELECT 1 FROM schema_migrations WHERE filename = $1', [filename]);
|
||||
if (exists.rowCount) return;
|
||||
@@ -66,25 +77,25 @@ async function applySqlFile(filePath: string) {
|
||||
await client.query('COMMIT');
|
||||
console.log(`Applied ${filename}`);
|
||||
} catch (error: any) {
|
||||
await client.query('ROLLBACK');
|
||||
await client.query('ROLLBACK').catch(() => undefined);
|
||||
const code = String(error?.code || '');
|
||||
const msg = String(error?.message || error);
|
||||
// 幂等重放容错:仅「对象已存在」类错误(42710 等)视为已应用;
|
||||
// 外键缺失(23503)/ 唯一冲突(23505)说明数据有问题,必须让迁移失败,不能标记已应用。
|
||||
const isDuplicateObject =
|
||||
/already exists/i.test(msg) && error?.code !== '23505' && error?.code !== '23503';
|
||||
if (isDuplicateObject || error?.code === '42710') {
|
||||
await pool.query('INSERT INTO schema_migrations (filename) VALUES ($1) ON CONFLICT DO NOTHING', [filename]);
|
||||
console.log(`Skipped ${filename} (${msg.split('\n')[0]})`);
|
||||
const firstLine = msg.split('\n')[0];
|
||||
if (IDEMPOTENT_OBJECT_EXISTS_SQLSTATES.has(code)) {
|
||||
// 对象已存在:幂等重放可接受,但**不登记**(本次文件可能只执行到一半,下次重跑继续尝试)
|
||||
console.warn(`[MIGRATION] ${filename} 命中可幂等 SQLSTATE ${code}(${firstLine}),未登记 schema_migrations,下次迁移将重跑该文件`);
|
||||
return;
|
||||
}
|
||||
if (error?.code === '23503' || error?.code === '23505') {
|
||||
console.error(
|
||||
`\n[MIGRATION FAILED] ${filename}: ${error.code === '23503' ? '外键约束失败(依赖数据缺失)' : '唯一约束冲突(数据重复)'}\n` +
|
||||
` ${msg.split('\n')[0]}\n` +
|
||||
` 该迁移未标记为已应用,请修复数据后重跑迁移。\n`
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
console.error(
|
||||
`\n[MIGRATION FAILED] ${filename}: SQLSTATE=${code || 'unknown'}\n` +
|
||||
` ${firstLine}\n` +
|
||||
(code === '23503'
|
||||
? ' 外键约束失败(依赖数据缺失)'
|
||||
: code === '23505'
|
||||
? ' 唯一约束冲突(数据重复)'
|
||||
: ' 非幂等错误(或未知错误码,文本 "already exists" 不再作为放行依据)') +
|
||||
`\n 该迁移未标记为已应用,请修复后重跑迁移。\n`
|
||||
);
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
@@ -230,7 +241,11 @@ async function main() {
|
||||
await pool.end();
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
// T4 测试卫生(T9 顺手修):仅作为入口脚本执行时才跑 main 并 process.exit;
|
||||
// 被测试 import(applySqlFile 单测)时不得触发真实迁移/退出进程。
|
||||
if (require.main === module) {
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { Router, Response } from 'express';
|
||||
import {
|
||||
assertOwnedStoragePaths as assertOwnedStoragePathsShared,
|
||||
assertStorageKeyOwned,
|
||||
} from '../../../services/storageObjectOwnership';
|
||||
import { pool } from '../../../db';
|
||||
import { authMiddleware, type AuthRequest } from '../../../middleware/auth';
|
||||
import { readOperatingBranchCode, getEffectiveBranchCode } from '../../../services/tenantScope';
|
||||
@@ -246,10 +250,22 @@ router.get('/finance/customer-invoices', authMiddleware, async (req: AuthRequest
|
||||
}
|
||||
});
|
||||
|
||||
async function assertOwnedStoragePath(ctx: any, bucket: string, raw: unknown): Promise<void> {
|
||||
const path = String(raw || '').trim();
|
||||
if (!path) return;
|
||||
await assertStorageKeyOwned(bucket, path, ctx);
|
||||
}
|
||||
|
||||
async function assertOwnedStoragePaths(ctx: any, bucket: string, raws: unknown): Promise<void> {
|
||||
// T9:批量写入口统一走公用断言(外链/data: 跳过;任一桶内 key 不属于本租户 ⇒ 403)
|
||||
await assertOwnedStoragePathsShared(ctx, bucket, raws);
|
||||
}
|
||||
|
||||
router.post('/finance/customer-invoices', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, ['finance_manage', 'statement_manage', 'invoice_manage']);
|
||||
await assertOwnedStoragePath(ctx, 'invoices', req.body?.invoice_url);
|
||||
const data = await insertCustomerInvoice(
|
||||
{
|
||||
invoice_no: req.body?.invoice_no,
|
||||
@@ -278,6 +294,7 @@ router.post('/finance/supplier-invoices', authMiddleware, async (req: AuthReques
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, ['finance_manage', 'statement_manage', 'invoice_manage']);
|
||||
await assertOwnedStoragePath(ctx, 'invoices', req.body?.invoice_url);
|
||||
const data = await insertSupplierInvoice(
|
||||
{
|
||||
invoice_no: req.body?.invoice_no,
|
||||
@@ -907,6 +924,8 @@ router.post('/cost/free-cost', authMiddleware, async (req: AuthRequest, res: Res
|
||||
const description = String(req.body?.description || req.body?.remark || '');
|
||||
const voucherUrls = req.body?.voucher_urls ?? req.body?.voucherUrls;
|
||||
const branchCode = getEffectiveBranchCode(ctx, readOperatingBranchCode(req));
|
||||
// T9:写库前校验 voucher_url 归属(跨分支 key ⇒ 403,不落库)
|
||||
await assertOwnedStoragePaths(ctx, 'invoices', voucherUrls);
|
||||
let status = 20;
|
||||
let requireVoucher = false;
|
||||
if (mpFreeCost) {
|
||||
@@ -931,6 +950,7 @@ router.post('/cost/free-cost', authMiddleware, async (req: AuthRequest, res: Res
|
||||
invoicePhoto: mpFreeCost && (req.body?.invoice_photo === true || req.body?.invoice_photo === 'true'),
|
||||
status,
|
||||
source: mpFreeCost ? 'mp' : 'web',
|
||||
ownerCtx: ctx,
|
||||
});
|
||||
return res.json({ data });
|
||||
} catch (error: any) {
|
||||
@@ -992,6 +1012,7 @@ router.post('/cost/free-cost/extract-invoice', authMiddleware, async (req: AuthR
|
||||
if (!req.userId) {
|
||||
return res.status(401).json({ error: 'unauthorized', error_description: '未登录' });
|
||||
}
|
||||
await assertOwnedStoragePath(ctx, 'invoices', req.body?.invoice_path || req.body?.path);
|
||||
const data = await extractFreeCostInvoice({
|
||||
invoicePath: String(req.body?.invoice_path || req.body?.path || ''),
|
||||
ctx,
|
||||
@@ -1014,6 +1035,7 @@ router.post('/cost/free-cost/invoices', authMiddleware, async (req: AuthRequest,
|
||||
if (!req.userId) {
|
||||
return res.status(401).json({ error: 'unauthorized', error_description: '未登录' });
|
||||
}
|
||||
await assertOwnedStoragePath(ctx, 'invoices', req.body?.invoice_path || req.body?.path);
|
||||
const data = await saveFreeCostInvoice({
|
||||
invoicePath: String(req.body?.invoice_path || req.body?.path || ''),
|
||||
costDetailIds: req.body?.cost_detail_ids ?? req.body?.costDetailIds,
|
||||
@@ -1073,8 +1095,15 @@ router.post(
|
||||
if (!req.userId) {
|
||||
return res.status(401).json({ error: 'unauthorized', error_description: '未登录' });
|
||||
}
|
||||
const items = Array.isArray(req.body?.items) ? req.body.items : [];
|
||||
// T9:写库前校验 storage_path 归属(跨分支 key ⇒ 403,事务内 ROLLBACK,不新增行)
|
||||
await assertOwnedStoragePaths(
|
||||
ctx,
|
||||
'invoices',
|
||||
items.map((item: any) => item?.path)
|
||||
);
|
||||
const data = await saveFreeCostPaymentVouchers({
|
||||
items: Array.isArray(req.body?.items) ? req.body.items : [],
|
||||
items,
|
||||
ctx,
|
||||
uploaderId: req.userId,
|
||||
branchCode: getEffectiveBranchCode(ctx, readOperatingBranchCode(req)),
|
||||
@@ -1246,6 +1275,7 @@ router.post('/cost/free-cost/voucher-amount', authMiddleware, async (req: AuthRe
|
||||
requireWorkflowPermission(ctx, ['cost_manage', 'finance_manage']);
|
||||
}
|
||||
const voucherPath = String(req.body?.voucher_path || req.body?.path || '').trim();
|
||||
await assertOwnedStoragePath(ctx, 'invoices', voucherPath);
|
||||
let imageBase64 = String(req.body?.image_base64 || req.body?.content || '');
|
||||
// 真机大图 base64 易超 express.json 2mb;优先用已上传 path 服务端读图
|
||||
if (voucherPath) {
|
||||
@@ -1599,6 +1629,9 @@ router.post('/finance/fixed-costs', authMiddleware, async (req: AuthRequest, res
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, ['cost_manage', 'finance_manage']);
|
||||
const voucherUrls = Array.isArray(req.body?.voucher_urls) ? req.body.voucher_urls.map(String) : undefined;
|
||||
// T9:写库前校验 voucher_urls 归属(跨分支 key ⇒ 403,不落库)
|
||||
await assertOwnedStoragePaths(ctx, 'invoices', voucherUrls);
|
||||
const data = await createFixedCost({
|
||||
cycleCode: String(req.body?.cycle_code || ''),
|
||||
costType: String(req.body?.cost_type || 'other'),
|
||||
@@ -1606,10 +1639,11 @@ router.post('/finance/fixed-costs', authMiddleware, async (req: AuthRequest, res
|
||||
actualAmount: Number(req.body?.actual_amount) || 0,
|
||||
allocationMethod: String(req.body?.allocation_method || 'amount'),
|
||||
remark: req.body?.remark ? String(req.body.remark) : null,
|
||||
voucherUrls: Array.isArray(req.body?.voucher_urls) ? req.body.voucher_urls.map(String) : undefined,
|
||||
voucherUrls,
|
||||
branchCode: getEffectiveBranchCode(ctx, readOperatingBranchCode(req)),
|
||||
inputterId: req.userId,
|
||||
allocate: req.body?.allocate !== false && req.body?.allocate !== 'false',
|
||||
ownerCtx: ctx,
|
||||
});
|
||||
return res.json({ data });
|
||||
} catch (error: any) {
|
||||
@@ -1693,6 +1727,8 @@ router.patch('/finance/fixed-costs/:id/vouchers', authMiddleware, async (req: Au
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, ['cost_manage', 'finance_manage']);
|
||||
const urls = Array.isArray(req.body?.voucher_urls) ? req.body.voucher_urls.map(String).filter(Boolean) : [];
|
||||
// T9:UPDATE 前校验 voucher_urls 归属(跨分支 key ⇒ 403,原值不变)
|
||||
await assertOwnedStoragePaths(ctx, 'invoices', urls);
|
||||
const data = await updateFixedCostVouchers(String(req.params.id), urls, ctx);
|
||||
return res.json({ data });
|
||||
} catch (error: any) {
|
||||
|
||||
@@ -129,7 +129,9 @@ export function mountMainSystemBidWorkflowRoutes(router: Router): void {
|
||||
requireAdminRole(ctx, '仅管理员可删除竞价邀约');
|
||||
const branchCode = branchOf(req, ctx) || ctx?.branchCode || '';
|
||||
const roundId = String(req.params?.roundId || '');
|
||||
const supplierCode = req.body?.supplier_code ?? req.query?.supplier_code ?? null;
|
||||
// 前端(workflowApi)按详情接口同款字段名传 `?supplier=`;旧调用方仍可传 `supplier_code`。
|
||||
const supplierCode =
|
||||
req.body?.supplier_code ?? req.body?.supplier ?? req.query?.supplier_code ?? req.query?.supplier ?? null;
|
||||
const result = await softDeleteBidInvitation({ branchCode, roundId, supplierCode, userId: ctx?.userId ?? null });
|
||||
if (!result.ok) {
|
||||
return res.status(result.status).json({ error: result.code, error_description: result.message });
|
||||
@@ -147,7 +149,9 @@ export function mountMainSystemBidWorkflowRoutes(router: Router): void {
|
||||
requireAdminRole(ctx, '仅管理员可恢复竞价邀约');
|
||||
const branchCode = branchOf(req, ctx) || ctx?.branchCode || '';
|
||||
const roundId = String(req.params?.roundId || '');
|
||||
const supplierCode = req.body?.supplier_code ?? req.query?.supplier_code ?? null;
|
||||
// 同上:兼容前端 `?supplier=` 与旧字段 `supplier_code`。
|
||||
const supplierCode =
|
||||
req.body?.supplier_code ?? req.body?.supplier ?? req.query?.supplier_code ?? req.query?.supplier ?? null;
|
||||
const result = await restoreBidInvitation({ branchCode, roundId, supplierCode });
|
||||
if (!result.ok) {
|
||||
return res.status(result.status).json({ error: result.code, error_description: result.message });
|
||||
|
||||
@@ -59,6 +59,7 @@ import {
|
||||
import { listPurchaseOrdersForManagement, sumSelfPurchaseTotalAmount } from '../../../services/purchaseOrderQueryService';
|
||||
import { listPriceInvertRisks } from '../../../services/priceInvertRiskQueryService';
|
||||
import { resolveSelfPurchaseWriteAccess } from '../../../services/selfPurchaseHttpAccess';
|
||||
import { assertOwnedStoragePaths } from '../../../services/storageObjectOwnership';
|
||||
|
||||
const PREP_AMEND_PERMS = [
|
||||
'preparation_manage',
|
||||
@@ -67,6 +68,20 @@ const PREP_AMEND_PERMS = [
|
||||
'order_entry',
|
||||
];
|
||||
|
||||
/**
|
||||
* T9:质检报告上传入口只对「桶内对象路径」做归属断言;
|
||||
* data:/裸 base64/外链不是桶内 key(服务端会另存或忽略),不参与归属校验。
|
||||
*/
|
||||
function uploadPathRefs(files: string[]): string[] {
|
||||
return files.filter((value) => {
|
||||
const text = String(value || '').trim();
|
||||
if (!text) return false;
|
||||
if (/^data:/i.test(text) || /^(?:https?:)?\/\//i.test(text)) return false;
|
||||
if (text.length > 200 && /^[A-Za-z0-9+/=\s]+$/.test(text)) return false;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/** 采购模块 workflow API(质检库与 /purchase*) */
|
||||
export function mountPurchaseWorkflowRoutes(router: Router): void {
|
||||
/**
|
||||
@@ -214,6 +229,8 @@ router.post('/quality-reports/library', authMiddleware, async (req: AuthRequest,
|
||||
? [String(req.body.file)]
|
||||
: [];
|
||||
const supplierCode = String(req.body?.supplier_code || '').trim();
|
||||
// T9:写库前校验报告文件 key 归属(跨分支 key ⇒ 403,不落库)
|
||||
await assertOwnedStoragePaths(ctx, 'quality-reports', uploadPathRefs(files));
|
||||
if (ctx!.isSupplierAccount) {
|
||||
if (!ctx!.supplierCode) {
|
||||
return res.status(403).json({
|
||||
@@ -456,6 +473,8 @@ router.post('/purchase/quality-reports', authMiddleware, async (req: AuthRequest
|
||||
: req.body?.file
|
||||
? [String(req.body.file)]
|
||||
: [];
|
||||
// T9:写库前校验报告文件 key 归属(跨分支 key ⇒ 403,不落库)
|
||||
await assertOwnedStoragePaths(ctx, 'quality-reports', uploadPathRefs(files));
|
||||
const data = await uploadQualityReport({
|
||||
purchaseCode,
|
||||
files,
|
||||
@@ -560,7 +579,7 @@ router.post('/purchase/direct-delivery-photo', authMiddleware, async (req: AuthR
|
||||
return res.json({
|
||||
success: true,
|
||||
path: data.path,
|
||||
photo_url: buildDirectDeliveryPhotoUrls(req, [data.path])[0] || '',
|
||||
photo_url: (await buildDirectDeliveryPhotoUrls(req, [data.path]))[0] || '',
|
||||
purchase_codes: data.purchase_codes,
|
||||
});
|
||||
} catch (error: any) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Router, Response } from 'express';
|
||||
import { authMiddleware, type AuthRequest } from '../../../middleware/auth';
|
||||
import { getEffectiveBranchCode, readOperatingBranchCode } from '../../../services/tenantScope';
|
||||
import { getWorkflowCtx, requireWorkflowPermission } from '../context';
|
||||
import { listSupplierSkuCandidates } from '../../../services/skuMappingService';
|
||||
|
||||
/** 报价单模块 workflow API */
|
||||
export function mountQuoteWorkflowRoutes(router: Router): void {
|
||||
@@ -180,23 +181,7 @@ router.get('/quote/sku-candidates', authMiddleware, async (req: AuthRequest, res
|
||||
if (!branchCode) return res.status(400).json({ error: 'branch_required', error_description: '请选择当前操作分公司' });
|
||||
const q = String(req.query?.q || '').trim();
|
||||
const limit = Math.min(Math.max(Number(req.query?.limit) || 20, 1), 50);
|
||||
const { pool } = await import('../../../db');
|
||||
const { runWithTenantDbContext } = await import('../../../services/tenantDbContext');
|
||||
const rows = await runWithTenantDbContext(branchCode, async () => {
|
||||
const params: unknown[] = [];
|
||||
let where = "(status IS NULL OR status = 1)";
|
||||
if (q) {
|
||||
params.push(`%${q}%`);
|
||||
where += ` AND (sku_name ILIKE $1 OR sku_code ILIKE $1)`;
|
||||
}
|
||||
params.push(limit);
|
||||
const res2 = await pool.query(
|
||||
`SELECT sku_code, COALESCE(NULLIF(TRIM(sku_name), ''), sku_code) AS sku_name, unit
|
||||
FROM skus WHERE ${where} ORDER BY sku_name ASC, sku_code ASC LIMIT $${params.length}`,
|
||||
params
|
||||
);
|
||||
return res2.rows;
|
||||
});
|
||||
const rows = await listSupplierSkuCandidates({ branchCode, q, limit });
|
||||
return res.json({ data: { rows, limit } });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Router, Response } from 'express';
|
||||
import { assertStorageKeyOwned } from '../services/storageObjectOwnership';
|
||||
import {
|
||||
learnAlias,
|
||||
parseImageOrder,
|
||||
@@ -118,6 +119,14 @@ router.post('/:name', authMiddleware, async (req: AuthRequest, res: Response) =>
|
||||
const storedPath = String(req.body?.path || '').trim();
|
||||
const imageBase64 = req.body?.image || req.body?.imageBase64;
|
||||
if (storedPath) {
|
||||
try {
|
||||
await assertStorageKeyOwned('invoices', storedPath, { branchCode });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 403).json({
|
||||
data: null,
|
||||
error: { message: error?.message || '对象不属于当前租户', code: 'forbidden' },
|
||||
});
|
||||
}
|
||||
const data = await scanInvoiceFromStoredPath(storedPath, branchCode);
|
||||
return res.json({ data, error: null });
|
||||
}
|
||||
|
||||
@@ -685,12 +685,12 @@ router.get('/purchase/orders', authMiddleware, async (req: AuthRequest, res: Res
|
||||
branch_code: row.branch_code || branchCode,
|
||||
}))
|
||||
);
|
||||
const data = withPhotoRule.map((row) => ({
|
||||
const data = await Promise.all(withPhotoRule.map(async (row) => ({
|
||||
...row,
|
||||
direct_delivery: row.direct_delivery === true || row.direct_delivery === 't',
|
||||
requires_photo_inspection: row.requires_photo_inspection !== false,
|
||||
direct_delivery_photo_urls: buildDirectDeliveryPhotoUrls(req, row.direct_delivery_photos),
|
||||
}));
|
||||
direct_delivery_photo_urls: await buildDirectDeliveryPhotoUrls(req, row.direct_delivery_photos),
|
||||
})));
|
||||
|
||||
return res.json({
|
||||
data,
|
||||
@@ -758,7 +758,7 @@ router.post('/purchase/direct-delivery-photo', authMiddleware, async (req: AuthR
|
||||
return res.json({
|
||||
success: true,
|
||||
path: data.path,
|
||||
photo_url: buildDirectDeliveryPhotoUrls(req, [data.path])[0] || '',
|
||||
photo_url: (await buildDirectDeliveryPhotoUrls(req, [data.path]))[0] || '',
|
||||
purchase_codes: data.purchase_codes,
|
||||
});
|
||||
} catch (error: any) {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { authMiddleware, AuthRequest } from '../../middleware/auth';
|
||||
import { pool } from '../../db';
|
||||
import { saveBase64Upload } from '../../services/storageUploadService';
|
||||
import { getStorageProvider } from '../../services/storageProvider';
|
||||
import { assertStorageKeyOwned } from '../../services/storageObjectOwnership';
|
||||
import { buildSignedStoragePath } from '../../services/storageSignedUrl';
|
||||
import { signedExistingPhotos } from '../../services/inspectionReviewService';
|
||||
import { submitInspectionCompliance } from '../../services/inspectionComplianceService';
|
||||
@@ -569,7 +570,15 @@ router.delete('/inspection/photo', authMiddleware, async (req: AuthRequest, res:
|
||||
|
||||
if (removed) {
|
||||
try {
|
||||
await getStorageProvider().deleteObject('inspection-photos', removed);
|
||||
// T9F-2:删除前校验归属;archive/* 保留期数据一律拒绝。
|
||||
if (removed === 'archive' || removed.startsWith('archive/')) {
|
||||
console.warn(`[mobile-inspection] 拒绝删除归档对象 ${removed}`);
|
||||
} else {
|
||||
await assertStorageKeyOwned('inspection-photos', removed, {
|
||||
branchCode: inspection.branch_code || null,
|
||||
});
|
||||
await getStorageProvider().deleteObject('inspection-photos', removed);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`[mobile-inspection] 删除存储照片失败 ${removed}:`, error);
|
||||
}
|
||||
|
||||
+30
-25
@@ -23,13 +23,15 @@ async function getRoleManagerContext(userId: string) {
|
||||
return { isSuperAdmin: set.has('super_admin') };
|
||||
}
|
||||
|
||||
async function assertRoleManager(userId: string) {
|
||||
await getRoleManagerContext(userId);
|
||||
}
|
||||
|
||||
function assertCanManageTargetRole(roleCode: string, isSuperAdmin: boolean) {
|
||||
if (SUPER_ADMIN_ONLY_ROLES.has(roleCode) && !isSuperAdmin) {
|
||||
throw Object.assign(new Error('仅超级管理员可查看或修改管理员角色权限'), {
|
||||
/**
|
||||
* SEC-4(2026-10-19):**全局**角色/角色权限的写操作仅 `super_admin`。
|
||||
* `role_permissions` / `role_definitions` 是全局表(无 branch_code),分公司 `admin`
|
||||
* 若能改就等于垂直提权到所有分公司。约定:在取连接/开事务**之前**拒绝(admin 403 且零写 SQL)。
|
||||
*/
|
||||
async function assertSuperAdmin(userId: string): Promise<void> {
|
||||
const { isSuperAdmin } = await getRoleManagerContext(userId);
|
||||
if (!isSuperAdmin) {
|
||||
throw Object.assign(new Error('仅超级管理员可管理角色与角色权限'), {
|
||||
status: 403,
|
||||
code: 'forbidden',
|
||||
});
|
||||
@@ -89,7 +91,8 @@ router.get('/', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
router.post('/', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
if (!req.userId) return res.status(401).json({ error: 'invalid_token' });
|
||||
await assertRoleManager(req.userId);
|
||||
// SEC-4:全局角色定义仅超级管理员可创建(admin 403)
|
||||
await assertSuperAdmin(req.userId);
|
||||
const roleCodeRaw = req.body?.role_code ?? req.body?.code;
|
||||
const roleCode =
|
||||
roleCodeRaw === undefined || roleCodeRaw === null || String(roleCodeRaw).trim() === ''
|
||||
@@ -107,23 +110,25 @@ router.post('/', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
});
|
||||
|
||||
router.put('/:roleCode/permissions', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
if (!req.userId) return res.status(401).json({ error: 'invalid_token' });
|
||||
/**
|
||||
* SEC-4:仅超级管理员可改全局角色权限;**必须在取连接/BEGIN 之前拒绝**,
|
||||
* 保证 admin 403 时既无 DELETE/INSERT 写 SQL,也不占用连接/事务。
|
||||
*/
|
||||
try {
|
||||
await assertSuperAdmin(req.userId);
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 403).json({
|
||||
error: error?.code || 'forbidden',
|
||||
error_description: error?.message || '仅超级管理员可修改角色权限',
|
||||
});
|
||||
}
|
||||
const roleCode = String(req.params.roleCode || '').trim();
|
||||
if (!roleCode) {
|
||||
return res.status(400).json({ error: 'invalid_request', error_description: '角色编码不能为空' });
|
||||
}
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
if (!req.userId) return res.status(401).json({ error: 'invalid_token' });
|
||||
const { isSuperAdmin } = await getRoleManagerContext(req.userId);
|
||||
const roleCode = String(req.params.roleCode || '').trim();
|
||||
if (!roleCode) {
|
||||
return res.status(400).json({ error: 'invalid_request', error_description: '角色编码不能为空' });
|
||||
}
|
||||
try {
|
||||
assertCanManageTargetRole(roleCode, isSuperAdmin);
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 403).json({
|
||||
error: error?.code || 'forbidden',
|
||||
error_description: error?.message || '无权修改该角色权限',
|
||||
});
|
||||
}
|
||||
|
||||
const permissionIds = Array.from(
|
||||
new Set(
|
||||
(Array.isArray(req.body?.permission_ids) ? req.body.permission_ids : [])
|
||||
@@ -165,9 +170,9 @@ router.put('/:roleCode/permissions', authMiddleware, async (req: AuthRequest, re
|
||||
router.delete('/:roleCode', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
if (!req.userId) return res.status(401).json({ error: 'invalid_token' });
|
||||
const { isSuperAdmin } = await getRoleManagerContext(req.userId);
|
||||
// SEC-4:全局角色定义仅超级管理员可删除(admin 403,且不触碰任何写 SQL)
|
||||
await assertSuperAdmin(req.userId);
|
||||
const roleCode = String(req.params.roleCode || '').trim();
|
||||
assertCanManageTargetRole(roleCode, isSuperAdmin);
|
||||
await deleteRoleDefinition(roleCode);
|
||||
return res.json({ success: true });
|
||||
} catch (error: any) {
|
||||
|
||||
@@ -1,22 +1,94 @@
|
||||
import { Router, Response } from 'express';
|
||||
import multer from 'multer';
|
||||
import { authMiddleware, AuthRequest } from '../middleware/auth';
|
||||
import { buildSignedStoragePath, verifyStorageSignature } from '../services/storageSignedUrl';
|
||||
import { verifyStorageSignature } from '../services/storageSignedUrl';
|
||||
import { buildSignedStoragePathForCtx, tryBuildSignedStoragePathForCtx } from '../services/storageObjectOwnership';
|
||||
import {
|
||||
assertBucketUploadAllowed,
|
||||
assertSafeBucketName,
|
||||
BUCKET_READ_PERMISSIONS,
|
||||
BUCKET_UPLOAD_PERMISSIONS,
|
||||
isWeighApkPublicPath,
|
||||
PUBLIC_READ_STORAGE_BUCKETS,
|
||||
randomizeStorageFileName,
|
||||
safeStorageFileName,
|
||||
validateStorageBucket,
|
||||
WEIGH_APK_BUCKET,
|
||||
} from '../services/storageBucketConfig';
|
||||
import { createHash } from 'crypto';
|
||||
import { loadTenantContext } from '../services/tenantScope';
|
||||
import { assertStorageKeyOwned, canAccessStorageKey } from '../services/storageObjectOwnership';
|
||||
import { getStorageProvider } from '../services/storageProvider';
|
||||
import { loadStorageThumbnail, parseThumbWidth } from '../services/storageThumbnail';
|
||||
|
||||
|
||||
const ADMIN_ROLES = new Set(['admin', 'super_admin']);
|
||||
|
||||
/**
|
||||
* SEC-5/7(2026-10-19 T9):桶级授权。
|
||||
* - super_admin/admin:全桶;
|
||||
* - 其它账号:必须命中桶的权限码(空数组=仅要求登录);weigh-apk 仅 admin/super_admin;
|
||||
* - 私有桶还要求租户上下文(有 branchCode),避免无租户的短借连接铸签名 URL。
|
||||
* 返回 ctx(鉴权通过)或 null(已写 403/401)。
|
||||
*/
|
||||
async function authorizeBucket(
|
||||
req: AuthRequest,
|
||||
res: Response,
|
||||
bucket: string,
|
||||
opts: { read: boolean; objectPath?: string }
|
||||
) {
|
||||
const ctx = await loadTenantContext(req.userId);
|
||||
if (!ctx) {
|
||||
res.status(401).json({ error: 'unauthorized', error_description: '请先登录' });
|
||||
return null;
|
||||
}
|
||||
const isAdmin = Boolean(ctx.isSuperAdmin) || ctx.roles?.some((role) => ADMIN_ROLES.has(role));
|
||||
if (isAdmin) return ctx;
|
||||
if (bucket === WEIGH_APK_BUCKET) {
|
||||
res.status(403).json({ error: 'forbidden', error_description: '仅管理员可操作称端安装包' });
|
||||
return null;
|
||||
}
|
||||
const map = opts.read ? BUCKET_READ_PERMISSIONS : BUCKET_UPLOAD_PERMISSIONS;
|
||||
const required = map[bucket] ?? [];
|
||||
// SEC-7 回归修复:小程序「成本录入」(purchaser/delivery + mp_purchaser_free_cost)
|
||||
// 上传凭证/发票走 invoices 桶 free-cost* 前缀;其余 invoices 上传仍要财务码。
|
||||
const freeCostPrefix = /^free-cost(-invoice)?\//.test(String(opts.objectPath || ''));
|
||||
const requiredWithFreeCost =
|
||||
bucket === 'invoices' && freeCostPrefix ? [...required, 'mp_purchaser_free_cost'] : required;
|
||||
const allowed =
|
||||
requiredWithFreeCost.length === 0 ||
|
||||
requiredWithFreeCost.some((perm) => ctx.permissions?.includes(perm));
|
||||
if (!allowed) {
|
||||
res.status(403).json({ error: 'forbidden', error_description: `无权操作存储桶 ${bucket}` });
|
||||
return null;
|
||||
}
|
||||
// 私有桶要求租户上下文(签名 URL 不能脱离租户签发)
|
||||
const isPublic = PUBLIC_READ_STORAGE_BUCKETS.has(bucket);
|
||||
if (!isPublic && !ctx.branchCode) {
|
||||
res.status(403).json({ error: 'forbidden', error_description: '缺少租户上下文,拒绝签发/操作私有文件' });
|
||||
return null;
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* SEC-5:对象归属统一走 `assertStorageKeyOwned`(前缀/旧 key 反查/无 branchCode 均 fail-closed)。
|
||||
* 本函数保留为路由内的布尔包装。
|
||||
*/
|
||||
export async function canAccessPrivateObject(
|
||||
ctx: { isSuperAdmin?: boolean; branchCode?: string | null },
|
||||
bucket: string,
|
||||
safeName: string
|
||||
): Promise<boolean> {
|
||||
return canAccessStorageKey(bucket, safeName, ctx);
|
||||
}
|
||||
|
||||
const router = Router();
|
||||
const upload = multer({
|
||||
storage: multer.memoryStorage(),
|
||||
limits: { fileSize: 10 * 1024 * 1024 },
|
||||
// SEC-7:与 BUCKET_UPLOAD_RULES['weigh-apk'].maxBytes 对齐(80MB),否则合法 APK 会先被 multer 拦成 413/500
|
||||
limits: { fileSize: 80 * 1024 * 1024 },
|
||||
});
|
||||
|
||||
router.post('/:bucket/upload', authMiddleware, upload.single('file'), async (req: AuthRequest, res: Response) => {
|
||||
@@ -24,6 +96,11 @@ router.post('/:bucket/upload', authMiddleware, upload.single('file'), async (req
|
||||
const bucket = req.params.bucket;
|
||||
validateStorageBucket(bucket);
|
||||
const filePath = req.body?.path || req.query.path;
|
||||
const ctx = await authorizeBucket(req, res, bucket, {
|
||||
read: false,
|
||||
objectPath: typeof filePath === 'string' ? filePath : undefined,
|
||||
});
|
||||
if (!ctx) return;
|
||||
if (!filePath || typeof filePath !== 'string') {
|
||||
return res.status(400).json({ error: 'Missing file path' });
|
||||
}
|
||||
@@ -42,6 +119,26 @@ router.post('/:bucket/upload', authMiddleware, upload.single('file'), async (req
|
||||
}
|
||||
|
||||
const originalBase = String(filePath).split('/').pop() || filePath;
|
||||
// SEC-7:APK/JSON 完整性校验(APK 必须是 ZIP 魔数;JSON 必须可解析);可选 x-content-sha256 必须匹配
|
||||
if (bucket === WEIGH_APK_BUCKET) {
|
||||
const ext = originalBase.toLowerCase().split('.').pop();
|
||||
if (ext === 'apk') {
|
||||
const isZip = buffer.length > 4 && buffer[0] === 0x50 && buffer[1] === 0x4b && buffer[2] === 0x03 && buffer[3] === 0x04;
|
||||
if (!isZip) return res.status(400).json({ error: 'invalid_apk', error_description: 'APK 必须是有效 ZIP 包(PK\x03\x04)' });
|
||||
} else if (ext === 'json') {
|
||||
try {
|
||||
const parsed = JSON.parse(buffer.toString('utf8'));
|
||||
if (!parsed || typeof parsed !== 'object') throw new Error('not object');
|
||||
} catch {
|
||||
return res.status(400).json({ error: 'invalid_manifest', error_description: 'manifest 必须是合法 JSON 对象' });
|
||||
}
|
||||
}
|
||||
const expectedHash = String(req.get('x-content-sha256') || '').trim().toLowerCase();
|
||||
const actualHash = createHash('sha256').update(buffer).digest('hex');
|
||||
if (expectedHash && expectedHash !== actualHash) {
|
||||
return res.status(400).json({ error: 'hash_mismatch', error_description: '文件哈希与 x-content-sha256 不一致' });
|
||||
}
|
||||
}
|
||||
try {
|
||||
assertBucketUploadAllowed(bucket, originalBase, contentType, buffer.length);
|
||||
} catch (e: any) {
|
||||
@@ -52,15 +149,24 @@ router.post('/:bucket/upload', authMiddleware, upload.single('file'), async (req
|
||||
const folderHint = String(filePath).includes('/')
|
||||
? String(filePath).replace(/\\/g, '/')
|
||||
: originalBase;
|
||||
const safeName = randomizeStorageFileName(folderHint);
|
||||
const randomized = randomizeStorageFileName(folderHint);
|
||||
// SEC-5:私有桶新对象加 `<branch>/` 前缀(公开桶/weigh-apk 保持原路径)
|
||||
const safeName =
|
||||
!PUBLIC_READ_STORAGE_BUCKETS.has(bucket) && bucket !== WEIGH_APK_BUCKET && ctx.branchCode
|
||||
? `${ctx.branchCode}/${randomized}`
|
||||
: randomized;
|
||||
|
||||
await storage.putObject(bucket, safeName, buffer, contentType);
|
||||
|
||||
if (PUBLIC_READ_STORAGE_BUCKETS.has(bucket)) {
|
||||
const redirectUrl = await storage.getReadRedirectUrl(bucket, safeName);
|
||||
return res.json({ path: safeName, publicUrl: redirectUrl || undefined });
|
||||
const sha256 = createHash('sha256').update(buffer).digest('hex');
|
||||
return res.json({ path: safeName, publicUrl: redirectUrl || undefined, ...(bucket === WEIGH_APK_BUCKET ? { sha256 } : {}) });
|
||||
}
|
||||
return res.json({ path: safeName, signedUrl: buildSignedStoragePath(bucket, safeName) });
|
||||
// T9F-5:上传返回的 key 若因缺 branchCode 变成无前缀旧形状,mint 会 fail-closed;
|
||||
// 此处用宽容版,仍返回 path,只是不返回不可证明归属的 signedUrl。
|
||||
const signedUrl = tryBuildSignedStoragePathForCtx(ctx, bucket, safeName);
|
||||
return res.json({ path: safeName, ...(signedUrl ? { signedUrl } : {}) });
|
||||
} catch (error: any) {
|
||||
console.error('Upload error:', error);
|
||||
return res.status(500).json({ error: error?.message || 'Upload failed' });
|
||||
@@ -77,6 +183,10 @@ async function servePublicStorageObject(
|
||||
validateStorageBucket(bucket);
|
||||
const safeName = safeStorageFileName(filenameRaw);
|
||||
const isPublic = PUBLIC_READ_STORAGE_BUCKETS.has(bucket);
|
||||
// SEC-7:weigh-apk 只公开 manifest.json 与 releases/*.apk,其余路径必须走签名
|
||||
if (bucket === WEIGH_APK_BUCKET && isPublic && !isWeighApkPublicPath(safeName)) {
|
||||
return res.status(403).json({ error: 'forbidden', error_description: '该文件不公开,请使用签名链接' });
|
||||
}
|
||||
if (!isPublic) {
|
||||
if (!verifyStorageSignature(bucket, safeName, req.query.exp, req.query.sig)) {
|
||||
return res.status(403).json({ error: 'invalid_signature', error_description: '链接无效或已过期' });
|
||||
@@ -144,11 +254,26 @@ router.get('/:bucket/public/:filename', async (req, res: Response) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/:bucket/public-url/:filename', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
router.get('/:bucket/public-url/*', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const bucket = req.params.bucket;
|
||||
validateStorageBucket(bucket);
|
||||
const safeName = safeStorageFileName(req.params.filename);
|
||||
// 支持多段 key(branch/folder/file);单段旧路径同样匹配通配符
|
||||
const rawName = String((req.params as Record<string, unknown>)['0'] || '');
|
||||
const safeName = safeStorageFileName(rawName);
|
||||
const ctx = await authorizeBucket(req, res, bucket, { read: true });
|
||||
if (!ctx) return;
|
||||
// avatars 无业务租户归属(个人头像),仅要求登录;公开桶不校验归属
|
||||
if (!PUBLIC_READ_STORAGE_BUCKETS.has(bucket) && bucket !== 'avatars') {
|
||||
try {
|
||||
await assertStorageKeyOwned(bucket, safeName, ctx);
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 403).json({
|
||||
error: 'forbidden',
|
||||
error_description: error?.message || '对象不属于当前租户',
|
||||
});
|
||||
}
|
||||
}
|
||||
const storage = getStorageProvider();
|
||||
|
||||
if (PUBLIC_READ_STORAGE_BUCKETS.has(bucket)) {
|
||||
@@ -158,9 +283,11 @@ router.get('/:bucket/public-url/:filename', authMiddleware, async (req: AuthRequ
|
||||
}
|
||||
}
|
||||
|
||||
// T9F-5:私有桶已在上面做过异步归属反查(assertStorageKeyOwned,含旧 key 的 DB 反查),
|
||||
// 这里把“已反查”显式告诉同步 mint;avatars 无租户归属语义(历史行为,仅要求登录)。
|
||||
const relativePath = PUBLIC_READ_STORAGE_BUCKETS.has(bucket)
|
||||
? `/api/storage/${bucket}/public/${encodeURIComponent(safeName)}`
|
||||
: buildSignedStoragePath(bucket, safeName);
|
||||
: buildSignedStoragePathForCtx(ctx, bucket, safeName, { legacyOwnershipVerified: true });
|
||||
const publicUrl = `${req.protocol}://${req.get('host')}${relativePath}`;
|
||||
return res.json({ publicUrl });
|
||||
} catch (error: any) {
|
||||
@@ -168,4 +295,12 @@ router.get('/:bucket/public-url/:filename', authMiddleware, async (req: AuthRequ
|
||||
}
|
||||
});
|
||||
|
||||
// SEC-8:multer 错误映射(APK 超限 ⇒ 413,而不是落到全局 500)
|
||||
router.use((err: any, _req: any, res: Response, next: (e?: unknown) => void) => {
|
||||
if (err?.code === 'LIMIT_FILE_SIZE') {
|
||||
return res.status(413).json({ error: 'payload_too_large', error_description: '文件超过大小上限' });
|
||||
}
|
||||
return next(err);
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
||||
@@ -81,6 +81,16 @@ const ALLOWED_TABLES = new Set([
|
||||
const DENY_WRITE_TABLES = new Set([
|
||||
'user_roles',
|
||||
'permissions',
|
||||
/**
|
||||
* 全局授权表(SEC-4,2026-10-19):`role_permissions` / `role_definitions` 是 **public**
|
||||
* 平台表(无 branch_code)。旧实现只把角色写端点收归 super_admin,却仍允许 admin 经通用网关
|
||||
* `/api/data/query` 对这两张表 insert/update/delete(实测 HTTP 200 + 真实写 SQL),
|
||||
* 等于绕过 `/api/roles` 的 super_admin 限制,甚至可给 super_admin 写权限。
|
||||
* ⇒ 网关一律 deny(super_admin 也必须走 `/api/roles`);读取不受影响(前端 useAuth 只 select)。
|
||||
* 放在这里(而不是 ADMIN_WRITE_TABLES)才能同时拦住超管绕过审计的裸写。
|
||||
*/
|
||||
'role_permissions',
|
||||
'role_definitions',
|
||||
'profiles',
|
||||
'supplier_users',
|
||||
'purchaser_users',
|
||||
@@ -125,8 +135,8 @@ const DENY_WRITE_TABLES = new Set([
|
||||
*/
|
||||
const DENY_DELETE_TABLES = new Set(['customers', 'order_items']);
|
||||
|
||||
/** 仅管理员(super_admin/admin)可写 */
|
||||
const ADMIN_WRITE_TABLES = new Set(['role_permissions', 'branches', 'system_configs']);
|
||||
/** 仅管理员(super_admin/admin)可写;`role_permissions` 已移入 DENY_WRITE_TABLES(SEC-4 收口) */
|
||||
const ADMIN_WRITE_TABLES = new Set(['branches', 'system_configs']);
|
||||
|
||||
/**
|
||||
* 非内部员工(finance/warehouse/delivery/supplier 等受限角色)写表所需权限码。
|
||||
@@ -360,6 +370,65 @@ export function assertSensitiveSelectColumns(spec: QuerySpec) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* T9F(2026-10-19 红队):通用数据网关不得写“存储对象 key”列。
|
||||
*
|
||||
* 这些列的值会参与后续 storage 对象的归属校验;如果允许客户端经 /api/data 任意
|
||||
* 写入,就能把 `archive/<other-branch>/...` 之类的 key 毒化进业务行,再借
|
||||
* “旧 key 反查业务表”的归属逻辑洗白,进而跨租户读取/删除对象。
|
||||
* 因此 insert/update 一律拒绝(super_admin 也必须走业务接口),delete 不受影响。
|
||||
*/
|
||||
const SENSITIVE_STORAGE_WRITE_COLUMNS = new Set([
|
||||
'inspection_photos',
|
||||
'photo_url',
|
||||
'outbound_photos',
|
||||
'loading_photos',
|
||||
'direct_delivery_photos',
|
||||
'inbound_photo',
|
||||
'processing_inspection_photos',
|
||||
'invoice_url',
|
||||
'voucher_url',
|
||||
'voucher_urls',
|
||||
'storage_path',
|
||||
'file_paths',
|
||||
'quality_report_files',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 递归查找敏感存储字段(含 JSON/JSONB 列里的嵌套对象与数组项)。
|
||||
* 只认列名本身,不按值猜;命中即拒绝,避免 `{ processing_details: { inspection_photos: [...] } }`
|
||||
* 这类“外层列名合法、内层 key 毒化”的绕过。
|
||||
*/
|
||||
function findSensitiveStorageField(value: unknown, depth = 0): string | null {
|
||||
if (!value || typeof value !== 'object' || depth > 12) return null;
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
const hit = findSensitiveStorageField(item, depth + 1);
|
||||
if (hit) return hit;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
|
||||
// SQL 列名在 queryExecutor 里是**不加引号**拼接的,PostgreSQL 会把 `Inspection_Photos`
|
||||
// 折叠成 `inspection_photos`;因此必须大小写归一后再比对,否则大小写变体可绕过。
|
||||
const normalized = key.trim().toLowerCase();
|
||||
if (SENSITIVE_STORAGE_WRITE_COLUMNS.has(normalized)) return normalized;
|
||||
const hit = findSensitiveStorageField(child, depth + 1);
|
||||
if (hit) return hit;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function assertNoSensitiveStorageWrites(spec: QuerySpec) {
|
||||
if (spec.action !== 'insert' && spec.action !== 'update') return;
|
||||
const payload = spec.action === 'insert' ? spec.insertData : spec.updateData;
|
||||
if (!payload || typeof payload !== 'object') return;
|
||||
const column = findSensitiveStorageField(payload);
|
||||
if (column) {
|
||||
throw forbidden(`字段 ${column} 不允许通过数据接口写入,请使用专用接口`);
|
||||
}
|
||||
}
|
||||
|
||||
/** 校验通用数据接口的表访问权限,违规时抛错 */
|
||||
export function assertTableAccess(spec: QuerySpec, ctx: TenantContext | null) {
|
||||
if (!ALLOWED_TABLES.has(spec.table)) {
|
||||
@@ -370,6 +439,7 @@ export function assertTableAccess(spec: QuerySpec, ctx: TenantContext | null) {
|
||||
throw forbidden('请先登录');
|
||||
}
|
||||
|
||||
assertNoSensitiveStorageWrites(spec);
|
||||
assertSensitiveSelectColumns(spec);
|
||||
|
||||
if (spec.action === 'select') {
|
||||
|
||||
@@ -52,28 +52,39 @@ export async function resolveOperatorProfile(operatorId: string | null | undefin
|
||||
|
||||
/** 与 migrations/20260814 后列宽对齐;防未迁移环境再次炸事务 */
|
||||
const OPERATOR_ROLE_MAX = 100;
|
||||
const SHORT_AUDIT_FIELD_MAX = 50;
|
||||
|
||||
/**
|
||||
* BUG(2026-10-19):`operation_logs` 的 operation_type/target_table/target_id/
|
||||
* ip_address/branch_code/action_category 都是 varchar(50),此前只裁剪了
|
||||
* operator_role(100)。当 target_id 取到较长的路径/对象 key(例如存储对象名)时,
|
||||
* 审计 INSERT 会因 `22001 value too long` 失败 —— 请求本身不报错,但审计丢失。
|
||||
* 这里保留 scrubAuditText 统一清洗,再按真实列宽硬裁(它超长时会追加省略号,
|
||||
* 得到 max+1,仍会 22001);完整值仍在 new_value JSON(已脱敏)里可追溯。
|
||||
*/
|
||||
function clipAuditText(text: string | null, max: number = SHORT_AUDIT_FIELD_MAX): string | null {
|
||||
return text ? text.slice(0, max) : null;
|
||||
}
|
||||
|
||||
async function insertAuditRow(input: AuditLogInput) {
|
||||
const roleRaw = input.operatorRole != null ? String(input.operatorRole).trim() : '';
|
||||
const operatorRole = roleRaw ? roleRaw.slice(0, OPERATOR_ROLE_MAX) : null;
|
||||
await pool.query(
|
||||
`INSERT INTO operation_logs (operator_id, operator_name, operator_role, operation_type, target_table, target_id, old_value, new_value, ip_address, trace_id, branch_code, action_category)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,
|
||||
[
|
||||
input.operatorId || null,
|
||||
// 这些短字段不走结构化脱敏,但同样做一次内容清洗(防"密钥写进 URL/表名"这类夹带)
|
||||
scrubAuditText(input.operatorName),
|
||||
scrubAuditText(operatorRole),
|
||||
scrubAuditText(input.operationType) || 'unknown',
|
||||
scrubAuditText(input.targetTable),
|
||||
scrubAuditText(input.targetId),
|
||||
clipAuditText(scrubAuditText(input.operatorName), 100),
|
||||
clipAuditText(scrubAuditText(input.operatorRole), OPERATOR_ROLE_MAX),
|
||||
clipAuditText(scrubAuditText(input.operationType)) || 'unknown',
|
||||
clipAuditText(scrubAuditText(input.targetTable)),
|
||||
clipAuditText(scrubAuditText(input.targetId)),
|
||||
// 脱敏唯一收口(幂等):即便某个调用方忘了脱敏,也不会把密钥写进审计
|
||||
safeAuditJson(input.oldValue, 'operation_logs.old_value'),
|
||||
safeAuditJson(input.newValue, 'operation_logs.new_value'),
|
||||
input.ipAddress || null,
|
||||
input.traceId || null,
|
||||
input.branchCode || null,
|
||||
input.actionCategory || null,
|
||||
clipAuditText(scrubAuditText(input.ipAddress)),
|
||||
clipAuditText(scrubAuditText(input.traceId), 100),
|
||||
clipAuditText(scrubAuditText(input.branchCode)),
|
||||
clipAuditText(scrubAuditText(input.actionCategory)),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -232,8 +232,9 @@ export async function applyBidCostAfterInbound(input: {
|
||||
const db = dbOf(input.client);
|
||||
if (orderCode) {
|
||||
await db.query(
|
||||
// DATA-3(2026-10-19):supplier_preparations 无 updated_at 列(只有 prepare_time)⇒ 不写。
|
||||
`UPDATE supplier_preparations
|
||||
SET purchase_price = $1, updated_at = NOW()
|
||||
SET purchase_price = $1
|
||||
WHERE order_code = $2
|
||||
AND sku_code = $3
|
||||
AND supplier_code = $4
|
||||
|
||||
@@ -42,6 +42,23 @@ export async function deleteCustomer(customerCode: string, ctx?: TenantContext |
|
||||
throw Object.assign(new Error('该客户存在历史订单,无法删除'), { status: 400 });
|
||||
}
|
||||
|
||||
/**
|
||||
* 报价单引用也不能硬删(2026-10-18 反向核对):
|
||||
* 旧实现只拦订单,解绑/改绑时 `deleteCustomer` 会把 `customer_quote_sheet_customers`、
|
||||
* `customer_quote_versions` 一起级联删掉(报价单本体还在,却失去客户归属、版本历史不可恢复)。
|
||||
* 有引用 ⇒ 返回 400,让调用方(绑定解绑)退化为「停用 status=40」。
|
||||
*/
|
||||
const quoteRefCount = await pool.query<{ cnt: number }>(
|
||||
`SELECT (
|
||||
(SELECT COUNT(*)::int FROM customer_quote_sheet_customers WHERE customer_code = $1) +
|
||||
(SELECT COUNT(*)::int FROM customer_quote_versions WHERE customer_code = $1)
|
||||
)::int AS cnt`,
|
||||
[code]
|
||||
);
|
||||
if ((quoteRefCount.rows[0]?.cnt || 0) > 0) {
|
||||
throw Object.assign(new Error('该客户存在报价单引用,无法删除(可停用)'), { status: 400 });
|
||||
}
|
||||
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { pool } from '../db';
|
||||
import { buildSignedStoragePath } from './storageSignedUrl';
|
||||
import { assertOwnedStoragePaths, buildSignedStoragePathForCtx } from './storageObjectOwnership';
|
||||
import type { TenantContext } from './tenantScope';
|
||||
import {
|
||||
assertAllocationsWithinInvoiceAmount,
|
||||
@@ -82,6 +82,8 @@ export async function insertCustomerInvoice(
|
||||
_ctx: TenantContext
|
||||
) {
|
||||
const row = normalizeCustomerInvoiceWrite(input);
|
||||
// T9:INSERT invoice_url 前校验归属(跨分支 key ⇒ 403,不落库)
|
||||
await assertOwnedStoragePaths(_ctx, 'invoices', [row.invoice_url]);
|
||||
const allocations = normalizeInvoiceAllocations(input.allocations);
|
||||
assertAllocationsWithinInvoiceAmount(allocations, row.amount);
|
||||
await assertInvoiceAllocationsOwned({
|
||||
@@ -171,7 +173,7 @@ export function mapCustomerInvoiceListRow(row: {
|
||||
ocr_data?: unknown;
|
||||
verify_status?: unknown;
|
||||
created_at?: unknown;
|
||||
}) {
|
||||
}, branchCode?: string | null) {
|
||||
const invoiceUrl = String(row.invoice_url || '').trim();
|
||||
return {
|
||||
id: String(row.id || ''),
|
||||
@@ -186,7 +188,17 @@ export function mapCustomerInvoiceListRow(row: {
|
||||
ocr_data: dropOcrItems(row.ocr_data),
|
||||
verify_status: row.verify_status == null ? null : Number(row.verify_status),
|
||||
created_at: row.created_at ? String(row.created_at) : null,
|
||||
signed_url: invoiceUrl ? buildSignedStoragePath('invoices', invoiceUrl) : null,
|
||||
signed_url: (() => {
|
||||
if (!invoiceUrl) return null;
|
||||
// T9 SEC-5:list 只为自己的 branch 签 URL(key 带前缀且不匹配 ⇒ 不签)
|
||||
const m = /^(BR[0-9A-Za-z_-]{1,20})\//.exec(invoiceUrl);
|
||||
if (m && branchCode && m[1] !== branchCode) return null;
|
||||
try {
|
||||
return buildSignedStoragePathForCtx({ branchCode: branchCode ?? null }, 'invoices', invoiceUrl);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -253,6 +265,6 @@ export async function listCustomerInvoices(input: {
|
||||
params
|
||||
);
|
||||
const hasMore = result.rows.length > query.limit;
|
||||
const rows = (hasMore ? result.rows.slice(0, query.limit) : result.rows).map(mapCustomerInvoiceListRow);
|
||||
const rows = (hasMore ? result.rows.slice(0, query.limit) : result.rows).map((row) => mapCustomerInvoiceListRow(row, query.branchCode));
|
||||
return { rows, has_more: hasMore, offset: query.offset, limit: query.limit };
|
||||
}
|
||||
|
||||
@@ -423,7 +423,7 @@ function pushOrderSettleRangePredicate(
|
||||
* 结算单是否关联到区间内订单(列表过滤用)。
|
||||
* dateFromParam / dateToParam 为 params 中日历日起止下标(含首尾)。
|
||||
*/
|
||||
function statementLinkedOrdersInDateRangeSql(
|
||||
export function statementLinkedOrdersInDateRangeSql(
|
||||
statementAlias: string,
|
||||
statementType: 'customer' | 'supplier',
|
||||
field: SettlementDateField,
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { pool } from '../db';
|
||||
import type { TenantContext } from './tenantScope';
|
||||
import { allocateCostPool, FIXED_COST_ALLOCATION_METHOD } from './costAllocationService';
|
||||
import { buildSignedStoragePath } from './storageSignedUrl';
|
||||
import {
|
||||
assertOwnedStoragePaths,
|
||||
buildSignedStoragePathForCtx,
|
||||
type StorageOwnerCtx,
|
||||
} from './storageObjectOwnership';
|
||||
import { safeStorageFileName } from './storageBucketConfig';
|
||||
import { withDistributedLock } from './distributedLock';
|
||||
import { runWithTenantDbContext } from './tenantDbContext';
|
||||
@@ -63,7 +67,7 @@ export function toFixedCostVoucherDisplayUrl(value: string): string {
|
||||
if (!text) return text;
|
||||
if (/^(https?:)?\/\//i.test(text) || text.startsWith('/')) return text;
|
||||
try {
|
||||
return buildSignedStoragePath('invoices', safeStorageFileName(text));
|
||||
return buildSignedStoragePathForCtx(undefined, 'invoices', safeStorageFileName(text));
|
||||
} catch {
|
||||
return text;
|
||||
}
|
||||
@@ -114,6 +118,8 @@ export async function createFixedCost(input: {
|
||||
allocate?: boolean;
|
||||
/** 非分摊入账时覆盖 cost_details.created_at(沿用上月用) */
|
||||
ledgerCreatedAt?: string | null;
|
||||
/** 写入口归属校验用租户上下文(route 传入;缺省按 branchCode fail-closed) */
|
||||
ownerCtx?: StorageOwnerCtx | null;
|
||||
}) {
|
||||
const cycleCode = String(input.cycleCode || '').trim();
|
||||
if (!cycleCode) throw Object.assign(new Error('请填写核算周期'), { status: 400 });
|
||||
@@ -124,6 +130,13 @@ export async function createFixedCost(input: {
|
||||
const ledgerType = COST_TYPE_TO_LEDGER[costType] || 'fixed_overhead';
|
||||
const wantAllocate = input.allocate !== false;
|
||||
const ledgerAt = input.ledgerCreatedAt ? String(input.ledgerCreatedAt).trim() : '';
|
||||
const voucherPaths = normalizeFixedCostVoucherPaths(input.voucherUrls);
|
||||
// T9:写库前校验 voucher_urls 归属(跨分支 key ⇒ 403,不落库)
|
||||
await assertOwnedStoragePaths(
|
||||
input.ownerCtx ?? { branchCode: input.branchCode || null },
|
||||
'invoices',
|
||||
voucherPaths
|
||||
);
|
||||
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
@@ -140,7 +153,7 @@ export async function createFixedCost(input: {
|
||||
Math.max(0, Number(input.budgetAmount) || 0),
|
||||
actual,
|
||||
method,
|
||||
input.voucherUrls?.length ? input.voucherUrls : null,
|
||||
voucherPaths.length ? voucherPaths : null,
|
||||
input.inputterId || null,
|
||||
input.branchCode || null,
|
||||
input.remark || null,
|
||||
@@ -608,6 +621,8 @@ export async function updateFixedCost(input: {
|
||||
}
|
||||
|
||||
export async function updateFixedCostVouchers(id: string, urls: string[], ctx?: TenantContext | null) {
|
||||
// T9:UPDATE 前校验归属(跨分支 key ⇒ 403,原值保持不变)
|
||||
await assertOwnedStoragePaths(ctx ?? null, 'invoices', urls);
|
||||
const params: unknown[] = [urls, id];
|
||||
const branchSql = branchFilter(ctx, 'fixed_costs', params);
|
||||
const result = await pool.query(
|
||||
|
||||
@@ -2,8 +2,8 @@ import { pool } from '../db';
|
||||
import type { TenantContext } from './tenantScope';
|
||||
import { scanInvoice, type InvoiceOcrResult } from './invoiceOcrService';
|
||||
import { getStorageProvider } from './storageProvider';
|
||||
import { buildSignedStoragePath } from './storageSignedUrl';
|
||||
import { safeStorageFileName } from './storageBucketConfig';
|
||||
import { assertOwnedStoragePaths, tryBuildSignedStoragePathForCtx } from './storageObjectOwnership';
|
||||
import { safeStorageFileName, stripStorageBranchPrefix } from './storageBucketConfig';
|
||||
import {
|
||||
FREE_COST_STATUS,
|
||||
labelForFreeSubtype,
|
||||
@@ -50,7 +50,8 @@ export function assertFreeCostInvoiceStoragePath(raw: string): string {
|
||||
} catch {
|
||||
throw Object.assign(new Error('发票路径无效'), { status: 400, code: 'invalid_request' });
|
||||
}
|
||||
if (!safe.startsWith(INVOICE_PREFIX)) {
|
||||
// SEC-5:允许新 key 的 `<branch>/` 前缀
|
||||
if (!stripStorageBranchPrefix(safe).startsWith(INVOICE_PREFIX)) {
|
||||
throw Object.assign(new Error('仅支持 free-cost-invoice 发票'), { status: 400, code: 'invalid_request' });
|
||||
}
|
||||
return safe;
|
||||
@@ -150,6 +151,12 @@ export async function saveFreeCostInvoice(input: {
|
||||
branchCode: string | null;
|
||||
}) {
|
||||
const invoicePath = assertFreeCostInvoiceStoragePath(input.invoicePath);
|
||||
// T9:写库前校验 storage_path 归属(跨分支 key ⇒ 403,不落库)
|
||||
await assertOwnedStoragePaths(
|
||||
input.ctx?.isSuperAdmin ? input.ctx : { branchCode: input.branchCode },
|
||||
'invoices',
|
||||
[invoicePath]
|
||||
);
|
||||
const ids = parseIdList(input.costDetailIds);
|
||||
if (ids.length > 1) {
|
||||
throw Object.assign(new Error('一张发票只能对应一条凭证记录'), {
|
||||
@@ -266,7 +273,7 @@ export async function decorateFreeCostRowsWithInvoices<T extends Record<string,
|
||||
const paths = hit?.paths || [];
|
||||
return {
|
||||
...row,
|
||||
invoice_urls: paths.map((path) => buildSignedStoragePath('invoices', path)),
|
||||
invoice_urls: paths.map((path) => tryBuildSignedStoragePathForCtx(undefined, 'invoices', path) ?? ''),
|
||||
invoice_match: hit
|
||||
? hit.match
|
||||
: { status: null, invoice_no: null, total_amount: null },
|
||||
|
||||
@@ -3,8 +3,8 @@ import type { TenantContext } from './tenantScope';
|
||||
import { callWithFile, callWithImage, hasRuntimeConfig } from './llmService';
|
||||
import { resolvePrompt } from './promptRegistryService';
|
||||
import { getStorageProvider } from './storageProvider';
|
||||
import { buildSignedStoragePath } from './storageSignedUrl';
|
||||
import { safeStorageFileName } from './storageBucketConfig';
|
||||
import { assertOwnedStoragePaths, tryBuildSignedStoragePathForCtx } from './storageObjectOwnership';
|
||||
import { safeStorageFileName, stripStorageBranchPrefix } from './storageBucketConfig';
|
||||
import {
|
||||
FREE_COST_STATUS,
|
||||
labelForFreeSubtype,
|
||||
@@ -87,7 +87,8 @@ export function assertFreeCostPaymentStoragePath(raw: string): string {
|
||||
} catch {
|
||||
throw Object.assign(new Error('付款凭证路径无效'), { status: 400, code: 'invalid_request' });
|
||||
}
|
||||
if (!safe.startsWith(PAYMENT_PREFIX)) {
|
||||
// SEC-5:允许新 key 的 `<branch>/` 前缀
|
||||
if (!stripStorageBranchPrefix(safe).startsWith(PAYMENT_PREFIX)) {
|
||||
throw Object.assign(new Error('仅支持 free-cost-payment 付款凭证'), {
|
||||
status: 400,
|
||||
code: 'invalid_request',
|
||||
@@ -220,7 +221,8 @@ export function payerNameMatches(payerName: unknown, applicantName: unknown): bo
|
||||
}
|
||||
|
||||
function costVoucherUrls(raw: unknown): string[] {
|
||||
return normalizeFreeCostVoucherPaths(raw).map((path) => buildSignedStoragePath('invoices', path));
|
||||
// T9F-5:无前缀旧 key 不再同步签发;未迁移时给空串,列表不 500。
|
||||
return normalizeFreeCostVoucherPaths(raw).map((path) => tryBuildSignedStoragePathForCtx(undefined, 'invoices', path) ?? '');
|
||||
}
|
||||
|
||||
export interface PaymentCandidate {
|
||||
@@ -341,6 +343,8 @@ export async function extractFreeCostPaymentVouchers(input: {
|
||||
throw Object.assign(new Error('请先选择要上传的付款凭证'), { status: 400, code: 'invalid_request' });
|
||||
}
|
||||
const branchCode = input.branchCode || input.ctx?.branchCode || null;
|
||||
// T9F-4:OCR 读取前先校验对象归属,不能只依赖 OCR 是否读到。
|
||||
await assertOwnedStoragePaths({ branchCode }, 'invoices', paths);
|
||||
const items = [];
|
||||
for (const path of paths) {
|
||||
const storagePath = assertFreeCostPaymentStoragePath(path);
|
||||
@@ -410,6 +414,12 @@ export async function saveFreeCostPaymentVouchers(input: {
|
||||
await client.query('BEGIN');
|
||||
for (const item of items) {
|
||||
const storagePath = assertFreeCostPaymentStoragePath(item.path);
|
||||
// T9:写库(同事务)前校验 storage_path 归属;跨分支 key ⇒ 403 + ROLLBACK,不新增行
|
||||
await assertOwnedStoragePaths(
|
||||
input.ctx?.isSuperAdmin ? input.ctx : { branchCode },
|
||||
'invoices',
|
||||
[storagePath]
|
||||
);
|
||||
const fileHash = item.file_hash == null ? null : String(item.file_hash).trim() || null;
|
||||
if (fileHash) {
|
||||
const dup = await client.query(
|
||||
@@ -513,7 +523,7 @@ function voucherDecor(row: Record<string, unknown>) {
|
||||
return {
|
||||
id: String(row.id),
|
||||
storage_path: String(row.storage_path || ''),
|
||||
url: buildSignedStoragePath('invoices', String(row.storage_path || '')),
|
||||
url: tryBuildSignedStoragePathForCtx(undefined, 'invoices', String(row.storage_path || '')) ?? '',
|
||||
amount: row.amount == null ? null : roundFreeCostMoney(row.amount),
|
||||
payer_name: row.payer_name == null ? null : String(row.payer_name),
|
||||
paid_at: toDateOnly(row.paid_at),
|
||||
|
||||
@@ -7,8 +7,12 @@ import {
|
||||
orderFinanceJoinSql,
|
||||
orderFinanceRangeCondSql,
|
||||
} from './marginQueryService';
|
||||
import { buildSignedStoragePath } from './storageSignedUrl';
|
||||
import { safeStorageFileName } from './storageBucketConfig';
|
||||
import {
|
||||
assertOwnedStoragePaths,
|
||||
tryBuildSignedStoragePathForCtx,
|
||||
type StorageOwnerCtx,
|
||||
} from './storageObjectOwnership';
|
||||
import { safeStorageFileName, stripStorageBranchPrefix } from './storageBucketConfig';
|
||||
import { getStorageProvider } from './storageProvider';
|
||||
import {
|
||||
buildFreeCostAuditSnapshot,
|
||||
@@ -171,7 +175,9 @@ export function assertFreeCostVoucherStoragePath(raw: string): string {
|
||||
} catch {
|
||||
throw Object.assign(new Error('凭证路径无效'), { status: 400, code: 'invalid_request' });
|
||||
}
|
||||
if (!safe.startsWith('free-cost/') || safe.startsWith('free-cost-invoice/')) {
|
||||
// SEC-5:允许新 key 的 `<branch>/` 前缀
|
||||
const withoutBranch = stripStorageBranchPrefix(safe);
|
||||
if (!withoutBranch.startsWith('free-cost/') || withoutBranch.startsWith('free-cost-invoice/')) {
|
||||
throw Object.assign(new Error('仅支持 free-cost 凭证'), { status: 400, code: 'invalid_request' });
|
||||
}
|
||||
return safe;
|
||||
@@ -187,7 +193,8 @@ export async function loadFreeCostVoucherImageBase64(voucherPath: string): Promi
|
||||
}
|
||||
|
||||
function signFreeCostVoucherUrls(paths: string[]): string[] {
|
||||
return paths.map((path) => buildSignedStoragePath('invoices', path));
|
||||
// T9F-5:无前缀旧 key 不再同步签发;未迁移时给空串,列表不 500。
|
||||
return paths.map((path) => tryBuildSignedStoragePathForCtx(undefined, 'invoices', path) ?? '');
|
||||
}
|
||||
|
||||
function normalizeTypeList(raw: unknown): FreeCostTypeItem[] {
|
||||
@@ -442,6 +449,8 @@ export async function createFreeCostEntry(input: {
|
||||
invoicePhoto?: boolean;
|
||||
status?: number;
|
||||
source?: FreeCostAuditSource;
|
||||
/** 写入口归属校验用租户上下文(route 传入;缺省按 branchCode fail-closed) */
|
||||
ownerCtx?: StorageOwnerCtx | null;
|
||||
}) {
|
||||
const types = await listFreeCostTypes(input.branchCode);
|
||||
let subtype = String(input.subtype || '').trim().toLowerCase();
|
||||
@@ -467,6 +476,12 @@ export async function createFreeCostEntry(input: {
|
||||
? FREE_COST_STATUS.pending
|
||||
: FREE_COST_STATUS.posted;
|
||||
const dayCycle = freeCostDayCycleCode();
|
||||
// T9 写入口:跨分支/无归属凭证 key 必须在 INSERT 之前 403,不能先落库再在装饰层才拦
|
||||
await assertOwnedStoragePaths(
|
||||
input.ownerCtx ?? { branchCode: input.branchCode || null },
|
||||
'invoices',
|
||||
voucherPaths
|
||||
);
|
||||
const result = await pool.query(
|
||||
`INSERT INTO cost_details (
|
||||
cycle_code, order_code, cost_type, cost_subtype, amount,
|
||||
|
||||
@@ -4,6 +4,7 @@ import { INTERNAL_PURCHASER_CODE } from './allocationRules';
|
||||
import { upsertOrderSkuPurchaseCostFromUnitCost } from './orderCostPostingService';
|
||||
import { recalculateStatementsAffectedByOrder } from './financeReconciliationService';
|
||||
import { sqlSelfPurchaseSupplierEquiv } from './inspectionRejectFulfillmentService';
|
||||
import { writeReattributedSelfPurchaseActual } from './inspectionComplianceService';
|
||||
import {
|
||||
countPreparationLinks,
|
||||
deleteSupplierPreparationRow,
|
||||
@@ -106,12 +107,16 @@ async function relabelInboundOwner(
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删掉该订单行的履约关联,返回**改派前**挂过的采购单号(去重、非空)。
|
||||
* 返回的旧单号用于转挂自采时按单归集实收(防同单同 SKU 多行互相串量,2026-10-19 对抗修复)。
|
||||
*/
|
||||
async function dropItemFulfillmentLinks(
|
||||
db: Db,
|
||||
orderCode: string,
|
||||
itemId: string,
|
||||
destIsSelfPurchase: boolean
|
||||
): Promise<void> {
|
||||
): Promise<string[]> {
|
||||
const linked = await db.query(
|
||||
`SELECT f.supplier_preparation_id, f.purchase_code, sp.sku_code AS prep_sku, sp.supplier_code AS prep_supplier
|
||||
FROM order_item_fulfillments f
|
||||
@@ -139,7 +144,7 @@ async function dropItemFulfillmentLinks(
|
||||
await deleteSupplierPreparationRow(db, orderCode, prep.id, prep.sku, prep.supplier);
|
||||
}
|
||||
|
||||
if (destIsSelfPurchase) return;
|
||||
if (destIsSelfPurchase) return [...new Set(purchaseCodes)];
|
||||
|
||||
const extraPos = await db.query(
|
||||
`SELECT purchase_code
|
||||
@@ -166,6 +171,7 @@ async function dropItemFulfillmentLinks(
|
||||
[purchaseCode]
|
||||
);
|
||||
}
|
||||
return uniqueCodes;
|
||||
}
|
||||
|
||||
async function ensureCompletedSelfPurchase(
|
||||
@@ -177,6 +183,8 @@ async function ensureCompletedSelfPurchase(
|
||||
qty: number;
|
||||
unitCost: number;
|
||||
branchCode: string | null;
|
||||
/** 改派前该行挂过的采购单号(按单归集实收,防同单同 SKU 多行串量) */
|
||||
sourcePurchaseCodes?: string[];
|
||||
}
|
||||
): Promise<void> {
|
||||
const existing = await db.query(
|
||||
@@ -193,16 +201,22 @@ async function ensureCompletedSelfPurchase(
|
||||
const purchaseCode = String(existing.rows[0].purchase_code);
|
||||
await db.query(
|
||||
`UPDATE purchase_orders
|
||||
SET purchase_status = 30,
|
||||
supplier_code = NULL,
|
||||
SET supplier_code = NULL,
|
||||
purchase_qty = $2,
|
||||
actual_qty = $2,
|
||||
purchase_price = $3,
|
||||
actual_price = $3,
|
||||
total_amount = ROUND($2::numeric * $3::numeric, 2)
|
||||
actual_price = $3
|
||||
WHERE purchase_code = $1`,
|
||||
[purchaseCode, qty, price]
|
||||
);
|
||||
// 状态/实收量由验收模块按「累计入库量」统一写(方案 C:验收是 actual_qty/30 的唯一写入方)
|
||||
// 传入改派前的旧采购单号 ⇒ 只累计本行份内的批次,不把同单同 SKU 其它行的入库算进来
|
||||
await writeReattributedSelfPurchaseActual(db, {
|
||||
purchaseCode,
|
||||
orderCode: args.orderCode,
|
||||
skuCode: args.skuCode || '',
|
||||
actualPrice: price,
|
||||
sourcePurchaseCodes: args.sourcePurchaseCodes,
|
||||
});
|
||||
await linkOrderItemToPurchase(db, {
|
||||
orderItemId: args.itemId,
|
||||
orderCode: args.orderCode,
|
||||
@@ -216,7 +230,7 @@ async function ensureCompletedSelfPurchase(
|
||||
`INSERT INTO purchase_orders (
|
||||
purchase_code, order_code, sku_code, supplier_code, purchase_qty, purchase_price, actual_qty, actual_price,
|
||||
purchase_status, is_temporary_supplier, source_type, source_id, remark, branch_code, total_amount
|
||||
) VALUES ($1, $2, $3, NULL, $4, $5, $4, $5, 30, false, 'order_no_supplier', $6, NULL, $7,
|
||||
) VALUES ($1, $2, $3, NULL, $4, $5, NULL, $5, 20, false, 'order_no_supplier', $6, NULL, $7,
|
||||
ROUND($4::numeric * $5::numeric, 2))`,
|
||||
[
|
||||
purchaseCode,
|
||||
@@ -228,6 +242,14 @@ async function ensureCompletedSelfPurchase(
|
||||
args.branchCode,
|
||||
]
|
||||
);
|
||||
// 已入库批次直接由验收模块落 30 + 实收(不在此直写,见方案 C)
|
||||
await writeReattributedSelfPurchaseActual(db, {
|
||||
purchaseCode,
|
||||
orderCode: args.orderCode,
|
||||
skuCode: args.skuCode || '',
|
||||
actualPrice: price,
|
||||
sourcePurchaseCodes: args.sourcePurchaseCodes,
|
||||
});
|
||||
await linkOrderItemToPurchase(db, {
|
||||
orderItemId: args.itemId,
|
||||
orderCode: args.orderCode,
|
||||
@@ -347,7 +369,8 @@ export async function reattributeInboundFulfillment(
|
||||
previousOwner,
|
||||
nextOwner,
|
||||
});
|
||||
await dropItemFulfillmentLinks(db, orderCode, itemId, destSelf);
|
||||
// 改派前挂过的采购单号(用于转挂自采时按单归集实收,防串量)
|
||||
const sourcePurchaseCodes = await dropItemFulfillmentLinks(db, orderCode, itemId, destSelf);
|
||||
|
||||
if (destSelf) {
|
||||
await ensureCompletedSelfPurchase(db, {
|
||||
@@ -357,6 +380,7 @@ export async function reattributeInboundFulfillment(
|
||||
qty,
|
||||
unitCost,
|
||||
branchCode: args.branchCode || null,
|
||||
sourcePurchaseCodes,
|
||||
});
|
||||
} else {
|
||||
await ensureCompletedSupplierPrep(db, {
|
||||
|
||||
@@ -41,6 +41,7 @@ import {
|
||||
import { ensureSkuAndBarcodeForInspection } from './skuProvisioningService';
|
||||
import { reserveLinkedItemsAfterPreparationInbound, reserveLinkedItemsAfterPurchaseInbound } from './inventoryStockCoverService';
|
||||
import { finalizeInspectionPhotosToResultFolder } from './storageUploadService';
|
||||
import { assertStorageKeyOwned } from './storageObjectOwnership';
|
||||
import { notifyInspectionRejected } from './inspectionRejectNotificationService';
|
||||
import { writeAuditLog } from './auditService';
|
||||
import { ensureSupplierStatementAfterInbound } from './financeReconciliationService';
|
||||
@@ -266,6 +267,10 @@ export function summarizeInboundBatches(rows: InboundBatchRow[]): number {
|
||||
/**
|
||||
* 取「订单 + SKU + 供应商口径 + 自采单号」下已完成的全部到货批次。
|
||||
* 存在采购单号时按其归集,避免同订单一 SKU 的多张自采单互相串量。
|
||||
*
|
||||
* `purchaseCodes`(2026-10-19):**入库后转挂**场景一次传多个旧采购单号(该行改派前挂过的
|
||||
* 全部自采/供货单)。只取命中这些单号的批次 ⇒ 同单同 SKU 多行改派时各自只累计自己的份额。
|
||||
* 不传 ⇒ 旧行为逐字不变(仅 `purchaseCode` 单号过滤,或不过滤)。
|
||||
*/
|
||||
export async function fetchInboundBatchRows(
|
||||
client: Pick<PoolClient, 'query'>,
|
||||
@@ -274,9 +279,13 @@ export async function fetchInboundBatchRows(
|
||||
skuCode: string;
|
||||
supplierCode?: string | null;
|
||||
purchaseCode?: string | null;
|
||||
purchaseCodes?: string[] | null;
|
||||
}
|
||||
): Promise<InboundBatchRow[]> {
|
||||
const purchaseCode = String(params.purchaseCode || '').trim();
|
||||
const purchaseCodes = [
|
||||
...new Set((params.purchaseCodes || []).map((code) => String(code || '').trim()).filter(Boolean)),
|
||||
];
|
||||
const supplierEquiv = sqlSelfPurchaseSupplierEquiv('supplier_code', '$3::text');
|
||||
const conditions = [
|
||||
'order_code IS NOT DISTINCT FROM $1',
|
||||
@@ -286,13 +295,23 @@ export async function fetchInboundBatchRows(
|
||||
"COALESCE(quality_rating, '') NOT LIKE '%不合格%'",
|
||||
'COALESCE(actual_qty, 0) > 0',
|
||||
];
|
||||
const queryParams: Array<string | null> = [params.orderCode, params.skuCode, params.supplierCode || null];
|
||||
const queryParams: Array<string | string[] | null> = [
|
||||
params.orderCode,
|
||||
params.skuCode,
|
||||
params.supplierCode || null,
|
||||
];
|
||||
if (purchaseCode) {
|
||||
queryParams.push(purchaseCode);
|
||||
conditions.push(
|
||||
`(processing_details->>'purchase_code' = $4
|
||||
OR COALESCE(processing_details->'purchase_codes', '[]'::jsonb) ? $4)`
|
||||
);
|
||||
} else if (purchaseCodes.length) {
|
||||
queryParams.push(purchaseCodes);
|
||||
conditions.push(
|
||||
`(processing_details->>'purchase_code' = ANY($4::text[])
|
||||
OR COALESCE(processing_details->'purchase_codes', '[]'::jsonb) ?| $4::text[])`
|
||||
);
|
||||
}
|
||||
const result = await client.query(
|
||||
`SELECT id::text AS id, actual_qty, created_at,
|
||||
@@ -320,11 +339,86 @@ export async function computeAccumulatedInboundQty(
|
||||
skuCode: string;
|
||||
supplierCode?: string | null;
|
||||
purchaseCode?: string | null;
|
||||
/** 多个采购单号(入库转挂:该行改派前挂过的旧单号),不传=旧行为 */
|
||||
purchaseCodes?: string[] | null;
|
||||
}
|
||||
): Promise<number> {
|
||||
return summarizeInboundBatches(await fetchInboundBatchRows(client, params));
|
||||
}
|
||||
|
||||
/**
|
||||
* 入库后转挂自采:由验收模块按「订单 + SKU + 自采口径」的**累计入库量**写
|
||||
* `purchase_status = 30` 与 `actual_qty`(2026-10-19)。
|
||||
*
|
||||
* 为什么放在验收模块:方案 C 规定 `purchase_orders.actual_qty` 与 `30` 的唯一写入方是验收
|
||||
* (`docs/design/20260920-self-purchase-actual-qty-single-writer.md`)。
|
||||
* `inboundFulfillmentReattributeService` 只负责把已入库批次归属改为自采,不得自己直写状态/实收。
|
||||
* 累计入库量为 0(无已完成入库批次)时不写 —— 不留下「状态 30 但实收为空」的半写。
|
||||
*
|
||||
* `sourcePurchaseCodes`(2026-10-19 对抗修复):改派前该订单行挂过的全部采购单号。
|
||||
* 传了就**只累计这些单号命中的入库批次**(同单同 SKU 多行改派时各计各的,不互相串量);
|
||||
* 不传时:仅当「同订单 + 同 SKU 只有 1 个有效订单行」才回退 order+sku 全量累计(旧行为);
|
||||
* 多行且无采购单号可归集 ⇒ **宁可不写也不放大**:跳过实收写入(保持 20),warn 留痕。
|
||||
*/
|
||||
export async function writeReattributedSelfPurchaseActual(
|
||||
client: Pick<PoolClient, 'query'>,
|
||||
params: {
|
||||
purchaseCode: string;
|
||||
orderCode: string;
|
||||
skuCode: string;
|
||||
actualPrice?: number | null;
|
||||
sourcePurchaseCodes?: string[] | null;
|
||||
}
|
||||
): Promise<number | null> {
|
||||
const purchaseCode = String(params.purchaseCode || '').trim();
|
||||
const orderCode = String(params.orderCode || '').trim();
|
||||
const skuCode = String(params.skuCode || '').trim();
|
||||
const sourcePurchaseCodes = [
|
||||
...new Set((params.sourcePurchaseCodes || []).map((code) => String(code || '').trim()).filter(Boolean)),
|
||||
];
|
||||
if (!purchaseCode || !orderCode || !skuCode) return null;
|
||||
|
||||
// R-A/R-A1(2026-10-19 verifier 增量复核):无采购单号可归集时,先确认同订单同 SKU 是否只有
|
||||
// **一行 order_items**。这里刻意**不过滤** `is_returned` / `is_extra_dish`:退货/加菜是硬删语义,
|
||||
// 但对应订单行上仍可能挂着 inspection 入库批次 —— 若只数"有效行",回退的累计仍会把这些批次算进来,
|
||||
// 1 个有效行 + 1 个退货行有批次时金额照样被放大。⇒ 统计全部行;>1 就跳过写入(保持 20 / actual 空)。
|
||||
if (!sourcePurchaseCodes.length) {
|
||||
const sibling = await client.query(
|
||||
`SELECT COUNT(*)::int AS cnt
|
||||
FROM order_items
|
||||
WHERE order_code = $1
|
||||
AND sku_code IS NOT DISTINCT FROM $2`,
|
||||
[orderCode, skuCode]
|
||||
);
|
||||
const siblingRows = Number(sibling.rows[0]?.cnt) || 0;
|
||||
if (siblingRows > 1) {
|
||||
console.warn(
|
||||
`[inspection] 无法按采购单归集,跳过实收写入(保持 20):order=${orderCode} sku=${skuCode} ` +
|
||||
`同订单同 SKU 行数=${siblingRows}(无改派前采购单号)`
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const accumulated = await computeAccumulatedInboundQty(client, {
|
||||
orderCode,
|
||||
skuCode,
|
||||
supplierCode: null,
|
||||
...(sourcePurchaseCodes.length ? { purchaseCodes: sourcePurchaseCodes } : {}),
|
||||
});
|
||||
if (!(accumulated > 1e-9)) return null;
|
||||
await client.query(
|
||||
`UPDATE purchase_orders
|
||||
SET purchase_status = 30,
|
||||
actual_qty = $2::numeric,
|
||||
actual_price = COALESCE($3::numeric, actual_price),
|
||||
total_amount = ROUND($2::numeric * COALESCE($3::numeric, actual_price, 0), 2)
|
||||
WHERE purchase_code = $1`,
|
||||
[purchaseCode, accumulated, params.actualPrice ?? null]
|
||||
);
|
||||
return accumulated;
|
||||
}
|
||||
|
||||
/**
|
||||
* 回写采购单实收:累计口径(首批 + 各补收批次)。
|
||||
* 采购单入库即置 30,所以不能用状态当门槛;改为判断已有实收是不是本流程自己写的:
|
||||
@@ -1319,6 +1413,26 @@ export async function submitInspectionCompliance(
|
||||
);
|
||||
const existingPhotos = Array.isArray(row.inspection_photos) ? row.inspection_photos : [];
|
||||
const incomingPhotos = Array.isArray(input.inspection_photos) ? input.inspection_photos : [];
|
||||
/**
|
||||
* B0(T9 红队):`inspection_photos` 客户端可控,必须先做归属白名单:
|
||||
* 允许 data:/http(s) URL;其余路径只允许 `<branch>/…` 或能反查到本租户的旧 key。
|
||||
* 拒绝 `archive/BR002/...` 等跨租户/任意路径(403),从源头阻断"读+删他租户对象"。
|
||||
*/
|
||||
if (incomingPhotos.length > 0) {
|
||||
for (const raw of incomingPhotos) {
|
||||
const photo = String(raw ?? '').trim();
|
||||
if (!photo) continue;
|
||||
if (photo.startsWith('data:') || /^https?:\/\//i.test(photo)) continue;
|
||||
try {
|
||||
await assertStorageKeyOwned('inspection-photos', photo, {
|
||||
branchCode: ctx?.branchCode,
|
||||
isSuperAdmin: ctx?.isSuperAdmin,
|
||||
});
|
||||
} catch {
|
||||
throw Object.assign(new Error('验收照片路径不属于当前租户'), { status: 403, code: 'forbidden' });
|
||||
}
|
||||
}
|
||||
}
|
||||
const sourcePhotos = incomingPhotos.length > 0 ? incomingPhotos : existingPhotos;
|
||||
const photoCount = sourcePhotos.length;
|
||||
if (photoRequired && photoCount <= 0 && !options?.allowMissingPhotos) {
|
||||
@@ -1393,6 +1507,7 @@ export async function submitInspectionCompliance(
|
||||
photos: sourcePhotos,
|
||||
productName: row.sku_name || row.item_name || row.sku_code,
|
||||
skuCode: row.sku_code,
|
||||
ctx: { branchCode: ctx?.branchCode, isSuperAdmin: ctx?.isSuperAdmin },
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { pool } from '../db';
|
||||
import { buildSignedStoragePath } from './storageSignedUrl';
|
||||
import { assertStorageKeyOwned, buildSignedStoragePathForCtxChecked } from './storageObjectOwnership';
|
||||
import { getStorageProvider } from './storageProvider';
|
||||
import { loadArchivedPhotoMap } from './inspectionPhotoArchiveService';
|
||||
import {
|
||||
@@ -101,7 +101,8 @@ export interface SignedPhotoRef {
|
||||
|
||||
export async function signedExistingPhotos(
|
||||
value: unknown,
|
||||
bucket = INSPECTION_PHOTO_BUCKET
|
||||
bucket = INSPECTION_PHOTO_BUCKET,
|
||||
ctx?: { branchCode?: string | null; isSuperAdmin?: boolean } | null
|
||||
): Promise<SignedPhotoRef[]> {
|
||||
const raw = Array.isArray(value) ? value : value != null ? [value] : [];
|
||||
const paths = raw
|
||||
@@ -128,16 +129,21 @@ export async function signedExistingPhotos(
|
||||
: new Map();
|
||||
|
||||
const out: SignedPhotoRef[] = [];
|
||||
paths.forEach((path, index) => {
|
||||
for (const [index, path] of paths.entries()) {
|
||||
if (existsFlags[index]) {
|
||||
out.push({ path, url: buildSignedStoragePath(bucket, path) });
|
||||
return;
|
||||
// T9F-5:无前缀旧 key 先异步反查归属再签;跨租户/毒化行在这里被 403,不会 500。
|
||||
try {
|
||||
out.push({ path, url: await buildSignedStoragePathForCtxChecked(ctx, bucket, path) });
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const archived = archivedMap.get(path);
|
||||
if (archived) {
|
||||
out.push({ path, url: '', archived: true, archive_month: archived.ym });
|
||||
}
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -433,7 +439,7 @@ export async function listPickingOutboundPhotoReviews(input: {
|
||||
/**
|
||||
* ⚠️ **出库留证照片存在 `delivery-photos` 桶**(上传侧:`workflowApi` 的
|
||||
* `/storage/delivery-photos/upload`;分拣详情读图同用
|
||||
* `pickingService.buildSignedStoragePath('delivery-photos', p)`)。
|
||||
* `pickingService.buildSignedStoragePathForCtx(undefined, 'delivery-photos', p)`)。
|
||||
*
|
||||
* 2026-10-14 缺陷:这里原来走 `signedExistingPhotos` 的默认桶 `inspection-photos`
|
||||
* ⇒ `storage.exists` 全为 false ⇒ 行被 `photos.length > 0` 过滤掉,**列表恒为空**,
|
||||
@@ -844,6 +850,12 @@ export async function clearInspectionReviewPhotos(input: {
|
||||
const storage = getStorageProvider();
|
||||
for (const photo of paths) {
|
||||
try {
|
||||
// T9F-2:删除前必须校验归属;archive/* 是保留期数据,一律拒绝删除。
|
||||
if (photo === 'archive' || photo.startsWith('archive/')) {
|
||||
console.warn(`[inspection-review] 拒绝删除归档对象 ${photo}`);
|
||||
continue;
|
||||
}
|
||||
await assertStorageKeyOwned('inspection-photos', photo, { branchCode: input.branchCode });
|
||||
await storage.deleteObject('inspection-photos', photo);
|
||||
} catch (error) {
|
||||
console.error(`[inspection-review] 删除存储照片失败 ${photo}:`, error);
|
||||
|
||||
@@ -16,7 +16,7 @@ import { pool } from '../db';
|
||||
import { writeAuditLog } from './auditService';
|
||||
import { getStorageProvider } from './storageProvider';
|
||||
import { safeStorageFileName } from './storageBucketConfig';
|
||||
import { buildSignedStoragePath } from './storageSignedUrl';
|
||||
import { assertOwnedStoragePaths, buildSignedStoragePathForCtx } from './storageObjectOwnership';
|
||||
import { resolvePrompt } from './promptRegistryService';
|
||||
import { callWithImage, callWithFile, hasRuntimeConfig } from './llmService';
|
||||
import { extractAiProductNames, productNamesMatch } from './qualityReportService';
|
||||
@@ -259,7 +259,7 @@ function mapReportRow(
|
||||
const paths = Array.isArray(raw.file_paths) ? raw.file_paths.map((p) => String(p)) : [];
|
||||
const fileUrls = paths.map((p) => {
|
||||
try {
|
||||
return buildSignedStoragePath(REPORT_BUCKET, safeStorageFileName(p));
|
||||
return buildSignedStoragePathForCtx(undefined, REPORT_BUCKET, safeStorageFileName(p));
|
||||
} catch {
|
||||
return p;
|
||||
}
|
||||
@@ -330,6 +330,9 @@ export async function createInventoryBatchReports(input: {
|
||||
}
|
||||
const reportNo = trimText(input.reportNo) || null;
|
||||
|
||||
// T9:读对象/INSERT file_paths 前校验归属(跨分支 key ⇒ 403,不落库)
|
||||
await assertOwnedStoragePaths({ branchCode }, 'quality-reports', files);
|
||||
|
||||
// 1) 落存储对象读回 + OCR(在事务外做,避免长时间占用连接)
|
||||
const parsed: Array<{ path: string; meta: ParsedMeta }> = [];
|
||||
for (const path of files) {
|
||||
|
||||
@@ -163,6 +163,11 @@ export async function fifoDeductInventory(
|
||||
respectOtherReservations?: boolean;
|
||||
/** 手选批次计划(可选):按顺序/数量优先扣;**不传 = 纯 FIFO(逐字不变)** */
|
||||
batchPlan?: Array<{ batchNo: string; qty: number }> | null;
|
||||
/**
|
||||
* 加工领料专用(可选):一次豁免**全部**本单订单号的预留(SQL 数组)。
|
||||
* 不传 ⇒ 旧口径逐字不变(只豁免 `orderCode` 一个)。
|
||||
*/
|
||||
reservationExemptOrderCodes?: string[] | null;
|
||||
},
|
||||
onBatchDeducted?: (
|
||||
batch: { batchNo: string; costPrice: number; supplierCode?: string | null; inboundAt?: string | null },
|
||||
@@ -183,10 +188,17 @@ export async function fifoDeductInventory(
|
||||
client,
|
||||
input.skuCode,
|
||||
input.branchCode,
|
||||
input.orderCode || undefined
|
||||
input.orderCode || undefined,
|
||||
input.reservationExemptOrderCodes
|
||||
);
|
||||
if (claimable + 1e-9 < remaining && input.branchCode) {
|
||||
claimable = await getClaimableStockQty(client, input.skuCode, null, input.orderCode || undefined);
|
||||
claimable = await getClaimableStockQty(
|
||||
client,
|
||||
input.skuCode,
|
||||
null,
|
||||
input.orderCode || undefined,
|
||||
input.reservationExemptOrderCodes
|
||||
);
|
||||
}
|
||||
if (claimable + 1e-9 < remaining) {
|
||||
const label = input.itemName ? `${input.itemName}(${input.skuCode})` : input.skuCode;
|
||||
|
||||
@@ -425,18 +425,57 @@ export async function sumOtherOrderReservations(
|
||||
return Number(result.rows[0]?.total) || 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 他单未消耗预留合计,**一次豁免** `exemptOrderCodes` 里的全部订单号(2026-10-19)。
|
||||
*
|
||||
* 旧 `sumOtherOrderReservations` 每次只排除一个 order_code:同一需求单含多张订单时,
|
||||
* 调用方若逐单号调用再相加,他单预留会被算 N 倍。本函数把豁免名单作为 SQL 数组一次传入。
|
||||
* 不传/空名单 ⇒ 等价于旧口径(该函数仅服务加工领料,故不改变其它调用方语义)。
|
||||
*/
|
||||
export async function sumOtherOrderReservationsExempting(
|
||||
db: Db,
|
||||
skuCode: string,
|
||||
branchCode: string | null | undefined,
|
||||
exemptOrderCodes: string[]
|
||||
): Promise<number> {
|
||||
const sku = String(skuCode || '').trim();
|
||||
if (!sku) return 0;
|
||||
const branch = String(branchCode || '').trim() || null;
|
||||
const exempt = Array.from(
|
||||
new Set((exemptOrderCodes || []).map((c) => String(c || '').trim()).filter(Boolean))
|
||||
);
|
||||
if (!exempt.length) return sumOtherOrderReservations(db, sku, branch, null);
|
||||
const result = await db.query(
|
||||
`SELECT COALESCE(SUM(qty), 0)::float AS total
|
||||
FROM inventory_reservations
|
||||
WHERE sku_code = $1
|
||||
AND status = 10
|
||||
AND ($2::text IS NULL OR branch_code IS NULL OR branch_code = $2)
|
||||
AND (order_code IS NULL OR NOT (order_code = ANY($3::text[])))`,
|
||||
[sku, branch, exempt]
|
||||
);
|
||||
return Number(result.rows[0]?.total) || 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 本单可扣库存:毛可用 − 他单预留(本单预留可消耗)。
|
||||
* 发车 / FIFO 出库前用此口径,避免抢走他单预留。
|
||||
*
|
||||
* `exemptOrderCodes`(可选,加工领料专用):一次豁免全部本单订单号;
|
||||
* 不传 ⇒ 逐字沿用旧口径(只豁免 `orderCode` 一个)。
|
||||
*/
|
||||
export async function getClaimableStockQty(
|
||||
db: Db,
|
||||
skuCode: string,
|
||||
branchCode?: string | null,
|
||||
orderCode?: string | null
|
||||
orderCode?: string | null,
|
||||
exemptOrderCodes?: string[] | null
|
||||
): Promise<number> {
|
||||
const available = await sumAvailableQty(db, skuCode, branchCode);
|
||||
const other = await sumOtherOrderReservations(db, skuCode, branchCode, orderCode);
|
||||
const other =
|
||||
exemptOrderCodes && exemptOrderCodes.length
|
||||
? await sumOtherOrderReservationsExempting(db, skuCode, branchCode, exemptOrderCodes)
|
||||
: await sumOtherOrderReservations(db, skuCode, branchCode, orderCode);
|
||||
return Math.max(0, available - other);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { callWithFile, callWithImage, hasRuntimeConfig } from './llmService';
|
||||
import { resolvePrompt } from './promptRegistryService';
|
||||
import { getStorageProvider } from './storageProvider';
|
||||
import { safeStorageFileName } from './storageBucketConfig';
|
||||
import { safeStorageFileName, stripStorageBranchPrefix } from './storageBucketConfig';
|
||||
|
||||
export interface InvoiceOcrResult {
|
||||
invoice_no: string | null;
|
||||
@@ -103,7 +103,8 @@ export function assertSupplierInvoiceStoragePath(raw: string): string {
|
||||
} catch {
|
||||
throw Object.assign(new Error('发票路径无效'), { status: 400, code: 'invalid_request' });
|
||||
}
|
||||
if (!safe.startsWith(SUPPLIER_INVOICE_FOLDER)) {
|
||||
// SEC-5:允许新 key 的 `<branch>/` 前缀(校验用去前缀视图,读写仍用完整 key)
|
||||
if (!stripStorageBranchPrefix(safe).startsWith(SUPPLIER_INVOICE_FOLDER)) {
|
||||
throw Object.assign(new Error('仅支持 supplier-invoices 发票'), { status: 400, code: 'invalid_request' });
|
||||
}
|
||||
return safe;
|
||||
|
||||
@@ -80,16 +80,24 @@ export function needBranchResponse(ticket: string, branches: BranchChoice[]) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 手机号+密码:任意一家验密成功后,选分公司名单用全部启用账号(含密码未对上的)。
|
||||
* 手机号+密码:**只有验密成功的账号**能进入选分公司名单(SEC-2,2026-10-19)。
|
||||
*
|
||||
* 旧实现只要任意一家验密成功,名单就返回**全部启用账号**(含密码没对上的另一分公司账号)
|
||||
* ⇒ 攻击者用 A 分公司的密码走到选分公司,再拿 ticket 选 B 分公司即可**免密登录 B**。
|
||||
* 新口径:
|
||||
* · 0 家命中 ⇒ fail;
|
||||
* · 1 家命中 ⇒ 直接 ok(无需选分公司);
|
||||
* · >1 家命中 ⇒ need_branch,users 只含命中账号。
|
||||
*/
|
||||
export function pickAccountsAfterAnyPasswordMatch<T extends { id: string }>(
|
||||
enabled: T[],
|
||||
matchedIds: Iterable<string>
|
||||
): { kind: 'fail' } | { kind: 'ok'; user: T } | { kind: 'need_branch'; users: T[] } {
|
||||
const matched = new Set(matchedIds);
|
||||
if (!enabled.some((u) => matched.has(u.id))) return { kind: 'fail' };
|
||||
if (enabled.length === 1) return { kind: 'ok', user: enabled[0] };
|
||||
return { kind: 'need_branch', users: enabled };
|
||||
const hits = enabled.filter((u) => matched.has(u.id));
|
||||
if (hits.length === 0) return { kind: 'fail' };
|
||||
if (hits.length === 1) return { kind: 'ok', user: hits[0] };
|
||||
return { kind: 'need_branch', users: hits };
|
||||
}
|
||||
|
||||
/** 测试用 */
|
||||
|
||||
@@ -722,6 +722,11 @@ export async function applyBidDetail(input: {
|
||||
* · 调用方带了 `supplierCode` ⇒ 精确匹配该行(前端列表里每行都带它,正常路径都走这条);
|
||||
* · 没带且只有一行 ⇒ 就用它(单绑定的常见情况);
|
||||
* · 没带且多行 ⇒ 返回 `ambiguous`,由调用方提示"请从清单里点具体那条",**绝不猜**(猜错会以另一家身份报价)。
|
||||
*
|
||||
* ⚠️ **已软删(`deleted_at` 非空)的行一律不算 `found`**(2026-10-19 BIZ-11):
|
||||
* 管理员「删除待报价」后,页面必须看不到、详情必须拿不到、提交必须被拒 ——
|
||||
* 否则供应商仍能从旧详情页/接口把这轮报到主系统去。两个分支都按此过滤,
|
||||
* 且额外区分出 `deleted`("行在、但已删")⇒ 调用方能给出 409「已删除」而不是含糊的 404。
|
||||
*/
|
||||
export async function findInvitationByRound(input: {
|
||||
branchCode: string;
|
||||
@@ -730,33 +735,41 @@ export async function findInvitationByRound(input: {
|
||||
}): Promise<
|
||||
| { kind: 'found'; row: BidInvitationRow }
|
||||
| { kind: 'missing' }
|
||||
| { kind: 'deleted'; supplierCodes: string[] }
|
||||
| { kind: 'ambiguous'; supplierCodes: string[] }
|
||||
> {
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
const roundId = String(input.roundId || '').trim();
|
||||
const supplierCode = String(input.supplierCode || '').trim();
|
||||
if (!branchCode || !roundId) return { kind: 'missing' };
|
||||
if (supplierCode) {
|
||||
const { rows } = await pool.query<BidInvitationRow>(
|
||||
`SELECT * FROM public.main_system_bid_invitations
|
||||
WHERE branch_code = $1 AND round_id = $2 AND upper(supplier_code) = upper($3)
|
||||
AND deleted_at IS NULL
|
||||
LIMIT 1`,
|
||||
[branchCode, roundId, supplierCode]
|
||||
);
|
||||
return rows[0] ? { kind: 'found', row: rows[0] } : { kind: 'missing' };
|
||||
}
|
||||
const { rows } = await pool.query<BidInvitationRow>(
|
||||
`SELECT * FROM public.main_system_bid_invitations
|
||||
WHERE branch_code = $1 AND round_id = $2
|
||||
ORDER BY created_at DESC`,
|
||||
[branchCode, roundId]
|
||||
);
|
||||
/**
|
||||
* 一次查询取回本次范围的全部行(**不**在 SQL 里排除已删行),再按 `deleted_at` 分区:
|
||||
* · 过滤只认一个判据(`deleted_at`),不会出现"某个分支忘了写 deleted_at IS NULL";
|
||||
* · 还能区分 missing / deleted,供提交入口给出明确 409。
|
||||
*/
|
||||
const { rows } = supplierCode
|
||||
? await pool.query<BidInvitationRow>(
|
||||
`SELECT * FROM public.main_system_bid_invitations
|
||||
WHERE branch_code = $1 AND round_id = $2 AND upper(supplier_code) = upper($3)
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1`,
|
||||
[branchCode, roundId, supplierCode]
|
||||
)
|
||||
: await pool.query<BidInvitationRow>(
|
||||
`SELECT * FROM public.main_system_bid_invitations
|
||||
WHERE branch_code = $1 AND round_id = $2
|
||||
ORDER BY created_at DESC`,
|
||||
[branchCode, roundId]
|
||||
);
|
||||
if (!rows.length) return { kind: 'missing' };
|
||||
if (rows.length > 1) {
|
||||
return { kind: 'ambiguous', supplierCodes: rows.map((row) => String(row.supplier_code || '')) };
|
||||
const active = rows.filter((row) => !row.deleted_at);
|
||||
if (!active.length) {
|
||||
return { kind: 'deleted', supplierCodes: rows.map((row) => String(row.supplier_code || '')) };
|
||||
}
|
||||
return { kind: 'found', row: rows[0] };
|
||||
if (active.length > 1) {
|
||||
return { kind: 'ambiguous', supplierCodes: active.map((row) => String(row.supplier_code || '')) };
|
||||
}
|
||||
return { kind: 'found', row: active[0] };
|
||||
}
|
||||
|
||||
export async function listInvitationRows(input: {
|
||||
@@ -900,6 +913,8 @@ export async function getBidInvitationDetail(input: {
|
||||
const found = await findInvitationByRound(input);
|
||||
if (found.kind !== 'found') return null;
|
||||
const row = found.row;
|
||||
// 双保险:即使上游忘了过滤,已软删的行也绝不出详情(详情页是"报价"的入口,BIZ-11)
|
||||
if (row.deleted_at) return null;
|
||||
const itemRows = await listInvitationItems(row.id);
|
||||
const itemCount = itemRows.length || Number(row.item_count) || 0;
|
||||
const deadlineMs = row.respond_deadline ? new Date(row.respond_deadline).getTime() : NaN;
|
||||
@@ -907,7 +922,9 @@ export async function getBidInvitationDetail(input: {
|
||||
// 「轮次还在报价中」是对方的事实(`open`);`closed`/`awarded`/`cancelled` 一律不可提交。
|
||||
// 另外派生状态已是终态(expired/won/lost/cancelled)也不可提交:对方说邀约过期时,
|
||||
// 即便本地时钟还没到截止,也不该再发出一次注定被拒的请求。
|
||||
// 已软删(管理员删除待报价)同样不可提交 —— 与 `findInvitationByRound` 的过滤同口径。
|
||||
const canQuote =
|
||||
!row.deleted_at &&
|
||||
!deadlinePassed &&
|
||||
row.round_status === 'open' &&
|
||||
row.local_status !== 'expired' &&
|
||||
|
||||
@@ -48,6 +48,7 @@ export const BID_ERROR_COPY: Record<string, string> = {
|
||||
request_failed: '提交报价失败,请稍后重试',
|
||||
// ── 我方错误码 ──
|
||||
bid_invitation_not_found: '本地没有这轮竞价的记录,请先点「同步」',
|
||||
bid_invitation_deleted: '该竞价邀约已被删除,无法再报价(管理员可在「显示已删除」里恢复)',
|
||||
quotes_required: '请至少填写一条报价',
|
||||
invalid_unit_price: '报价必须是大于 0 且最多 4 位小数的数字',
|
||||
sku_not_in_round: '该商品不在本轮竞价的商品清单里,请先刷新',
|
||||
@@ -306,6 +307,15 @@ async function resolveInvitation(input: {
|
||||
}),
|
||||
};
|
||||
}
|
||||
/**
|
||||
* **已软删的邀约不得报价/刷新**(2026-10-19 BIZ-11):管理员「删除待报价」是本地隐藏、
|
||||
* 可恢复的台账操作;若这里放行,旧详情页仍能把报价推到主系统。
|
||||
* 显式 409(而不是 404)—— 用户点的是"明明在清单里存在过的这轮",需要看到"已删除",
|
||||
* 而不是"本地没有记录,请先同步"这种误导文案。**零出站**:不刷新、不提交。
|
||||
*/
|
||||
if (found.kind === 'deleted') {
|
||||
return { ok: false, failure: localFailure({ code: 'bid_invitation_deleted', status: 409 }) };
|
||||
}
|
||||
if (found.kind !== 'found') {
|
||||
return { ok: false, failure: localFailure({ code: 'bid_invitation_not_found', status: 404 }) };
|
||||
}
|
||||
|
||||
@@ -35,6 +35,11 @@ import {
|
||||
retryPendingFulfillmentEvents,
|
||||
} from './mainSystemFulfillmentEvents';
|
||||
import { lookupPreparationStatesForBranch } from './mainSystemBranchApi';
|
||||
import {
|
||||
clearReverseTombstone,
|
||||
listReallocatedReverseTombstones,
|
||||
listReverseTombstoneKeys,
|
||||
} from './mainSystemReverseEvents';
|
||||
|
||||
/**
|
||||
* 把主系统「分配给我们分公司(= 主系统某供应商)」的备货任务,走本系统自己的录单流程生成订单。
|
||||
@@ -98,7 +103,8 @@ export type ImportedOrderResult = {
|
||||
mainOrderCode: string;
|
||||
ourOrderCode: string | null;
|
||||
itemCount: number;
|
||||
status: 'created' | 'appended' | 'skipped' | 'failed';
|
||||
/** `skipped_tombstoned` = 命中反向事件墓碑(主系统已删单/删行),明确不建单/不建行(BIZ-6) */
|
||||
status: 'created' | 'appended' | 'skipped' | 'skipped_tombstoned' | 'failed';
|
||||
message?: string;
|
||||
/** 未匹配报价/零价的明细数(前端提示补价用) */
|
||||
zeroPriceCount?: number;
|
||||
@@ -487,8 +493,17 @@ async function loadPrepLedgerByOrder(branchCode: string): Promise<Map<string, Pr
|
||||
* `disposition='imported'` + `our_order_item_id=NULL` 的自相矛盾态会**永久卡死** ——
|
||||
* 真库事故 BR003「米块」:主系统一直分配着、我方订单里永远没有它);
|
||||
* - 只有**人工/业务已定性的终态**才不再自动动(见 `APPEND_BLOCKED_DISPOSITIONS`)。
|
||||
*
|
||||
* BIZ-9(2026-10-19):`reallocated`(改派走)**不阻断** —— 改派是往返的(A→他人→A),
|
||||
* 同一 `prep_id` 再次分配回来必须允许重配/追加;`removed`(主系统删行)是硬删,继续阻断。
|
||||
*/
|
||||
const APPEND_BLOCKED_DISPOSITIONS = new Set(['cancelled', 'returned', 'completed', 'suspended']);
|
||||
const APPEND_BLOCKED_DISPOSITIONS = new Set([
|
||||
'cancelled',
|
||||
'returned',
|
||||
'completed',
|
||||
'suspended',
|
||||
'removed',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 当日订单的**追加阀门**(2026-10-12 开发者口径):
|
||||
@@ -510,10 +525,16 @@ export function needsAppendToOrder(
|
||||
if (row.isStockout) return false;
|
||||
const existing = ledgerRows?.find((entry) => String(entry.prep_id) === String(row.id));
|
||||
if (!existing) return true;
|
||||
if (existing.our_order_item_id) return false;
|
||||
if (existing.our_order_item_id) {
|
||||
/**
|
||||
* 已有对照,默认不再动。**例外 `reallocated`**:改派走时台账保留的旧对照指向的行已被移除
|
||||
* (或即将被移除)⇒ 主系统再次分配回同一 `prep_id` 时必须允许重配,否则永远卡死(BIZ-9)。
|
||||
*/
|
||||
return String(existing.disposition || '') === 'reallocated';
|
||||
}
|
||||
/**
|
||||
* ⚠️ 链接为空 ⇒ 我方订单里**没有**这一行(或链接丢了)⇒ 默认要补;
|
||||
* 只排除人工/业务已定性的终态(`cancelled`/`returned`/`completed`/`suspended`)。
|
||||
* 只排除人工/业务已定性的终态(`cancelled`/`returned`/`completed`/`suspended`/`removed`)。
|
||||
* 旧实现只重试 `pending`/`skipped_stockout` ⇒ `imported` + 空链接会永久卡死(见上方注释)。
|
||||
*/
|
||||
return !APPEND_BLOCKED_DISPOSITIONS.has(String(existing.disposition || ''));
|
||||
@@ -534,6 +555,60 @@ export function needsAppendToOrder(
|
||||
* - 主系统没定价 ⇒ 我们的售价是 0,这类订单里**已有的零价行不能挡住追加**
|
||||
* (`allowUnpriced`,与导入建单同一口径)。
|
||||
*/
|
||||
/**
|
||||
* 追加/重建时**可被行级台账认领的订单行候选**(2026-10-19 T2 红队攻破 2 修复)。
|
||||
*
|
||||
* 必须排除**已退货行**(`is_returned=true`)与加菜行:旧行软退货后仍留在 `order_items`,
|
||||
* 若参与「同名 + 数量就近」映射,会把 E1 重新分配回来的 `prep_id` 配到那条退役行上
|
||||
* ⇒ 台账记 `imported` 却指向旧行;之后删行发现 already_returned,新行永远留下、台账却 removed。
|
||||
* 排序保持 `sort_order NULLS LAST, created_at, id`(与建单/详情一致,结果可复现)。
|
||||
*/
|
||||
export async function loadMappingCandidateOrderItems(
|
||||
db: { query: (sql: string, params?: unknown[]) => Promise<{ rows: Array<Record<string, unknown>> }> },
|
||||
ourOrderCode: string,
|
||||
options?: {
|
||||
/**
|
||||
* B1(2026-10-19 终局复攻):候选还要排除**已被同分公司其它备货行占用**的订单行
|
||||
* (`main_system_order_import_items.our_order_item_id` 指向),保证一对一认领。
|
||||
* `excludePrepIds` = 本次正在补齐的 prep_id 集合(它们自己的旧对照不算"被占用")。
|
||||
*/
|
||||
branchCode?: string | null;
|
||||
excludePrepIds?: string[] | null;
|
||||
}
|
||||
): Promise<Array<{ id: string; item_name: string | null }>> {
|
||||
const branchCode = String(options?.branchCode || '').trim();
|
||||
const excludePrepIds = [
|
||||
...new Set((options?.excludePrepIds || []).map((id) => String(id || '').trim()).filter(Boolean)),
|
||||
];
|
||||
const extraWhere: string[] = [];
|
||||
const params: unknown[] = [ourOrderCode];
|
||||
if (branchCode) {
|
||||
params.push(branchCode, excludePrepIds);
|
||||
extraWhere.push(
|
||||
`AND NOT EXISTS (
|
||||
SELECT 1 FROM public.main_system_order_import_items claimed
|
||||
WHERE claimed.branch_code = $2
|
||||
AND claimed.our_order_item_id = order_items.id
|
||||
AND NOT (claimed.prep_id = ANY($3::uuid[]))
|
||||
)`
|
||||
);
|
||||
}
|
||||
const rows = await db.query(
|
||||
`SELECT id::text AS id, item_name
|
||||
FROM order_items
|
||||
WHERE order_code = $1
|
||||
AND COALESCE(is_returned, false) = false
|
||||
AND COALESCE(is_extra_dish, false) = false
|
||||
${extraWhere.join('\n ')}
|
||||
ORDER BY sort_order NULLS LAST, created_at, id`,
|
||||
params
|
||||
);
|
||||
return rows.rows.map((row) => ({
|
||||
id: String(row.id),
|
||||
item_name: (row.item_name as string | null) ?? null,
|
||||
}));
|
||||
}
|
||||
|
||||
async function appendNewRowsToDayOrder(params: {
|
||||
branchCode: string;
|
||||
userId: string | null;
|
||||
@@ -610,16 +685,9 @@ async function appendNewRowsToDayOrder(params: {
|
||||
* `suspend=true` 时把新行挂待处理(订单已进履约,交人工)。
|
||||
*/
|
||||
const persistRows = async (groupsToWrite: MainOrderGroup[], suspend: boolean, reason: string | null) => {
|
||||
const ourItems = await runWithTenantDataAccess(branchCode, async (client) => {
|
||||
const rows = await client.query<{ id: string; item_name: string | null }>(
|
||||
`SELECT id::text AS id, item_name
|
||||
FROM order_items
|
||||
WHERE order_code = $1
|
||||
ORDER BY sort_order NULLS LAST, created_at, id`,
|
||||
[ourOrderCode]
|
||||
);
|
||||
return rows.rows;
|
||||
});
|
||||
const ourItems = await runWithTenantDataAccess(branchCode, async (client) =>
|
||||
loadMappingCandidateOrderItems(client, ourOrderCode)
|
||||
);
|
||||
/**
|
||||
* ⚠️ 对照必须**整单算一次**(2026-10-11 修):一张我方订单由多张主系统单合并而来,
|
||||
* 同名商品会在多张单里各出现一次(实测「肉片」`…_0006` 3.5 斤 / `…_0007` 6 斤)。
|
||||
@@ -994,6 +1062,8 @@ type DayClaimResult =
|
||||
* - 占不到坑且已有单号 ⇒ 该日订单已存在,转**行级追加**;
|
||||
* - 占不到坑且没有单号 ⇒ 另一次导入正在建单,本轮跳过(下轮再来)。
|
||||
* 崩溃遗留的空坑超过 **2 分钟**视为陈旧,可被重新占用(不会永久卡住一个配送日)。
|
||||
* ⚠️ 重占时 **必须同时刷新 `created_at`**:并发轮次会等行锁,若只看 `updated_at`,
|
||||
* 第二个轮次在第一个提交后仍会判定"陈旧"而再次抢到同一坑 ⇒ 两张同日单。
|
||||
*
|
||||
* ⚠️ 2026-10-18 由 10 分钟收到 2 分钟:真机事故 `ORD_WEB_20261018_BR002_0002` —— 一次建单中断留下
|
||||
* 空坑,10 分钟内该配送日的**所有推送都被"占坑未取得"静默跳过、且返回 200**(主系统记成功、我们没导入)。
|
||||
@@ -1014,6 +1084,7 @@ async function claimDayOrder(params: {
|
||||
VALUES ($1, $2, $3::date, NULL, $4)
|
||||
ON CONFLICT (branch_code, main_branch_code, delivery_date) DO UPDATE
|
||||
SET updated_at = NOW(),
|
||||
created_at = NOW(),
|
||||
row_count = EXCLUDED.row_count
|
||||
WHERE public.main_system_daily_order_imports.our_order_code IS NULL
|
||||
AND public.main_system_daily_order_imports.created_at < NOW() - INTERVAL '2 minutes'
|
||||
@@ -1436,6 +1507,8 @@ async function createDayOrder(params: {
|
||||
`SELECT id::text AS id, item_name, quantity
|
||||
FROM order_items
|
||||
WHERE order_code = $1
|
||||
AND COALESCE(is_returned, false) = false
|
||||
AND COALESCE(is_extra_dish, false) = false
|
||||
ORDER BY sort_order NULLS LAST, created_at, id`,
|
||||
[result.order_code]
|
||||
);
|
||||
@@ -1530,6 +1603,134 @@ async function createDayOrder(params: {
|
||||
* 按给定的分组直接导入(webhook 推送的 payload 里已带全部备货行,不必再拉一次)。
|
||||
* 幂等与台账逻辑与拉取路径完全一致。
|
||||
*/
|
||||
/**
|
||||
* BIZ-6(2026-10-19):E1 导入侧的**墓碑过滤**。
|
||||
*
|
||||
* 反向事件可能先于 E1 到达(E1 受主系统"发送供应商"三档闸门延迟);当时未知的
|
||||
* `prep_id` / `main_order_code` 已落持久墓碑。这里在**建单/追加之前**精确过滤:
|
||||
* · group 的 `main_order_code` 命中 order 墓碑 ⇒ 整组跳过(不建订单/行,返回 skipped_tombstoned);
|
||||
* · prep 行 `prep_id` 命中 prep 墓碑 ⇒ 该行不追加、不建行(台账 disposition 保持阻断)。
|
||||
* 键精确到业务键,绝不按 branch/日期放宽(否则会误杀正常导入)。
|
||||
*/
|
||||
export async function filterTombstonedGroups(
|
||||
branchCode: string,
|
||||
groups: MainOrderGroup[]
|
||||
): Promise<{ groups: MainOrderGroup[]; skipped: ImportedOrderResult[] }> {
|
||||
if (!groups.length) return { groups, skipped: [] };
|
||||
const orderKeys = groups.map((group) => String(group.orderCode || '').trim()).filter(Boolean);
|
||||
const prepKeys = groups
|
||||
.flatMap((group) => group.rows.map((row) => String(row.id || '').trim()))
|
||||
.filter(Boolean);
|
||||
let orderBlocked: Set<string>;
|
||||
let prepAll: Set<string>;
|
||||
try {
|
||||
[orderBlocked, prepAll] = await Promise.all([
|
||||
listReverseTombstoneKeys({ branchCode, kind: 'order', keys: orderKeys }),
|
||||
listReverseTombstoneKeys({ branchCode, kind: 'prep', keys: prepKeys }),
|
||||
]);
|
||||
} catch (error) {
|
||||
// 墓碑查询失败不应阻断正常导入(宁可照旧导入,也不因新表缺失把主系统单全挂掉)
|
||||
console.error(
|
||||
`[main-system-import] 墓碑查询失败(本轮不过滤)${branchCode}:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
return { groups, skipped: [] };
|
||||
}
|
||||
if (!orderBlocked.size && !prepAll.size) return { groups, skipped: [] };
|
||||
|
||||
/**
|
||||
* prep 墓碑(2026-10-19 红队攻破 1):按 reason 区分语义 ——
|
||||
* · `reallocated`(改派走)**不阻断**:E1 重新分配到同一 prep_id 时解除墓碑并放行;
|
||||
* · 其余(`item_removed`/`deleted`…)硬删语义,继续阻断。
|
||||
* 只对命中的 prep 键查 reason(查询失败按"全部阻断"保守处理)。
|
||||
*/
|
||||
let reallocatedTombstones = new Set<string>();
|
||||
if (prepAll.size) {
|
||||
try {
|
||||
reallocatedTombstones = await listReallocatedReverseTombstones({
|
||||
branchCode,
|
||||
keys: [...prepAll],
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`[main-system-import] 改派墓碑 reason 查询失败(本轮按阻断处理)${branchCode}:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
}
|
||||
const prepBlocked = new Set([...prepAll].filter((key) => !reallocatedTombstones.has(key)));
|
||||
|
||||
const kept: MainOrderGroup[] = [];
|
||||
const skipped: ImportedOrderResult[] = [];
|
||||
for (const group of groups) {
|
||||
const mainOrderCode = String(group.orderCode || '').trim();
|
||||
if (mainOrderCode && orderBlocked.has(mainOrderCode)) {
|
||||
skipped.push({
|
||||
mainOrderCode,
|
||||
ourOrderCode: null,
|
||||
itemCount: group.rows.length,
|
||||
status: 'skipped_tombstoned',
|
||||
message: '主系统已删除该订单(反向事件墓碑),跳过建单/追加',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const rows: typeof group.rows = [];
|
||||
for (const row of group.rows) {
|
||||
const key = String(row.id || '').trim().toLowerCase();
|
||||
if (prepBlocked.has(key)) continue;
|
||||
if (reallocatedTombstones.has(key)) {
|
||||
/**
|
||||
* 改派是往返的:E1 把同一 prep_id 重新分配回来 ⇒ 解除墓碑、放行并允许台账复活为 imported。
|
||||
* ⚠️ A2(TOCTOU):读到的是 reallocated,但并发 item_removed 可能已把墓碑升级为硬删——
|
||||
* `clearReverseTombstone` 带 reason='reallocated' 守卫,**只有真的删掉 1 行才放行**;
|
||||
* 0 行说明已被硬删覆盖 ⇒ 按 blocked 处理,绝不放行导入。
|
||||
*/
|
||||
try {
|
||||
const cleared = await clearReverseTombstone({ branchCode, kind: 'prep', businessKey: key });
|
||||
if (cleared === 1) {
|
||||
console.info(
|
||||
`[main-system-import] ${branchCode} prep ${key} 改派墓碑解除(主系统重新分配回来),按新行导入`
|
||||
);
|
||||
rows.push(row);
|
||||
} else {
|
||||
console.warn(
|
||||
`[main-system-import] ${branchCode} prep ${key} 墓碑在读取后被升级为硬删(clear=0),按阻断处理`
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
// 解除失败时保守按阻断处理(宁可少建一行,也不把已删行建回来)
|
||||
console.error(
|
||||
`[main-system-import] ${branchCode} 解除 prep ${key} 改派墓碑失败(按阻断处理):`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
rows.push(row);
|
||||
}
|
||||
if (rows.length === group.rows.length) {
|
||||
kept.push(group);
|
||||
continue;
|
||||
}
|
||||
const dropped = group.rows.length - rows.length;
|
||||
if (!rows.length) {
|
||||
skipped.push({
|
||||
mainOrderCode,
|
||||
ourOrderCode: null,
|
||||
itemCount: group.rows.length,
|
||||
status: 'skipped_tombstoned',
|
||||
message: `该主系统单的备货行已全部删除(墓碑 ${dropped} 行),跳过导入`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
console.info(
|
||||
`[main-system-import] ${branchCode} 主系统单 ${mainOrderCode}:${dropped} 行命中墓碑,跳过这些行`
|
||||
);
|
||||
kept.push({ ...group, rows });
|
||||
}
|
||||
return { groups: kept, skipped };
|
||||
}
|
||||
|
||||
export async function importMainSystemGroups(params: {
|
||||
branchCode: string;
|
||||
userId: string | null;
|
||||
@@ -1548,8 +1749,9 @@ async function importMainSystemGroupsInTenant(params: {
|
||||
groups: MainOrderGroup[];
|
||||
}): Promise<{ created: number; appended: number; skipped: number; failed: number; results: ImportedOrderResult[] }> {
|
||||
const { branchCode, userId, supplierCode, groups } = params;
|
||||
const buckets = bucketGroupsByDeliveryDate(groups);
|
||||
const results: ImportedOrderResult[] = [];
|
||||
const filtered = await filterTombstonedGroups(branchCode, groups);
|
||||
const buckets = bucketGroupsByDeliveryDate(filtered.groups);
|
||||
const results: ImportedOrderResult[] = [...filtered.skipped];
|
||||
for (const bucket of buckets) {
|
||||
results.push(
|
||||
...(await importDayBucket({ branchCode, userId, supplierCode, bucket, ledgerByOrder: new Map() }))
|
||||
@@ -1941,7 +2143,7 @@ function summarizeResults(results: ImportedOrderResult[]) {
|
||||
return {
|
||||
created: results.filter((r) => r.status === 'created').length,
|
||||
appended: results.filter((r) => r.status === 'appended').length,
|
||||
skipped: results.filter((r) => r.status === 'skipped').length,
|
||||
skipped: results.filter((r) => r.status === 'skipped' || r.status === 'skipped_tombstoned').length,
|
||||
failed: results.filter((r) => r.status === 'failed').length,
|
||||
results,
|
||||
};
|
||||
@@ -2492,7 +2694,10 @@ async function importMainSystemOrdersInTenant(params: {
|
||||
const wanted = onlyMainOrderCodes?.length ? new Set(onlyMainOrderCodes) : null;
|
||||
const groups = wanted ? outcome.orders.filter((group) => wanted.has(group.orderCode)) : outcome.orders;
|
||||
|
||||
for (const bucket of bucketGroupsByDeliveryDate(groups)) {
|
||||
// BIZ-6:命中反向事件墓碑的组/行不导入(先于建单/追加过滤)
|
||||
const filteredGroups = await filterTombstonedGroups(branchCode, groups);
|
||||
results.push(...filteredGroups.skipped);
|
||||
for (const bucket of bucketGroupsByDeliveryDate(filteredGroups.groups)) {
|
||||
results.push(
|
||||
...(await importDayBucket({
|
||||
branchCode,
|
||||
|
||||
@@ -19,6 +19,14 @@ export type PrepLedgerDisposition =
|
||||
| 'returned'
|
||||
| 'cancelled'
|
||||
| 'suspended'
|
||||
/**
|
||||
* 主系统**改派走**(`preparations.reallocated`,2026-10-19 T2/BIZ-9):与 `removed` 区分开,
|
||||
* 因为改派是往返的(A→他人→A)——同一 `prep_id` 再次分配回来时允许复活为 `imported`;
|
||||
* 而 `removed`(主系统删商品行)是硬删除语义,再出现也要继续阻断。
|
||||
*/
|
||||
| 'reallocated'
|
||||
/** 主系统**删商品行**(`preparations.item_removed`):硬删语义,同 prep_id 再出现也阻断 */
|
||||
| 'removed'
|
||||
/** 主系统标了缺货:本系统没建对应订单行,无需回写/跟随 */
|
||||
| 'skipped_stockout';
|
||||
|
||||
@@ -170,6 +178,8 @@ export async function healOrderPrepMapping(params: {
|
||||
`SELECT id::text AS id, item_name, quantity, main_order_code
|
||||
FROM order_items
|
||||
WHERE order_code = $1
|
||||
AND COALESCE(is_returned, false) = false
|
||||
AND COALESCE(is_extra_dish, false) = false
|
||||
ORDER BY sort_order NULLS LAST, created_at, id`,
|
||||
[orderCode]
|
||||
)
|
||||
@@ -319,7 +329,24 @@ export async function recordImportedPrepItems(params: {
|
||||
ON CONFLICT (branch_code, prep_id) DO UPDATE
|
||||
SET our_order_code = EXCLUDED.our_order_code,
|
||||
-- ⚠️ 已建立的对照**优先保留**:重算映射可能因"另一行已被占用"而变化,覆盖会把行配错
|
||||
our_order_item_id = COALESCE(public.main_system_order_import_items.our_order_item_id, EXCLUDED.our_order_item_id),
|
||||
-- 例外(BIZ-9,2026-10-19):'reallocated'(改派走)的旧对照指向的行已被移除,
|
||||
-- 主系统重新分配回同一 prep_id 时必须用本次映射覆盖,否则永远指向不存在的行。
|
||||
our_order_item_id = CASE
|
||||
-- B-A3/B-A4(2026-10-19):硬终态台账**强制 NULL**,即使 EXCLUDED 带了映射也不挂回活行
|
||||
--(否则重复 item_removed 会拿这个指针删掉活行);
|
||||
-- suspended/completed 属"保留指针"档,不得强制 NULL(否则 follow 会删错行)。
|
||||
WHEN LOWER(TRIM(COALESCE(public.main_system_order_import_items.disposition, '')))
|
||||
IN ('removed', 'returned', 'cancelled')
|
||||
THEN NULL
|
||||
-- RELATED-1:保留档(suspended/completed)在无指针时不得用本次映射填空(保持 NULL)
|
||||
WHEN LOWER(TRIM(COALESCE(public.main_system_order_import_items.disposition, '')))
|
||||
IN ('suspended', 'completed')
|
||||
AND public.main_system_order_import_items.our_order_item_id IS NULL
|
||||
THEN NULL
|
||||
WHEN public.main_system_order_import_items.disposition = 'reallocated'
|
||||
THEN EXCLUDED.our_order_item_id
|
||||
ELSE COALESCE(public.main_system_order_import_items.our_order_item_id, EXCLUDED.our_order_item_id)
|
||||
END,
|
||||
item_name = EXCLUDED.item_name,
|
||||
main_sku_code = COALESCE(EXCLUDED.main_sku_code, public.main_system_order_import_items.main_sku_code),
|
||||
last_prepare_qty = EXCLUDED.last_prepare_qty,
|
||||
@@ -332,6 +359,11 @@ export async function recordImportedPrepItems(params: {
|
||||
WHEN public.main_system_order_import_items.disposition = 'skipped_stockout'
|
||||
AND EXCLUDED.our_order_item_id IS NOT NULL
|
||||
THEN EXCLUDED.disposition
|
||||
-- BIZ-9(2026-10-19):改派往返 A→他人→A。'reallocated' 且本次真配到订单行 ⇒ 复位 imported;
|
||||
-- 配不上就保持 reallocated(下一轮继续重试)。'removed' 是硬删语义,不在此列(保持阻断)。
|
||||
WHEN public.main_system_order_import_items.disposition = 'reallocated'
|
||||
AND EXCLUDED.our_order_item_id IS NOT NULL
|
||||
THEN EXCLUDED.disposition
|
||||
ELSE public.main_system_order_import_items.disposition
|
||||
END,
|
||||
payload = EXCLUDED.payload,
|
||||
@@ -502,9 +534,32 @@ export async function markPrepDisposition(params: {
|
||||
/** 传入事务连接时与调用方同事务(删明细必须和处置一起提交) */
|
||||
client?: { query: (sql: string, values?: unknown[]) => Promise<unknown> };
|
||||
}): Promise<void> {
|
||||
/**
|
||||
* B2(2026-10-19 终局复攻):处置**按优先级合并** —— `reallocated` 不得把硬删
|
||||
* (`removed`/`cancelled`/…)降级(否则 needsAppend 会重建已删行);
|
||||
* 反过来 `removed` 可以覆盖 `reallocated`(升级)。`disposed_at` 保留首次处置时间。
|
||||
*/
|
||||
await (params.client || pool).query(
|
||||
`UPDATE public.main_system_order_import_items
|
||||
SET disposition = $3, disposition_reason = $4, disposed_at = NOW(), updated_at = NOW()
|
||||
SET disposition = CASE
|
||||
WHEN $3::text = 'reallocated'
|
||||
AND LOWER(TRIM(COALESCE(disposition, ''))) IN ('removed', 'cancelled', 'returned', 'completed', 'suspended')
|
||||
THEN disposition
|
||||
ELSE $3
|
||||
END,
|
||||
disposition_reason = CASE
|
||||
WHEN $3::text = 'reallocated'
|
||||
AND LOWER(TRIM(COALESCE(disposition, ''))) IN ('removed', 'cancelled', 'returned', 'completed', 'suspended')
|
||||
THEN disposition_reason
|
||||
ELSE $4
|
||||
END,
|
||||
disposed_at = CASE
|
||||
WHEN $3::text = 'reallocated'
|
||||
AND LOWER(TRIM(COALESCE(disposition, ''))) IN ('removed', 'cancelled', 'returned', 'completed', 'suspended')
|
||||
THEN COALESCE(disposed_at, NOW())
|
||||
ELSE NOW()
|
||||
END,
|
||||
updated_at = NOW()
|
||||
WHERE branch_code = $1 AND prep_id = $2::uuid`,
|
||||
[params.branchCode, params.prepId, params.disposition, params.reason ?? null]
|
||||
);
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
setOurOrderItemId,
|
||||
touchLastSeenActiveAt,
|
||||
updatePrepSnapshot,
|
||||
mapPrepRowsToOurItems,
|
||||
type PrepLedgerRow,
|
||||
} from './mainSystemPrepLedger';
|
||||
import { runWithTenantDbContext } from './tenantDbContext';
|
||||
@@ -169,7 +168,7 @@ async function loadItemFacts(branchCode: string, orderCode: string, itemId: stri
|
||||
* 用整单台账里存的 payload 快照补录行级对照。幂等(upsert),只补对照不改业务数据。
|
||||
* @returns 本次补录的行数
|
||||
*/
|
||||
async function repairMissingPrepLedgerRows(branchCode: string): Promise<number> {
|
||||
export async function repairMissingPrepLedgerRows(branchCode: string): Promise<number> {
|
||||
const missing = await pool.query<{
|
||||
main_order_code: string;
|
||||
our_order_code: string;
|
||||
@@ -202,22 +201,123 @@ async function repairMissingPrepLedgerRows(branchCode: string): Promise<number>
|
||||
typeof recordImportedPrepItems
|
||||
>[0]['prepRows'];
|
||||
if (!prepRows.length) continue;
|
||||
const ourItems = await runWithTenantDbContext(branchCode, async () =>
|
||||
pool.query<{ id: string; item_name: string | null }>(
|
||||
`SELECT id::text AS id, item_name
|
||||
FROM order_items
|
||||
WHERE order_code = $1
|
||||
ORDER BY sort_order NULLS LAST, created_at, id`,
|
||||
[row.our_order_code]
|
||||
// 2026-10-19 T2 攻破 B:候选必须排除已退货/加菜行,否则 reallocated 复活会把对照
|
||||
// 复位到退役旧行(同名旧行排前,台账 imported 却指向已退货行,之后删行 already_returned)。
|
||||
const { loadMappingCandidateOrderItems } = await import('./mainSystemOrderImport');
|
||||
const { mapOrderPrepRowsToOurItems } = await import('./mainSystemPrepLedger');
|
||||
const prepIds = prepRows.map((prep) => String(prep.id));
|
||||
/**
|
||||
* R4(2026-10-19 终局复攻):同单重复认领。
|
||||
* 候选**排除所有已被台账占用的订单行**(`excludePrepIds: []` ⇒ 全部 claimed 行都排除),
|
||||
* 本 payload 里已建立对照的 prep(P1→R2)不再参与重新映射(固定保留),
|
||||
* 缺行(P2)只能从剩余未占用行里按同名映射 —— 候选不足就保持 pending,绝不硬塞。
|
||||
*/
|
||||
/**
|
||||
* B-A3/B-A4(2026-10-19 终局复攻):repair 按 disposition 分三档处理 ——
|
||||
* ① `removed/returned/cancelled`:硬终态,强制 `our_order_item_id=NULL`,不参与映射;
|
||||
* ② `suspended/completed`:**保留已有有效指针**、不参与重新映射(无效指针则清 NULL,不猜);
|
||||
* ③ `imported/pending/reallocated/skipped_stockout`(或无台账的新行):可复活,参与预清 + 映射。
|
||||
* 若把 suspended 当硬终态清指针,follow 的惰性重配会让别的行抢走它的订单行、随后删错行。
|
||||
*/
|
||||
const REVIVABLE_DISPOSITIONS = new Set(['imported', 'pending', 'reallocated', 'skipped_stockout']);
|
||||
const revivableSql = `LOWER(TRIM(COALESCE(li.disposition, ''))) IN ('imported', 'pending', 'reallocated', 'skipped_stockout')`;
|
||||
const hardSql = `LOWER(TRIM(COALESCE(li.disposition, ''))) IN ('removed', 'returned', 'cancelled')`;
|
||||
const preserveSql = `LOWER(TRIM(COALESCE(li.disposition, ''))) IN ('suspended', 'completed')`;
|
||||
const invalidLinkSql = `NOT EXISTS (
|
||||
SELECT 1 FROM order_items oi
|
||||
WHERE oi.id = li.our_order_item_id
|
||||
AND oi.order_code = $3
|
||||
AND COALESCE(oi.is_returned, false) = false
|
||||
AND COALESCE(oi.is_extra_dish, false) = false
|
||||
)`;
|
||||
const clearLinks = async (condition: string, params: unknown[]) =>
|
||||
runWithTenantDbContext(branchCode, async () =>
|
||||
pool.query(
|
||||
`UPDATE public.main_system_order_import_items li
|
||||
SET our_order_item_id = NULL, updated_at = NOW()
|
||||
WHERE li.branch_code = $1
|
||||
AND li.prep_id = ANY($2::uuid[])
|
||||
AND li.our_order_item_id IS NOT NULL
|
||||
AND ${condition}`,
|
||||
params
|
||||
)
|
||||
);
|
||||
// ① 硬终态:无条件清空指针(即使它当前指向一个"活行"也不允许再被使用)
|
||||
await clearLinks(hardSql, [branchCode, prepIds]);
|
||||
// ② 保留档:有效指针不动;指向已退货/加菜/不存在行的坏指针清 NULL,但不重新映射
|
||||
await clearLinks(`${preserveSql} AND ${invalidLinkSql}`, [branchCode, prepIds, row.our_order_code]);
|
||||
// ③ 可复活档:清掉历史坏对照,随后按一对一重新映射
|
||||
await clearLinks(`${revivableSql} AND ${invalidLinkSql}`, [branchCode, prepIds, row.our_order_code]);
|
||||
// 本 payload 各 prep 的 disposition(用于把硬终态/保留档排除出映射;无台账行=新行,可参与)
|
||||
const ledgerStates = await runWithTenantDbContext(branchCode, async () =>
|
||||
pool.query<{ prep_id: string; disposition: string | null }>(
|
||||
`SELECT li.prep_id::text AS prep_id, li.disposition
|
||||
FROM public.main_system_order_import_items li
|
||||
-- GAP-1:保留档判定只按 (branch_code, prep_id),purge 产物 our_order_code=NULL 也认
|
||||
WHERE li.branch_code = $1 AND li.prep_id = ANY($2::uuid[])`,
|
||||
[branchCode, prepIds]
|
||||
)
|
||||
);
|
||||
const dispositionByPrep = new Map(
|
||||
ledgerStates.rows.map((state) => [String(state.prep_id), String(state.disposition || '').trim().toLowerCase()])
|
||||
);
|
||||
const linkedRows = await runWithTenantDbContext(branchCode, async () =>
|
||||
pool.query<{ prep_id: string; our_order_item_id: string }>(
|
||||
`SELECT li.prep_id::text AS prep_id, li.our_order_item_id::text AS our_order_item_id
|
||||
FROM public.main_system_order_import_items li
|
||||
JOIN order_items oi ON oi.id = li.our_order_item_id AND oi.order_code = $2
|
||||
WHERE li.branch_code = $1
|
||||
AND li.our_order_item_id IS NOT NULL
|
||||
AND li.prep_id = ANY($3::uuid[])
|
||||
-- 已改派/硬终态/已退货/加菜行不能作为"固定保留"的对照(否则会把 imported 复位到退役行);
|
||||
-- B-A4:suspended/completed 的有效对照必须原样保留(不参与重新映射,也不许被清)
|
||||
AND LOWER(TRIM(COALESCE(li.disposition, '')))
|
||||
IN ('imported', 'pending', 'skipped_stockout', 'suspended', 'completed')
|
||||
AND COALESCE(oi.is_returned, false) = false
|
||||
AND COALESCE(oi.is_extra_dish, false) = false`,
|
||||
[branchCode, row.our_order_code, prepIds]
|
||||
)
|
||||
);
|
||||
const fixedMapping = new Map<string, string>(
|
||||
linkedRows.rows.map((linked) => [String(linked.prep_id), String(linked.our_order_item_id)])
|
||||
);
|
||||
const ourItems = await runWithTenantDbContext(branchCode, async () =>
|
||||
loadMappingCandidateOrderItems(
|
||||
{ query: (sql: string, params?: unknown[]) => pool.query(sql, params) },
|
||||
String(row.our_order_code),
|
||||
// 排除所有已被其它备货行占用的订单行(含本 payload 里 P1 的 R2);P1 用 fixedMapping 保留
|
||||
{ branchCode, excludePrepIds: [] }
|
||||
)
|
||||
);
|
||||
/**
|
||||
* 只处理"新行/可复活"备货行;**保留档(suspended/completed)整行跳过**:
|
||||
* 不重算映射、也不 upsert(避免把 purge 出来的 `our_order_code=NULL` 写回、把有效指针改掉)。
|
||||
*/
|
||||
const prepRowsToRecord = prepRows.filter((prep) => {
|
||||
const disposition = dispositionByPrep.get(String(prep.id));
|
||||
return disposition === undefined || REVIVABLE_DISPOSITIONS.has(disposition);
|
||||
});
|
||||
if (!prepRowsToRecord.length) continue;
|
||||
const unlinkedRows = prepRowsToRecord.filter((prep) => {
|
||||
const prepId = String(prep.id);
|
||||
if (fixedMapping.has(prepId)) return false;
|
||||
const disposition = dispositionByPrep.get(prepId);
|
||||
return disposition === undefined || REVIVABLE_DISPOSITIONS.has(disposition);
|
||||
});
|
||||
const computedMapping = mapOrderPrepRowsToOurItems(
|
||||
[{ orderCode: row.main_order_code, rows: unlinkedRows }],
|
||||
ourItems
|
||||
);
|
||||
// 一对一对照:已 linked 的原样保留 + 缺行只从剩余未占用行里配(配不上 → pending)
|
||||
const mapping = new Map<string, string>([...fixedMapping, ...computedMapping]);
|
||||
written += await recordImportedPrepItems({
|
||||
branchCode,
|
||||
mainOrderCode: row.main_order_code,
|
||||
supplierCode: row.main_supplier_code,
|
||||
ourOrderCode: row.our_order_code,
|
||||
prepRows,
|
||||
ourItems: ourItems.rows,
|
||||
prepRows: prepRowsToRecord,
|
||||
ourItems,
|
||||
mapping,
|
||||
});
|
||||
}
|
||||
return written;
|
||||
@@ -524,7 +624,7 @@ async function followMainSystemPrepChangesLocked(
|
||||
* 若把已退货行排除掉,这种行会被误判成"未记录到对应订单行"而**永久挂起**。
|
||||
* 同名多行时优先取未退货的那条(`ORDER BY is_returned`)。
|
||||
*/
|
||||
async function resolveOurItemIdByName(
|
||||
export async function resolveOurItemIdByName(
|
||||
branchCode: string,
|
||||
orderCode: string,
|
||||
itemName: string,
|
||||
@@ -543,12 +643,19 @@ async function resolveOurItemIdByName(
|
||||
`SELECT id::text AS id, item_name
|
||||
FROM order_items
|
||||
WHERE order_code = $1
|
||||
-- GAP-2:加菜行不是备货行对应的订单行,不能作为惰性对照目标
|
||||
AND COALESCE(is_extra_dish, false) = false
|
||||
ORDER BY COALESCE(is_returned, false), sort_order NULLS LAST, created_at, id`,
|
||||
[orderCode]
|
||||
);
|
||||
const available = result.rows.filter((item) => !claimed.has(String(item.id)));
|
||||
const mapping = mapPrepRowsToOurItems([{ id: 'probe', itemName: name }], available);
|
||||
return mapping.get('probe') ?? '';
|
||||
/**
|
||||
* GAP-2:惰性对照**只承认唯一同名命中**。同名多行/无命中时宁可不配(下游挂 suspended/人工核对),
|
||||
* 也不能按出现次序猜一行然后硬删别人的行。
|
||||
*/
|
||||
const sameName = available.filter((item) => String(item.item_name ?? '').trim() === name);
|
||||
if (sameName.length !== 1) return '';
|
||||
return String(sameName[0].id);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -29,6 +29,160 @@ export function isReverseOrderEvent(event: unknown): boolean {
|
||||
return name === REALLOCATED_EVENT || name === ITEM_REMOVED_EVENT || name === ORDER_CANCELLED_EVENT;
|
||||
}
|
||||
|
||||
/* ── BIZ-6:未知业务键墓碑(2026-10-19)────────────────────────────────────
|
||||
*
|
||||
* 反向事件可能**先于 E1** 到达;未知 prep_id/订单时先落一条持久墓碑,
|
||||
* E1 之后到达时导入侧命中墓碑即跳过(不建单/不建行),避免"已删的行被建回来"。
|
||||
* 键精确到 `prep_id`(小写)/ `main_order_code`,绝不按 branch/日期放宽。
|
||||
* 表为 public 平台台账(见 migrations/20261059_main_system_reverse_tombstones.sql),
|
||||
* 不进 tenant_business_tables()。可清理:`purgeReverseTombstones(days)`(不接定时任务)。
|
||||
*/
|
||||
export type ReverseTombstoneKind = 'prep' | 'order';
|
||||
|
||||
const REVERSE_TOMBSTONE_TABLE = 'public.main_system_reverse_tombstones';
|
||||
|
||||
function normalizeTombstoneKey(kind: ReverseTombstoneKind, key: unknown): string {
|
||||
const text = String(key ?? '').trim();
|
||||
return kind === 'prep' ? text.toLowerCase() : text;
|
||||
}
|
||||
|
||||
/**
|
||||
* 墓碑 reason 的**硬删语义** SQL 片段(`item_removed`/`deleted`/`removed`)。
|
||||
* 这些原因优先级最高:同 business_key 先 `reallocated` 后 `item_removed` 时,
|
||||
* 墓碑必须升级为硬删,绝不能停在 reallocated 被后续导入放行(2026-10-19 T2 攻破 A)。
|
||||
*/
|
||||
const HARD_DELETE_REASON_SQL_EXCLUDED = `LOWER(TRIM(COALESCE(EXCLUDED.reason, ''))) IN ('item_removed', 'deleted', 'removed')`;
|
||||
const HARD_DELETE_REASON_SQL_STORED = `LOWER(TRIM(COALESCE(${REVERSE_TOMBSTONE_TABLE}.reason, ''))) IN ('item_removed', 'deleted', 'removed')`;
|
||||
|
||||
/**
|
||||
* 落墓碑(幂等 + **reason 按优先级合并**,2026-10-19 T2 攻破 A)。
|
||||
*
|
||||
* 同一 `(branch, kind, business_key)` 重复投递时:
|
||||
* · 新 reason 是硬删类 ⇒ 覆盖(`reallocated` → `item_removed` 必须升级);
|
||||
* · 已存 reason 是硬删类 ⇒ 保留(硬删语义不能被后到的 `reallocated` 降级);
|
||||
* · 其余(reallocated ↔ 其它 / 仅 payload 变化)⇒ 以最新一次为准。
|
||||
* `kind`/`business_key` 不变;`created_at` 保留首次写入时间。
|
||||
* `updated_at`:表无该列(迁移未加,避免与迁移写者冲突),本轮不更新。
|
||||
*/
|
||||
export async function recordReverseTombstone(input: {
|
||||
branchCode: string;
|
||||
kind: ReverseTombstoneKind;
|
||||
businessKey: string;
|
||||
reason?: string | null;
|
||||
payload?: Record<string, unknown> | null;
|
||||
}): Promise<void> {
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
const businessKey = normalizeTombstoneKey(input.kind, input.businessKey);
|
||||
// A1(2026-10-19 终局复攻):reason 先 trim 再入库/比较,' item_removed ' 也必须是硬删
|
||||
const reason = input.reason === null || input.reason === undefined ? null : String(input.reason).trim() || null;
|
||||
if (!branchCode || !businessKey) return;
|
||||
await pool.query(
|
||||
`INSERT INTO ${REVERSE_TOMBSTONE_TABLE}
|
||||
(branch_code, kind, business_key, reason, payload, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5::jsonb, NOW())
|
||||
ON CONFLICT (branch_code, kind, business_key) DO UPDATE
|
||||
SET reason = CASE
|
||||
WHEN ${HARD_DELETE_REASON_SQL_EXCLUDED} THEN EXCLUDED.reason
|
||||
WHEN ${HARD_DELETE_REASON_SQL_STORED} THEN ${REVERSE_TOMBSTONE_TABLE}.reason
|
||||
WHEN EXCLUDED.reason IS NOT NULL THEN EXCLUDED.reason
|
||||
ELSE ${REVERSE_TOMBSTONE_TABLE}.reason
|
||||
END,
|
||||
payload = CASE
|
||||
WHEN ${HARD_DELETE_REASON_SQL_EXCLUDED} THEN EXCLUDED.payload
|
||||
WHEN ${HARD_DELETE_REASON_SQL_STORED} THEN ${REVERSE_TOMBSTONE_TABLE}.payload
|
||||
WHEN EXCLUDED.reason IS NOT NULL THEN EXCLUDED.payload
|
||||
ELSE ${REVERSE_TOMBSTONE_TABLE}.payload
|
||||
END`,
|
||||
[branchCode, input.kind, businessKey, reason, JSON.stringify(input.payload ?? {})]
|
||||
);
|
||||
}
|
||||
|
||||
/** 批量查墓碑键集合(导入侧过滤用;返回的 prep 键均为小写) */
|
||||
export async function listReverseTombstoneKeys(input: {
|
||||
branchCode: string;
|
||||
kind: ReverseTombstoneKind;
|
||||
keys: string[];
|
||||
}): Promise<Set<string>> {
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
const keys = [
|
||||
...new Set((input.keys || []).map((key) => normalizeTombstoneKey(input.kind, key)).filter(Boolean)),
|
||||
];
|
||||
if (!branchCode || !keys.length) return new Set();
|
||||
const result = await pool.query<{ business_key: string }>(
|
||||
`SELECT business_key FROM ${REVERSE_TOMBSTONE_TABLE}
|
||||
WHERE branch_code = $1 AND kind = $2 AND business_key = ANY($3::text[])`,
|
||||
[branchCode, input.kind, keys]
|
||||
);
|
||||
return new Set(result.rows.map((row) => String(row.business_key)));
|
||||
}
|
||||
|
||||
/**
|
||||
* **改派墓碑**(`reason='reallocated'`)键集合(2026-10-19 T2 红队攻破 1 修复)。
|
||||
*
|
||||
* 改派是往返的(A→他人→A):这类墓碑**不阻断**导入,E1 把同一 prep_id 重新分配回来时
|
||||
* 还要删除墓碑、允许台账复活为 `imported`。只有 `item_removed`/`deleted` 等硬删语义继续阻断。
|
||||
* SQL 故意用独立形态(`business_key AS key` + reason 过滤),与 `listReverseTombstoneKeys`
|
||||
* 分开,便于旧调用/测试只钉"全部墓碑"语义时互不影响。
|
||||
*/
|
||||
export async function listReallocatedReverseTombstones(input: {
|
||||
branchCode: string;
|
||||
keys: string[];
|
||||
}): Promise<Set<string>> {
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
const keys = [
|
||||
...new Set((input.keys || []).map((key) => normalizeTombstoneKey('prep', key)).filter(Boolean)),
|
||||
];
|
||||
if (!branchCode || !keys.length) return new Set();
|
||||
const result = await pool.query<{ key: string }>(
|
||||
`SELECT business_key AS key FROM ${REVERSE_TOMBSTONE_TABLE}
|
||||
WHERE branch_code = $1 AND kind = 'prep' AND reason = 'reallocated'
|
||||
AND business_key = ANY($2::text[])`,
|
||||
[branchCode, keys]
|
||||
);
|
||||
return new Set(result.rows.map((row) => String(row.key)));
|
||||
}
|
||||
|
||||
/** 删除单条墓碑(E1 把改派走的 prep 重新分配回来时解除;幂等) */
|
||||
export async function clearReverseTombstone(input: {
|
||||
branchCode: string;
|
||||
kind: ReverseTombstoneKind;
|
||||
businessKey: string;
|
||||
}): Promise<number> {
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
const businessKey = normalizeTombstoneKey(input.kind, input.businessKey);
|
||||
if (!branchCode || !businessKey) return 0;
|
||||
/**
|
||||
* A2(2026-10-19 终局复攻,TOCTOU):只允许删除 **reallocated** 墓碑。
|
||||
* E1 读到时是 reallocated,但并发 item_removed 可能已把它升级为硬删 —— 这条 DELETE
|
||||
* 若不带 reason 守卫会误删硬删墓碑、放行导入。返回 rowCount,调用方只在 =1 时放行。
|
||||
*/
|
||||
const result = await pool.query(
|
||||
`DELETE FROM ${REVERSE_TOMBSTONE_TABLE}
|
||||
WHERE branch_code = $1 AND kind = $2 AND business_key = $3
|
||||
AND LOWER(TRIM(COALESCE(reason, ''))) = 'reallocated'`,
|
||||
[branchCode, input.kind, businessKey]
|
||||
);
|
||||
return result.rowCount || 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理墓碑(D6:只提供导出 + 单测,**不**接自动定时任务)。
|
||||
* `olderThanDays` 必须是非负数字;`null`/`undefined`/`NaN`/负值一律拒绝(**不做默认天数**),
|
||||
* 否则 `Number(null) === 0` 会被当成"删 0 天前"而清空全部历史墓碑(T2 红队顺手修,2026-10-19)。
|
||||
*/
|
||||
export async function purgeReverseTombstones(olderThanDays: number): Promise<number> {
|
||||
if (typeof olderThanDays !== 'number' || !Number.isFinite(olderThanDays) || olderThanDays < 0) {
|
||||
throw new Error('purgeReverseTombstones: olderThanDays 必须是非负数字(不接受 null/NaN/负数)');
|
||||
}
|
||||
const days = Math.floor(olderThanDays);
|
||||
const result = await pool.query(
|
||||
`DELETE FROM ${REVERSE_TOMBSTONE_TABLE}
|
||||
WHERE created_at < NOW() - make_interval(days => $1::int)`,
|
||||
[days]
|
||||
);
|
||||
return result.rowCount || 0;
|
||||
}
|
||||
|
||||
/** 我方订单行的定位结果(按 `prep_id` 反查行级台账,兼容台账缺失时按"主系统单 + 商品名"回退) */
|
||||
type LocalItemLink = { ourOrderCode: string; itemId: string | null };
|
||||
|
||||
@@ -78,28 +232,77 @@ export async function applyItemNoLongerOurs(input: {
|
||||
itemName: input.itemName ?? null,
|
||||
});
|
||||
if (!link) {
|
||||
// 未知 prep_id(E1 未到 / 不是我方的行)⇒ 幂等忽略,不报错、不建数据
|
||||
/**
|
||||
* 未知 prep_id(E1 未到 / 不是我方的行):落**持久墓碑**再幂等忽略 —— 等 E1 之后到达时
|
||||
* 导入侧命中墓碑会跳过该行,不能把已被删/改派的行建回来(BIZ-6)。
|
||||
* 墓碑写失败不改变返回(忽略仍是安全结论),只记日志。
|
||||
*/
|
||||
await recordReverseTombstone({
|
||||
branchCode,
|
||||
kind: 'prep',
|
||||
businessKey: prepId,
|
||||
reason: input.reason,
|
||||
payload: {
|
||||
main_order_code: input.mainOrderCode ?? null,
|
||||
item_name: input.itemName ?? null,
|
||||
sku_code: input.skuCode ?? null,
|
||||
},
|
||||
}).catch((error: unknown) => {
|
||||
console.error(
|
||||
`[main-system-reverse] 落 prep 墓碑失败(仍按 ignored 处理)${branchCode} ${prepId}:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
});
|
||||
return { status: 'ignored' };
|
||||
}
|
||||
|
||||
// 台账处置先落(与退货跟随同口径):下一轮导入不会把这一行重新加回来
|
||||
// 台账处置先落(与退货跟随同口径):下一轮导入不会把这一行重新加回来。
|
||||
// BIZ-9:改派与删行**分开记** —— `reallocated` 可复活(A→他人→A 往返),`removed` 是硬删。
|
||||
await markPrepDisposition({
|
||||
branchCode,
|
||||
prepId,
|
||||
disposition: 'cancelled',
|
||||
disposition: input.reason === 'reallocated' ? 'reallocated' : 'removed',
|
||||
reason: input.reason === 'reallocated' ? '主系统改派(不再归我方)' : '主系统删除商品行',
|
||||
});
|
||||
|
||||
if (!link.itemId) return { status: 'already_gone', ourOrderCode: link.ourOrderCode };
|
||||
|
||||
const { removeOrderItemForMainSystemReturn } = await import('./orderManageItemsService');
|
||||
const outcome = await runWithTenantDbContext(branchCode, async () =>
|
||||
removeOrderItemForMainSystemReturn({
|
||||
orderCode: link.ourOrderCode,
|
||||
branchCode,
|
||||
itemId: link.itemId!,
|
||||
})
|
||||
);
|
||||
let outcome: 'deleted' | 'returned' | 'already_returned';
|
||||
try {
|
||||
outcome = await runWithTenantDbContext(branchCode, async () =>
|
||||
removeOrderItemForMainSystemReturn({
|
||||
orderCode: link.ourOrderCode,
|
||||
branchCode,
|
||||
itemId: link.itemId!,
|
||||
})
|
||||
);
|
||||
} catch (error) {
|
||||
/**
|
||||
* B2(2026-10-19 终局复攻):重复投递 item_removed 时,台账仍指向**已被删掉**的行
|
||||
* ⇒ 移除函数 404。这类事件本质是幂等重复,不能抛 404 让路由 500:返回 already_gone。
|
||||
*/
|
||||
const status = Number((error as { status?: number })?.status);
|
||||
const code = String((error as { code?: string })?.code || '');
|
||||
if (status === 404 || code === 'not_found') {
|
||||
return { status: 'already_gone', ourOrderCode: link.ourOrderCode, itemId: link.itemId };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
/**
|
||||
* ⚠️ **删行/红冲后必须重算订单头**(与退货跟随同一口径,2026-10-12 真库事故):
|
||||
* 事件路径此前漏了这一步 ⇒ 行已移除,订单列表仍按旧 `total_amount` 显示。
|
||||
* 失败只记日志,不影响本次移除结论。
|
||||
*/
|
||||
try {
|
||||
const { recalcOrderHeaderTotals } = await import('./mainSystemStockout');
|
||||
await recalcOrderHeaderTotals({ branchCode, orderCode: link.ourOrderCode });
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`[main-system-reverse] 订单头重算失败(不影响移除结果)${link.ourOrderCode}:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
// 反向变更也要有站内通知(开发者 2026-10-18):删商品行 / 改派走
|
||||
try {
|
||||
const { notifyRoleUsers } = await import('./notificationService');
|
||||
@@ -129,7 +332,7 @@ export async function applyOrderCancelledByMainSystem(input: {
|
||||
branchCode: string;
|
||||
orderCode: string;
|
||||
reason?: string | null;
|
||||
}): Promise<{ status: 'ignored' | 'cancelled' | 'already' }> {
|
||||
}): Promise<{ status: 'ignored' | 'cancelled' | 'already' | 'skipped_completed' }> {
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
const orderCode = String(input.orderCode || '').trim();
|
||||
if (!branchCode || !orderCode) return { status: 'ignored' };
|
||||
@@ -150,7 +353,23 @@ export async function applyOrderCancelledByMainSystem(input: {
|
||||
const mainOrderCodes = mapped.rows.map((row) => String(row.main_order_code || '')).filter(Boolean);
|
||||
const ourOrderCodes = [...new Set(mapped.rows.map((row) => String(row.our_order_code || '')).filter(Boolean))];
|
||||
if (!mainOrderCodes.length || !ourOrderCodes.length) {
|
||||
// 不是主系统单(或尚未导入/没有对照)⇒ 与我方无关,幂等忽略
|
||||
/**
|
||||
* 不是主系统单(或尚未导入/没有对照)⇒ 与我方无关,幂等忽略;
|
||||
* 但先落 **order 墓碑**:等 E1 之后到达时,导入侧按 `main_order_code` 命中即整组跳过,
|
||||
* 不能把主系统已删除的单建回来(BIZ-6)。
|
||||
*/
|
||||
await recordReverseTombstone({
|
||||
branchCode,
|
||||
kind: 'order',
|
||||
businessKey: orderCode,
|
||||
reason: input.reason ?? null,
|
||||
payload: { event: ORDER_CANCELLED_EVENT },
|
||||
}).catch((error: unknown) => {
|
||||
console.error(
|
||||
`[main-system-reverse] 落 order 墓碑失败(仍按 ignored 处理)${branchCode} ${orderCode}:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
});
|
||||
return { status: 'ignored' };
|
||||
}
|
||||
|
||||
@@ -158,54 +377,242 @@ export async function applyOrderCancelledByMainSystem(input: {
|
||||
/** 本事件覆盖到的**我方**订单号(主系统一张单可能映射到多张/一张合并单) */
|
||||
const targetOrderCodes = ourOrderCodes;
|
||||
|
||||
/**
|
||||
* ⚠️ 合并单不是"删一张主系统单就删整张我方单"(设计 2026-10-12 §5 验收 #2):
|
||||
* 一天的多张主系统单会合并成一张我方单;主系统只删 A 时,B 的行必须原样保留,
|
||||
* 订单更不能被停用。旧实现按 `order_code = ANY(合并单)` 清全部行并软删整单 ⇒ B 被误删且永久不可再导入。
|
||||
*
|
||||
* 同时补上最高优先安全边界:我方订单**已完成(90)** + 主系统删整单 ⇒ 订单/明细/结算零改动,只留痕。
|
||||
*/
|
||||
const orderRows = await runWithTenantDbContext(branchCode, async () =>
|
||||
pool.query<{ order_code: string; order_status: number | null }>(
|
||||
`SELECT order_code, order_status FROM orders WHERE order_code = ANY($1::text[])`,
|
||||
[targetOrderCodes]
|
||||
)
|
||||
);
|
||||
const statusByOrder = new Map(
|
||||
orderRows.rows.map((row) => [String(row.order_code), Number(row.order_status) || 0] as const)
|
||||
);
|
||||
const completedOrderCodes = new Set(
|
||||
targetOrderCodes.filter((code) => (statusByOrder.get(code) || 0) >= 90)
|
||||
);
|
||||
/** 未完成的目标单才允许动明细/停用 */
|
||||
const activeOrderCodes = targetOrderCodes.filter((code) => !completedOrderCodes.has(code));
|
||||
|
||||
/**
|
||||
* **整单收口必须先清剩余行**(2026-10-18 真机 `ORD_WEB_20261018_BR002_0003`):
|
||||
* 删单事件到达时,行级跟随可能只处理了一部分(真机:一行已删、一行被标退货),
|
||||
* 旧实现只停用订单骨架 ⇒ 界面出现"订单还在、只剩半行"。
|
||||
* 这里复用与行级跟随**完全相同**的移除语义(红冲/释放/事务),再停用订单,保证两者不打架。
|
||||
* 这里复用与行级跟随**完全相同**的移除语义(红冲/释放/事务),但只移除**属于被取消主系统单**的行:
|
||||
* `order_items.main_order_code` 优先,存量行退回行级台账的 `our_order_item_id`;手加行(无来源)不动。
|
||||
*/
|
||||
try {
|
||||
const { removeOrderItemForMainSystemReturn } = await import('./orderManageItemsService');
|
||||
const remaining = await runWithTenantDbContext(branchCode, async () =>
|
||||
pool.query<{ id: string }>(
|
||||
`SELECT id, order_code FROM order_items
|
||||
WHERE order_code = ANY($1::text[]) AND COALESCE(is_returned, false) = false`,
|
||||
[targetOrderCodes]
|
||||
if (activeOrderCodes.length) {
|
||||
try {
|
||||
const { removeOrderItemForMainSystemReturn } = await import('./orderManageItemsService');
|
||||
const cancelledRows = await runWithTenantDbContext(branchCode, async () =>
|
||||
pool.query<{ id: string; order_code: string }>(
|
||||
`SELECT oi.id::text AS id, oi.order_code
|
||||
FROM order_items oi
|
||||
WHERE oi.order_code = ANY($1::text[])
|
||||
AND COALESCE(oi.is_returned, false) = false
|
||||
AND (
|
||||
oi.main_order_code = ANY($2::text[])
|
||||
OR oi.id IN (
|
||||
SELECT it.our_order_item_id
|
||||
FROM public.main_system_order_import_items it
|
||||
WHERE it.branch_code = $3
|
||||
AND it.main_order_code = ANY($2::text[])
|
||||
AND it.our_order_item_id IS NOT NULL
|
||||
)
|
||||
)`,
|
||||
[activeOrderCodes, mainOrderCodes, branchCode]
|
||||
)
|
||||
);
|
||||
for (const row of cancelledRows.rows) {
|
||||
await runWithTenantDbContext(branchCode, async () =>
|
||||
removeOrderItemForMainSystemReturn({
|
||||
orderCode: String(row.order_code || activeOrderCodes[0]),
|
||||
branchCode,
|
||||
itemId: String(row.id),
|
||||
})
|
||||
).catch((error) => {
|
||||
console.error(
|
||||
`[main-system-reverse] 整单作废时移除行失败(继续停用订单)${orderCode} ${row.id}:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`[main-system-reverse] 整单作废时清理剩余行失败(仍会停用订单)${orderCode}:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ⚠️ **删行/红冲后必须重算订单头**(与退货跟随同一口径,2026-10-12 真库事故):
|
||||
* 合并单只删 A 时订单仍在,若不重算,列表/详情仍按含 A 的旧 `total_amount` 显示。
|
||||
* 失败只记日志,不影响后续停用判定。
|
||||
*/
|
||||
if (activeOrderCodes.length) {
|
||||
try {
|
||||
const { recalcOrderHeaderTotals } = await import('./mainSystemStockout');
|
||||
for (const code of activeOrderCodes) {
|
||||
await recalcOrderHeaderTotals({ branchCode, orderCode: code });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`[main-system-reverse] 整单作废后订单头重算失败(不影响处理)${orderCode}:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停用判定(D5 策略 A,2026-10-19 T2/BIZ-8):
|
||||
* · 剩余 0 行 ⇒ 照旧停用(整单收口);
|
||||
* · 剩余行**全是 orphan** ⇒ 停用订单,但**保留 orphan 行原样**(不物理删、不红冲),
|
||||
* 写 `operation_logs` + 通知 admin/operator 人工确认,并清当日占坑指针;
|
||||
* · 剩余行里还有**有来源**的行(其它主系统单/台账指向)⇒ 保持当前"不停用"(合并单场景)。
|
||||
*
|
||||
* orphan 定义(AC-T2.2.1):`main_order_code` 为空/不属于被取消主系统单,且 `id` 不被
|
||||
* `main_system_order_import_items.our_order_item_id` 指向。
|
||||
* ⚠️ 关于"手加行"(2026-10-19 裁决):数据模型里手加行与 orphan **完全同形**
|
||||
* (都无 `main_order_code`、都无台账指向,没有任何可靠 marker 可区分)⇒ 无法按
|
||||
* AC-T2.2.2 原文把"手加行"单独留成 active。统一按策略 A 处理:订单停用但**行保留**、
|
||||
* 写 operation_logs + 通知 admin/operator「N 行无来源/手加行需人工确认」。
|
||||
* 这样既不物理删数据,也不会让无来源行永久阻止整单收口。
|
||||
*/
|
||||
let deletableOrderCodes: string[] = [];
|
||||
/** 策略 A:只剩 orphan 行而停用的订单 → orphan 行数(留痕/通知用) */
|
||||
const orphanRowCountByOrder = new Map<string, number>();
|
||||
if (activeOrderCodes.length) {
|
||||
const leftovers = await runWithTenantDbContext(branchCode, async () =>
|
||||
pool.query<{ order_code: string; n: number; sourced_n: number }>(
|
||||
`SELECT oi.order_code,
|
||||
COUNT(*)::int AS n,
|
||||
COUNT(*) FILTER (
|
||||
WHERE (oi.main_order_code IS NOT NULL AND NOT (oi.main_order_code = ANY($2::text[])))
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM public.main_system_order_import_items it
|
||||
WHERE it.branch_code = $3 AND it.our_order_item_id = oi.id
|
||||
)
|
||||
)::int AS sourced_n
|
||||
FROM order_items oi
|
||||
WHERE oi.order_code = ANY($1::text[]) AND COALESCE(oi.is_returned, false) = false
|
||||
GROUP BY oi.order_code`,
|
||||
[activeOrderCodes, mainOrderCodes, branchCode]
|
||||
)
|
||||
);
|
||||
for (const row of remaining.rows) {
|
||||
await runWithTenantDbContext(branchCode, async () =>
|
||||
removeOrderItemForMainSystemReturn({
|
||||
orderCode: String((row as { order_code?: string }).order_code || targetOrderCodes[0]),
|
||||
branchCode,
|
||||
itemId: String(row.id),
|
||||
})
|
||||
).catch((error) => {
|
||||
console.error(
|
||||
`[main-system-reverse] 整单作废时移除行失败(继续停用订单)${orderCode} ${row.id}:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
});
|
||||
const remainingByOrder = new Map(
|
||||
leftovers.rows.map((row) => [String(row.order_code), Number(row.n) || 0] as const)
|
||||
);
|
||||
const sourcedByOrder = new Map(
|
||||
leftovers.rows.map((row) => [String(row.order_code), Number(row.sourced_n) || 0] as const)
|
||||
);
|
||||
for (const code of activeOrderCodes) {
|
||||
const remaining = remainingByOrder.get(code) || 0;
|
||||
if (remaining === 0) {
|
||||
deletableOrderCodes.push(code);
|
||||
continue;
|
||||
}
|
||||
if ((sourcedByOrder.get(code) || 0) === 0) {
|
||||
deletableOrderCodes.push(code);
|
||||
orphanRowCountByOrder.set(code, remaining);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`[main-system-reverse] 整单作废时清理剩余行失败(仍会停用订单)${orderCode}:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
const updated = await runWithTenantDbContext(branchCode, async () => {
|
||||
return pool.query(
|
||||
`UPDATE orders
|
||||
SET deleted_at = COALESCE(deleted_at, NOW()),
|
||||
cancel_reason = $2,
|
||||
updated_at = NOW()
|
||||
WHERE order_code = ANY($1::text[]) AND deleted_at IS NULL`,
|
||||
[targetOrderCodes, `主系统作废:${reason}`]
|
||||
);
|
||||
});
|
||||
|
||||
// 台账:把它们置 cancelled,避免下一轮导入把这单又建回来
|
||||
let updatedRowCount = 0;
|
||||
if (deletableOrderCodes.length) {
|
||||
const updated = await runWithTenantDbContext(branchCode, async () => {
|
||||
return pool.query(
|
||||
`UPDATE orders
|
||||
SET deleted_at = COALESCE(deleted_at, NOW()),
|
||||
cancel_reason = $2,
|
||||
updated_at = NOW()
|
||||
WHERE order_code = ANY($1::text[]) AND deleted_at IS NULL`,
|
||||
[deletableOrderCodes, `主系统作废:${reason}`]
|
||||
);
|
||||
});
|
||||
updatedRowCount = updated.rowCount || 0;
|
||||
/**
|
||||
* 停用后必须清当日占坑指针,否则主系统下一批给同一天分配时,
|
||||
* `claimDayOrder` 会把它当成"订单已存在"⇒ 往垃圾桶里的单追加(`appendNewRowsToDayOrder`
|
||||
* 不筛 `deleted_at`)。与 `closeEmptyMirrorOrderIfNeeded` 的收口后处理同一口径。
|
||||
* 重复投递也执行(幂等),可顺带修掉历史残留指针。
|
||||
*/
|
||||
try {
|
||||
const { clearDayPointerIfPointsTo } = await import('./mirrorOrderClosureService');
|
||||
for (const code of deletableOrderCodes) {
|
||||
await clearDayPointerIfPointsTo(branchCode, code);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`[main-system-reverse] 清当日占坑指针失败(不影响停用)${orderCode}:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 策略 A 留痕 + 通知:停用订单但**保留**孤儿行(不物理删、不红冲)——必须让人知道
|
||||
* "有行无来源待确认",否则数据静默留在垃圾桶订单里没人处理。
|
||||
*/
|
||||
if (orphanRowCountByOrder.size) {
|
||||
try {
|
||||
const { writeAuditLog } = await import('./auditService');
|
||||
for (const [code, orphanCount] of orphanRowCountByOrder) {
|
||||
await writeAuditLog({
|
||||
operatorId: null,
|
||||
operatorRole: 'system',
|
||||
operationType: 'main_system_order_deleted_orphans_kept',
|
||||
targetTable: 'orders',
|
||||
targetId: code,
|
||||
oldValue: null,
|
||||
newValue: {
|
||||
main_order_code: orderCode,
|
||||
our_order_code: code,
|
||||
orphan_row_count: orphanCount,
|
||||
action: 'deleted_orphans_kept',
|
||||
reason,
|
||||
},
|
||||
branchCode,
|
||||
actionCategory: 'order',
|
||||
}).catch(() => undefined);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[main-system-reverse] orphan 行留痕失败(不影响停用):', (error as Error)?.message || error);
|
||||
}
|
||||
try {
|
||||
const { notifyRoleUsers } = await import('./notificationService');
|
||||
const entries = [...orphanRowCountByOrder.entries()];
|
||||
await notifyRoleUsers({
|
||||
roles: ['admin', 'operator'],
|
||||
notifyType: 'main_system_order_deleted_orphans_kept',
|
||||
title: '主系统删单:订单已停用,存在无来源/手加行商品行',
|
||||
content:
|
||||
entries.map(([code, n]) => `订单 ${code}:${n} 行无来源/手加行需人工确认`).join(';') +
|
||||
'。相关商品行已保留(未物理删除/未红冲),请人工核对处理。',
|
||||
relatedOrderCode: entries[0]?.[0] ?? null,
|
||||
branchCode,
|
||||
dedupWithinHours: 1,
|
||||
}).catch(() => undefined);
|
||||
} catch (error) {
|
||||
console.error('[main-system-reverse] orphan 行通知失败(不影响停用):', (error as Error)?.message || error);
|
||||
}
|
||||
}
|
||||
|
||||
// 台账:把它们置 cancelled,避免下一轮导入把这单又建回来;已完成订单按口径零改动。
|
||||
const completedMainOrderCodes = new Set(
|
||||
mapped.rows
|
||||
.filter((row) => completedOrderCodes.has(String(row.our_order_code || '')))
|
||||
.map((row) => String(row.main_order_code || ''))
|
||||
.filter(Boolean)
|
||||
);
|
||||
for (const mainOrderCode of mainOrderCodes) {
|
||||
if (completedMainOrderCodes.has(mainOrderCode)) continue;
|
||||
try {
|
||||
await pool.query(
|
||||
`UPDATE public.main_system_order_import_items
|
||||
@@ -221,15 +628,44 @@ export async function applyOrderCancelledByMainSystem(input: {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 已完成订单:只写审计留痕,不改订单/明细/结算(开发者 2026-10-12 安全边界,最高优先)。
|
||||
if (completedOrderCodes.size) {
|
||||
try {
|
||||
const { writeAuditLog } = await import('./auditService');
|
||||
for (const code of completedOrderCodes) {
|
||||
await writeAuditLog({
|
||||
operatorId: null,
|
||||
operatorRole: 'system',
|
||||
operationType: 'main_system_order_deleted_follow',
|
||||
targetTable: 'orders',
|
||||
targetId: code,
|
||||
oldValue: null,
|
||||
newValue: {
|
||||
main_order_code: orderCode,
|
||||
our_order_code: code,
|
||||
our_order_status: statusByOrder.get(code) ?? null,
|
||||
action: 'no_change_completed',
|
||||
reason: '主系统删除整单;本系统订单已完成,未做任何变更',
|
||||
},
|
||||
branchCode,
|
||||
actionCategory: 'order',
|
||||
}).catch(() => undefined);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[main-system-reverse] 已完成订单留痕失败(不影响处理):', (error as Error)?.message || error);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
if ((updated.rowCount || 0) > 0) {
|
||||
if (updatedRowCount > 0) {
|
||||
const { notifyRoleUsers } = await import('./notificationService');
|
||||
await notifyRoleUsers({
|
||||
roles: ['admin', 'operator'],
|
||||
notifyType: 'main_system_order_cancelled',
|
||||
title: '主系统删除订单,我方已停用',
|
||||
content: `订单 ${targetOrderCodes.join('、')} 已被主系统删除(原因:${reason}),我方已停用,无需再备货。`,
|
||||
relatedOrderCode: targetOrderCodes[0],
|
||||
content: `订单 ${deletableOrderCodes.join('、')} 已被主系统删除(原因:${reason}),我方已停用,无需再备货。`,
|
||||
relatedOrderCode: deletableOrderCodes[0] || targetOrderCodes[0],
|
||||
branchCode,
|
||||
dedupWithinHours: 1,
|
||||
}).catch(() => undefined);
|
||||
@@ -237,5 +673,6 @@ export async function applyOrderCancelledByMainSystem(input: {
|
||||
} catch (error) {
|
||||
console.error('[main-system-reverse] 整单停用通知失败(不影响处理):', (error as Error)?.message || error);
|
||||
}
|
||||
return { status: (updated.rowCount || 0) > 0 ? 'cancelled' : 'already' };
|
||||
if (!activeOrderCodes.length && completedOrderCodes.size) return { status: 'skipped_completed' };
|
||||
return { status: updatedRowCount > 0 ? 'cancelled' : 'already' };
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { PoolClient } from 'pg';
|
||||
import { pool } from '../db';
|
||||
import { runWithTenantDataAccess } from './tenantSchemaService';
|
||||
import { runWithTenantDbContext } from './tenantDbContext';
|
||||
@@ -49,29 +50,52 @@ import { closeEmptyMirrorOrderIfNeeded } from './mirrorOrderClosureService';
|
||||
* `calcItemAmount(quantity, price)` 的落库值);重量按 `sumWeightInJin` 折算到斤。
|
||||
* 为什么必须做:既有的独立删行入口(退货跟随/售后取消履约)都**不**重算订单头,
|
||||
* 缺货是本次新流程,不能一上线就让列表金额挂着已删掉的商品。
|
||||
*
|
||||
* ⚠️ 计算与写入被拆成两个导出函数(2026-10-19 BIZ-16),供「存量对账」在**同一个租户连接**
|
||||
* 里复用同一份口径(`orderHeaderReconcileService`)—— 对账不得另写第二套金额算法。
|
||||
*/
|
||||
export type OrderHeaderTotals = { totalAmount: number; totalWeight: number };
|
||||
|
||||
/** 只用到 `query` 的客户端形态(租户连接 / 假库都满足),与 `unitConversionService` 的 `Db` 同源 */
|
||||
type QueryOnly = Pick<PoolClient, 'query'>;
|
||||
|
||||
/** 按既有口径算出订单头应有金额/重量(只读;调用方负责租户上下文) */
|
||||
export async function computeOrderHeaderTotals(client: QueryOnly, orderCode: string): Promise<OrderHeaderTotals> {
|
||||
const rows = await client.query<{ quantity: string | null; unit: string | null; amount: string | null }>(
|
||||
`SELECT quantity, unit, amount
|
||||
FROM order_items
|
||||
WHERE order_code = $1 AND COALESCE(is_returned, false) = false`,
|
||||
[orderCode]
|
||||
);
|
||||
const totalAmount =
|
||||
Math.round(rows.rows.reduce((sum, row) => sum + (Number(row.amount) || 0), 0) * 100) / 100;
|
||||
const weightFactors = await loadWeightUnitFactors(client);
|
||||
const totalWeight = sumWeightInJin(
|
||||
rows.rows.map((row) => ({ quantity: Number(row.quantity) || 0, unit: String(row.unit || '斤') })),
|
||||
weightFactors
|
||||
);
|
||||
return { totalAmount, totalWeight };
|
||||
}
|
||||
|
||||
/** 把算好的金额/重量写回订单头(SQL 与原 `recalcOrderHeaderTotals` 完全一致) */
|
||||
export async function writeOrderHeaderTotals(
|
||||
client: QueryOnly,
|
||||
orderCode: string,
|
||||
totals: OrderHeaderTotals
|
||||
): Promise<void> {
|
||||
await client.query(
|
||||
`UPDATE orders SET total_amount = $2, total_weight = $3, updated_at = NOW() WHERE order_code = $1`,
|
||||
[orderCode, totals.totalAmount, totals.totalWeight]
|
||||
);
|
||||
}
|
||||
|
||||
export async function recalcOrderHeaderTotals(params: {
|
||||
branchCode: string;
|
||||
orderCode: string;
|
||||
}): Promise<void> {
|
||||
await runWithTenantDataAccess(params.branchCode, async (client) => {
|
||||
const rows = await client.query<{ quantity: string | null; unit: string | null; amount: string | null }>(
|
||||
`SELECT quantity, unit, amount
|
||||
FROM order_items
|
||||
WHERE order_code = $1 AND COALESCE(is_returned, false) = false`,
|
||||
[params.orderCode]
|
||||
);
|
||||
const totalAmount =
|
||||
Math.round(rows.rows.reduce((sum, row) => sum + (Number(row.amount) || 0), 0) * 100) / 100;
|
||||
const weightFactors = await loadWeightUnitFactors(client);
|
||||
const totalWeight = sumWeightInJin(
|
||||
rows.rows.map((row) => ({ quantity: Number(row.quantity) || 0, unit: String(row.unit || '斤') })),
|
||||
weightFactors
|
||||
);
|
||||
await client.query(
|
||||
`UPDATE orders SET total_amount = $2, total_weight = $3, updated_at = NOW() WHERE order_code = $1`,
|
||||
[params.orderCode, totalAmount, totalWeight]
|
||||
);
|
||||
const totals = await computeOrderHeaderTotals(client, params.orderCode);
|
||||
await writeOrderHeaderTotals(client, params.orderCode, totals);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -78,6 +78,8 @@ export async function writebackDeliveredOrderToMainSystem(
|
||||
`SELECT id::text AS id, sku_code, item_name, quantity, unit, price
|
||||
FROM order_items
|
||||
WHERE order_code = $1
|
||||
AND COALESCE(is_returned, false) = false
|
||||
AND COALESCE(is_extra_dish, false) = false
|
||||
ORDER BY sort_order NULLS LAST, created_at, id`,
|
||||
[orderCode]
|
||||
)
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { pool } from '../db';
|
||||
import { salesVisibleOrderSql } from './independentInbound';
|
||||
import type { TenantContext } from './tenantScope';
|
||||
import { customerStatementSharedFiltersSql } from './financeReconciliationService';
|
||||
import {
|
||||
customerStatementSharedFiltersSql,
|
||||
statementLinkedOrdersInDateRangeSql,
|
||||
} from './financeReconciliationService';
|
||||
import { statementHasLiveOrderLinkSql } from './statementScopeSql';
|
||||
import {
|
||||
computeFinanceNetProfit,
|
||||
@@ -2549,20 +2552,25 @@ export async function getFinanceOverviewStats(
|
||||
const receivableTotal = Number(receivables.rows[0]?.range_total) || 0;
|
||||
const openRecvCount = Number(receivables.rows[0]?.open_count) || 0;
|
||||
|
||||
const cycleOverlapSqlPay = cycleOverlapSql.replace(/cs\./g, 'ss.');
|
||||
const payParams: unknown[] = [rangeToDate, rangeFromDate];
|
||||
/**
|
||||
* BIZ-5 / T8(2026-10-19,用户批准口径 A):应付卡片不再按 `cycle_code` 账期重叠统计,
|
||||
* 改用与「应付明细列表」(financeReconciliationService 的 statementLinkedOrdersInDateRangeSql)
|
||||
* **完全相同**的"关联订单日"谓词(默认 delivery_date,可切 created_at / inbound),
|
||||
* 与应收同轴。`payable_amount` 与 open_count 口径保持不变。
|
||||
*/
|
||||
const payParams: unknown[] = [rangeFromDate, rangeToDate];
|
||||
let payBranch = '';
|
||||
if (ctx?.branchCode && !ctx.isSuperAdmin) {
|
||||
payParams.push(ctx.branchCode);
|
||||
payBranch = `AND ss.branch_code = $${payParams.length}`;
|
||||
}
|
||||
const payLinkedOrdersSql = statementLinkedOrdersInDateRangeSql('ss', 'supplier', dateField, 1, 2);
|
||||
const payables = await pool.query(
|
||||
`SELECT
|
||||
COALESCE(SUM(ss.payable_amount), 0)::numeric AS range_total,
|
||||
COALESCE(SUM(CASE WHEN COALESCE(ss.statement_status,0) < 30 AND COALESCE(ss.payable_amount,0) > 0 THEN 1 ELSE 0 END), 0)::int AS open_count
|
||||
FROM supplier_statements ss
|
||||
WHERE ${cycleOverlapSqlPay} ${payBranch}
|
||||
AND ${statementHasLiveOrderLinkSql('ss', 'supplier')}`,
|
||||
WHERE ${payLinkedOrdersSql} ${payBranch}`,
|
||||
payParams
|
||||
);
|
||||
const payableTotal = Number(payables.rows[0]?.range_total) || 0;
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
* 只显示**已人工确认**的批次报告(`inventory_batch_reports.status = 30`)与既有质检报告同一列渲染。
|
||||
*/
|
||||
import { pool } from '../db';
|
||||
import { buildSignedStoragePath } from './storageSignedUrl';
|
||||
import { buildSignedStoragePathForCtxChecked } from './storageObjectOwnership';
|
||||
import { classifyQualityReportFileKind, type OrderQualityReportFile } from './orderQualityReportFilesService';
|
||||
|
||||
export type OrderLineBatchReport = {
|
||||
@@ -87,6 +87,18 @@ export async function listOrderBatchReportFiles(orderCode: string): Promise<{
|
||||
const items: OrderLineBatchReport[] = [];
|
||||
for (const row of result.rows as Record<string, unknown>[]) {
|
||||
const filePaths = Array.isArray(row.file_paths) ? (row.file_paths as string[]) : [];
|
||||
const files: OrderLineBatchReport['files'] = [];
|
||||
for (const filename of filePaths.filter(Boolean)) {
|
||||
const safe = String(filename);
|
||||
// T9F-5:旧 key 先异步反查归属再签;未迁移/跨租户返回空 URL,不影响列表主数据。
|
||||
let url = '';
|
||||
try {
|
||||
url = await buildSignedStoragePathForCtxChecked(undefined, 'quality-reports', safe);
|
||||
} catch {
|
||||
url = '';
|
||||
}
|
||||
files.push({ path: safe, url, kind: classifyQualityReportFileKind(safe) });
|
||||
}
|
||||
items.push({
|
||||
our_order_item_id: String(row.our_order_item_id),
|
||||
sku_code: row.sku_code ? String(row.sku_code) : null,
|
||||
@@ -97,15 +109,7 @@ export async function listOrderBatchReportFiles(orderCode: string): Promise<{
|
||||
produced_at: row.produced_at ? String(row.produced_at) : null,
|
||||
testing_org: row.testing_org ? String(row.testing_org) : null,
|
||||
product_names: Array.isArray(row.product_names) ? (row.product_names as string[]).map(String) : [],
|
||||
files: filePaths.filter(Boolean).map((filename) => {
|
||||
const safe = String(filename);
|
||||
return {
|
||||
path: safe,
|
||||
// 与既有质检报告同一套签名机制(同一个 `quality-reports` 桶)
|
||||
url: buildSignedStoragePath('quality-reports', safe),
|
||||
kind: classifyQualityReportFileKind(safe),
|
||||
};
|
||||
}),
|
||||
files,
|
||||
});
|
||||
}
|
||||
return { items };
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* **订单头金额对账**(2026-10-19 BIZ-16)。
|
||||
*
|
||||
* 缺陷:`orders.total_amount` 是**冗余汇总**(行被删/退货红冲后本应跟着重算),但历史上只有
|
||||
* 「缺货删行 / 退货跟随 / 售后取消履约」三条路径调了 `recalcOrderHeaderTotals`;
|
||||
* 其余入口(旧数据、异常路径、手工 SQL)会留下"头与明细不一致"的存量行
|
||||
* (审计样本 `ORD_API_20261018_BR002_0001`:头 253.00,未退货明细合计 249.00,差 ¥4)。
|
||||
*
|
||||
* 本服务只做**一次性对账**:
|
||||
* · 找出 `|头金额 − 未退货明细金额之和| > 0.005` 的订单(分页上限);
|
||||
* · `apply=true` 时用**同一条既有口径**(`computeOrderHeaderTotals` / `writeOrderHeaderTotals`,
|
||||
* 与 `recalcOrderHeaderTotals` 共用,不另写算法)把头和重量写回去;
|
||||
* · 默认 **dry-run**(只报告)。明细金额本身不动 ⇒ 不改任何财务口径。
|
||||
*
|
||||
* ⚠️ 红冲/退货行按既有口径排除(`COALESCE(is_returned, false) = false`)——
|
||||
* 这正是「红冲后 header 过期」的修复面,不是新规则。
|
||||
*
|
||||
* 用法(本地库;脚本会拒绝非 localhost):
|
||||
* npm --prefix server run reconcile:order-header-totals -- --branch BR002 # 只报告
|
||||
* npm --prefix server run reconcile:order-header-totals -- --branch BR002 --apply # 写回
|
||||
*/
|
||||
import { runWithTenantDataAccess } from './tenantSchemaService';
|
||||
import { computeOrderHeaderTotals, writeOrderHeaderTotals } from './mainSystemStockout';
|
||||
|
||||
/** 金额对账容差:`numeric(12,2)` 下 0.005 以下视为一致(四舍五入误差) */
|
||||
export const ORDER_HEADER_TOLERANCE = 0.005;
|
||||
|
||||
export type OrderHeaderMismatch = {
|
||||
orderCode: string;
|
||||
headerAmount: number;
|
||||
itemAmount: number;
|
||||
/** 头 − 明细(正数 = 头偏大 / 负数 = 头偏小) */
|
||||
diff: number;
|
||||
};
|
||||
|
||||
export type OrderHeaderReconcileResult = {
|
||||
branchCode: string;
|
||||
apply: boolean;
|
||||
limit: number;
|
||||
/** 本次扫描到的前 `limit` 条不一致(顺序稳定:order_code ASC) */
|
||||
mismatchCount: number;
|
||||
mismatches: OrderHeaderMismatch[];
|
||||
/** apply=true 时真正写回的订单(含写回前后金额与重量) */
|
||||
fixed: Array<{ orderCode: string; beforeAmount: number; afterAmount: number; afterWeight: number }>;
|
||||
/** 本次结束后**仍不一致**的订单总数(不受 limit 限制;dry-run 时 = 全量不一致数) */
|
||||
remaining: number;
|
||||
};
|
||||
|
||||
const round2 = (n: number) => Math.round((Number(n) || 0) * 100) / 100;
|
||||
|
||||
/** 同一段「头 vs 未退货明细」判据;SELECT 与 COUNT 共用,避免两处口径漂移 */
|
||||
const MISMATCH_FROM_WHERE = `
|
||||
FROM orders o
|
||||
LEFT JOIN (
|
||||
SELECT order_code, SUM(COALESCE(amount, 0)) AS item_amount
|
||||
FROM order_items
|
||||
WHERE COALESCE(is_returned, false) = false
|
||||
GROUP BY order_code
|
||||
) s ON s.order_code = o.order_code
|
||||
WHERE o.deleted_at IS NULL
|
||||
AND ABS(COALESCE(o.total_amount, 0) - COALESCE(s.item_amount, 0)) > $1::numeric`;
|
||||
|
||||
/**
|
||||
* 一次性重算/对账:把「头金额 ≠ 未退货明细之和」的订单按既有口径写回。
|
||||
* 默认 dry-run(`apply` 缺省 false)——**只报告不改库**。
|
||||
*/
|
||||
export async function reconcileOrderHeaderTotals(input: {
|
||||
branchCode: string;
|
||||
apply?: boolean;
|
||||
limit?: number;
|
||||
}): Promise<OrderHeaderReconcileResult> {
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
if (!branchCode) {
|
||||
throw Object.assign(new Error('缺少分公司'), { status: 400, code: 'branch_required' });
|
||||
}
|
||||
const limit = Math.min(Math.max(Number(input.limit) || 200, 1), 2000);
|
||||
const apply = Boolean(input.apply);
|
||||
|
||||
return runWithTenantDataAccess(branchCode, async (client) => {
|
||||
const listed = await client.query<{
|
||||
order_code: string;
|
||||
header_amount: number | string;
|
||||
item_amount: number | string;
|
||||
}>(
|
||||
`SELECT o.order_code,
|
||||
COALESCE(o.total_amount, 0)::float AS header_amount,
|
||||
COALESCE(s.item_amount, 0)::float AS item_amount
|
||||
${MISMATCH_FROM_WHERE}
|
||||
ORDER BY o.order_code
|
||||
LIMIT $2`,
|
||||
[ORDER_HEADER_TOLERANCE, limit]
|
||||
);
|
||||
const mismatches: OrderHeaderMismatch[] = listed.rows.map((row) => {
|
||||
const headerAmount = round2(Number(row.header_amount) || 0);
|
||||
const itemAmount = round2(Number(row.item_amount) || 0);
|
||||
return {
|
||||
orderCode: String(row.order_code),
|
||||
headerAmount,
|
||||
itemAmount,
|
||||
diff: round2(headerAmount - itemAmount),
|
||||
};
|
||||
});
|
||||
|
||||
const fixed: OrderHeaderReconcileResult['fixed'] = [];
|
||||
if (apply) {
|
||||
for (const mismatch of mismatches) {
|
||||
const totals = await computeOrderHeaderTotals(client, mismatch.orderCode);
|
||||
await writeOrderHeaderTotals(client, mismatch.orderCode, totals);
|
||||
fixed.push({
|
||||
orderCode: mismatch.orderCode,
|
||||
beforeAmount: mismatch.headerAmount,
|
||||
afterAmount: totals.totalAmount,
|
||||
afterWeight: totals.totalWeight,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const remainingRow = await client.query<{ n: number | string }>(
|
||||
`SELECT COUNT(*)::int AS n ${MISMATCH_FROM_WHERE}`,
|
||||
[ORDER_HEADER_TOLERANCE]
|
||||
);
|
||||
|
||||
return {
|
||||
branchCode,
|
||||
apply,
|
||||
limit,
|
||||
mismatchCount: mismatches.length,
|
||||
mismatches,
|
||||
fixed,
|
||||
remaining: Number(remainingRow.rows[0]?.n) || 0,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** 只读报告(= `reconcileOrderHeaderTotals({apply:false})`,语义更直白) */
|
||||
export async function findOrderHeaderMismatches(input: {
|
||||
branchCode: string;
|
||||
limit?: number;
|
||||
}): Promise<OrderHeaderReconcileResult> {
|
||||
return reconcileOrderHeaderTotals({ ...input, apply: false });
|
||||
}
|
||||
@@ -527,6 +527,13 @@ export async function freezeOrderSettlementQtyOnComplete(
|
||||
if (!statusResult.rowCount) return;
|
||||
if (!options?.force && Number(statusResult.rows[0].order_status) >= 90) return;
|
||||
|
||||
/**
|
||||
* ⚠️ `loaded_qty` 与 `required_qty` 必须取同一 `picking_items` 行(2026-10-19 T14 红队第二轮):
|
||||
* `resolveCompleteReceivedSettlementQty` 用 loaded 与 required 是否相等判断"核货镜像"。
|
||||
* 旧实现 required 按 picked 排序,多行时可能与 loaded 行不同 ⇒ 镜像被误判为真人实配,
|
||||
* 结算量写成镜像值(例:实拣 7 被写成 5)。故两者共用同一 WHERE(loaded>0)与同一
|
||||
* ORDER BY(loaded DESC, picked DESC, id DESC)。picked_qty/picked_weight/unit 本轮不动。
|
||||
*/
|
||||
const items = await db.query(
|
||||
`SELECT oi.id::text AS order_item_id,
|
||||
oi.quantity::float8 AS quantity,
|
||||
@@ -548,7 +555,7 @@ export async function freezeOrderSettlementQtyOnComplete(
|
||||
SELECT pi.loaded_qty::float8
|
||||
FROM picking_items pi
|
||||
WHERE pi.order_item_id = oi.id AND COALESCE(pi.loaded_qty, 0) > 0
|
||||
ORDER BY pi.loaded_qty DESC NULLS LAST
|
||||
ORDER BY COALESCE(pi.loaded_qty, 0) DESC, COALESCE(pi.picked_qty, 0) DESC, pi.id DESC
|
||||
LIMIT 1
|
||||
) AS loaded_qty,
|
||||
(
|
||||
@@ -561,8 +568,8 @@ export async function freezeOrderSettlementQtyOnComplete(
|
||||
(
|
||||
SELECT pi.required_qty::float8
|
||||
FROM picking_items pi
|
||||
WHERE pi.order_item_id = oi.id
|
||||
ORDER BY COALESCE(pi.picked_qty, 0) DESC, COALESCE(pi.picked_weight, 0) DESC, COALESCE(pi.loaded_qty, 0) DESC
|
||||
WHERE pi.order_item_id = oi.id AND COALESCE(pi.loaded_qty, 0) > 0
|
||||
ORDER BY COALESCE(pi.loaded_qty, 0) DESC, COALESCE(pi.picked_qty, 0) DESC, pi.id DESC
|
||||
LIMIT 1
|
||||
) AS required_qty
|
||||
FROM order_items oi
|
||||
|
||||
@@ -2151,8 +2151,9 @@ export async function syncCustomerMappings(body: {
|
||||
if (existingRule.rowCount) {
|
||||
if (existingRule.rows[0].category_code !== categoryCode) {
|
||||
await pool.query(
|
||||
// DATA-4(2026-10-19):smart_classification_rules 只有 created_at,无 updated_at ⇒ 不写。
|
||||
`UPDATE smart_classification_rules
|
||||
SET category_code = $2, updated_at = NOW()
|
||||
SET category_code = $2
|
||||
WHERE keyword = $1 AND is_active = true AND branch_code = $3`,
|
||||
[originalName, categoryCode, branchCode]
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { pool } from '../db';
|
||||
import { buildSignedStoragePath } from './storageSignedUrl';
|
||||
import { tryBuildSignedStoragePathForCtx } from './storageObjectOwnership';
|
||||
import {
|
||||
QUALITY_REPORT_SELF_SUPPLIER_KEY,
|
||||
QUALITY_REPORT_STATUS,
|
||||
@@ -404,8 +404,8 @@ export async function listOrderQualityReportFiles(
|
||||
for (const filename of report.file_paths) {
|
||||
if (!filename || bucket.seen.has(filename)) continue;
|
||||
bucket.seen.add(filename);
|
||||
const path = buildSignedStoragePath('quality-reports', filename);
|
||||
const url = host && !path.startsWith('http') ? `${host}${path}` : path;
|
||||
const path = tryBuildSignedStoragePathForCtx(undefined, 'quality-reports', filename) ?? '';
|
||||
const url = path && host && !path.startsWith('http') ? `${host}${path}` : path;
|
||||
bucket.files.push({
|
||||
path: filename,
|
||||
url,
|
||||
|
||||
@@ -93,7 +93,9 @@ export async function countUnfinishedBackfillPickingItems(orderCode: string): Pr
|
||||
return Number(result.rows[0]?.cnt || 0);
|
||||
}
|
||||
|
||||
function pickQtySubquery(column: 'picked_weight' | 'picked_qty' | 'loaded_qty' | 'unit'): string {
|
||||
function pickQtySubquery(
|
||||
column: 'picked_weight' | 'picked_qty' | 'loaded_qty' | 'required_qty' | 'unit'
|
||||
): string {
|
||||
if (column === 'unit') {
|
||||
return `(
|
||||
SELECT pi.unit
|
||||
@@ -107,6 +109,29 @@ function pickQtySubquery(column: 'picked_weight' | 'picked_qty' | 'loaded_qty' |
|
||||
LIMIT 1
|
||||
)`;
|
||||
}
|
||||
/**
|
||||
* **required_qty 必须与 loaded_qty 取同一行**(2026-10-19 对抗复核修复)。
|
||||
*
|
||||
* 镜像判断是「loaded 与 required 是否相等」⇒ 两者必须来自同一 picking_items 行,否则
|
||||
* 「旧拣货行 required=12 / 新核货行 loaded=5」会跨行比较成 5≠12,把镜像量误判成真人实配。
|
||||
* 因此 loaded_qty 与 required_qty 共用同一排序键(loaded_qty DESC, picked_qty DESC, id DESC 作
|
||||
* 确定性次序)与同一过滤(loaded_qty > 0),LIMIT 1 才能保证落到同一行。
|
||||
* 其余列(picked_weight/picked_qty)语义不变,仍按自身列取最大。
|
||||
*/
|
||||
if (column === 'loaded_qty' || column === 'required_qty') {
|
||||
return `(
|
||||
SELECT pi.${column}::float8
|
||||
FROM picking_items pi
|
||||
WHERE pi.order_code = oi.order_code
|
||||
AND COALESCE(pi.loaded_qty, 0) > 0
|
||||
AND (
|
||||
pi.order_item_id = oi.id
|
||||
OR (pi.order_item_id IS NULL AND pi.sku_code IS NOT DISTINCT FROM oi.sku_code)
|
||||
)
|
||||
ORDER BY COALESCE(pi.loaded_qty, 0) DESC, COALESCE(pi.picked_qty, 0) DESC, pi.id DESC
|
||||
LIMIT 1
|
||||
)`;
|
||||
}
|
||||
return `(
|
||||
SELECT pi.${column}::float8
|
||||
FROM picking_items pi
|
||||
@@ -346,6 +371,7 @@ export async function ensureBackfillInboundOnConfirm(input: {
|
||||
${pickQtySubquery('picked_weight')} AS picked_weight,
|
||||
${pickQtySubquery('picked_qty')} AS picked_qty,
|
||||
${pickQtySubquery('loaded_qty')} AS loaded_qty,
|
||||
${pickQtySubquery('required_qty')} AS required_qty,
|
||||
${pickQtySubquery('unit')} AS pick_unit
|
||||
FROM order_items oi
|
||||
LEFT JOIN order_item_fulfillments f ON f.order_item_id = oi.id
|
||||
@@ -374,7 +400,8 @@ export async function ensureBackfillInboundOnConfirm(input: {
|
||||
row.picked_weight,
|
||||
row.loaded_qty,
|
||||
row.pick_unit || row.unit,
|
||||
row.picked_qty
|
||||
row.picked_qty,
|
||||
row.required_qty
|
||||
);
|
||||
const planQty = Number(row.uncovered_qty) || 0;
|
||||
/**
|
||||
|
||||
@@ -50,7 +50,7 @@ import {
|
||||
import { resolvePickingScanRow } from './labelScanResolver';
|
||||
import { isPickingScaleRequired } from './pickingScaleService';
|
||||
import { salesVisibleOrderSql } from './independentInbound';
|
||||
import { buildSignedStoragePath } from './storageSignedUrl';
|
||||
import { buildSignedStoragePathForCtxChecked } from './storageObjectOwnership';
|
||||
|
||||
type PickingProgressRow = {
|
||||
id: string;
|
||||
@@ -3136,15 +3136,24 @@ const PICKING_ITEMS_ENRICHED_SQL = `
|
||||
export async function listPickingItemsEnriched(pickCodes: string[]) {
|
||||
if (!pickCodes.length) return [];
|
||||
const result = await pool.query(PICKING_ITEMS_ENRICHED_SQL, [pickCodes]);
|
||||
return result.rows.map((row: any) => {
|
||||
return Promise.all(result.rows.map(async (row: any) => {
|
||||
const photos = Array.isArray(row.outbound_photos)
|
||||
? row.outbound_photos.map((p: unknown) => String(p || '').trim()).filter(Boolean)
|
||||
: [];
|
||||
const urls: string[] = [];
|
||||
for (const photo of photos) {
|
||||
// T9F-5:`delivery-photos` 旧 key 先异步反查归属再签;跨租户/毒化 key 不返回 URL。
|
||||
try {
|
||||
urls.push(await buildSignedStoragePathForCtxChecked(undefined, 'delivery-photos', photo));
|
||||
} catch {
|
||||
urls.push('');
|
||||
}
|
||||
}
|
||||
return {
|
||||
...row,
|
||||
outbound_photos: photos,
|
||||
// 分拣出库留证照(商品级)的可读链接:签名 15 分钟有效。见 docs/design/20261103-分拣出库拍照留证.md
|
||||
outbound_photo_urls: photos.map((p: string) => buildSignedStoragePath('delivery-photos', p)),
|
||||
outbound_photo_urls: urls,
|
||||
};
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -10,9 +10,9 @@ import { reduceInventoryHoldingForMaterialPicks, type InventoryDeductBatch } fro
|
||||
import { settleDemandSheetCostOnCompletion } from './processingDemandSheetService';
|
||||
import {
|
||||
claimOwnOrderReservationForProcessingPick,
|
||||
sumActiveReservationsForOrders,
|
||||
resolveProcessingPickReservationSplit,
|
||||
} from './processingPickReservationService';
|
||||
import { sumAvailableQty, sumOtherOrderReservations } from './inventoryStockCoverService';
|
||||
import { sumAvailableQty } from './inventoryStockCoverService';
|
||||
|
||||
const PROCESS_COMPLETED = 40;
|
||||
const PROCESS_REJECTED = 50;
|
||||
@@ -277,22 +277,20 @@ async function addCompletedDemandPick(
|
||||
)
|
||||
).rows.map((r) => String(r.order_code));
|
||||
const grossAvailable = await sumAvailableQty(client, skuCode, input.branchCode);
|
||||
let otherReserved = 0;
|
||||
for (const code of ownOrderCodes.length ? ownOrderCodes.map((c) => c as string | null) : [null]) {
|
||||
otherReserved += await sumOtherOrderReservations(client, skuCode, input.branchCode, code);
|
||||
}
|
||||
const availableQty = Math.max(0, grossAvailable - otherReserved);
|
||||
// 他单预留一次成型 = 全部在用预留 − 本单自己的在用预留(逐单号循环会算 N 倍)
|
||||
const reservationSplit = await resolveProcessingPickReservationSplit(client, {
|
||||
orderCodes: ownOrderCodes,
|
||||
skuCode,
|
||||
branchCode: input.branchCode,
|
||||
});
|
||||
const availableQty = Math.max(0, grossAvailable - reservationSplit.otherReserved);
|
||||
if (availableQty + 1e-9 < input.qty) {
|
||||
throw Object.assign(new Error(`库存不足:本分公司可用 ${availableQty},需要 ${input.qty}`), {
|
||||
status: 400,
|
||||
code: 'insufficient_stock',
|
||||
});
|
||||
}
|
||||
const plannedOwnReservation = await sumActiveReservationsForOrders(client, {
|
||||
orderCodes: ownOrderCodes,
|
||||
skuCode,
|
||||
branchCode: input.branchCode,
|
||||
});
|
||||
const plannedOwnReservation = reservationSplit.ownReserved;
|
||||
const deductedBatches: (FIFODeductBatch & { deductedQty: number })[] = [];
|
||||
await fifoDeductInventory(
|
||||
client,
|
||||
@@ -302,6 +300,8 @@ async function addCompletedDemandPick(
|
||||
branchCode: input.branchCode,
|
||||
// 传本单订单号 ⇒ 内部按「毛可用 − 他单预留」校验/扣减(与上面同口径)
|
||||
orderCode: ownOrderCodes[0] || null,
|
||||
// 内部预留守卫一次豁免全部本单订单号
|
||||
reservationExemptOrderCodes: ownOrderCodes,
|
||||
pickCode: input.taskCode,
|
||||
operatorId: input.operatorId || null,
|
||||
itemName: skuName,
|
||||
|
||||
@@ -20,13 +20,10 @@ import { upsertInventoryHoldingCost } from './inventorySurplusCostService';
|
||||
import { listStandaloneProcessingSkuOptions } from './processingStandaloneService';
|
||||
import { notVoidedByLineReturnSql } from './inboundCoverageSql';
|
||||
import { healOrphanIndependentInboundsAfterPass } from './selfPurchaseStockInboundService';
|
||||
import {
|
||||
sumAvailableQty,
|
||||
sumOtherOrderReservations,
|
||||
} from './inventoryStockCoverService';
|
||||
import { sumAvailableQty } from './inventoryStockCoverService';
|
||||
import {
|
||||
claimOwnOrderReservationForProcessingPick,
|
||||
sumActiveReservationsForOrders,
|
||||
resolveProcessingPickReservationSplit,
|
||||
} from './processingPickReservationService';
|
||||
|
||||
type Db = Pick<PoolClient, 'query'>;
|
||||
@@ -1071,24 +1068,22 @@ export async function pickDemandSheetMaterial(input: {
|
||||
).rows.map((r) => String(r.order_code));
|
||||
|
||||
// 可领量 = 毛可用 − 他单预留(本单自己的预留可被本单领料消耗)
|
||||
// 他单预留一次成型 = 全部在用预留 − 本单自己的在用预留(逐单号循环会算 N 倍,见测试 ①)
|
||||
const grossAvailable = await sumAvailableQty(client, skuCode, branchCode);
|
||||
let otherReserved = 0;
|
||||
for (const code of ownOrderCodes.length ? ownOrderCodes.map((c) => c as string | null) : [null]) {
|
||||
otherReserved += await sumOtherOrderReservations(client, skuCode, branchCode, code);
|
||||
}
|
||||
const claimableQty = Math.max(0, grossAvailable - otherReserved);
|
||||
const reservationSplit = await resolveProcessingPickReservationSplit(client, {
|
||||
orderCodes: ownOrderCodes,
|
||||
skuCode,
|
||||
branchCode,
|
||||
});
|
||||
const claimableQty = Math.max(0, grossAvailable - reservationSplit.otherReserved);
|
||||
if (claimableQty + 1e-9 < qty) {
|
||||
throw Object.assign(
|
||||
new Error(`库存不足:本分公司可用 ${claimableQty},需要 ${qty}`),
|
||||
{ status: 400, code: 'insufficient_stock' }
|
||||
);
|
||||
}
|
||||
// 领料前的本单活跃预留(供"只领了一部分"时精确降额)
|
||||
const plannedOwnReservation = await sumActiveReservationsForOrders(client, {
|
||||
orderCodes: ownOrderCodes,
|
||||
skuCode,
|
||||
branchCode,
|
||||
});
|
||||
// 领料前的本单活跃预留(供"只领了一部分"时精确降额;复用切分结果,不多查一次)
|
||||
const plannedOwnReservation = reservationSplit.ownReserved;
|
||||
|
||||
const deductedBatches: (FIFODeductBatch & { deductedQty: number })[] = [];
|
||||
await fifoDeductInventory(
|
||||
@@ -1099,6 +1094,8 @@ export async function pickDemandSheetMaterial(input: {
|
||||
branchCode,
|
||||
// 传本单订单号 ⇒ 内部 `getClaimableStockQty` 按「毛可用 − 他单预留」校验/扣减(与上面同口径)
|
||||
orderCode: ownOrderCodes[0] || null,
|
||||
// 内部预留守卫一次豁免全部本单订单号(只免第一个会把他单自己的另几张单当"他单"挡住)
|
||||
reservationExemptOrderCodes: ownOrderCodes,
|
||||
pickCode: String(row.task_code || taskId),
|
||||
operatorId: input.operatorId || null,
|
||||
itemName: skuName,
|
||||
|
||||
@@ -123,3 +123,39 @@ export async function sumActiveReservationsForOrders(
|
||||
return Math.round((Number(r.rows[0]?.total) || 0) * 1000) / 1000;
|
||||
}
|
||||
|
||||
/**
|
||||
* 领料可扣量切分:**他单预留 = 全部在用预留 − 本单自己的在用预留**(一次成型)。
|
||||
*
|
||||
* 旧写法对每个本单订单号各调一次 `sumOtherOrderReservations` 再相加,而该函数每次只排除
|
||||
* **一个** order_code ⇒ 同一需求单含 A、B 两张订单时,他单预留被算 N 倍(见
|
||||
* `processingPickOwnReservationMultiOrder.test.ts` ①)。本函数只读、不产生写语句;
|
||||
* `orderCodes` 为空(自采/独立加工)时他单 = 全部在用预留,且省掉 own 查询。
|
||||
*/
|
||||
export async function resolveProcessingPickReservationSplit(
|
||||
db: Db,
|
||||
input: { orderCodes: string[]; skuCode: string; branchCode?: string | null }
|
||||
): Promise<{ totalReserved: number; ownReserved: number; otherReserved: number }> {
|
||||
const sku = String(input.skuCode || '').trim();
|
||||
const codes = Array.from(
|
||||
new Set((input.orderCodes || []).map((c) => String(c || '').trim()).filter(Boolean))
|
||||
);
|
||||
const branch = String(input.branchCode || '').trim() || null;
|
||||
if (!sku) return { totalReserved: 0, ownReserved: 0, otherReserved: 0 };
|
||||
const totalRow = await db.query(
|
||||
`SELECT COALESCE(SUM(qty), 0)::float AS total
|
||||
FROM inventory_reservations
|
||||
WHERE sku_code = $1
|
||||
AND status = 10
|
||||
AND ($2::text IS NULL OR branch_code IS NULL OR branch_code = $2)`,
|
||||
[sku, branch]
|
||||
);
|
||||
const totalReserved = Math.round((Number(totalRow.rows[0]?.total) || 0) * 1000) / 1000;
|
||||
const ownReserved = codes.length
|
||||
? await sumActiveReservationsForOrders(db, { orderCodes: codes, skuCode: sku, branchCode: branch })
|
||||
: 0;
|
||||
const otherReserved = Math.max(
|
||||
0,
|
||||
Math.round((totalReserved - ownReserved) * 1000) / 1000
|
||||
);
|
||||
return { totalReserved, ownReserved, otherReserved };
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import { ensureCustomerStatementAfterOrderComplete, ensureSupplierStatementsForO
|
||||
import { postProcessingLaborCost } from './operationCostPostingService';
|
||||
import { finalizeInspectionPhotosToResultFolder } from './storageUploadService';
|
||||
import { getStorageProvider } from './storageProvider';
|
||||
import { buildSignedStoragePath } from './storageSignedUrl';
|
||||
import { buildSignedStoragePathForCtxChecked } from './storageObjectOwnership';
|
||||
import { loadArchivedPhotoMap } from './inspectionPhotoArchiveService';
|
||||
import { orderCodeActiveExistsSql } from './orderTrashScope';
|
||||
import { isOrderCodeSearch } from '../utils/orderCodeQuery';
|
||||
@@ -59,14 +59,19 @@ async function signedExistingProcessingPhotos(
|
||||
: new Map();
|
||||
|
||||
const out: Array<{ path: string; url: string; archived?: boolean; archive_month?: string }> = [];
|
||||
paths.forEach((path, index) => {
|
||||
for (const [index, path] of paths.entries()) {
|
||||
if (existsFlags[index]) {
|
||||
out.push({ path, url: buildSignedStoragePath(PROCESSING_INSPECTION_PHOTO_BUCKET, path) });
|
||||
return;
|
||||
// T9F-5:旧 key 先异步反查归属再签;跨租户 key 不返回 URL
|
||||
try {
|
||||
out.push({ path, url: await buildSignedStoragePathForCtxChecked(undefined, PROCESSING_INSPECTION_PHOTO_BUCKET, path) });
|
||||
} catch {
|
||||
out.push({ path, url: '' });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const archived = archivedMap.get(path);
|
||||
if (archived) out.push({ path, url: '', archived: true, archive_month: archived.ym });
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -1117,6 +1122,7 @@ export async function submitProcessingInspection(input: {
|
||||
photos: existingPhotos,
|
||||
productName: row.item_name || row.sku_code,
|
||||
skuCode: row.sku_code,
|
||||
ctx: { branchCode: row.branch_code },
|
||||
})
|
||||
: null;
|
||||
|
||||
|
||||
@@ -58,9 +58,10 @@ export function parseTraceKey(raw: unknown): { orderCode: string; skuCode: strin
|
||||
*/
|
||||
async function loadTracePhotos(
|
||||
photos: unknown,
|
||||
bucket: 'inspection-photos' | 'delivery-photos' = 'inspection-photos'
|
||||
bucket: 'inspection-photos' | 'delivery-photos' = 'inspection-photos',
|
||||
branchCode?: string | null
|
||||
): Promise<TracePhoto[]> {
|
||||
const signed = await signedExistingPhotos(photos, bucket);
|
||||
const signed = await signedExistingPhotos(photos, bucket, { branchCode: branchCode || null });
|
||||
return signed.map((item) => ({
|
||||
path: item.path,
|
||||
url: item.url,
|
||||
@@ -717,7 +718,7 @@ async function getProductTraceInCurrentSchema(input: {
|
||||
// 照片一律相对签名路径(与验收复核一致),经同源 /api 访问,避免管理端 Vite/反代下绝对 Host 裂图。
|
||||
// 小程序端自行把相对路径补成 apiBase 绝对地址。
|
||||
// 三源**分源返回、不合并**:验收照 / 配送补拍(含加菜核货照)/ 直送照语义不同。
|
||||
const inspectionPhotos = await loadTracePhotos(insp?.inspection_photos, 'inspection-photos');
|
||||
const inspectionPhotos = await loadTracePhotos(insp?.inspection_photos, 'inspection-photos', branchForLookup);
|
||||
const orderLinePhotos = await loadOrderLineTracePhotos(orderCode, skuCode, branchForLookup);
|
||||
const publicUrl = buildPublicTraceUrl(batchNo, host);
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { PoolClient } from 'pg';
|
||||
import type { Request } from 'express';
|
||||
import { pool } from '../db';
|
||||
import { saveBase64Upload } from './storageUploadService';
|
||||
import { buildSignedStoragePath } from './storageSignedUrl';
|
||||
import { buildSignedStoragePathForCtxChecked } from './storageObjectOwnership';
|
||||
import { isCategoryPhotoInspectionRequired } from './inspectionPhotoService';
|
||||
import { isSkuDirectDeliveryForPurchase } from './skuDirectDelivery';
|
||||
import { assertPurchaseOrderInBranch } from './purchaserBranchScope';
|
||||
@@ -16,11 +16,20 @@ function parsePhotoArray(raw: unknown): string[] {
|
||||
return raw.map((item) => String(item || '').trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
export function buildDirectDeliveryPhotoUrls(req: Request, photos: unknown): string[] {
|
||||
export async function buildDirectDeliveryPhotoUrls(req: Request, photos: unknown): Promise<string[]> {
|
||||
const filenames = parsePhotoArray(photos);
|
||||
if (!filenames.length) return [];
|
||||
const host = `${req.protocol}://${req.get('host')}`;
|
||||
return filenames.map((filename) => `${host}${buildSignedStoragePath(DIRECT_DELIVERY_PHOTO_BUCKET, filename)}`);
|
||||
const out: string[] = [];
|
||||
for (const filename of filenames) {
|
||||
// T9F-5:`sku-direct/...` 无分支前缀,先异步反查归属再签;跨租户/毒化行不返回 URL。
|
||||
try {
|
||||
out.push(`${host}${await buildSignedStoragePathForCtxChecked(undefined, DIRECT_DELIVERY_PHOTO_BUCKET, filename)}`);
|
||||
} catch {
|
||||
out.push('');
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export async function isPurchaseSkuDirectDelivery(purchaseCode: string, db: Db = pool): Promise<boolean> {
|
||||
|
||||
@@ -3,10 +3,11 @@ import { pool } from '../db';
|
||||
import { callWithImage as callArkWithImage, callWithFile, hasRuntimeConfig as hasArkRuntimeConfig } from './llmService';
|
||||
import { resolvePrompt } from './promptRegistryService';
|
||||
import { isQualityReportHardGateEnabled, getQuarantineValidDays } from './qualityReportGateConfigService';
|
||||
import { buildSignedStoragePath } from './storageSignedUrl';
|
||||
import { assertOwnedStoragePaths, tryBuildSignedStoragePathForCtx } from './storageObjectOwnership';
|
||||
import { saveBase64Upload } from './storageUploadService';
|
||||
import { getStorageProvider } from './storageProvider';
|
||||
import { safeStorageFileName } from './storageBucketConfig';
|
||||
import { getTenantDbStore } from './tenantDbContext';
|
||||
import { orderCodeActiveExistsSql } from './orderTrashScope';
|
||||
import {
|
||||
LEGACY_QUALITY_REPORT_TYPE_LABELS,
|
||||
@@ -640,6 +641,12 @@ async function resolveMatchUploadEntry(
|
||||
return null;
|
||||
}
|
||||
if (!safe) return null;
|
||||
// T9:客户端给的桶内旧 key 先做归属反查(调用者分支 RLS),跨分支 key 直接 403,不读他租户对象
|
||||
await assertOwnedStoragePaths(
|
||||
{ branchCode: getTenantDbStore()?.branchCode || null },
|
||||
'quality-reports',
|
||||
[safe]
|
||||
);
|
||||
const obj = await getStorageProvider().getObject('quality-reports', safe);
|
||||
if (!obj?.buffer?.length) return null;
|
||||
const ext = (safe.split('.').pop() || 'jpg').toLowerCase();
|
||||
@@ -689,7 +696,9 @@ export interface QualityReportRow {
|
||||
function mapReportRow(row: Record<string, unknown>, absoluteHost?: string | null): QualityReportRow {
|
||||
const paths = Array.isArray(row.file_paths) ? row.file_paths.map(String).filter(Boolean) : [];
|
||||
const file_urls = paths.map((filename) => {
|
||||
const path = buildSignedStoragePath('quality-reports', filename);
|
||||
// T9F-5:未迁移的无前缀旧 key 不再同步签发,给空 URL 避免列表 500。
|
||||
const path = tryBuildSignedStoragePathForCtx(undefined, 'quality-reports', filename);
|
||||
if (!path) return '';
|
||||
if (absoluteHost) return `${String(absoluteHost).replace(/\/+$/, '')}${path}`;
|
||||
return path;
|
||||
});
|
||||
@@ -1648,7 +1657,13 @@ export async function uploadQualityReport(input: {
|
||||
const parsed = await resolveMatchUploadEntry(file);
|
||||
if (!parsed) continue;
|
||||
const filename =
|
||||
parsed.storedPath || (await saveBase64Upload('quality-reports', parsed.content, parsed.ext));
|
||||
parsed.storedPath ||
|
||||
(await saveBase64Upload(
|
||||
'quality-reports',
|
||||
parsed.content,
|
||||
parsed.ext,
|
||||
branchCode ? { objectPrefix: branchCode } : undefined
|
||||
));
|
||||
savedPaths.push(filename);
|
||||
const ext = parsed.ext.toLowerCase();
|
||||
if (!firstImageBase64 && IMAGE_EXTS.has(ext)) {
|
||||
@@ -1833,6 +1848,9 @@ export async function uploadQualityReport(input: {
|
||||
await voidPrepLinksForPrepType(prepId, reportType);
|
||||
}
|
||||
|
||||
// T9:INSERT file_paths 前校验归属(跨分支 key ⇒ 403,不落库)
|
||||
await assertOwnedStoragePaths({ branchCode }, 'quality-reports', filePaths);
|
||||
|
||||
const result = await pool.query(
|
||||
`INSERT INTO quality_reports (
|
||||
branch_code, report_type, report_label, preparation_id, purchase_code,
|
||||
@@ -2627,7 +2645,12 @@ export async function uploadLibraryQualityReport(input: {
|
||||
for (const file of input.files || []) {
|
||||
const parsed = parseUploadPayload(file);
|
||||
if (!parsed) continue;
|
||||
const filename = await saveBase64Upload('quality-reports', parsed.content, parsed.ext);
|
||||
const filename = await saveBase64Upload(
|
||||
'quality-reports',
|
||||
parsed.content,
|
||||
parsed.ext,
|
||||
input.branchCode ? { objectPrefix: String(input.branchCode) } : undefined
|
||||
);
|
||||
savedPaths.push(filename);
|
||||
if (!firstImageBase64 && IMAGE_EXTS.has(parsed.ext.toLowerCase())) {
|
||||
firstImageBase64 = parsed.content;
|
||||
@@ -2675,6 +2698,9 @@ export async function uploadLibraryQualityReport(input: {
|
||||
testedAt: tested_at,
|
||||
});
|
||||
|
||||
// T9:INSERT file_paths 前校验归属(跨分支 key ⇒ 403,不落库)
|
||||
await assertOwnedStoragePaths({ branchCode: input.branchCode || null }, 'quality-reports', savedPaths);
|
||||
|
||||
const result = await pool.query(
|
||||
`INSERT INTO quality_reports (
|
||||
branch_code, report_type, report_label, preparation_id, purchase_code,
|
||||
@@ -3474,7 +3500,13 @@ export async function matchUploadQualityReports(input: {
|
||||
if (!parsed) continue;
|
||||
// 已由 multer 通道落存储的对象直接用其路径;旧 data URL 口径仍按原样保存
|
||||
const filename =
|
||||
parsed.storedPath || (await saveBase64Upload('quality-reports', parsed.content, parsed.ext));
|
||||
parsed.storedPath ||
|
||||
(await saveBase64Upload(
|
||||
'quality-reports',
|
||||
parsed.content,
|
||||
parsed.ext,
|
||||
input.branchCode ? { objectPrefix: String(input.branchCode) } : undefined
|
||||
));
|
||||
const meta = await parseMatchUploadMeta(parsed.content, parsed.ext, input.branchCode, reportHint);
|
||||
const matched = matchDayItemSku(meta, dayItems);
|
||||
const product_name = matched.product_name || meta.product_name;
|
||||
@@ -3488,6 +3520,8 @@ export async function matchUploadQualityReports(input: {
|
||||
const ai_parsed_at = meta.ai_raw ? new Date().toISOString() : null;
|
||||
|
||||
const isSelf = isQualityReportSelfSupplier(supplierCode);
|
||||
// T9:INSERT file_paths 前校验归属(跨分支 key ⇒ 403,不落库)
|
||||
await assertOwnedStoragePaths({ branchCode: input.branchCode || null }, 'quality-reports', [filename]);
|
||||
const result = await pool.query(
|
||||
`INSERT INTO quality_reports (
|
||||
branch_code, report_type, report_label, preparation_id, purchase_code,
|
||||
|
||||
@@ -406,7 +406,13 @@ async function activateQuoteSheet(
|
||||
return sheet;
|
||||
}
|
||||
|
||||
async function materializeQuoteVersions(
|
||||
/**
|
||||
* 物化 `customer_quote_versions`(报价单明细 → 客户版本行,逐客户 × 逐 SKU 升版本)。
|
||||
*
|
||||
* 导出原因(2026-10-19):报价提议审批通过(`quotePriceProposalService.approvePriceProposal`)
|
||||
* 同样改了生效单价格,必须在**同一事务内**物化版本 —— 复用本实现,禁止复制第二份。
|
||||
*/
|
||||
export async function materializeQuoteVersions(
|
||||
client: import('pg').PoolClient,
|
||||
sheet: {
|
||||
quote_sheet_code: string;
|
||||
|
||||
@@ -305,6 +305,26 @@ export async function confirmRetailOrderComplete(
|
||||
|
||||
await client.query('BEGIN');
|
||||
try {
|
||||
/**
|
||||
* **并发串行化点**:事务内先对订单行 `FOR UPDATE` 占锁,再重查状态。
|
||||
* 两笔并发「确认完成」时,后到者会阻塞在先到者的订单行锁上;先到者提交后,
|
||||
* 后到者重读即命中 `>= 90` 守卫(`already_completed`),不会再走一遍 FIFO 扣库。
|
||||
* 锁必须早于 `fifoDeductInventory`(否则库存行锁无法阻止同一订单二次扣减)。
|
||||
*/
|
||||
const lockedRow = (
|
||||
await client.query<{ order_status: number; customer_code: string }>(
|
||||
`SELECT COALESCE(order_status, 0) AS order_status, customer_code FROM orders WHERE order_code = $1 FOR UPDATE`,
|
||||
[code]
|
||||
)
|
||||
).rows[0];
|
||||
if (!lockedRow) throw businessError('订单不存在', 404, 'not_found');
|
||||
if (!isRetailCustomer(lockedRow.customer_code)) {
|
||||
throw businessError('只有散客录单单可以一键确认完成', 400, 'not_retail_order');
|
||||
}
|
||||
if (Number(lockedRow.order_status) >= 90) {
|
||||
throw businessError('该订单已完成', 409, 'already_completed');
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化(兼容历史):散客单**永远不该有分拣/配送**。若它曾被通用推进到 40/45/50
|
||||
* (在守卫上线之前录的单),先清掉分拣行并把状态拉回 **30「待确认」**,否则结案通道
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user