Merge remote-tracking branch 'origin/codex/xuxiake-mainline' into codex/wuyongjie-production-stop-skip-same-stage2-20261126

This commit is contained in:
apple 2026-11-26 09:56:30 +08:00
commit da7ee15f5f
110 changed files with 4824 additions and 341 deletions

View File

@ -85,3 +85,6 @@ agents/script-monitor/config.json
# 产品档案对账诊断报告
/data/archive-reconcile-diagnostics/
# Private daily carrier snapshots and message receipts
.daily-express/

View File

@ -0,0 +1,64 @@
# 快递承运量看版
任务:快递承运量看版完整迁入由壹点。更新日期:2026-11-26。
## 页面与权限
入口:供应链中心 → 经营管理 → 每日快递承运量看板,路径 `/supply-chain/management/daily-express-volume`。页面内有三个分支:各快递30日承运量看版、发货地省份区域承运量、已发货未揽收看版。保留现有 `dailyExpressVolume` 权限节点,页面与 API 均验证查看权限;Excel 导出额外验证下载权限。
页面复用 `PlatformSection`、`PlatformMetricStrip` 和 `Button`,使用浅色实体表格。没有占比、已剔除订单统计,也不将未完整取数当作零。
## 当前统计口径
- 主看板:`jst_Orders` 与 `jst_qmcust_orderlist`,按北京时间发货日期、`Sent` 状态读取。每张 ERP 内部订单计一单,跨来源重复内部单号阻止发布。仓库按 `co_id + wms_co_id` 匹配 `jst_warehouseInfo.name`。剔除空白或含 `@` 的快递单号,以及常州简尚家居有限公司、未设定发货仓库、未匹配、名称含 `配件-` 的仓库。
- 省份:优先使用订单 `receiver_state`;缺失时以内部单号、线上单号、运单号同时匹配物流记录,读取详细地址的省级部分。冲突阻止发布。
- 地区分支:省份与区域、仓库与发货地使用已确认映射;默认最新日期,按单日和发货地查询。优先排列常州自有仓、苏北自有仓、山东自有仓、河南自有仓、常州代发仓、河北代发仓-自有快递。
- 未揽收:`jst_order_express_details` 昨日发货、揽收时间为空、物流状态为未揽收。剔除首次问题类型 `1688一件代发`、空运单、指定快递关键词、`ECLP/CLPS/1688一件代发/刷单待处理` 标签、含 `(收)` 或 `BBFF` 的订单备注。通过普通/奇门主表及商品明细核对退款;任一明细 `refund_status=success` 整单剔除。未知退款状态不可冒充无退款。
- 未揽收分支不套用主看板的仓库剔除规则。
## 运行与持久化
共享规则及只读 SQL 在 `scripts/daily-express-dashboard/`;`run.mjs` 每次补齐保留窗口缺失日期,再读取最新未揽收与退款信息。所有数据校验完成后,以不可变 generation 目录和原子 `latest.json` 指针发布;页面查询只读快照,不现场发起慢 SQL。
`DAILY_EXPRESS_DATA_DIR` 指定持久化目录,生产为 `/opt/furniture-3d-system-prod/shared/daily-express`,不在发布目录中。目录包含 `days/`、`generations/`、`mappings.json`、`notifications/` 和 `last-run.json`。生成物、真实订单、映射数据和凭据不得提交 Git。仅保留最近30天主订单;未揽收只保留最新成功日;旧 generation 发布后移除。
数据源使用现有 `JST_REPORT_DB_*` 环境变量。`DAILY_EXPRESS_DINGTALK_CONFIG` 指向服务器本地机器人配置(字段与原员工离职通知的 webhook 配置一致);不要把内容写入文档。普通运行命令:
```bash
node scripts/daily-express-dashboard/run.mjs
./node_modules/.bin/tsx scripts/verify-daily-express-snapshot.ts
```
`--seed=<本地已核对任务目录>` 仅用于首次搬入已核对数据,不查库、不发送消息,不得拿它代替日更。首次基线是 2026-11-24、主看板 7,908 单、未揽收 9 条;这是核对基线,不是每日硬编码数量。
## 定时与通知
`scripts/install-daily-express-timer.sh` 安装 `furniture-daily-express.service/timer`,每日北京时间09:00执行,失败15分钟后重试,最多4次启动。需要单独执行安装脚本;仅发布代码不会启用。服务器任务确认就绪后才停用电脑同名业务任务,避免重复发送。
仅成功更新后发送原钉钉机器人文字消息;同一快递、同一仓库的单号逐行归组,不同仓库分开,相近快递名称用中文自然排序相邻显示。保留每日期发送记录,接口明确拒绝可恢复,网络结果不明时阻止自动重发。迁入既有发送记录,避免首日重复通知。
## 验证与限制
规则、退款、30日窗口、映射、快递分组排序和通知重试测试:`node --test scripts/daily-express-dashboard/*.test.mjs`。页面/权限/导出回归:对应 `DailyExpressVolumeView.test.tsx`、`daily-express-volume.service.test.ts`、`supply-chain-page-permissions.test.ts`。数据独立核对:`verify-daily-express-snapshot.ts`。
生产上线后须核对 commit、PM2、端口、健康检查、三个分支、导出、定时器及日志。此前本地报表查询有 SQL Server 1222 锁等待,迁移不绕过锁读取脏数据;失败保留最后成功快照,并在 `last-run.json` 记录原因,不发送旧数据。
规范自审:passed with warnings。这是自审,不是独立复审。架构沿用 Route → Service → Repository,后台复用已核对规则,未改变主数据或 Prisma 模型;视觉复用平台组件;原生快照与严格退款校验保持数据一致性。报表库锁等待风险仍需生产运行持续观察。
## 2026-11-26:累计窗口调整为30日
主承运量从15日改为30日滚动累计,沿用2026-11-24起始日;未满30日仅展示已累计日期,不补造历史。第31日移除最早日期,日均值按实际累计天数计算。地区分支可选日期沿用所保留的30日数据;未揽收仍只展示最新成功日,通知发送方式和15日发送记录保留期不变。
验证:35项数据/通知测试通过,补充30日校验、31日拒绝、30列数据及合计导出检查;8项页面/服务测试通过。本地已发布看板标题及Excel文件名改为30日,63,264个明细单元格核对一致,桌面/手机及下载链接验证通过。
规范自审:passed。这是自审,不是独立复审。仅修改累计窗口、对应校验与展示命名,保持数据源、退款剔除和单日未揽收口径不变。
## 2026-11-26:主看板按发货日期筛选
主看板默认展示保留窗口内的全部日期,每日承运量各占一列;新增发货日期选择和「筛选」按钮。选择日期后点击筛选,汇总、图表、快递列表以及 Excel 汇总/订单明细同时切换到该日;「全部日期」恢复完整窗口。零发货量的已更新日期可正常选择,未发布日期由服务校验拒绝,不回退显示其他日期。日期候选始终来自完整快照,不因当前筛选而丢失。
实现保持 Route → Service → Repository 分层:Service 对同一快照执行日期投影,导出使用相同口径;前端复用原平台组件,只增加日期控件和手机端换行样式。切换分支时重置主看板日期条件,其他分支及通知逻辑保持既有行为。未重新查询数据库或发送通知。
验证:11项页面/服务测试通过,覆盖默认全部日期、点击后应用筛选、恢复、零发货日、无效日期和同日 Excel 明细;相关生产文件 ESLint 通过。本地日期选择/发布测试3项通过。实际组件浏览器验证多日切换、恢复、零发货日及 1920×1080 / 390×844 布局;本地看板同样验证通过,现有已核对数据仍为 2026-11-24、7,908 单。
规范自审:passed。这是自审,不是独立复审。架构边界保留、控件沿用组件库、日期筛选和导出共用数据投影;筛选直接作用于日期数据,未用页面隐藏替代统计计算。线上生效须随共享主线变更合入生产 main 后部署。

View File

@ -3,6 +3,9 @@
"version": "0.1.0",
"private": true,
"scripts": {
"snapshot:daily-express": "node scripts/daily-express-dashboard/run.mjs",
"verify:daily-express": "node --test scripts/daily-express-dashboard/*.test.mjs",
"verify:daily-express:snapshot": "tsx scripts/verify-daily-express-snapshot.ts",
"worker:ai-image": "node scripts/run-ai-image-worker.mjs",
"predev": "npm run prisma:check-client-sync",
"dev": "next dev --webpack",

View File

@ -0,0 +1,28 @@
-- Freeze component-level stock, demand and BOM results together with each
-- modular processing main-table batch.
CREATE TABLE "ModularProcessingComponentBatchSnapshot" (
"id" TEXT NOT NULL,
"snapshotDate" TEXT NOT NULL,
"batchKey" TEXT NOT NULL,
"generationSlot" TEXT NOT NULL,
"parentBarcode" TEXT NOT NULL,
"componentBarcode" TEXT NOT NULL DEFAULT '',
"recordKey" TEXT NOT NULL,
"rowJson" JSONB NOT NULL,
"generatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "ModularProcessingComponentBatchSnapshot_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "ModularProcessingComponentBatchSnapshot_batchKey_recordKey_key"
ON "ModularProcessingComponentBatchSnapshot"("batchKey", "recordKey");
CREATE INDEX "ModularProcessingComponentBatchSnapshot_batch_parent_idx"
ON "ModularProcessingComponentBatchSnapshot"("batchKey", "parentBarcode");
CREATE INDEX "ModularProcessingComponentSnapshot_date_slot_generatedAt_idx"
ON "ModularProcessingComponentBatchSnapshot"("snapshotDate", "generationSlot", "generatedAt");
CREATE INDEX "ModularProcessingComponentBatchSnapshot_component_idx"
ON "ModularProcessingComponentBatchSnapshot"("componentBarcode");

View File

@ -1233,6 +1233,28 @@ model ModularProcessingOrderDailySnapshot {
@@map("ModularProcessingBatchSnapshot")
}
/// 模块化商品加工主表部件批次快照:冻结生成时的 BOM、库存、需求和判定结果。
model ModularProcessingComponentDailySnapshot {
id String @id @default(cuid())
snapshotDate String
/// 日期+时段批次键,例如 2026-11-25:09:00
batchKey String
/// 北京时间生成时段:09:00 / 15:00
generationSlot String
parentBarcode String
componentBarcode String @default("")
recordKey String
rowJson Json
generatedAt DateTime @default(now())
createdAt DateTime @default(now())
@@unique([batchKey, recordKey])
@@index([batchKey, parentBarcode], map: "ModularProcessingComponentBatchSnapshot_batch_parent_idx")
@@index([snapshotDate, generationSlot, generatedAt], map: "ModularProcessingComponentSnapshot_date_slot_generatedAt_idx")
@@index([componentBarcode], map: "ModularProcessingComponentBatchSnapshot_component_idx")
@@map("ModularProcessingComponentBatchSnapshot")
}
/// 模块化商品加工单每日生成运行状态:记录定时生成、人工刷新、失败原因和通知结果。
model ModularProcessingGenerationRun {
id String @id @default(cuid())

View File

@ -0,0 +1,93 @@
export const RULE_VERSION='orders-sent-warehouse-v1';
export const INITIAL_DATE='2026-11-24';
export const RETAIN_DAYS=30;
export const SOURCES=['jst_Orders','jst_qmcust_orderlist'];
export const DETAIL_VERSION=1;
export const DETAIL_COLUMNS=[
['o_id','ERP 内部订单号(订单编号)'],['so_id','线上订单号(交易单号)'],
['logistics_company','快递名称'],['l_id','快递单号'],['receiver_state','省份'],
['send_date','发货日期'],['wms_co_id','发货仓编号'],['warehouse_name','仓库名称']
];
export const RULES=[
['blankTracking','快递单号为空',r=>String(r.l_id??'').trim()===''],
['atTracking','快递单号含 @',r=>String(r.l_id??'').includes('@')],
['mainWarehouse','仓库为常州简尚家居有限公司',r=>String(r.warehouse_name??'').trim()==='常州简尚家居有限公司'],
['unsetWarehouse','仓库为未设定发货仓库',r=>String(r.warehouse_name??'').trim()==='未设定发货仓库'],
['unmatchedWarehouse','仓库未匹配',r=>['','未匹配'].includes(String(r.warehouse_name??'').trim())],
['accessoryWarehouse','仓库包含配件-',r=>String(r.warehouse_name??'').includes('配件-')]
];
export function assertDate(date){if(!/^\d{4}-\d{2}-\d{2}$/.test(date)||new Date(date+'T00:00:00Z').toISOString().slice(0,10)!==date)throw new Error('INVALID_DATE');return date;}
export function addDays(date,days){assertDate(date);return new Date(Date.parse(date+'T00:00:00Z')+days*86400000).toISOString().slice(0,10);}
export function businessYesterday(now=new Date()){return addDays(new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai',year:'numeric',month:'2-digit',day:'2-digit'}).format(now),-1);}
export function windowDates(end,initialDate=INITIAL_DATE){assertDate(end);assertDate(initialDate);const start=[initialDate,addDays(end,1-RETAIN_DAYS)].sort().at(-1);const dates=[];for(let day=start;day<=end;day=addDays(day,1))dates.push(day);if(!dates.length)throw new Error('NO_DATES');return dates;}
export function expiredSnapshotFiles(files,end){const retained=new Set(windowDates(end).map(day=>day+'.json'));return files.filter(name=>/^\d{4}-\d{2}-\d{2}\.json$/.test(name)&&!retained.has(name));}
export function aggregateDay(date,orders,warehouses,{extractedAt=new Date().toISOString(),seed=false}={}){
assertDate(date);
const lookup=new Map();for(const warehouse of warehouses){const key=String(warehouse.co_id)+'|'+String(warehouse.wms_co_id);const names=lookup.get(key)||new Set();if(warehouse.name!=null&&String(warehouse.name).trim())names.add(warehouse.name);lookup.set(key,names);}
const snapshot={date,ruleVersion:RULE_VERSION,complete:true,extractedAt,seed,raw:orders.length,excluded:0,total:0,distinctOrders:0,carriers:[],sourceCounts:SOURCES.map(source=>({source,raw:0,total:0})),exclusionRules:RULES.map(([key,label])=>({key,label,totalMatches:0,excludedAfterPriorRules:0}))};
const ids=new Set(),counts=new Map(),details=[];
for(const order of orders){
if(order.send_date?.slice(0,10)!==date||order.status!=='Sent'||!SOURCES.includes(order.source)||!order.o_id)throw new Error('SOURCE_FILTER_MISMATCH');
if(ids.has(String(order.o_id)))throw new Error('DUPLICATE_ORDER_ID');ids.add(String(order.o_id));
const source=snapshot.sourceCounts.find(item=>item.source===order.source);source.raw++;
const names=[...(lookup.get(String(order.co_id)+'|'+String(order.wms_co_id))||[])];
const row={...order,warehouse_name:names.length===1?names[0]:null};let first=-1;
RULES.forEach(([, ,predicate],index)=>{if(predicate(row)){snapshot.exclusionRules[index].totalMatches++;if(first===-1)first=index;}});
if(first!==-1){snapshot.excluded++;snapshot.exclusionRules[first].excludedAfterPriorRules++;continue;}
snapshot.total++;source.total++;
details.push(Object.fromEntries(DETAIL_COLUMNS.map(([key])=>[key,row[key]==null?'':String(row[key])])));
const name=row.logistics_company==null||row.logistics_company===''?'未填写快递名称':row.logistics_company;
counts.set(name,(counts.get(name)||0)+1);
}
snapshot.distinctOrders=ids.size;
snapshot.detailVersion=DETAIL_VERSION;
snapshot.details=details.sort((a,b)=>a.send_date.localeCompare(b.send_date)||a.o_id.localeCompare(b.o_id,'en',{numeric:true}));
snapshot.carriers=[...counts].map(([name,count])=>({name,count})).sort((a,b)=>b.count-a.count||a.name.localeCompare(b.name,'zh-CN'));
validateDayDetails(snapshot);return snapshot;
}
export function validateDayDetails(day){
validateDay(day);
if(day.detailVersion!==DETAIL_VERSION||!Array.isArray(day.details)||day.details.length!==day.total)throw new Error('INVALID_DAY_DETAILS');
const ids=new Set(),counts=new Map();
for(const row of day.details){
if(Object.keys(row).length!==DETAIL_COLUMNS.length||DETAIL_COLUMNS.some(([key])=>typeof row[key]!=='string')||!row.o_id||ids.has(row.o_id)||row.send_date.slice(0,10)!==day.date||RULES.some(([, ,predicate])=>predicate(row)))throw new Error('INVALID_DETAIL_ROW');
ids.add(row.o_id);
const name=row.logistics_company===''?'未填写快递名称':row.logistics_company;counts.set(name,(counts.get(name)||0)+1);
}
if(counts.size!==day.carriers.length||day.carriers.some(({name,count})=>counts.get(name)!==count))throw new Error('DETAIL_COUNTS_MISMATCH');
return day;
}
export function collectDetails(snapshots){
const ids=new Set(),rows=[];
for(const snapshot of snapshots){validateDayDetails(snapshot);for(const row of snapshot.details){if(ids.has(row.o_id))throw new Error('DUPLICATE_ORDER_ACROSS_DAYS');ids.add(row.o_id);rows.push(row);}}
return rows;
}
export function enrichDayDetails(previous,fresh,baselineRows){
validateDay(previous);validateDayDetails(fresh);
const shape=day=>JSON.stringify([day.date,day.total,day.sourceCounts.map(r=>[r.source,r.total]),day.carriers]);
if(shape(previous)!==shape(fresh))throw Object.assign(new Error('SNAPSHOT_COUNTS_CHANGED'),{code:'SNAPSHOT_COUNTS_CHANGED_'+previous.date});
if(baselineRows){
const baseline=new Map(baselineRows.filter(row=>row.send_date.slice(0,10)===previous.date).map(row=>[String(row.o_id),row]));
if(baseline.size!==fresh.details.length||fresh.details.some(row=>{const old=baseline.get(row.o_id);return !old||DETAIL_COLUMNS.some(([key])=>key!=='receiver_state'&&String(old[key]??'')!==row[key]);}))throw Object.assign(new Error('HISTORICAL_DETAIL_CHANGED'),{code:'HISTORICAL_DETAIL_CHANGED_'+previous.date});
}
return validateDayDetails({...previous,detailVersion:DETAIL_VERSION,details:fresh.details,detailExtractedAt:fresh.extractedAt,detailBackfillRawDelta:fresh.raw-previous.raw});
}
export function validateDay(day){
assertDate(day.date);
if(day.ruleVersion!==RULE_VERSION||day.complete!==true||day.distinctOrders!==day.raw||!Number.isInteger(day.raw)||day.raw<0||!Number.isInteger(day.total)||day.total<0||!Number.isInteger(day.excluded)||day.excluded<0||day.raw!==day.excluded+day.total)throw new Error('INVALID_DAY_SNAPSHOT');
if(!Array.isArray(day.carriers)||new Set(day.carriers.map(r=>r.name)).size!==day.carriers.length||day.carriers.some(r=>!Number.isInteger(r.count)||r.count<=0)||day.carriers.reduce((a,r)=>a+r.count,0)!==day.total)throw new Error('INVALID_CARRIER_COUNTS');
if(day.sourceCounts.length!==2||new Set(day.sourceCounts.map(r=>r.source)).size!==2||SOURCES.some(source=>!day.sourceCounts.some(r=>r.source===source))||day.sourceCounts.reduce((a,r)=>a+r.raw,0)!==day.raw||day.sourceCounts.reduce((a,r)=>a+r.total,0)!==day.total)throw new Error('INVALID_SOURCE_COUNTS');
if(day.exclusionRules.reduce((a,r)=>a+r.excludedAfterPriorRules,0)!==day.excluded)throw new Error('INVALID_EXCLUSION_COUNTS');
return day;
}
export function buildFacts(snapshots,end,{initialDate=INITIAL_DATE}={}){
const dates=windowDates(end,initialDate),byDate=new Map();for(const snapshot of snapshots){validateDay(snapshot);if(byDate.has(snapshot.date))throw new Error('DUPLICATE_DATE');byDate.set(snapshot.date,snapshot);}
const days=dates.map(date=>{if(!byDate.has(date))throw new Error('MISSING_DAY_'+date);return byDate.get(date);});
const counts=new Map();days.forEach((day,index)=>day.carriers.forEach(({name,count})=>{const daily=counts.get(name)||Array(dates.length).fill(0);daily[index]=count;counts.set(name,daily);}));
const ranking=[...counts].map(([name,daily])=>({name,daily,total:daily.reduce((a,b)=>a+b,0)})).sort((a,b)=>b.total-a.total||a.name.localeCompare(b.name,'zh-CN')).map((r,index)=>({...r,rank:index+1}));
const daily=days.map(({date,raw,excluded,total})=>({date,raw,excluded,total}));
const facts={dateFrom:dates[0],dateTo:end,days:dates,daily,original:daily.reduce((a,d)=>a+d.raw,0),excluded:daily.reduce((a,d)=>a+d.excluded,0),total:daily.reduce((a,d)=>a+d.total,0),carrierCount:ranking.length,ranking,sourceCounts:SOURCES.map(source=>({source,raw:days.reduce((a,d)=>a+d.sourceCounts.find(r=>r.source===source).raw,0),count:days.reduce((a,d)=>a+d.sourceCounts.find(r=>r.source===source).total,0)})),ruleVersion:RULE_VERSION,retentionDays:RETAIN_DAYS,extractedAt:days.at(-1).extractedAt,updatedAt:new Date().toISOString(),countUnit:'每张 ERP 内部订单计 1 单,按原始快递名称及发货日期汇总'};
facts.sourceRevisions=days.filter(day=>day.revision).map(day=>({date:day.date,...day.revision}));
facts.initialDate=initialDate;
if(facts.total+facts.excluded!==facts.original||ranking.reduce((a,r)=>a+r.total,0)!==facts.total)throw new Error('TOTAL_MISMATCH');return facts;
}

View File

@ -0,0 +1,66 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {aggregateDay,buildFacts,addDays,businessYesterday,windowDates,validateDay,validateDayDetails,collectDetails,enrichDayDetails,DETAIL_COLUMNS,expiredSnapshotFiles} from './core.mjs';
const root=path.dirname(fileURLToPath(import.meta.url));
const warehouse=[{co_id:'1',wms_co_id:'2',name:'简尚-崔桥工厂仓'},{co_id:'9',wms_co_id:'2',name:'常州简尚家居有限公司'}];
const order=(id,patch={})=>({o_id:String(id),status:'Sent',send_date:'2026-11-24 13:00:00.000',source:'jst_Orders',logistics_company:'快递甲',l_id:'NUMBER'+id,co_id:'1',wms_co_id:'2',...patch});
test('one approved day grows to 30 and day 31 removes the first day',()=>{
assert.deepEqual(windowDates('2026-11-24'),['2026-11-24']);
assert.equal(windowDates('2026-11-25').length,2);
assert.equal(windowDates('2026-12-08').length,15);
assert.deepEqual([windowDates('2026-12-24')[0],windowDates('2026-12-24').at(-1)],['2026-11-25','2026-12-24']);
assert.equal(windowDates('2026-12-23').length,30);
});
test('day boundaries use Shanghai even when execution host uses UTC',()=>{
assert.equal(businessYesterday(new Date('2026-11-24T16:01:00Z')),'2026-11-24');
assert.equal(businessYesterday(new Date('2026-11-24T15:59:00Z')),'2026-11-23');
});
test('retention removes only expired snapshots and keeps exactly 30 days',()=>{
const files=[...Array.from({length:35},(_,i)=>addDays('2026-11-24',i)+'.json'),'notes.json','2026-11-24.json.tmp'];
const removed=expiredSnapshotFiles(files,'2026-12-28');
assert.deepEqual(removed,['2026-11-24.json','2026-11-25.json','2026-11-26.json','2026-11-27.json','2026-11-28.json']);
assert.equal(files.filter(file=>/^\d{4}-\d{2}-\d{2}\.json$/.test(file)&&!removed.includes(file)).length,30);
assert.deepEqual(expiredSnapshotFiles(windowDates('2026-11-24').map(date=>date+'.json'),'2026-11-24'),[]);
});
test('applies all approved exclusions once and isolates warehouse companies',()=>{
const orders=[order(1),order(2,{l_id:' '}),order(3,{l_id:'@bad'}),order(4,{co_id:'9'}),order(5,{wms_co_id:'0'}),order(6,{wms_co_id:'3'}),order(7,{wms_co_id:'4'})];
const result=aggregateDay('2026-11-24',orders,[...warehouse,{co_id:'1',wms_co_id:'3',name:'未设定发货仓库'},{co_id:'1',wms_co_id:'4',name:'配件-测试仓'}]);
assert.equal(result.raw,7);assert.equal(result.excluded,6);assert.equal(result.total,1);assert.deepEqual(result.carriers,[{name:'快递甲',count:1}]);
});
test('same order appearing in either source is rejected, and incomplete days cannot pass as zero',()=>{
assert.throws(()=>aggregateDay('2026-11-24',[order(1),order(1,{source:'jst_qmcust_orderlist'})],warehouse),/DUPLICATE_ORDER_ID/);
const completeZero=aggregateDay('2026-11-24',[],warehouse);assert.equal(completeZero.total,0);
assert.throws(()=>validateDay({...completeZero,complete:false}),/INVALID_DAY/);
assert.throws(()=>buildFacts([completeZero],'2026-11-25'),/MISSING_DAY/);
});
test('detail preserves long identifiers and missing province, with the correct company warehouse',()=>{
const result=aggregateDay('2026-11-24',[order('9007199254740993123',{so_id:'000123456789012345678901',receiver_state:'浙江省'}),order('2',{source:'jst_qmcust_orderlist',receiver_state:null})],warehouse);
const long=result.details.find(row=>row.o_id==='9007199254740993123');
assert.deepEqual(Object.keys(long),DETAIL_COLUMNS.map(([key])=>key));
assert.equal(long.so_id,'000123456789012345678901');assert.equal(long.receiver_state,'浙江省');assert.equal(long.warehouse_name,'简尚-崔桥工厂仓');
assert.equal(result.details.find(row=>row.o_id==='2').receiver_state,'');
assert.equal(result.details.length,result.total);validateDayDetails(result);
const corrupt=structuredClone(result);corrupt.details[0].logistics_company='另一快递';assert.throws(()=>validateDayDetails(corrupt),/DETAIL_COUNTS/);
});
test('incomplete detail and duplicate orders on different dates block publication',()=>{
const a=aggregateDay('2026-11-24',[order(1)],warehouse);
assert.throws(()=>validateDayDetails({...a,details:[]}),/INVALID_DAY_DETAILS/);
const b=aggregateDay('2026-11-25',[order(1,{send_date:'2026-11-25 08:00:00.000'})],warehouse);
assert.throws(()=>collectDetails([a,b]),/DUPLICATE_ORDER_ACROSS_DAYS/);
});
test('province enrichment preserves the accepted snapshot when only excluded source rows changed',()=>{
const original=aggregateDay('2026-11-24',[order(1)],warehouse),prior=structuredClone(original);delete prior.details;delete prior.detailVersion;
const fresh=aggregateDay('2026-11-24',[order(1,{receiver_state:'江苏省'}),order(2,{l_id:''})],warehouse);
const enriched=enrichDayDetails(prior,fresh,original.details);
assert.equal(enriched.raw,1);assert.equal(enriched.excluded,0);assert.equal(enriched.total,1);assert.equal(enriched.details[0].receiver_state,'江苏省');assert.equal(enriched.detailBackfillRawDelta,1);
const differentId=aggregateDay('2026-11-24',[order(3,{receiver_state:'江苏省'})],warehouse);
assert.throws(()=>enrichDayDetails(prior,differentId,original.details),/HISTORICAL_DETAIL_CHANGED/);
const changedCarrier=aggregateDay('2026-11-24',[order(1,{logistics_company:'另一快递'})],warehouse);
assert.throws(()=>enrichDayDetails(prior,changedCarrier,original.details),/SNAPSHOT_COUNTS_CHANGED/);
});

View File

@ -0,0 +1,6 @@
const fs=require('node:fs'),path=require('node:path'),{createRequire}=require('node:module');
const app=path.resolve(__dirname,'../..'),req=createRequire(path.join(app,'package.json'));
const file=process.env.DAILY_EXPRESS_ENV_FILE||path.join(app,'.env');
const credentials=process.env.DAILY_EXPRESS_ENV_JSON?JSON.parse(fs.readFileSync(process.env.DAILY_EXPRESS_ENV_JSON,'utf8')):{};
const env={...(fs.existsSync(file)?req('dotenv').parse(fs.readFileSync(file)):{}),...process.env,...credentials};
module.exports={app,req,env};

View File

@ -0,0 +1,37 @@
const fs=require('node:fs/promises'),path=require('node:path');
const {pool,sql,schema}=require('./report-db-readonly.cjs');
(async()=>{try{
const {applyUncollectedBaseRules}=await import('./uncollected.mjs');
const sourceFile=path.resolve(process.argv.find(arg=>arg.startsWith('--source='))?.slice(9)||path.join(__dirname,'staging/uncollected-source.json'));
const output=path.resolve(process.argv.find(arg=>arg.startsWith('--output='))?.slice(9)||path.join(__dirname,'staging/uncollected-refund-checks.json'));
const snapshot=JSON.parse(await fs.readFile(sourceFile,'utf8')),candidates=applyUncollectedBaseRules(snapshot.rows);
const ids=[...new Set(candidates.map(row=>String(row.inner_order_id)))];
if(ids.some(id=>!/^\d+$/.test(id)))throw new Error('REFUND_INVALID_ORDER_ID');
const masters=[],items=[],checkedAt=new Date().toISOString();
if(ids.length){
await pool.connect();
for(const table of ['jst_Orders','jst_qmcust_orderlist']){
const request=pool.request().input('ids',sql.NVarChar(sql.MAX),JSON.stringify(ids));request.timeout=90000;
const rows=(await request.query(`SET LOCK_TIMEOUT 45000;
SELECT CAST(co_id AS varchar(40)) AS co_id,CAST(o_id AS varchar(40)) AS o_id,so_id,l_id
FROM [${schema}].[${table}] WHERE o_id IN (SELECT CONVERT(bigint,value) FROM OPENJSON(@ids));`)).recordset;
masters.push(...rows.map(row=>({...row,source:table})));
console.log(JSON.stringify({stage:'refund_order_source_checked',source:table,matched:rows.length}));
}
for(const [master,item] of [['jst_Orders','jst_OrderItem'],['jst_qmcust_orderlist','jst_qmcust_orderlist_item']]){
const target=masters.filter(row=>row.source===master).map(row=>row.o_id);if(!target.length)continue;
const request=pool.request().input('ids',sql.NVarChar(sql.MAX),JSON.stringify(target));request.timeout=90000;
const rows=(await request.query(`SET LOCK_TIMEOUT 45000;
SELECT CAST(o_id AS varchar(40)) AS o_id,CAST(oi_id AS varchar(40)) AS oi_id,raw_so_id,refund_status,item_status,qty
FROM [${schema}].[${item}] WHERE o_id IN (SELECT CONVERT(bigint,value) FROM OPENJSON(@ids));`)).recordset;
items.push(...rows.map(row=>({...row,source:item})));
console.log(JSON.stringify({stage:'refund_item_source_checked',source:item,items:rows.length}));
}
}
const audit={version:'item-refund-success-v1',date:snapshot.summary.date,sourceQueriedAt:snapshot.summary.queriedAt,checkedAt,completedAt:new Date().toISOString(),candidates:candidates.map(row=>({id:String(row.id),o_id:String(row.inner_order_id),so_id:row.so_id??null,l_id:row.logistic_id??null})),masters,items};
const {attachRefundChecks}=await import('./refund.mjs');
const enriched=attachRefundChecks(snapshot.rows,audit,snapshot.summary.date);
const checked=applyUncollectedBaseRules(enriched);
await fs.mkdir(path.dirname(output),{recursive:true});await fs.writeFile(output+'.tmp',JSON.stringify(audit,null,2));await fs.rename(output+'.tmp',output);
console.log(JSON.stringify({stage:'refund_checks_complete',candidates:checked.length,refundSuccess:checked.filter(row=>row.refund_success).map(row=>row.inner_order_id),retained:checked.filter(row=>!row.refund_success).length,statuses:checked.map(row=>({o_id:row.inner_order_id,refund_status:row.refund_status}))}));
}catch(error){console.error(JSON.stringify({errorCode:error.code||error.message||error.name,number:error.number||null}));process.exitCode=1;}finally{await pool.close();}})();

View File

@ -0,0 +1,26 @@
const fs=require('node:fs/promises'),path=require('node:path');
const {pool,sql,schema}=require('./report-db-readonly.cjs');
(async()=>{try{
const {businessYesterday}=await import('./core.mjs');
const date=process.argv.find(arg=>arg.startsWith('--date='))?.slice(7)||businessYesterday();
if(!/^\d{4}-\d{2}-\d{2}$/.test(date)||new Date(date+'T00:00:00Z').toISOString().slice(0,10)!==date)throw new Error('INVALID_DATE');
const from=date+' 00:00:00',to=new Date(Date.parse(date+'T00:00:00Z')+86400000).toISOString().slice(0,10)+' 00:00:00';
const output=path.resolve(process.argv.find(arg=>arg.startsWith('--output='))?.slice(9)||path.join(__dirname,'staging/uncollected-source.json'));
await pool.connect();
const startedAt=new Date().toISOString();
const rows=(await pool.request().input('from',sql.VarChar(19),from).input('to',sql.VarChar(19),to).query(`SET LOCK_TIMEOUT 15000;
SELECT id,CAST(inner_order_id AS varchar(40)) AS inner_order_id,so_id,logistic_id,logistic_company_name,
logistic_status_name,order_status_name,logistic_return_flag,aftersale_status_name,
shop_name,platform_name,dis_co_name,warehouse_name,order_labels,remark,
CONVERT(varchar(19),send_time,120) AS send_time,CONVERT(varchar(19),fetch_time,120) AS fetch_time,
CONVERT(varchar(19),sign_time,120) AS sign_time,CONVERT(varchar(19),logistic_time,120) AS logistic_time,
CONVERT(varchar(19),query_time,120) AS query_time,first_question_type,
CONVERT(varchar(19),first_question_time,120) AS first_question_time,CONVERT(varchar(19),updatedAt,120) AS updatedAt
FROM [${schema}].[jst_order_express_details]
WHERE send_time >= CONVERT(datetime,@from,120) AND send_time < CONVERT(datetime,@to,120) AND fetch_time IS NULL;`)).recordset;
rows.sort((a,b)=>a.send_time.localeCompare(b.send_time)||Number(a.id)-Number(b.id));
const snapshot={summary:{date,source:schema+'.jst_order_express_details',filters:{send_timeFromInclusive:from,send_timeToExclusive:to,fetch_time:'IS NULL'},startedAt,queriedAt:new Date().toISOString(),rowCount:rows.length},rows};
const {validateUncollected,summarizeUncollected}=await import('./uncollected.mjs');validateUncollected(snapshot);
await fs.mkdir(path.dirname(output),{recursive:true});await fs.writeFile(output+'.tmp',JSON.stringify(snapshot));await fs.rename(output+'.tmp',output);
console.log(JSON.stringify({stage:'uncollected_fetched',date,total:rows.length,pending:summarizeUncollected(rows).pending}));
}catch(error){console.error(JSON.stringify({errorCode:error.code||error.name,number:error.number||null}));process.exitCode=1;}finally{await pool.close();}})();

View File

@ -0,0 +1,26 @@
import {validateDayDetails} from './core.mjs';
export const PROVINCE_VERSION=1;
const regions=new Set(['北京','北京市','天津','天津市','上海','上海市','重庆','重庆市','河北省','山西省','内蒙古自治区','辽宁省','吉林省','黑龙江省','江苏省','浙江省','安徽省','福建省','江西省','山东省','河南省','湖北省','湖南省','广东省','广西壮族自治区','海南省','四川省','贵州省','云南省','西藏自治区','陕西省','甘肃省','青海省','宁夏回族自治区','新疆维吾尔自治区','台湾省','香港特别行政区','澳门特别行政区']);
const key=row=>JSON.stringify([String(row.o_id??''),String(row.so_id??''),String(row.l_id??'').trim()]);
export function completeDayProvinces(snapshot,candidates,{checkedAt=new Date().toISOString()}={}){
validateDayDetails(snapshot);
const index=new Map();
for(const row of candidates){const province=String(row.region??'').split('-')[0].trim();if(!regions.has(province))continue;const id=key(row);const values=index.get(id)||new Set();values.add(province);index.set(id,values);}
const records=[],unresolved=[];
const details=snapshot.details.map(row=>{
if(row.receiver_state.trim())return {...row};
const provinces=[...(index.get(key(row))||[])];
if(provinces.length>1)throw new Error('CONFLICTING_LOGISTICS_PROVINCES');
if(!provinces.length){unresolved.push(row.o_id);return {...row};}
records.push({o_id:row.o_id,province:provinces[0]});return {...row,receiver_state:provinces[0]};
});
const day={...snapshot,details,provinceEnrichment:{version:PROVINCE_VERSION,source:'jst_order_express_details.receiver_address',checkedAt,requested:records.length+unresolved.length,filled:records.length,unresolved:unresolved.length,records}};
return validateProvinceEnrichment(day);
}
export function validateProvinceEnrichment(day){
validateDayDetails(day);const audit=day.provinceEnrichment;
if(audit?.version!==PROVINCE_VERSION||audit.source!=='jst_order_express_details.receiver_address'||!Number.isInteger(audit.filled)||!Number.isInteger(audit.unresolved)||audit.filled<0||audit.unresolved<0||audit.requested!==audit.filled+audit.unresolved||audit.records.length!==audit.filled)throw new Error('INVALID_PROVINCE_AUDIT');
const byId=new Map(day.details.map(row=>[row.o_id,row]));
if(new Set(audit.records.map(row=>row.o_id)).size!==audit.records.length||audit.records.some(row=>!regions.has(row.province)||byId.get(row.o_id)?.receiver_state!==row.province)||day.details.filter(row=>!row.receiver_state.trim()).length!==audit.unresolved)throw new Error('PROVINCE_AUDIT_MISMATCH');
return day;
}

View File

@ -0,0 +1,29 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {aggregateDay,buildFacts,addDays,windowDates} from './core.mjs';
import {completeDayProvinces,validateProvinceEnrichment} from './province.mjs';
const root=path.dirname(fileURLToPath(import.meta.url));
const warehouse=[{co_id:'1',wms_co_id:'2',name:'核对仓'}];
const order=(o_id,province='')=>({o_id,so_id:'online-'+o_id,l_id:'waybill-'+o_id,source:'jst_Orders',status:'Sent',send_date:'2026-11-24 13:00:00.000',co_id:'1',wms_co_id:'2',logistics_company:'快递甲',receiver_state:province});
test('fills only missing provinces and requires internal, online and waybill numbers to match',()=>{
const original=aggregateDay('2026-11-24',[order('1'),order('2','江苏省'),order('3')],warehouse);
const result=completeDayProvinces(original,[{o_id:'1',so_id:'online-1',l_id:'waybill-1',region:'山东省-德州市'},{o_id:'2',so_id:'online-2',l_id:'waybill-2',region:'广东省'},{o_id:'3',so_id:'online-3',l_id:'different-waybill',region:'北京市'}]);
assert.deepEqual(result.details.map(row=>row.receiver_state),['山东省','江苏省','']);
assert.equal(result.provinceEnrichment.filled,1);assert.equal(result.provinceEnrichment.unresolved,1);
assert.equal(original.details[0].receiver_state,'');validateProvinceEnrichment(result);
});
test('rejects conflicting logistics regions and accepts municipality aliases',()=>{
const original=aggregateDay('2026-11-24',[order('1')],warehouse);
const candidate={o_id:'1',so_id:'online-1',l_id:'waybill-1',region:'重庆'};
assert.equal(completeDayProvinces(original,[candidate]).details[0].receiver_state,'重庆');
assert.throws(()=>completeDayProvinces(original,[candidate,{...candidate,region:'北京市'}]),/CONFLICTING/);
});
test('missing dates cannot silently produce a complete 30-day history and repeats do not duplicate orders',()=>{
const days=Array.from({length:31},(_,i)=>{const date=addDays('2026-11-24',i);return aggregateDay(date,[{...order(String(i)),send_date:date+' 13:00:00.000'}],warehouse);});
const facts=buildFacts(days,'2026-12-24');assert.equal(facts.days.length,30);assert.equal(facts.total,30);assert.equal(facts.dateFrom,'2026-11-25');
assert.deepEqual(buildFacts(days,'2026-12-24').ranking,facts.ranking);
assert.throws(()=>buildFacts(days.filter(day=>day.date!=='2026-12-01'),'2026-12-24'),/MISSING_DAY/);
});

View File

@ -0,0 +1,28 @@
import {applyUncollectedBaseRules} from './uncollected.mjs';
const text=value=>String(value??'').trim();
const ITEM_SOURCE={jst_Orders:'jst_OrderItem',jst_qmcust_orderlist:'jst_qmcust_orderlist_item'};
export function attachRefundChecks(rows,audit,date){
if(audit?.version!=='item-refund-success-v1'||audit.date!==date||!Array.isArray(audit.candidates)||!Array.isArray(audit.masters)||!Array.isArray(audit.items)||!Number.isFinite(Date.parse(audit.completedAt)))throw new Error('INVALID_REFUND_AUDIT');
const candidates=applyUncollectedBaseRules(rows),identity=row=>({id:String(row.id),o_id:text(row.inner_order_id),so_id:row.so_id??null,l_id:row.logistic_id??null});
if(JSON.stringify(candidates.map(identity))!==JSON.stringify(audit.candidates))throw new Error('REFUND_CANDIDATE_MISMATCH');
const checked=new Map();
for(const row of candidates){
const masters=audit.masters.filter(master=>text(master.o_id)===text(row.inner_order_id));
if(!masters.length)throw new Error('REFUND_ORDER_NOT_FOUND_'+row.inner_order_id);
const statuses=new Set(),itemKeys=new Set();let itemCount=0;
for(const master of masters){
if(!ITEM_SOURCE[master.source]||text(master.so_id)!==text(row.so_id)||text(master.l_id)!==text(row.logistic_id))throw new Error('REFUND_ORDER_IDENTITY_MISMATCH_'+row.inner_order_id);
const items=audit.items.filter(item=>item.source===ITEM_SOURCE[master.source]&&text(item.o_id)===text(row.inner_order_id));
if(!items.length)throw new Error('REFUND_ITEMS_NOT_FOUND_'+row.inner_order_id);
for(const item of items){
if(!text(item.oi_id)||!Object.prototype.hasOwnProperty.call(item,'refund_status'))throw new Error('INVALID_REFUND_ITEM');
const key=item.source+':'+item.oi_id;
if(itemKeys.has(key))throw new Error('DUPLICATE_REFUND_ITEM');itemKeys.add(key);
statuses.add(text(item.refund_status));itemCount++;
}
}
const raw=[...statuses].filter(Boolean).sort();
checked.set(String(row.id),{...row,refund_checked:true,refund_status:raw.join(' / '),refund_success:raw.some(status=>status.toLowerCase()==='success'),refund_item_count:itemCount});
}
return rows.map(row=>checked.get(String(row.id))||row);
}

View File

@ -0,0 +1,25 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {attachRefundChecks} from './refund.mjs';
import {applyUncollectedRules} from './uncollected.mjs';
const rows=[{id:1,inner_order_id:'10356744',so_id:'S1',logistic_id:'L1',logistic_status_name:'未揽收',logistic_company_name:'中通速递',order_labels:null,remark:null}];
const audit=()=>({version:'item-refund-success-v1',date:'2026-11-24',completedAt:'2026-11-25T08:00:00Z',candidates:[{id:'1',o_id:'10356744',so_id:'S1',l_id:'L1'}],masters:[{source:'jst_Orders',o_id:'10356744',so_id:'S1',l_id:'L1'}],items:[{source:'jst_OrderItem',o_id:'10356744',oi_id:'I1',refund_status:'success'}]});
test('success on any item excludes its order; blank or pending refund values remain distinct from success',()=>{
assert.equal(applyUncollectedRules(attachRefundChecks(rows,audit(),'2026-11-24')).length,0);
for(const status of [null,'','waiting','closed']){
const data=audit();data.items[0].refund_status=status;
const enriched=attachRefundChecks(rows,data,'2026-11-24');assert.equal(enriched[0].refund_success,false);assert.equal(applyUncollectedRules(enriched).length,1);
}
const data=audit();data.items.push({...data.items[0],oi_id:'I2',refund_status:''});assert.equal(applyUncollectedRules(attachRefundChecks(rows,data,'2026-11-24')).length,0);
});
test('Qimen item source is checked and incomplete, mismatched or duplicate evidence cannot pass',()=>{
const data=audit();data.masters[0].source='jst_qmcust_orderlist';data.items[0].source='jst_qmcust_orderlist_item';
assert.equal(attachRefundChecks(rows,data,'2026-11-24')[0].refund_success,true);
for(const mutate of [d=>d.masters=[],d=>d.items=[],d=>d.masters[0].so_id='OTHER',d=>d.masters[0].l_id='OTHER',d=>d.date='2026-11-23',d=>d.candidates=[],d=>d.items.push({...d.items[0]}),d=>delete d.items[0].refund_status]){
const invalid=audit();mutate(invalid);assert.throws(()=>attachRefundChecks(rows,invalid,'2026-11-24'));
}
});
test('no eligible candidates permits a valid empty audit',()=>{
const data=audit();data.candidates=[];data.masters=[];data.items=[];
assert.deepEqual(attachRefundChecks([],data,'2026-11-24'),[]);
});

View File

@ -0,0 +1,74 @@
const text=value=>String(value??'').normalize('NFKC').trim();
export const UNMAPPED_ORIGIN='未匹配发货地';
export const UNMAPPED_REGION='未配置区域';
export const PRIORITY_ORIGINS=['常州自有仓','苏北自有仓','山东自有仓','河南自有仓','常州代发仓','河北代发仓-自有快递'];
function compareOrigins(a,b){
const aIndex=PRIORITY_ORIGINS.indexOf(a.name),bIndex=PRIORITY_ORIGINS.indexOf(b.name);
const priority=(aIndex<0?PRIORITY_ORIGINS.length:aIndex)-(bIndex<0?PRIORITY_ORIGINS.length:bIndex);
return priority||b.total-a.total||a.name.localeCompare(b.name,'zh-CN');
}
export function provinceKey(value){
return text(value).replace(/壮族自治区$|回族自治区$|维吾尔自治区$|自治区$|特别行政区$|省$|市$/u,'').replace(/^黑龙$/u,'黑龙江').replace(/^内蒙$/u,'内蒙古');
}
export function warehouseKey(value){return text(value).replace(/^(?:仓库|简尚|工厂|三方|京仓)\s*[--—]\s*/u,'').trim();}
export function compileMappings(mapping){
if(!Array.isArray(mapping?.warehouses)||!mapping.warehouses.length||!Array.isArray(mapping.provinces)||!mapping.provinces.length)throw new Error('LOCAL_LOGISTICS_MAPPINGS_REQUIRED');
const provinces=new Map(),warehouses=new Map(),aliases=new Map(),regions=[];
for(const row of mapping.provinces){
const key=provinceKey(row.province),region=text(row.region);
if(!key)throw new Error('EMPTY_MAPPING_PROVINCE');
if(provinces.has(key)&&provinces.get(key).region!==region)throw new Error('CONFLICTING_PROVINCE_MAPPING');
provinces.set(key,{province:text(row.province),region:region||UNMAPPED_REGION,index:provinces.size});
if(region&&!regions.includes(region))regions.push(region);
}
for(const row of mapping.warehouses){
const exact=text(row.warehouse),key=warehouseKey(row.warehouse),origin=text(row.origin);
if(!key||!origin)continue;
const exactValues=warehouses.get(exact)||new Set();exactValues.add(origin);warehouses.set(exact,exactValues);
const values=aliases.get(key)||new Set();values.add(origin);aliases.set(key,values);
}
return {provinces,warehouses,aliases,regions:[...regions,UNMAPPED_REGION]};
}
export function buildRegionalDay(day,mapping){
const compiled=compileMappings(mapping),rows=new Map(),originCounts=new Map(),unmappedWarehouses=new Map(),unmappedProvinces=new Map();
const ids=new Set();
for(const row of day.details){
if(ids.has(row.o_id))throw new Error('DUPLICATE_REGIONAL_ORDER');ids.add(row.o_id);
if(row.send_date.slice(0,10)!==day.date)throw new Error('REGIONAL_DATE_MISMATCH');
const exact=compiled.warehouses.get(text(row.warehouse_name));
if(exact?.size>1)throw new Error('CONFLICTING_WAREHOUSE_ORIGIN_'+row.warehouse_name);
const origins=exact||compiled.aliases.get(warehouseKey(row.warehouse_name));
const origin=origins?.size===1?[...origins][0]:UNMAPPED_ORIGIN;
const province=compiled.provinces.get(provinceKey(row.receiver_state))||{province:text(row.receiver_state)||'未填写省份',region:UNMAPPED_REGION,index:999};
if(origin===UNMAPPED_ORIGIN)unmappedWarehouses.set(row.warehouse_name,(unmappedWarehouses.get(row.warehouse_name)||0)+1);
if(province.region===UNMAPPED_REGION)unmappedProvinces.set(province.province,(unmappedProvinces.get(province.province)||0)+1);
const carrier=row.logistics_company||'未填写快递名称';
const key=JSON.stringify([origin,province.region,province.province,carrier]);
const current=rows.get(key)||{origin,region:province.region,province:province.province,provinceOrder:province.index,carrier,count:0};current.count++;rows.set(key,current);
originCounts.set(origin,(originCounts.get(origin)||0)+1);
}
if(ids.size!==day.total||[...rows.values()].reduce((n,row)=>n+row.count,0)!==day.total)throw new Error('REGIONAL_TOTAL_MISMATCH');
const provinces=[...compiled.provinces.values()].map(row=>({region:row.region,province:row.province,provinceOrder:row.index}));
for(const row of rows.values())if(!provinces.some(item=>item.province===row.province&&item.region===row.region))provinces.push({region:row.region,province:row.province,provinceOrder:row.provinceOrder});
return {date:day.date,total:day.total,rows:[...rows.values()],provinces,origins:[...originCounts].map(([name,total])=>({name,total})).sort(compareOrigins),regions:compiled.regions,unmappedWarehouses:[...unmappedWarehouses].map(([name,total])=>({name,total})),unmappedProvinces:[...unmappedProvinces].map(([name,total])=>({name,total}))};
}
export function regionalPivot(day,origin=''){
const facts=day.rows.filter(row=>!origin||row.origin===origin),carrierCounts=new Map(),provinceRows=new Map();
for(const row of day.provinces)provinceRows.set(JSON.stringify([row.region,row.province]),{...row,counts:{},total:0});
for(const row of facts){
carrierCounts.set(row.carrier,(carrierCounts.get(row.carrier)||0)+row.count);
const key=JSON.stringify([row.region,row.province]);const province=provinceRows.get(key)||{region:row.region,province:row.province,provinceOrder:row.provinceOrder,counts:{},total:0};
province.counts[row.carrier]=(province.counts[row.carrier]||0)+row.count;province.total+=row.count;provinceRows.set(key,province);
}
const carriers=[...carrierCounts].sort((a,b)=>b[1]-a[1]||a[0].localeCompare(b[0],'zh-CN')).map(([name])=>name),rows=[];
for(const region of day.regions){
const group=[...provinceRows.values()].filter(row=>row.region===region).sort((a,b)=>a.provinceOrder-b.provinceOrder||a.province.localeCompare(b.province,'zh-CN'));
if(!group.length)continue;
rows.push(...group.map(row=>({...row,kind:'province'})));
const counts=Object.fromEntries(carriers.map(name=>[name,group.reduce((n,row)=>n+(row.counts[name]||0),0)]));
rows.push({region,province:region+'小计',kind:'subtotal',counts,total:group.reduce((n,row)=>n+row.total,0)});
}
const total=[...carrierCounts.values()].reduce((n,value)=>n+value,0);
rows.push({region:'',province:'总计',kind:'total',counts:Object.fromEntries(carrierCounts),total});
return {carriers,rows,total};
}

View File

@ -0,0 +1,22 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {buildRegionalDay,regionalPivot,UNMAPPED_ORIGIN,UNMAPPED_REGION} from './regional.mjs';
const map={provinces:[{province:'江苏',region:'一区'},{province:'山东',region:'二区'}],warehouses:[{warehouse:'崔桥工厂仓',origin:'常州'},{warehouse:'新苏北仓',origin:'苏北'}]};
const order=(id,province,warehouse,carrier='快递甲')=>({o_id:id,receiver_state:province,warehouse_name:warehouse,logistics_company:carrier,send_date:'2026-11-24 12:00:00'});
test('province aliases and local warehouse names map without changing totals',()=>{
const day=buildRegionalDay({date:'2026-11-24',total:3,details:[order('1','江苏省','简尚-崔桥工厂仓'),order('2','山东省','简尚-新苏北仓'),order('3','江苏省','简尚-崔桥工厂仓','快递乙')]},map);
const all=regionalPivot(day),changzhou=regionalPivot(day,'常州');assert.equal(all.total,3);assert.equal(changzhou.total,2);
assert.equal(changzhou.rows.find(row=>row.kind==='subtotal').total,2);assert.deepEqual(changzhou.carriers,['快递甲','快递乙']);
assert.equal(day.rows.find(row=>row.province==='江苏').region,'一区');
});
test('unmatched keys stay visible and conflicting local mappings fail',()=>{
const day=buildRegionalDay({date:'2026-11-24',total:1,details:[order('1','西藏','未知仓')]},map);
assert.equal(day.rows[0].origin,UNMAPPED_ORIGIN);assert.equal(day.rows[0].region,UNMAPPED_REGION);assert.equal(regionalPivot(day).total,1);
assert.throws(()=>buildRegionalDay({date:'2026-11-24',total:1,details:[order('1','江苏','崔桥工厂仓')]},{...map,warehouses:[...map.warehouses,{warehouse:'崔桥工厂仓',origin:'山东'}]}),/CONFLICTING/);
});
test('missing mappings, duplicate orders and wrong dates cannot pass as valid data',()=>{
assert.throws(()=>buildRegionalDay({date:'2026-11-24',total:0,details:[]},{provinces:[],warehouses:[]}),/REQUIRED/);
const row=order('1','江苏省','简尚-崔桥工厂仓');
assert.throws(()=>buildRegionalDay({date:'2026-11-24',total:2,details:[row,row]},map),/DUPLICATE/);
assert.throws(()=>buildRegionalDay({date:'2026-11-25',total:1,details:[row]},map),/DATE/);
});

View File

@ -0,0 +1,6 @@
const {req,env}=require('./environment.cjs'),sql=req('mssql');
const required=key=>{if(!env[key])throw new Error('MISSING_'+key);return env[key];};
const schema=env.JST_REPORT_DB_SCHEMA||'rpt';if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(schema))throw new Error('INVALID_SCHEMA');
const bool=key=>!['false','0'].includes(String(env[key]??'true').toLowerCase());
const pool=new sql.ConnectionPool({server:required('JST_REPORT_DB_HOST'),port:Number(env.JST_REPORT_DB_PORT||1433),database:required('JST_REPORT_DB_NAME'),user:required('JST_REPORT_DB_USER'),password:required('JST_REPORT_DB_PASSWORD'),options:{encrypt:bool('JST_REPORT_DB_ENCRYPT'),trustServerCertificate:bool('JST_REPORT_DB_TRUST_SERVER_CERTIFICATE'),readOnlyIntent:true,useUTC:true,appName:'codex-province-alternative-readonly'},pool:{min:0,max:2,idleTimeoutMillis:30000},connectionTimeout:20000,requestTimeout:180000});
module.exports={pool,sql,schema};

View File

@ -0,0 +1,67 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {spawn} from 'node:child_process';
import environment from './environment.cjs';
import {aggregateDay,validateDayDetails,windowDates,expiredSnapshotFiles,businessYesterday} from './core.mjs';
import {completeDayProvinces,validateProvinceEnrichment,PROVINCE_VERSION} from './province.mjs';
import {openSource} from './source.mjs';
import {buildSnapshot,publishSnapshot} from './snapshot.mjs';
import {deliverNotification,validateNotificationReport,validateRobotConfig} from './uncollected-notifications.mjs';
const root=path.dirname(fileURLToPath(import.meta.url)),{env,app}=environment;
const directory=path.resolve(env.DAILY_EXPRESS_DATA_DIR||path.join(app,'.daily-express'));
const read=async file=>JSON.parse(await fs.readFile(file,'utf8'));
const seed=process.argv.find(arg=>arg.startsWith('--seed='))?.slice(7);
const target=process.argv.find(arg=>arg.startsWith('--date='))?.slice(7)||businessYesterday();
const startedAt=new Date().toISOString();
async function child(file,args){await new Promise((resolve,reject)=>{
const proc=spawn(process.execPath,[path.join(root,file),...args],{windowsHide:true,env:{...process.env,...env},stdio:['ignore','pipe','pipe']});let output='';
proc.stdout.on('data',chunk=>{output+=chunk});proc.stderr.on('data',chunk=>{output+=chunk});proc.on('error',reject);
proc.on('exit',code=>{if(code===0)resolve();else{let last;for(const line of output.split('\n'))try{const item=JSON.parse(line);if(item.errorCode)last=item;}catch{}
reject(Object.assign(new Error('DAILY_EXPRESS_SOURCE_FAILED'),{code:last?.errorCode||'QUERY_FAILED',number:last?.number}));}});
});}
let source,lock;
try{
await fs.mkdir(directory,{recursive:true});
const lockFile=path.join(directory,'generation.lock');
try{lock=await fs.open(lockFile,'wx');}catch(error){
if(error.code!=='EEXIST')throw error;
const owner=await read(lockFile);
try{process.kill(owner.pid,0);throw new Error('GENERATION_ALREADY_RUNNING');}catch(check){if(check.code!=='ESRCH')throw check;}
await fs.unlink(lockFile);lock=await fs.open(lockFile,'wx');
}
await lock.writeFile(JSON.stringify({pid:process.pid,startedAt}));
const daysDir=seed?path.join(seed,'days'):path.join(directory,'days');await fs.mkdir(daysDir,{recursive:true});
const snapshots=[];
for(const date of windowDates(target)){
const file=path.join(daysDir,date+'.json');let day;
try{day=validateDayDetails(await read(file));}catch(error){if(error.code!=='ENOENT')throw error;}
if(!day){if(seed)throw new Error('SEED_MISSING_DATE');source??=await openSource();day=aggregateDay(date,await source.fetchDay(date),source.warehouses);}
if(day.provinceEnrichment?.version!==PROVINCE_VERSION){source??=await openSource();const missing=day.details.filter(row=>!row.receiver_state.trim());day=completeDayProvinces(day,await source.fetchProvinceCandidates(missing));}
validateProvinceEnrichment(day);snapshots.push(day);
if(!seed){await fs.writeFile(file+'.tmp',JSON.stringify(day));await fs.rename(file+'.tmp',file);}
}
if(source){await source.close();source=null;}
const stage=seed?path.join(seed,'staging'):path.join(directory,'staging');await fs.mkdir(stage,{recursive:true});
if(!seed){await child('fetch-uncollected.cjs',['--date='+target,'--output='+path.join(stage,'uncollected-source.json')]);await child('fetch-refund-checks.cjs',['--source='+path.join(stage,'uncollected-source.json'),'--output='+path.join(stage,'uncollected-refund-checks.json')]);}
const mappings=await read(seed?path.join(seed,'local-logistics-mappings.json'):path.join(directory,'mappings.json'));
const built=buildSnapshot(snapshots,await read(path.join(stage,'uncollected-source.json')),await read(path.join(stage,'uncollected-refund-checks.json')),mappings);
if(!seed)validateNotificationReport(built.report.uncollected,{target,refreshedAfter:startedAt});
const pointer=await publishSnapshot(directory,built);
if(seed){
await fs.mkdir(path.join(directory,'days'),{recursive:true});
for(const day of snapshots)await fs.writeFile(path.join(directory,'days',day.date+'.json'),JSON.stringify(day));
await fs.writeFile(path.join(directory,'mappings.json'),JSON.stringify({version:mappings.version,provinces:mappings.provinces,warehouses:mappings.warehouses}));
}
let notification={status:'seed_not_sent'};
if(!seed){
if(!env.DAILY_EXPRESS_DINGTALK_CONFIG)throw new Error('DINGTALK_CONFIG_REQUIRED');
const config=validateRobotConfig(await read(env.DAILY_EXPRESS_DINGTALK_CONFIG));
notification=await deliverNotification({directory:path.join(directory,'notifications'),report:built.report.uncollected,config});
}
const status={status:'success',date:target,generation:pointer.generation,total:built.report.overview.total,uncollected:built.report.uncollected.summary.total,notification,updatedAt:new Date().toISOString()};
await fs.writeFile(path.join(directory,'last-run.json'),JSON.stringify(status));
if(!seed)for(const name of expiredSnapshotFiles(await fs.readdir(daysDir),target))await fs.unlink(path.join(daysDir,name));
console.log(JSON.stringify(status));
}catch(error){const status={status:'failed',date:target,errorCode:error.code||error.message||error.name,number:error.number||null,updatedAt:new Date().toISOString()};await fs.writeFile(path.join(directory,'last-run.json'),JSON.stringify(status));console.error(JSON.stringify(status));process.exitCode=1;}
finally{if(source)await source.close().catch(()=>{});if(lock){await lock.close();await fs.unlink(path.join(directory,'generation.lock'));}}

View File

@ -0,0 +1,37 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import {createHash,randomUUID} from 'node:crypto';
import {buildFacts,collectDetails,validateDayDetails} from './core.mjs';
import {buildRegionalDay} from './regional.mjs';
import {validateUncollected,applyUncollectedRules,summarizeUncollected,UNCOLLECTED_COLUMNS} from './uncollected.mjs';
import {attachRefundChecks} from './refund.mjs';
const hash=data=>createHash('sha256').update(data).digest('hex');
export function buildSnapshot(days,source,refund,mappings){
days.forEach(validateDayDetails);validateUncollected(source);
const latest=days.at(-1).date;
if(source.summary.date!==latest||refund.sourceQueriedAt!==source.summary.queriedAt)throw new Error('SNAPSHOT_SOURCE_MISMATCH');
const facts=buildFacts(days,latest),details=collectDetails(days);
const rows=applyUncollectedRules(attachRefundChecks(source.rows,refund,latest));
const overview={dateFrom:facts.dateFrom,dateTo:facts.dateTo,days:facts.days,daily:facts.daily.map(({date,total})=>({date,total})),total:facts.total,carrierCount:facts.carrierCount,ranking:facts.ranking};
const report={version:1,dateTo:latest,updatedAt:new Date().toISOString(),overview,
regional:{dates:facts.days,latestDate:latest,days:days.map(day=>buildRegionalDay(day,mappings))},
uncollected:{date:latest,queriedAt:source.summary.queriedAt,refundCheckedAt:refund.completedAt,summary:summarizeUncollected(rows),columns:UNCOLLECTED_COLUMNS.map(([key,label])=>({key,label})),rows}};
return {report,details};
}
export async function publishSnapshot(directory,{report,details}){
await fs.mkdir(directory,{recursive:true});
let previous;try{previous=JSON.parse(await fs.readFile(path.join(directory,'latest.json'),'utf8'));}catch(error){if(error.code!=='ENOENT')throw error;}
if(previous&&previous.dateTo>report.dateTo)throw new Error('CANNOT_PUBLISH_OLDER_DATE');
const generation=report.updatedAt.replace(/[^0-9]/g,'')+'-'+randomUUID();
const target=path.join(directory,'generations',generation);await fs.mkdir(target,{recursive:true});
const reportBytes=JSON.stringify(report),detailsBytes=JSON.stringify(details);
await fs.writeFile(path.join(target,'report.json'),reportBytes);await fs.writeFile(path.join(target,'details.json'),detailsBytes);
const pointer={version:1,generation,dateTo:report.dateTo,updatedAt:report.updatedAt,reportHash:hash(reportBytes),detailsHash:hash(detailsBytes)};
const temporary=path.join(directory,'latest.'+randomUUID()+'.tmp');await fs.writeFile(temporary,JSON.stringify(pointer));await fs.rename(temporary,path.join(directory,'latest.json'));
// Expired generations contain order details; retain only the atomically selected generation.
for(const name of await fs.readdir(path.join(directory,'generations'))){if(name===generation||!/^\d+-[a-f0-9-]+$/.test(name))continue;
const expired=path.resolve(directory,'generations',name);if(path.dirname(expired)!==path.resolve(directory,'generations'))throw new Error('INVALID_RETENTION_PATH');
await fs.rm(expired,{recursive:true,force:true});
}
return pointer;
}

View File

@ -0,0 +1,19 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import {createHash} from 'node:crypto';
import {aggregateDay} from './core.mjs';
import {buildSnapshot,publishSnapshot} from './snapshot.mjs';
test('published snapshots reconcile all views and refuse older dates',async()=>{
const day=aggregateDay('2026-11-24',[{o_id:'1',so_id:'001',source:'jst_Orders',status:'Sent',send_date:'2026-11-24 10:00:00',l_id:'001234',logistics_company:'测试快递',receiver_state:'江苏',co_id:'1',wms_co_id:'2'}],[{co_id:'1',wms_co_id:'2',name:'测试仓'}]);
const queriedAt='2026-11-25T01:00:00Z',source={summary:{date:day.date,queriedAt,rowCount:0},rows:[]};
const refund={version:'item-refund-success-v1',date:day.date,sourceQueriedAt:queriedAt,completedAt:queriedAt,candidates:[],masters:[],items:[]};
const built=buildSnapshot([day],source,refund,{provinces:[{province:'江苏',region:'华东'}],warehouses:[{warehouse:'测试仓',origin:'常州自有仓'}]});
assert.equal(built.report.overview.total,1);assert.equal(built.report.regional.days[0].total,1);assert.equal(built.report.uncollected.summary.total,0);assert.equal(built.details[0].l_id,'001234');
assert.throws(()=>buildSnapshot([day],{...source,summary:{...source.summary,date:'2026-11-23'}},refund,{}),/SOURCE_MISMATCH/);
const root=await fs.mkdtemp(path.join(os.tmpdir(),'express-snapshot-'));
try{await publishSnapshot(root,built);const pointer=JSON.parse(await fs.readFile(path.join(root,'latest.json'),'utf8'));const bytes=await fs.readFile(path.join(root,'generations',pointer.generation,'report.json'));assert.equal(pointer.reportHash,createHash('sha256').update(bytes).digest('hex'));await assert.rejects(()=>publishSnapshot(root,{...built,report:{...built.report,dateTo:'2026-11-23'}}),/OLDER_DATE/);}
finally{assert.equal(path.dirname(root),os.tmpdir());await fs.rm(root,{recursive:true,force:true});}
});

View File

@ -0,0 +1,40 @@
import fs from 'node:fs';
import {createRequire} from 'node:module';
import {addDays,assertDate,SOURCES} from './core.mjs';
import environment from './environment.cjs';
const {app}=environment;
const require=createRequire(app+'/package.json'),sql=require('mssql');
export async function openSource(){
const {env}=environment;
const required=key=>{if(!env[key])throw Object.assign(new Error('Missing configuration'),{code:'MISSING_'+key});return env[key];};
const schema=env.JST_REPORT_DB_SCHEMA||'rpt';if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(schema))throw new Error('INVALID_SCHEMA');
const bool=key=>!['false','0'].includes(String(env[key]??'true').toLowerCase());
const pool=new sql.ConnectionPool({server:required('JST_REPORT_DB_HOST'),port:Number(env.JST_REPORT_DB_PORT||1433),database:required('JST_REPORT_DB_NAME'),user:required('JST_REPORT_DB_USER'),password:required('JST_REPORT_DB_PASSWORD'),options:{encrypt:bool('JST_REPORT_DB_ENCRYPT'),trustServerCertificate:bool('JST_REPORT_DB_TRUST_SERVER_CERTIFICATE'),readOnlyIntent:true,appName:'codex-carrier-daily-readonly',useUTC:true},pool:{min:0,max:2,idleTimeoutMillis:30000},connectionTimeout:20000,requestTimeout:180000});
await pool.connect();
try{
const warehouses=(await pool.request().query(`SET LOCK_TIMEOUT 15000; SELECT CAST(co_id AS varchar(40)) AS co_id,CAST(wms_co_id AS varchar(40)) AS wms_co_id,name FROM [${schema}].[jst_warehouseInfo];`)).recordset;
const fetchRange=async(from,to)=>{
assertDate(from);assertDate(to);if(to<=from)throw new Error('INVALID_SOURCE_RANGE');
const results=await Promise.allSettled(SOURCES.map(async source=>{
const startedAt=Date.now();console.log(JSON.stringify({from,toExclusive:to,source,stage:'source_started'}));
const result=await pool.request().input('start',sql.Date,from).input('end',sql.Date,to).query(`SET LOCK_TIMEOUT 15000;
SELECT CAST(o_id AS varchar(40)) AS o_id,so_id,logistics_company,l_id,receiver_state,CONVERT(varchar(23),send_date,121) AS send_date,CAST(co_id AS varchar(40)) AS co_id,CAST(wms_co_id AS varchar(40)) AS wms_co_id,status
FROM [${schema}].[${source}] WHERE send_date>=@start AND send_date<@end;`);
const rows=result.recordset.filter(r=>r.status==='Sent').map(r=>({...r,source}));
console.log(JSON.stringify({from,toExclusive:to,source,stage:'source_complete',rows:rows.length,elapsedSeconds:Math.round((Date.now()-startedAt)/1000)}));return rows;
}));
for(const result of results)if(result.status==='rejected')throw result.reason;
return results.flatMap(result=>result.value);
};
const fetchProvinceCandidates=async details=>{
if(!details.length)return [];
const result=await pool.request().input('ids',sql.NVarChar(sql.MAX),JSON.stringify(details.map(row=>row.o_id))).query(`SET LOCK_TIMEOUT 15000;
SELECT CAST(inner_order_id AS varchar(40)) AS o_id,so_id,logistic_id AS l_id,
LEFT(LTRIM(receiver_address),CHARINDEX(N'-',LTRIM(receiver_address)+N'-')-1) AS region
FROM [${schema}].[jst_order_express_details]
WHERE inner_order_id IN (SELECT CONVERT(bigint,value) FROM OPENJSON(@ids));`);
return result.recordset;
};
return {warehouses,close:()=>pool.close(),fetchRange,fetchDay:date=>fetchRange(date,addDays(date,1)),fetchProvinceCandidates};
}catch(error){await pool.close();throw error;}
}

View File

@ -0,0 +1,187 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import assert from 'node:assert/strict';
import {createHash,createHmac} from 'node:crypto';
import {businessYesterday,addDays} from './core.mjs';
import {validateUncollected,applyUncollectedRules,summarizeUncollected} from './uncollected.mjs';
import {attachRefundChecks} from './refund.mjs';
const hash=value=>createHash('sha256').update(value).digest('hex');
const fail=code=>Object.assign(new Error(code),{code});
const readJson=async file=>JSON.parse(await fs.readFile(file,'utf8'));
const singleLine=value=>String(value??'').replace(/[\r\n\t]+/g,' ').trim()||'未填写';
const localTime=value=>new Intl.DateTimeFormat('sv-SE',{timeZone:'Asia/Shanghai',year:'numeric',month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',second:'2-digit',hour12:false}).format(new Date(value));
async function saveJson(file,value){
await fs.writeFile(file+'.tmp',JSON.stringify(value,null,2));
await fs.rename(file+'.tmp',file);
}
export function validateNotificationReport(report,{target,now=new Date(),refreshedAfter,reviewedSnapshot=false}){
if(target!==businessYesterday(now)||report.date!==target)throw fail('NOTIFICATION_NOT_YESTERDAY');
const queried=Date.parse(report.queriedAt),refund=Date.parse(report.refundCheckedAt);
if(!Number.isFinite(queried)||!Number.isFinite(refund)||queried>+now||refund>+now||refund<queried)throw fail('NOTIFICATION_INVALID_QUERY_TIME');
if(businessYesterday(new Date(queried))!==target)throw fail('NOTIFICATION_STALE_QUERY');
if(!reviewedSnapshot&&(!Number.isFinite(Date.parse(refreshedAfter))||queried<Date.parse(refreshedAfter)))throw fail('NOTIFICATION_NOT_REFRESHED_THIS_RUN');
if(!Array.isArray(report.rows))throw fail('NOTIFICATION_MISSING_ROWS');
const ids=new Set();
for(const row of report.rows){
if(row.id==null||ids.has(String(row.id))||row.fetch_time!==null||!String(row.send_time).startsWith(target+' '))throw fail('NOTIFICATION_INVALID_ROW');
ids.add(String(row.id));
}
assert.deepEqual(applyUncollectedRules(report.rows),report.rows,'Notification contains excluded records');
assert.deepEqual(summarizeUncollected(report.rows),report.summary,'Notification totals do not match details');
return report;
}
export async function readNotificationReport({root,output,target,now=new Date(),refreshedAfter,reviewedSnapshot=false}){
const receipt=await readJson(path.join(root,'published-state.json'));
const html=await fs.readFile(path.join(output,'发货揽收看板.html'),'utf8');
const summary=await fs.readFile(path.join(output,'uncollected-summary.json'));
if(receipt.files['发货揽收看板.html']!==hash(html)||receipt.files['uncollected-summary.json']!==hash(summary))throw fail('NOTIFICATION_UNVERIFIED_PUBLICATION');
const match=html.match(/^const payload=(.*);$/m);
if(!match)throw fail('NOTIFICATION_MISSING_PAYLOAD');
const report=JSON.parse(match[1]);
const source=validateUncollected(await readJson(path.join(root,'staging/uncollected-source.json')));
const refunds=await readJson(path.join(root,'staging/uncollected-refund-checks.json'));
if(source.summary.date!==target||source.summary.queriedAt!==report.queriedAt||refunds.sourceQueriedAt!==report.queriedAt||refunds.completedAt!==report.refundCheckedAt)throw fail('NOTIFICATION_SOURCE_CHANGED');
assert.deepEqual(applyUncollectedRules(attachRefundChecks(source.rows,refunds,target)),report.rows);
assert.deepEqual(JSON.parse(summary),{date:report.date,queriedAt:report.queriedAt,...report.summary});
return validateNotificationReport(report,{target,now,refreshedAfter,reviewedSnapshot});
}
export function buildNotificationTexts(report,{keyword='',reviewedSnapshot=false}={}){
const header=[`昨日未揽收订单提醒${reviewedSnapshot?'(已核对快照)':''}`,`发货日期:${report.date}`,`数据查询:${localTime(report.queriedAt)}(北京时间)`,`退款核对:${localTime(report.refundCheckedAt)}(北京时间)`,`未揽收:${report.rows.length} 单`].join('\n');
const budget=14000-Buffer.byteLength(keyword,'utf8');
const messagePrefix=header+'\n第 999999/999999 条消息\n\n';
const fits=block=>Buffer.byteLength(messagePrefix+block,'utf8')<=budget;
// Keep all tracking numbers of a carrier together, but never mix their warehouses.
const carriers=new Map();
for(const row of report.rows){
const carrier=String(row.logistic_company_name??'').trim(),warehouse=String(row.warehouse_name??'').trim();
if(!carriers.has(carrier))carriers.set(carrier,new Map());
const warehouses=carriers.get(carrier);
if(!warehouses.has(warehouse))warehouses.set(warehouse,[]);
warehouses.get(warehouse).push(singleLine(row.logistic_id));
}
const blocks=[];let groupIndex=0;
const carrierOrder=new Intl.Collator('zh-CN',{numeric:true});
for(const [carrier,warehouses] of [...carriers].sort(([a],[b])=>carrierOrder.compare(a,b)))for(const [warehouse,trackingNumbers] of warehouses){
groupIndex++;let currentTracking=[],continuation=false;
const render=numbers=>`${groupIndex}. 快递单号${continuation?'(续)':''}:\n${numbers.join('\n')}\n快递名称:${singleLine(carrier)}\n发货仓库:${singleLine(warehouse)}`;
for(const tracking of trackingNumbers){
if(!fits(render([...currentTracking,tracking]))){
if(!currentTracking.length)throw fail('NOTIFICATION_ROW_TOO_LONG');
blocks.push(render(currentTracking));currentTracking=[];continuation=true;
}
if(!fits(render([tracking])))throw fail('NOTIFICATION_ROW_TOO_LONG');
currentTracking.push(tracking);
}
if(currentTracking.length)blocks.push(render(currentTracking));
}
const groups=[];let current=[];
for(const block of blocks){
if(current.length&&!fits([...current,block].join('\n\n'))){groups.push(current);current=[];}
current.push(block);
}
if(current.length||groups.length===0)groups.push(current);
return groups.map((group,index)=>header+(groups.length>1?`\n第 ${index+1}/${groups.length} 条消息`:'')+'\n\n'+(group.length?group.join('\n\n'):'昨日无符合条件的未揽收订单。'));
}
export function validateRobotConfig(config){
let url;try{url=new URL(config.webhook);}catch{throw fail('INVALID_DINGTALK_CONFIGURATION');}
if(url.protocol!=='https:'||url.hostname!=='oapi.dingtalk.com'||url.port||url.pathname!=='/robot/send'||url.username||url.password||url.hash||!url.searchParams.get('access_token')||url.searchParams.has('sign')||url.searchParams.has('timestamp'))throw fail('INVALID_DINGTALK_CONFIGURATION');
if(!Array.isArray(config.atMobiles)||typeof config.isAtAll!=='boolean')throw fail('INVALID_DINGTALK_RECIPIENTS');
return config;
}
export async function loadNotificationConfig(root){
const settings=await readJson(path.join(root,'notification-config.json'));
if(settings.enabled!==true)throw fail('NOTIFICATIONS_DISABLED');
const original=await readJson(settings.offboardingTaskConfigPath);
if(!path.isAbsolute(original.notificationConfigPath))throw fail('INVALID_ORIGINAL_NOTIFICATION_PATH');
return validateRobotConfig(await readJson(original.notificationConfigPath));
}
export function buildRobotRequest(config,text,now=Date.now()){
validateRobotConfig(config);
const url=new URL(config.webhook);
if(config.secret){
const timestamp=String(now);
const signature=createHmac('sha256',config.secret).update(timestamp+'\n'+config.secret).digest('base64');
url.searchParams.set('timestamp',timestamp);url.searchParams.set('sign',signature);
}
const content=(config.keyword?config.keyword+'\n':'')+text;
const body=JSON.stringify({msgtype:'text',text:{content},at:{atMobiles:config.atMobiles,isAtAll:config.isAtAll}});
if(Buffer.byteLength(body,'utf8')>18000)throw fail('NOTIFICATION_MESSAGE_TOO_LONG');
return {url:url.href,body};
}
export async function sendRobotText(config,text){
const request=buildRobotRequest(config,text);
let response,answer;
try{
response=await fetch(request.url,{method:'POST',headers:{'Content-Type':'application/json; charset=utf-8'},body:request.body,redirect:'error',signal:AbortSignal.timeout(15000)});
answer=await response.json();
}catch{throw fail('DINGTALK_DELIVERY_UNKNOWN');}
if(!response.ok||!Number.isInteger(answer?.errcode))throw fail('DINGTALK_DELIVERY_UNKNOWN');
if(answer.errcode!==0)throw Object.assign(fail('DINGTALK_REJECTED_'+answer.errcode),{definitelyRejected:true});
return {accepted:true,acceptedAt:new Date().toISOString()};
}
async function lockDelivery(directory){
await fs.mkdir(directory,{recursive:true});
const file=path.join(directory,'send.lock');
const open=async()=>{const handle=await fs.open(file,'wx');await handle.writeFile(JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()}));return handle;};
let handle;
try{handle=await open();}catch(error){
if(error.code!=='EEXIST')throw error;
const holder=await readJson(file);
try{process.kill(holder.pid,0);throw fail('NOTIFICATION_ALREADY_RUNNING');}catch(check){if(check.code!=='ESRCH')throw check;}
await fs.unlink(file);handle=await open();
}
return async()=>{await handle.close();await fs.unlink(file);};
}
export async function deliverNotification({directory,report,config,reviewedSnapshot=false,deliveryRevision='',transport=sendRobotText,pause=ms=>new Promise(resolve=>setTimeout(resolve,ms))}){
validateRobotConfig(config);
if(deliveryRevision&&!/^[a-z][a-z0-9-]{0,40}$/.test(deliveryRevision))throw fail('INVALID_NOTIFICATION_REVISION');
const release=await lockDelivery(directory);
try{
const filename=path.join(directory,report.date+(deliveryRevision?'.'+deliveryRevision:'')+'.json');
const destination=hash(config.webhook);
let state;try{state=await readJson(filename);}catch(error){if(error.code!=='ENOENT')throw error;}
if(state&&state.destination!==destination)throw fail('NOTIFICATION_DESTINATION_CHANGED');
if(state?.status==='sent')return {status:'already_sent',date:state.date,total:state.total,parts:state.parts.length,sentAt:state.sentAt};
if(state?.parts.some(part=>part.status==='sending'||part.status==='unknown'))throw fail('DINGTALK_DELIVERY_NEEDS_RECONCILIATION');
if(!state){
state={version:1,format:'carrier-name-sorted-v3',deliveryRevision,date:report.date,total:report.rows.length,queriedAt:report.queriedAt,refundCheckedAt:report.refundCheckedAt,destination,reviewedSnapshot,status:'pending',createdAt:new Date().toISOString(),parts:buildNotificationTexts(report,{keyword:config.keyword,reviewedSnapshot}).map((text,index)=>({index,text,status:'pending',attempts:0}))};
await saveJson(filename,state);
}
// Retain only this task's last 15 shipment dates, including message bodies.
for(const name of await fs.readdir(directory))if(/^\d{4}-\d{2}-\d{2}(?:\.[a-z][a-z0-9-]{0,40})?\.json$/.test(name)&&name.slice(0,10)<addDays(report.date,-14))await fs.unlink(path.join(directory,name));
let sentThisRun=0;
for(const part of state.parts){
if(part.status==='sent')continue;
if(sentThisRun)await pause(3200);
part.status='sending';part.attempts++;await saveJson(filename,state);
try{
const result=await transport(config,part.text);
if(result?.accepted!==true)throw fail('DINGTALK_DELIVERY_UNKNOWN');
part.status='sent';part.sentAt=result.acceptedAt||new Date().toISOString();delete part.lastError;
}catch(error){
part.status=error.definitelyRejected?'pending':'unknown';part.lastError=error.code?.match(/^DINGTALK_[A-Z_0-9]+$/)?error.code:'DINGTALK_DELIVERY_UNKNOWN';
state.status=part.status==='unknown'?'delivery_unknown':'pending_retry';
await saveJson(filename,state);throw fail(part.lastError);
}
await saveJson(filename,state);sentThisRun++;
}
state.status='sent';state.sentAt=new Date().toISOString();await saveJson(filename,state);
return {status:'sent',date:state.date,total:state.total,parts:state.parts.length,sentAt:state.sentAt};
}finally{await release();}
}
export async function notifyPublishedUncollected(options){
const report=await readNotificationReport(options);
const config=await loadNotificationConfig(options.root);
return deliverNotification({directory:path.join(options.root,'notifications'),report,config,reviewedSnapshot:options.reviewedSnapshot,deliveryRevision:options.deliveryRevision});
}

View File

@ -0,0 +1,93 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import {createHmac} from 'node:crypto';
import {summarizeUncollected} from './uncollected.mjs';
import {validateNotificationReport,buildNotificationTexts,buildRobotRequest,deliverNotification} from './uncollected-notifications.mjs';
const config={webhook:'https://oapi.dingtalk.com/robot/send?access_token=unit-test-only',secret:'unit-test-secret',keyword:'测试',atMobiles:[],isAtAll:false};
const row=(id)=>({id,inner_order_id:String(id),logistic_id:'3311719'+String(id).padStart(6,'0'),logistic_company_name:'测试中通',warehouse_name:'常州测试仓',send_time:'2026-11-24 11:15:00',fetch_time:null,logistic_status_name:'未揽收',order_status_name:'已发货',first_question_type:null,order_labels:'',remark:'',refund_checked:true,refund_success:false});
function report(count=2){const rows=Array.from({length:count},(_,i)=>row(i+1));return {date:'2026-11-24',queriedAt:'2026-11-25T01:01:00Z',refundCheckedAt:'2026-11-25T01:02:00Z',rows,summary:summarizeUncollected(rows)};}
const gate={target:'2026-11-24',now:new Date('2026-11-25T01:05:00Z'),refreshedAfter:'2026-11-25T01:00:00Z'};
async function fixture(action){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jst-notification-test-'));try{await action(dir);}finally{assert.ok(path.resolve(dir).startsWith(path.resolve(os.tmpdir())+path.sep));await fs.rm(dir,{recursive:true,force:true});}}
const accepted=()=>Promise.resolve({accepted:true,acceptedAt:'2026-11-25T01:05:00Z'});
test('same carrier and warehouse share one tracking list, name and warehouse label',()=>{
const value=report();validateNotificationReport(value,gate);
const texts=buildNotificationTexts(value);
assert.equal(texts.length,1);assert.match(texts[0],/发货日期:2026-11-24/);assert.match(texts[0],/数据查询:2026-11-25 09:01:00/);
assert.ok(texts[0].includes('快递单号:\n'+value.rows.map(item=>item.logistic_id).join('\n')));
assert.equal(texts[0].split('快递名称:测试中通').length-1,1);assert.equal(texts[0].split('发货仓库:常州测试仓').length-1,1);
assert.ok(!texts[0].includes('内部订单号'));assert.ok(!texts[0].includes('已剔除'));assert.ok(!texts[0].includes('占比'));
});
test('carriers stay together and separate warehouses preserve the correct tracking lists',()=>{
const value=report(5);
value.rows[1].logistic_company_name='另一家快递';
value.rows[2].warehouse_name='山东测试仓';
value.rows[4].warehouse_name='山东测试仓';
const text=buildNotificationTexts(value)[0];
const blocks=text.split(/\n\n/).slice(1);
assert.equal(blocks.length,3);
assert.ok(blocks[0].includes(value.rows[0].logistic_id+'\n'+value.rows[3].logistic_id));
assert.ok(blocks[0].endsWith('快递名称:测试中通\n发货仓库:常州测试仓'));
assert.ok(blocks[1].includes(value.rows[2].logistic_id+'\n'+value.rows[4].logistic_id));
assert.ok(blocks[1].endsWith('快递名称:测试中通\n发货仓库:山东测试仓'));
assert.ok(blocks[2].endsWith('快递名称:另一家快递\n发货仓库:常州测试仓'));
});
test('failed refresh, stale date, unchecked refund and mismatched totals cannot send',()=>{
assert.throws(()=>validateNotificationReport(report(),{...gate,refreshedAfter:'2026-11-25T01:03:00Z'}),/NOT_REFRESHED/);
assert.throws(()=>validateNotificationReport(report(),{...gate,target:'2026-11-23'}),/NOT_YESTERDAY/);
const stale=report();stale.queriedAt='2026-11-24T00:00:00Z';assert.throws(()=>validateNotificationReport(stale,{...gate,reviewedSnapshot:true}),/STALE_QUERY/);
const unchecked=report();unchecked.rows[0].refund_checked=false;assert.throws(()=>validateNotificationReport(unchecked,gate),/REFUND_STATUS_NOT_CHECKED/);
const refund=report();refund.rows[0].refund_success=true;assert.throws(()=>validateNotificationReport(refund,gate));
const wrong=report();wrong.summary.total++;assert.throws(()=>validateNotificationReport(wrong,gate));
});
test('large results split without truncation, zero results still notify, request preserves recipient settings and signing',()=>{
const value=report(1500),texts=buildNotificationTexts(value,{keyword:config.keyword});assert.ok(texts.length>1);
for(const text of texts){const request=buildRobotRequest(config,text,1795568700000);assert.ok(Buffer.byteLength(request.body)<18000);const body=JSON.parse(request.body);assert.deepEqual(body.at,{atMobiles:[],isAtAll:false});assert.equal(body.msgtype,'text');assert.ok(body.text.content.startsWith(config.keyword+'\n'));const u=new URL(request.url);assert.equal(u.searchParams.get('sign'),createHmac('sha256',config.secret).update('1795568700000\n'+config.secret).digest('base64'));}
for(const item of value.rows)assert.equal(texts.join('\n').split('\n'+item.logistic_id+'\n').length-1,1);
for(const text of texts){assert.match(text,/快递名称:测试中通/);assert.match(text,/发货仓库:常州测试仓/);}
assert.match(texts[1],/快递单号(续)/);
assert.match(buildNotificationTexts(report(0))[0],/未揽收:0 单/);
assert.throws(()=>buildRobotRequest({...config,webhook:'https://example.com/robot/send?access_token=x'},'test'),/INVALID_DINGTALK/);
});
test('successful daily delivery does not resend even if later data changes',async()=>fixture(async directory=>{
let calls=0;const transport=async()=>{calls++;return accepted();};
assert.equal((await deliverNotification({directory,report:report(),config,transport})).status,'sent');
assert.equal((await deliverNotification({directory,report:report(3),config,transport})).status,'already_sent');assert.equal(calls,1);
}));
test('explicit rejection resumes only unsent parts and retains the original report',async()=>fixture(async directory=>{
let calls=0,first;
const many=report(1500);
await assert.rejects(()=>deliverNotification({directory,report:many,config,pause:async()=>{},transport:async(_,text)=>{calls++;if(calls===1){first=text;return accepted();}throw Object.assign(new Error('reject'),{code:'DINGTALK_REJECTED_130101',definitelyRejected:true});}}),/DINGTALK_REJECTED/);
const saved=JSON.parse(await fs.readFile(path.join(directory,many.date+'.json'),'utf8'));
assert.equal(saved.parts[0].status,'sent');assert.equal(saved.parts[1].status,'pending');
const resumed=[];const result=await deliverNotification({directory,report:report(1),config,pause:async()=>{},transport:async(_,text)=>{resumed.push(text);return accepted();}});
assert.equal(result.total,1500);assert.ok(!resumed.includes(first));assert.equal(resumed.length,saved.parts.length-1);
}));
test('explicit grouped revision can be sent once without changing the daily receipt',async()=>fixture(async directory=>{
let calls=0;const transport=async()=>{calls++;return accepted();};
await deliverNotification({directory,report:report(),config,transport});
const original=await fs.readFile(path.join(directory,'2026-11-24.json'),'utf8');
await fs.writeFile(path.join(directory,'2026-11-01.carrier-grouped-v2.json'),'{}');
const options={directory,report:report(),config,transport,deliveryRevision:'carrier-grouped-v2'};
assert.equal((await deliverNotification(options)).status,'sent');
assert.equal((await deliverNotification(options)).status,'already_sent');
assert.equal((await deliverNotification({directory,report:report(),config,transport})).status,'already_sent');
assert.equal(calls,2);assert.equal(await fs.readFile(path.join(directory,'2026-11-24.json'),'utf8'),original);
await assert.rejects(()=>fs.access(path.join(directory,'2026-11-01.carrier-grouped-v2.json')));
}));
test('ambiguous network delivery is retained for reconciliation and is never automatically resent',async()=>fixture(async directory=>{
let calls=0;
await assert.rejects(()=>deliverNotification({directory,report:report(),config,transport:async()=>{calls++;throw new Error('network failure containing secrets');}}),/DINGTALK_DELIVERY_UNKNOWN/);
await assert.rejects(()=>deliverNotification({directory,report:report(),config,transport:accepted}),/NEEDS_RECONCILIATION/);assert.equal(calls,1);
const saved=await fs.readFile(path.join(directory,'2026-11-24.json'),'utf8');assert.ok(!saved.includes('containing secrets'));
}));
test('destination changes and concurrent sending stop without contacting a new recipient',async()=>fixture(async directory=>{
await deliverNotification({directory,report:report(),config,transport:accepted});
await assert.rejects(()=>deliverNotification({directory,report:report(),config:{...config,webhook:config.webhook+'2'},transport:accepted}),/DESTINATION_CHANGED/);
await fs.writeFile(path.join(directory,'send.lock'),JSON.stringify({pid:process.pid}));
await assert.rejects(()=>deliverNotification({directory,report:report(),config,transport:accepted}),/ALREADY_RUNNING/);
}));

View File

@ -0,0 +1,53 @@
export const UNCOLLECTED_COLUMNS=[
['inner_order_id','ERP 内部订单号',23],['so_id','线上订单号(交易单号)',34],['logistic_company_name','快递名称',26],['logistic_id','快递单号',30],
['warehouse_name','仓库名称',35],['send_time','发货时间',24],['fetch_time','揽收时间',24],['order_status_name','订单状态',15],
['logistic_status_name','物流状态',15],['logistic_return_flag','拦截状态',15],['aftersale_status_name','售后状态',15],
['shop_name','店铺名称',35],['platform_name','平台名称',20],['dis_co_name','分销商名称',30],['sign_time','签收时间',24],
['logistic_time','物流时间(logistic_time)',28],['query_time','物流查询时间',24],['first_question_type','首次问题类型',30],
['first_question_time','首次问题时间',24],['updatedAt','数据更新时间',24],['id','来源记录 ID',16],['order_labels','订单标签',65],['remark','订单备注',75],['refund_status','商品明细退款状态',26]
];
const text=value=>String(value??'').trim();
export const UNCOLLECTED_EXCLUSIONS={firstQuestionType:'1688一件代发',carrierContains:['京喜','京东自营','顺丰','京东','中铁','自提','武进安能','壹米滴答专线'],blankTracking:true,labelContains:['ECLP','CLPS','1688一件代发','刷单待处理'],remarkContains:['(收)','BBFF'],refundSuccess:true};
export function uncollectedExclusionReasons(row){
const reasons=[];
if(text(row.first_question_type)===UNCOLLECTED_EXCLUSIONS.firstQuestionType)reasons.push('first_question_type');
if(UNCOLLECTED_EXCLUSIONS.carrierContains.some(keyword=>text(row.logistic_company_name).includes(keyword)))reasons.push('carrier');
if(UNCOLLECTED_EXCLUSIONS.blankTracking&&!text(row.logistic_id))reasons.push('blank_tracking');
if(UNCOLLECTED_EXCLUSIONS.labelContains.some(keyword=>text(row.order_labels).toUpperCase().includes(keyword.toUpperCase())))reasons.push('order_labels');
const remark=text(row.remark).normalize('NFKC').toUpperCase();
if(UNCOLLECTED_EXCLUSIONS.remarkContains.some(keyword=>remark.includes(keyword.normalize('NFKC').toUpperCase())))reasons.push('remark');
return reasons;
}
export const applyUncollectedExclusions=rows=>rows.filter(row=>uncollectedExclusionReasons(row).length===0);
export const isUncollected=row=>text(row.logistic_status_name)==='未揽收';
export const applyUncollectedBaseRules=rows=>applyUncollectedExclusions(rows).filter(isUncollected);
export function applyUncollectedRules(rows){
const candidates=applyUncollectedBaseRules(rows);
for(const row of candidates)if(row.refund_checked!==true||typeof row.refund_success!=='boolean')throw new Error('REFUND_STATUS_NOT_CHECKED_'+row.inner_order_id);
return candidates.filter(row=>!row.refund_success);
}
export function groupUncollected(rows,key){
const map=new Map();for(const row of rows){const name=text(row[key])||'未填写';map.set(name,(map.get(name)||0)+1);}
return [...map].map(([name,count])=>({name,count})).sort((a,b)=>b.count-a.count||a.name.localeCompare(b.name,'zh-CN'));
}
export function validateUncollected(snapshot){
const date=snapshot?.summary?.date;
if(!/^\d{4}-\d{2}-\d{2}$/.test(date||'')||!Array.isArray(snapshot.rows)||!Number.isFinite(Date.parse(snapshot.summary.queriedAt)))throw new Error('INVALID_UNCOLLECTED_SNAPSHOT');
const ids=new Set();
for(const row of snapshot.rows){
if(!Object.prototype.hasOwnProperty.call(row,'order_labels'))throw new Error('UNCOLLECTED_ORDER_LABELS_REQUIRED');
if(!Object.prototype.hasOwnProperty.call(row,'remark'))throw new Error('UNCOLLECTED_ORDER_REMARK_REQUIRED');
if(!/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(row.send_time||'')||row.send_time.slice(0,10)!==date||row.fetch_time!==null)throw new Error('UNCOLLECTED_SOURCE_FILTER_MISMATCH');
if(row.id==null||ids.has(String(row.id)))throw new Error('DUPLICATE_UNCOLLECTED_RECORD');ids.add(String(row.id));
}
if(snapshot.summary.rowCount!==snapshot.rows.length)throw new Error('UNCOLLECTED_SOURCE_COUNT_MISMATCH');
return snapshot;
}
export function selectUncollected(rows,{pendingOnly=false,query=''}={}){
const search=text(query).toLocaleLowerCase('zh-CN');
return rows.filter(row=>(!pendingOnly||isUncollected(row))&&(!search||UNCOLLECTED_COLUMNS.slice(0,11).some(([key])=>text(row[key]).toLocaleLowerCase('zh-CN').includes(search))));
}
export function summarizeUncollected(rows){
return {total:rows.length,pending:rows.filter(isUncollected).length,uniqueOrders:new Set(rows.map(row=>text(row.inner_order_id)).filter(Boolean)).size,
carriers:groupUncollected(rows,'logistic_company_name'),warehouses:groupUncollected(rows,'warehouse_name'),statuses:groupUncollected(rows,'logistic_status_name'),orderStatuses:groupUncollected(rows,'order_status_name')};
}

View File

@ -0,0 +1,55 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {selectUncollected,summarizeUncollected,validateUncollected,applyUncollectedExclusions,applyUncollectedRules,uncollectedExclusionReasons} from './uncollected.mjs';
const row=(id,status)=>({id,inner_order_id:String(id),send_time:'2026-11-24 12:00:00',fetch_time:null,logistic_status_name:status,warehouse_name:'常州仓',logistic_company_name:'快递A',order_labels:null,remark:null,refund_checked:true,refund_success:false});
test('pending selection uses the logistics status, preserving signed or in-transit rows in the full set',()=>{
const rows=[row(1,'未揽收'),row(2,'已签收'),row(3,'运输中'),row(4,null)];
assert.equal(selectUncollected(rows).length,4);
assert.deepEqual(selectUncollected(rows,{pendingOnly:true}).map(r=>r.id),[1]);
assert.equal(summarizeUncollected(rows).pending,1);
assert.equal(selectUncollected(rows,{pendingOnly:true,query:'已签收'}).length,0);
assert.equal(selectUncollected(rows,{query:'快递a'}).length,4);
});
test('refund success is excluded and an unchecked candidate blocks publication',()=>{
const base={...row(1,'未揽收'),logistic_id:'012345',logistic_company_name:'中通速递'};
assert.deepEqual(applyUncollectedRules([base,{...base,id:2,refund_success:true}]),[base]);
assert.throws(()=>applyUncollectedRules([{...base,refund_checked:false}]),/REFUND_STATUS_NOT_CHECKED/);
const missing={...base};delete missing.refund_success;assert.throws(()=>applyUncollectedRules([missing]),/REFUND_STATUS_NOT_CHECKED/);
});
test('wrong shipping dates, populated pickup times and duplicate source records cannot be published',()=>{
const snapshot={summary:{date:'2026-11-24',queriedAt:'2026-11-25T07:00:00Z',rowCount:1},rows:[row(1,'未揽收')]};
assert.equal(validateUncollected(snapshot),snapshot);
for(const change of [{send_time:'2026-11-25 00:00:00'},{fetch_time:'2026-11-25 01:00:00'},{fetch_time:''}])assert.throws(()=>validateUncollected({...snapshot,rows:[{...snapshot.rows[0],...change}]}));
const missingLabels={...snapshot.rows[0]};delete missingLabels.order_labels;assert.throws(()=>validateUncollected({...snapshot,rows:[missingLabels]}),/ORDER_LABELS_REQUIRED/);
const missingRemark={...snapshot.rows[0]};delete missingRemark.remark;assert.throws(()=>validateUncollected({...snapshot,rows:[missingRemark]}),/ORDER_REMARK_REQUIRED/);
assert.throws(()=>validateUncollected({...snapshot,summary:{...snapshot.summary,rowCount:2},rows:[snapshot.rows[0],snapshot.rows[0]]}));
});
test('any excluded order label matches inside a multi-label value and Latin label matching ignores case',()=>{
const base={...row(1,'未揽收'),logistic_id:'012345',logistic_company_name:'中通速递'};
for(const order_labels of ['其他,ECLP,普通','【CLPS】','其他;1688一件代发仓','1688一件代发','其他,1688一件代发订单','刷单待处理,有赠品','eclp','clps'])assert.equal(applyUncollectedExclusions([{...base,order_labels}]).length,0);
for(const order_labels of [null,'','普通订单,有赠品'])assert.equal(applyUncollectedExclusions([{...base,order_labels}]).length,1);
assert.deepEqual(uncollectedExclusionReasons({...base,order_labels:'ECLP,CLPS,刷单待处理'}),['order_labels']);
});
test('published data contains only uncollected logistics status after every exclusion',()=>{
const base={...row(1,'未揽收'),logistic_id:'012345',logistic_company_name:'中通速递'};
const records=[base,{...base,id:2,logistic_status_name:'运输中'},{...base,id:3,logistic_status_name:'已签收'},{...base,id:4,logistic_status_name:null},{...base,id:5,order_labels:'1688一件代发'},{...base,id:6,logistic_company_name:'京喜京东快递'}];
assert.deepEqual(applyUncollectedRules(records),[base]);
assert.deepEqual(applyUncollectedRules([]),[]);
});
test('a zero-record day keeps valid empty summaries and filters',()=>{
const snapshot={summary:{date:'2026-11-24',queriedAt:'2026-11-25T07:00:00Z',rowCount:0},rows:[]};
validateUncollected(snapshot);assert.equal(summarizeUncollected([]).total,0);assert.deepEqual(selectUncollected([],{pendingOnly:true}),[]);
});
test('business exclusions match the exact first problem, all specified carrier substrings and blank tracking',()=>{
const base={...row(1,'未揽收'),logistic_id:'012345',logistic_company_name:'中通速递',first_question_type:null};
assert.deepEqual(applyUncollectedExclusions([base]),[base]);
for(const patch of [{first_question_type:' 1688一件代发 '},{logistic_company_name:'京喜京东快递'},{logistic_company_name:'京东自营快递贝壳家'},{logistic_company_name:'横林顺丰干配'},{logistic_company_name:'京东快递'},{logistic_company_name:'中铁物流'},{logistic_company_name:'客户自提'},{logistic_company_name:'武进安能-大件'},{logistic_company_name:'壹米滴答专线-干线'},{logistic_id:null},{logistic_id:''},{logistic_id:' \t '}])assert.deepEqual(applyUncollectedExclusions([{...base,...patch}]),[]);
assert.equal(applyUncollectedExclusions([{...base,first_question_type:'1688一件代发-其他'}]).length,1);
assert.deepEqual(uncollectedExclusionReasons({...base,first_question_type:'1688一件代发',logistic_company_name:'顺丰速运',logistic_id:null}),['first_question_type','carrier','blank_tracking']);
});
test('remark exclusions use the order remark, normalize parentheses and Latin case, and preserve ordinary remarks',()=>{
const base={...row(1,'未揽收'),logistic_id:'012345',logistic_company_name:'名屋居安能快运'};
for(const remark of ['(收)发货','(收)订单','前缀BBFF后缀','bbff','BBFF'])assert.deepEqual(applyUncollectedRules([{...base,remark}]),[]);
for(const remark of [null,'','正常发货','收到货后处理'])assert.deepEqual(applyUncollectedRules([{...base,remark}]),[{...base,remark}]);
assert.equal(applyUncollectedRules([{...base,remark_content:'BBFF',buyer_message:'(收)'}]).length,1);
});

View File

@ -0,0 +1,38 @@
#!/usr/bin/env bash
set -euo pipefail
BASE="/opt/furniture-3d-system-prod"
test -d "$BASE/current/furniture-3d-system"
test -s "$BASE/shared/daily-express/mappings.json"
test -s "$BASE/shared/daily-express/dingtalk-config.json"
cat > /etc/systemd/system/furniture-daily-express.service <<'EOF'
[Unit]
Description=Daily carrier volume and uncollected shipments
After=network-online.target
StartLimitIntervalSec=3600
StartLimitBurst=4
[Service]
Type=oneshot
WorkingDirectory=/opt/furniture-3d-system-prod/current/furniture-3d-system
EnvironmentFile=/opt/furniture-3d-system-prod/shared/.env
Environment=DAILY_EXPRESS_DATA_DIR=/opt/furniture-3d-system-prod/shared/daily-express
Environment=DAILY_EXPRESS_DINGTALK_CONFIG=/opt/furniture-3d-system-prod/shared/daily-express/dingtalk-config.json
Environment=DAILY_EXPRESS_ENV_JSON=/opt/furniture-3d-system-prod/shared/daily-express/report-env.json
ExecStart=/usr/bin/env node scripts/daily-express-dashboard/run.mjs
TimeoutStartSec=1800
Restart=on-failure
RestartSec=900
UMask=0077
EOF
cat > /etc/systemd/system/furniture-daily-express.timer <<'EOF'
[Unit]
Description=Refresh carrier dashboards daily at 09:00 Asia/Shanghai
[Timer]
OnCalendar=*-*-* 09:00:00 Asia/Shanghai
Persistent=true
Unit=furniture-daily-express.service
[Install]
WantedBy=timers.target
EOF
systemctl daemon-reload
systemctl enable --now furniture-daily-express.timer
systemctl list-timers furniture-daily-express.timer --no-pager

View File

@ -0,0 +1,18 @@
import { DailyExpressVolumeRepository } from '../src/server/repositories/daily-express-volume.repository'
import { expressRegionalPivot } from '../src/lib/daily-express-snapshot'
import assert from 'node:assert/strict'
async function main() {
const repository = new DailyExpressVolumeRepository()
const { report, pointer } = await repository.readLatest()
const details = await repository.readDetails(pointer)
assert.equal(details.length, report.overview.total)
assert.equal(report.overview.ranking.reduce((total, row) => total + row.total, 0), details.length)
for (const day of report.regional.days) {
assert.equal(expressRegionalPivot(day, '').total, details.filter(row => row.send_date.startsWith(day.date)).length)
for (const origin of day.origins) assert.equal(expressRegionalPivot(day, origin.name).total, origin.total)
}
assert.equal(report.uncollected.rows.length, report.uncollected.summary.total)
assert.ok(report.uncollected.rows.every(row => row.refund_checked === true && row.refund_success === false && String(row.logistic_status_name).trim() === '未揽收'))
console.log(JSON.stringify({ date: report.dateTo, total: report.overview.total, days: report.overview.days.length, uncollected: report.uncollected.summary.total, verified: true }))
}
void main().catch(error => { console.error(error instanceof Error ? error.message : 'Snapshot verification failed'); process.exitCode = 1 })

View File

@ -5,11 +5,14 @@ import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
import type { SupplierReissueResponseInput } from '@/lib/supplier-reissue-response'
import { checkShareAccessRateLimit } from '@/server/services/share-rate-limit.service'
import { supplierReissueResponseService } from '@/server/services/supplier-reissue-response.service'
import { wecomReissueService } from '@/server/services/wecom-reissue.service'
const payloadSchema = z.object({
items: z.array(z.object({
recordId: z.string().trim().min(1).max(200),
reasonRoot: z.string().trim().min(1).max(40),
reasonCategory: z.string().trim().min(1).max(300),
reasonOtherNote: z.string().trim().max(1000).optional().default(''),
solution: z.string().trim().min(2).max(1000),
expectedSolveDate: z.string().trim().regex(/^\d{4}-\d{2}-\d{2}$/),
})).min(1).max(200),
@ -51,19 +54,26 @@ export async function POST(
if (!parsed.success) {
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '填报数据格式不正确或字段未填写完整', 400, ctx.requestId)
}
return jsonSuccess(
await supplierReissueResponseService.submitResponses(
token,
parsed.data.items as SupplierReissueResponseInput[],
{
const submission = await supplierReissueResponseService.submitResponses(
token,
parsed.data.items as SupplierReissueResponseInput[],
{
ip: request.headers.get('x-forwarded-for')?.split(',')[0]?.trim()
|| request.headers.get('x-real-ip')?.trim()
|| '',
userAgent: request.headers.get('user-agent')?.trim() || '',
},
),
200,
ctx.requestId,
},
)
if (submission.pendingReasonReviewRecordIds.length) {
void wecomReissueService
.notifyPendingReasonReviews(submission.pendingReasonReviewRecordIds)
.catch((error) => {
console.warn(
'非工厂原因待判定提醒发送失败:',
error instanceof Error ? error.message : '未知错误',
)
})
}
return jsonSuccess(submission, 200, ctx.requestId)
}, { requireAuth: false })
}

View File

@ -1,9 +1,16 @@
import { NextRequest } from 'next/server'
import { handleRequest, jsonSuccess } from '@/server/core/response'
import { supplyChainBrandUpgradeApprovalService } from '@/server/services/supply-chain-brand-upgrade-approval.service'
import { ErrorCode } from '@/server/core/errors'
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
import {
hasBrandUpgradeApprovalAccess,
supplyChainBrandUpgradeApprovalService,
} from '@/server/services/supply-chain-brand-upgrade-approval.service'
export async function GET(request: NextRequest, context: { params: Promise<{ id: string }> }) {
return handleRequest(request, async (ctx) => {
if (!(await hasBrandUpgradeApprovalAccess(ctx.user))) {
return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '当前账号没有品牌升级审核查看权限', 403, ctx.requestId)
}
const { id } = await context.params
return jsonSuccess(await supplyChainBrandUpgradeApprovalService.get(id), 200, ctx.requestId)
}, { requireAuth: true })

View File

@ -1,9 +1,14 @@
import { NextRequest } from 'next/server'
import { handleRequest, jsonSuccess } from '@/server/core/response'
import { isAdmin } from '@/lib/role-scope'
import { ErrorCode } from '@/server/core/errors'
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
import { supplyChainBrandUpgradeApprovalService } from '@/server/services/supply-chain-brand-upgrade-approval.service'
export async function GET(request: NextRequest) {
return handleRequest(request, async (ctx) => {
if (!isAdmin(ctx.user)) {
return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '只有管理员可以配置审批人', 403, ctx.requestId)
}
return jsonSuccess(await supplyChainBrandUpgradeApprovalService.getConfig(), 200, ctx.requestId)
}, { requireAuth: true })
}

View File

@ -1,9 +1,16 @@
import { NextRequest } from 'next/server'
import { handleRequest, jsonSuccess } from '@/server/core/response'
import { supplyChainBrandUpgradeApprovalService } from '@/server/services/supply-chain-brand-upgrade-approval.service'
import { ErrorCode } from '@/server/core/errors'
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
import {
hasBrandUpgradeApprovalAccess,
supplyChainBrandUpgradeApprovalService,
} from '@/server/services/supply-chain-brand-upgrade-approval.service'
export async function GET(request: NextRequest) {
return handleRequest(request, async (ctx) => {
if (!(await hasBrandUpgradeApprovalAccess(ctx.user))) {
return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '当前账号没有品牌升级审核查看权限', 403, ctx.requestId)
}
const periodKey = request.nextUrl.searchParams.get('period')?.trim() || undefined
const status = request.nextUrl.searchParams.get('status')?.trim() || undefined
return jsonSuccess({

View File

@ -27,6 +27,15 @@ export async function GET(request: NextRequest) {
const roundValue = Number(request.nextUrl.searchParams.get('round') ?? '')
const pageValue = Number(request.nextUrl.searchParams.get('page') ?? '')
const pageSizeValue = Number(request.nextUrl.searchParams.get('pageSize') ?? '')
const rawFilters = request.nextUrl.searchParams.get('filters')
let filters: unknown = []
if (rawFilters) {
try {
filters = JSON.parse(rawFilters)
} catch {
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '自定义筛选参数格式不正确', 400, ctx.requestId)
}
}
return jsonSuccess(await supplyChainClearanceService.getReviewWorkbench({
periodKey: request.nextUrl.searchParams.get('period'),
round: roundValue === 1 || roundValue === 2 ? roundValue : null,
@ -35,6 +44,7 @@ export async function GET(request: NextRequest) {
query: request.nextUrl.searchParams.get('query') ?? '',
profitCenter: request.nextUrl.searchParams.get('profitCenter') ?? '',
status: request.nextUrl.searchParams.get('status') ?? '',
filters,
}), 200, ctx.requestId)
}, { requireAuth: true })
}

View File

@ -0,0 +1,11 @@
import { NextResponse, type NextRequest } from 'next/server'
import { handleRequest } from '@/server/core/response'
import { dailyExpressVolumeService } from '@/server/services/daily-express-volume.service'
export const dynamic = 'force-dynamic'
export async function GET(request: NextRequest) {
return handleRequest(request, async (ctx) => {
const params = request.nextUrl.searchParams
const file = await dailyExpressVolumeService.export({ view: params.get('view') || 'overview', date: params.get('date') || undefined, origin: params.get('origin') || '' }, ctx.user)
return new NextResponse(new Uint8Array(file.bytes), { headers: { 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(file.filename)}`, 'Cache-Control': 'private, no-store' } })
}, { requireAuth: true })
}

View File

@ -0,0 +1,11 @@
import type { NextRequest } from 'next/server'
import { handleRequest, jsonSuccess } from '@/server/core/response'
import { dailyExpressVolumeService } from '@/server/services/daily-express-volume.service'
export const dynamic = 'force-dynamic'
export async function GET(request: NextRequest) {
return handleRequest(request, async (ctx) => {
const params = request.nextUrl.searchParams
const response = jsonSuccess(await dailyExpressVolumeService.getDashboard({ view: params.get('view') || 'overview', date: params.get('date') || undefined, origin: params.get('origin') || '' }, ctx.user), 200, ctx.requestId)
response.headers.set('Cache-Control', 'private, no-store'); return response
}, { requireAuth: true })
}

View File

@ -24,6 +24,8 @@ const querySchema = z.object({
column: z.string().trim().min(1).max(64),
keyword: z.string().trim().max(160).optional(),
limit: z.coerce.number().int().min(1).max(200).optional(),
snapshotDate: z.string().trim().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
generationSlot: z.enum(['09:00', '15:00']).optional(),
filters: z.string().max(3000).optional().transform((value, context) => {
if (!value) return undefined
try {
@ -60,6 +62,8 @@ export async function GET(request: NextRequest) {
keyword: parsed.data.keyword,
limit: parsed.data.limit,
columnFilters: parsed.data.filters?.columnFilters,
snapshotDate: parsed.data.snapshotDate,
generationSlot: parsed.data.generationSlot,
}),
200,
ctx.requestId,

View File

@ -22,6 +22,8 @@ const querySchema = z.object({
barcode: z.string().trim().min(1).max(160),
page: z.coerce.number().int().min(1).default(1),
pageSize: z.coerce.number().int().min(1).max(1000).default(50),
snapshotDate: z.string().trim().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
generationSlot: z.enum(['09:00', '15:00']).optional(),
sortKey: z.string().trim().max(64).optional(),
sortDirection: z.enum(['asc', 'desc']).optional(),
columnFilters: z.string().max(3000).optional().transform((value, context) => {
@ -64,6 +66,8 @@ export async function GET(request: NextRequest) {
columnFilters: parsed.data.columnFilters,
sortKey: parsed.data.sortKey,
sortDirection: parsed.data.sortDirection,
snapshotDate: parsed.data.snapshotDate,
generationSlot: parsed.data.generationSlot,
},
),
200,

View File

@ -40,6 +40,8 @@ const payloadSchema = z.object({
sortDirection: z.enum(['asc', 'desc']).optional(),
componentSortKey: z.string().trim().max(64).optional(),
componentSortDirection: z.enum(['asc', 'desc']).optional(),
snapshotDate: z.string().trim().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
generationSlot: z.enum(['09:00', '15:00']).optional(),
}).refine((filters) => !filters.sortKey || isModularProcessingOrderSortKey(filters.sortKey), {
message: '主表排序字段不正确',
path: ['sortKey'],

View File

@ -1,5 +1,6 @@
import { NextRequest } from 'next/server'
import { z } from 'zod'
import { reissueHasCallback, type ReissueRecord } from '@/lib/purchase-legacy-modules'
import { ErrorCode } from '@/server/core/errors'
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
import { purchaseLegacyModulesService } from '@/server/services/purchase-legacy-modules.service'
@ -79,6 +80,17 @@ export async function PUT(
ctx.requestId,
)
}
if (parsed.data.records.some((record) =>
record.reasonReviewStatus === 'PENDING_FOLLOWUP'
&& reissueHasCallback(record as ReissueRecord),
)) {
return jsonError(
ErrorCode.VALIDATION_INVALID_FORMAT,
'非工厂原因尚未完成跟单员最终判定,暂不能回传闭环',
400,
ctx.requestId,
)
}
const saved = await purchaseLegacyModulesService.saveReissueStore(parsed.data as never)
await reissueHistoryService.refreshCurrent(saved)
return jsonSuccess<unknown>(saved, 200, ctx.requestId)

View File

@ -0,0 +1,44 @@
import { NextRequest } from 'next/server'
import { z } from 'zod'
import { ErrorCode } from '@/server/core/errors'
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
import { getPurchaseLegacyModuleAccess } from '@/server/services/supply-chain-purchase-page-permission'
import { supplierReissueResponseService } from '@/server/services/supplier-reissue-response.service'
const payloadSchema = z.object({
recordId: z.string().trim().min(1).max(200),
finalReasonCategory: z.string().trim().min(1).max(300),
reasonNote: z.string().trim().max(1000).default(''),
feedbackContent: z.string().trim().max(3000).optional().default(''),
}).strict()
export async function POST(request: NextRequest) {
return handleRequest(request, async (ctx) => {
const access = await getPurchaseLegacyModuleAccess(ctx.user, 'reissue-reminder')
if (!access.edit) {
return jsonError(
ErrorCode.AUTH_PERMISSION_DENIED,
'没有应发未发提醒最终判定权限',
403,
ctx.requestId,
)
}
const parsed = payloadSchema.safeParse(await request.json().catch(() => null))
if (!parsed.success) {
return jsonError(
ErrorCode.VALIDATION_INVALID_FORMAT,
'最终原因判定数据格式不正确',
400,
ctx.requestId,
)
}
return jsonSuccess(
await supplierReissueResponseService.completeReasonReview(
parsed.data as never,
ctx.user.name,
),
200,
ctx.requestId,
)
}, { requireAuth: true })
}

View File

@ -1,12 +1,21 @@
'use client'
import { useMemo, useState } from 'react'
import type { SupplierReissuePublicPage } from '@/lib/supplier-reissue-response'
import {
requiresReasonOtherNote,
supplierReasonCategoriesForRoot,
supplierReasonRootForCategory,
type SupplierReissueOrder,
type SupplierReissuePublicPage,
type SupplierReissueSubmission,
} from '@/lib/supplier-reissue-response'
import { SupplierDeliverySection } from './SupplierDeliverySection'
import styles from './supplier-response.module.css'
type Draft = {
reasonRoot: string
reasonCategory: string
reasonOtherNote: string
solution: string
expectedSolveDate: string
}
@ -24,7 +33,9 @@ export function SupplierResponseClient({
const [success, setSuccess] = useState('')
const [draft, setDraft] = useState<Record<string, Draft>>(() => Object.fromEntries(
initialData.orders.map((order) => [order.id, {
reasonRoot: order.reasonRoot || supplierReasonRootForCategory(order.reasonCategory) || '',
reasonCategory: order.reasonCategory,
reasonOtherNote: order.reasonOtherNote,
solution: order.solution,
expectedSolveDate: order.expectedSolveDate,
}]),
@ -56,9 +67,19 @@ export function SupplierResponseClient({
...draft[order.id],
}))
if (items.some((item) =>
!item.reasonCategory || !item.solution.trim() || !item.expectedSolveDate,
!item.reasonRoot
|| !item.reasonCategory
|| supplierReasonRootForCategory(item.reasonCategory) !== item.reasonRoot
|| !item.solution.trim()
|| !item.expectedSolveDate,
)) {
throw new Error('请为每条订单完整填写原因分类、解决方案和预计解决日期')
throw new Error('请为每条订单完整填写一级原因、二级原因、解决方案和预计解决日期')
}
if (items.some((item) =>
requiresReasonOtherNote(item.reasonCategory)
&& item.reasonOtherNote.trim().length < 10,
)) {
throw new Error('选择“非工厂原因-其他”时,请填写不少于 10 个字的具体说明')
}
const response = await fetch(`/api/supplier-response/${encodeURIComponent(token)}`, {
method: 'POST',
@ -69,8 +90,11 @@ export function SupplierResponseClient({
if (!response.ok || !payload?.success) {
throw new Error(payload?.error?.message || '提交失败,请稍后重试')
}
setData(payload.data as SupplierReissuePublicPage)
setSuccess('反馈已提交,系统已自动回传。如需修改,可在本页重新提交。')
const submission = payload.data as SupplierReissueSubmission
setData(submission.page)
setSuccess(submission.pendingReasonReviewRecordIds.length
? `反馈已提交。其中 ${submission.pendingReasonReviewRecordIds.length} 条非工厂原因已提醒对应跟单员完成最终判定。`
: '反馈已提交,系统已自动回传。如需修改,可在本页重新提交。')
} catch (cause) {
setError(cause instanceof Error ? cause.message : '提交失败,请稍后重试')
} finally {
@ -78,12 +102,24 @@ export function SupplierResponseClient({
}
}
function orderStatus(order: SupplierReissueOrder) {
if (order.reasonReviewStatus === 'PENDING_FOLLOWUP') {
return { label: '待跟单员判定', className: styles.review }
}
if (order.reasonReviewStatus === 'COMPLETED') {
return { label: '跟单员已判定', className: styles.responded }
}
return order.respondedAt
? { label: '已反馈', className: styles.responded }
: { label: '待填写', className: styles.pending }
}
return (
<main className={styles.page}>
<header className={styles.hero}>
<span className={styles.eyebrow}>应发未发异常反馈</span>
<h1>{data.supplier}</h1>
<p>请逐条说明未发出的原因、解决方案和预计解决日期。提交后系统会自动同步给采购跟单人员。</p>
<p>请先选择一级原因和二级原因,再填写解决方案与预计解决日期。非工厂原因提交后会进入“待跟单员判定”,由对应跟单员完成最终原因确认。</p>
<div className={styles.progress}>
<strong>{data.orders.length}</strong>
<span>条待处理异常</span>
@ -98,6 +134,12 @@ export function SupplierResponseClient({
<section className={styles.list}>
{data.orders.map((order, index) => {
const value = draft[order.id]
const status = orderStatus(order)
const reasonGroup = data.reasonGroups.find((group) => group.root === value?.reasonRoot)
const categories = value?.reasonRoot
? supplierReasonCategoriesForRoot(value.reasonRoot)
: []
const needsFollowupReview = value?.reasonRoot === '非工厂原因'
return (
<article className={styles.card} key={order.id}>
<div className={styles.cardHeader}>
@ -105,9 +147,7 @@ export function SupplierResponseClient({
<span>异常明细 {index + 1}</span>
<h2>{order.orderNo || '未填订单号'}</h2>
</div>
<span className={order.respondedAt ? styles.responded : styles.pending}>
{order.respondedAt ? '已反馈' : '待填写'}
</span>
<span className={status.className}>{status.label}</span>
</div>
<div className={styles.meta}>
<div><span>SKU / 条码</span><strong>{order.barcode || '—'}</strong></div>
@ -117,14 +157,43 @@ export function SupplierResponseClient({
</div>
<div className={styles.formGrid}>
<label>
原因分类 <b>*</b>
一级原因 <b>*</b>
<select
value={value?.reasonCategory || ''}
onChange={(event) => updateDraft(order.id, { reasonCategory: event.target.value })}
value={value?.reasonRoot || ''}
onChange={(event) => updateDraft(order.id, {
reasonRoot: event.target.value,
reasonCategory: '',
reasonOtherNote: '',
})}
required
>
<option value="">请选择原因分类</option>
{data.reasonCategories.map((category) => <option key={category}>{category}</option>)}
<option value="">请选择一级原因</option>
{data.reasonGroups.map((group) => (
<option key={group.root} value={group.root}>{group.root}</option>
))}
</select>
</label>
<label>
二级原因(工厂初判) <b>*</b>
<select
value={value?.reasonCategory || ''}
disabled={!value?.reasonRoot}
onChange={(event) => updateDraft(order.id, {
reasonCategory: event.target.value,
reasonOtherNote: requiresReasonOtherNote(event.target.value)
? value?.reasonOtherNote || ''
: '',
})}
required
>
<option value="">
{value?.reasonRoot ? '请选择二级原因' : '请先选择一级原因'}
</option>
{categories.map((category) => (
<option key={category} value={category}>
{category.slice(value!.reasonRoot.length + 1)}
</option>
))}
</select>
</label>
<label>
@ -137,6 +206,28 @@ export function SupplierResponseClient({
required
/>
</label>
{needsFollowupReview ? (
<div className={`${styles.reasonNotice} ${styles.wide}`}>
<strong>需要跟单员最终判定</strong>
<span>{reasonGroup?.description}。工厂初判会先保留,跟单员最终确认后再闭环。</span>
</div>
) : null}
{requiresReasonOtherNote(value?.reasonCategory || '') ? (
<label className={styles.wide}>
其他原因说明 <b>*</b>
<textarea
rows={3}
value={value?.reasonOtherNote || ''}
onChange={(event) => updateDraft(order.id, {
reasonOtherNote: event.target.value,
})}
placeholder="请填写不少于 10 个字的具体原因"
minLength={10}
maxLength={1000}
required
/>
</label>
) : null}
<label className={styles.wide}>
解决方案 <b>*</b>
<textarea

View File

@ -127,7 +127,8 @@
}
.responded,
.pending {
.pending,
.review {
flex: 0 0 auto;
padding: 5px 11px;
border-radius: 999px;
@ -145,6 +146,11 @@
color: #c2410c !important;
}
.review {
background: #fffbeb;
color: #a16207 !important;
}
.meta {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
@ -227,6 +233,23 @@
resize: vertical;
}
.reasonNotice {
display: flex;
gap: 10px;
align-items: flex-start;
padding: 13px 14px;
border: 1px solid #fde68a;
border-radius: 12px;
background: #fffbeb;
color: #92400e;
font-size: 13px;
line-height: 1.6;
}
.reasonNotice strong {
flex: 0 0 auto;
}
.wide {
grid-column: 1 / -1;
}

View File

@ -113,6 +113,7 @@ export const SUPPLY_CHAIN_ROUTE_TITLES: Record<string, string> = {
'/supply-chain/management/shortage-order-details': '缺货订单明细',
'/supply-chain/management/shortage-order-details/report': '缺货报表',
'/supply-chain/management/logistics-arrival-signing-duration': '物流到货签收时长看板',
'/supply-chain/management/daily-express-volume': '每日快递承运量看板',
'/supply-chain/management/order-not-dispatched': '应发未发',
'/supply-chain/management/production-stop-demands': '停产需求管理',
'/supply-chain/management/product-inventory-stop': '商品是否建议盘停监控',

View File

@ -189,6 +189,11 @@ export const SUPPLY_CHAIN_MENU: SupplyChainMenuModule[] = [
route: '/supply-chain/management/logistics-arrival-signing-duration',
targetKey: 'logisticsArrivalSigningDuration',
},
{
label: '每日快递承运量看板',
route: '/supply-chain/management/daily-express-volume',
targetKey: 'dailyExpressVolume',
},
{
label: '应发未发',
route: '/supply-chain/management/order-not-dispatched',

View File

@ -103,12 +103,13 @@ function summarize(profitCenters: DepartmentProfitCenterBlock[]) {
}
export function DepartmentDistributionView({
definition, canExport, canConfigure, canViewDetail = true,
definition, canExport, canConfigure, canViewDetail = true, canViewApprovals = false,
}: {
definition: ManagementBlankPageDefinition
canExport: boolean
canConfigure: boolean
canViewDetail?: boolean
canViewApprovals?: boolean
}) {
const initial = useMemo(() => previousMonth(), [])
const [year, setYear] = useState(initial.year)
@ -318,7 +319,7 @@ export function DepartmentDistributionView({
<header className={styles.header}>
<div><h1>{definition.label} · 各部门数据分类</h1><p>SupplyChainProductArchive 商品主表 · 按利润中心汇总(生成后冻结)</p></div>
</header>
<SabcTabNav pageKey={definition.key} active="departments" showDetail={canViewDetail} />
<SabcTabNav pageKey={definition.key} active="departments" showDetail={canViewDetail} showApprovals={canViewApprovals} />
<form className={styles.deptToolbar} onSubmit={(event) => { event.preventDefault(); void load() }}>
<label className={styles.sabcMonthField}>
<span>核算月份</span>

View File

@ -179,11 +179,12 @@ function FilterFieldCombo({ label, field, value, year, month, onChange }: {
)
}
export function ProductSabcView({ definition, canCalculate, canDownload, canViewDepartments = true }: {
export function ProductSabcView({ definition, canCalculate, canDownload, canViewDepartments = true, canViewApprovals = false }: {
definition: ManagementBlankPageDefinition
canCalculate: boolean
canDownload: boolean
canViewDepartments?: boolean
canViewApprovals?: boolean
}) {
const initial = useMemo(() => previousMonth(), [])
const [year, setYear] = useState(initial.year)
@ -307,7 +308,7 @@ export function ProductSabcView({ definition, canCalculate, canDownload, canView
<header className={styles.header}>
<div><h1>{definition.label}</h1><p>SupplyChainProductArchive 商品主表 · 月度自动核算</p></div>
</header>
<SabcTabNav pageKey={definition.key} active="detail" showDepartments={canViewDepartments} />
<SabcTabNav pageKey={definition.key} active="detail" showDepartments={canViewDepartments} showApprovals={canViewApprovals} />
<div className={`${styles.toolbar} ${styles.sabcToolbar}`}>
<form className={styles.sabcFilterForm} onSubmit={submitFilters}>
<div className={styles.sabcFilterHead}>

View File

@ -2,11 +2,12 @@ import Link from 'next/link'
import styles from './management-blank-page.module.css'
/** 商品SABC打标页内切换:明细 / 各部门数据分类(没有对应权限的页签不展示)。 */
export function SabcTabNav({ pageKey, active, showDetail = true, showDepartments = true }: {
export function SabcTabNav({ pageKey, active, showDetail = true, showDepartments = true, showApprovals = false }: {
pageKey: string
active: 'detail' | 'departments' | 'approvals'
showDetail?: boolean
showDepartments?: boolean
showApprovals?: boolean
}) {
const base = `/supply-chain/management/blank-pages/${pageKey}`
return (
@ -15,7 +16,9 @@ export function SabcTabNav({ pageKey, active, showDetail = true, showDepartments
{showDepartments ? (
<Link href={`${base}/departments`} className={active === 'departments' ? styles.sabcTabActive : undefined}>各部门数据分类</Link>
) : null}
<Link href={`${base}/approvals`} className={active === 'approvals' ? styles.sabcTabActive : undefined}>品牌升级审核</Link>
{showApprovals ? (
<Link href={`${base}/approvals`} className={active === 'approvals' ? styles.sabcTabActive : undefined}>品牌升级审核</Link>
) : null}
</nav>
)
}

View File

@ -2,7 +2,7 @@ import { notFound, redirect } from 'next/navigation'
import { isAdmin } from '@/lib/role-scope'
import { requireSession } from '@/lib/server-session'
import { getManagementBlankPage } from '@/lib/supply-chain-management-blank-pages'
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
import { hasBrandUpgradeApprovalAccess } from '@/server/services/supply-chain-brand-upgrade-approval.service'
import { BrandUpgradeApprovalView } from '../../BrandUpgradeApprovalView'
export default async function ManagementBlankPageApprovals({ params }: { params: Promise<{ pageKey: string }> }) {
@ -11,8 +11,8 @@ export default async function ManagementBlankPageApprovals({ params }: { params:
if (definition.key !== 'blank-page-3') notFound()
const { authUser } = await requireSession('/login')
const access = await supplyChainPermissionSettingsService.getUserAccess(authUser, 'productSabc')
if (!access.view) redirect('/supply-chain')
// 品牌升级审核:专属权限节点(经管/管理员/运营总监),其余账号无权限
if (!(await hasBrandUpgradeApprovalAccess(authUser))) redirect('/supply-chain')
return (
<BrandUpgradeApprovalView

View File

@ -2,6 +2,7 @@ import { notFound, redirect } from 'next/navigation'
import { requireSession } from '@/lib/server-session'
import { getManagementBlankPage } from '@/lib/supply-chain-management-blank-pages'
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
import { hasBrandUpgradeApprovalAccess } from '@/server/services/supply-chain-brand-upgrade-approval.service'
import { DepartmentDistributionView } from '../../DepartmentDistributionView'
export default async function ManagementBlankPageDepartments({ params }: { params: Promise<{ pageKey: string }> }) {
@ -15,6 +16,7 @@ export default async function ManagementBlankPageDepartments({ params }: { param
if (!access.view) redirect('/supply-chain')
const detailAccess = await supplyChainPermissionSettingsService.getUserAccess(authUser, 'productSabc')
const configAccess = await supplyChainPermissionSettingsService.getUserAccess(authUser, 'departmentDistributionConfig')
const canViewApprovals = await hasBrandUpgradeApprovalAccess(authUser)
return (
<DepartmentDistributionView
@ -22,6 +24,7 @@ export default async function ManagementBlankPageDepartments({ params }: { param
canExport={access.download}
canConfigure={configAccess.edit}
canViewDetail={detailAccess.view}
canViewApprovals={canViewApprovals}
/>
)
}

View File

@ -2,6 +2,7 @@ import { notFound, redirect } from 'next/navigation'
import { requireSession } from '@/lib/server-session'
import { getManagementBlankPage } from '@/lib/supply-chain-management-blank-pages'
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
import { hasBrandUpgradeApprovalAccess } from '@/server/services/supply-chain-brand-upgrade-approval.service'
import { ManagementBlankPageView } from '../ManagementBlankPageView'
import { ProductSabcView } from '../ProductSabcView'
import { ProductSelectionView } from '../ProductSelectionView'
@ -25,12 +26,14 @@ export default async function ManagementBlankPage({ params }: { params: Promise<
'productSabcCalculation',
)
const departmentsAccess = await supplyChainPermissionSettingsService.getUserAccess(authUser, 'departmentDistribution')
const canViewApprovals = await hasBrandUpgradeApprovalAccess(authUser)
return (
<ProductSabcView
definition={definition}
canCalculate={calculationAccess.edit}
canDownload={access.download}
canViewDepartments={departmentsAccess.view}
canViewApprovals={canViewApprovals}
/>
)
}

View File

@ -0,0 +1,23 @@
import { fireEvent, render, screen } from '@testing-library/react'
import { PoolImageCell } from './ClearanceView'
describe('PoolImageCell', () => {
it('shows a larger preview on hover and hides it on leave', () => {
render(
<PoolImageCell
row={{
image: '/test-image.jpg',
barcode: 'SKU-A',
productName: '测试商品',
}}
/>,
)
const trigger = screen.getByLabelText('预览 测试商品 图片')
fireEvent.mouseEnter(trigger)
expect(screen.getByRole('img', { name: '测试商品 放大图片' })).toBeInTheDocument()
fireEvent.mouseLeave(trigger)
expect(screen.queryByRole('img', { name: '测试商品 放大图片' })).not.toBeInTheDocument()
})
})

View File

@ -27,6 +27,7 @@ const row = {
totalStock: 110,
clearanceTotal: 100,
dailySales: 2,
thirtyDayClearableQty: 60,
availableDays: '55',
taskQty: 20,
discount: 0.7,
@ -48,6 +49,7 @@ const row = {
describe('ClearanceReviewWorkbench', () => {
beforeEach(() => {
jest.clearAllMocks()
window.localStorage.clear()
global.fetch = jest.fn((input, init) => {
if (init?.method === 'POST') {
return jsonResponse({ count: 2, ids: ['task-a', 'task-b'], stage: 'READY' })
@ -98,6 +100,8 @@ describe('ClearanceReviewWorkbench', () => {
expect(screen.queryByText('入库天数分数')).not.toBeInTheDocument()
expect(screen.getByText('总分数')).toBeInTheDocument()
expect(screen.getByText('建议折扣')).toBeInTheDocument()
expect(screen.getByRole('columnheader', { name: /30天可清货量/ })).toBeInTheDocument()
expect(screen.getAllByText('60')).toHaveLength(2)
expect(screen.getAllByText('SKU-A')).toHaveLength(4)
expect(screen.queryByText('退回后重新提交')).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: '删除历史退回' })).not.toBeInTheDocument()
@ -117,6 +121,106 @@ describe('ClearanceReviewWorkbench', () => {
await waitFor(() => expect(barcodeColumn).toHaveStyle({ width: '120px' }))
})
it('applies custom filters to the server-side review query', async () => {
render(<ClearanceReviewWorkbench
periodKey="2026-11"
round={1}
onClose={jest.fn()}
onReviewed={jest.fn()}
/>)
expect(await screen.findByText('申请人A')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: '批量审核显示设置' }))
fireEvent.click(screen.getByRole('menuitem', { name: '筛选设置' }))
expect(screen.getByRole('dialog', { name: '筛选设置' })).toBeInTheDocument()
expect(screen.getByLabelText('启用30天可清货量筛选')).toBeChecked()
fireEvent.click(screen.getByRole('button', { name: '完成' }))
fireEvent.click(screen.getByRole('button', { name: '30天可清货量筛选' }))
fireEvent.click(screen.getByRole('checkbox', { name: '60' }))
expect(await screen.findByText('属于:60')).toBeInTheDocument()
await waitFor(() => {
const filteredCall = (global.fetch as jest.Mock).mock.calls.find(([url]) => (
String(url).includes('/review-workbench')
&& String(url).includes('filters=')
))
expect(filteredCall).toBeTruthy()
const requestUrl = new URL(String(filteredCall[0]), 'http://localhost')
expect(JSON.parse(requestUrl.searchParams.get('filters') ?? '[]')).toEqual([
{ key: 'thirtyDayClearableQty', operator: 'equals', value: '60' },
])
})
})
it('provides compact, column and filter settings from the review settings menu', async () => {
render(<ClearanceReviewWorkbench
periodKey="2026-11"
round={1}
onClose={jest.fn()}
onReviewed={jest.fn()}
/>)
expect(await screen.findByText('申请人A')).toBeInTheDocument()
const settingsButton = screen.getByRole('button', { name: '批量审核显示设置' })
fireEvent.click(settingsButton)
expect(screen.getByRole('menuitemcheckbox', { name: /紧凑展示/ })).toBeInTheDocument()
expect(screen.getByRole('menuitem', { name: '列设置' })).toBeInTheDocument()
expect(screen.getByRole('menuitem', { name: '筛选设置' })).toBeInTheDocument()
fireEvent.click(screen.getByRole('menuitemcheckbox', { name: /紧凑展示/ }))
expect(screen.getByRole('table')).toHaveClass('compactTable')
fireEvent.click(screen.getByRole('menuitem', { name: '列设置' }))
expect(screen.getByRole('dialog', { name: '列设置' })).toBeInTheDocument()
fireEvent.click(screen.getByLabelText('显示申请原因'))
fireEvent.click(screen.getByRole('button', { name: '完成' }))
expect(screen.queryByRole('columnheader', { name: /^申请原因/ })).not.toBeInTheDocument()
fireEvent.click(settingsButton)
fireEvent.click(screen.getByRole('menuitem', { name: '筛选设置' }))
expect(screen.getByRole('dialog', { name: '筛选设置' })).toBeInTheDocument()
expect(screen.getByLabelText('启用SPU筛选')).toBeChecked()
expect(screen.getByLabelText('启用货号筛选')).toBeChecked()
})
it('labels expanded combination components instead of treating them as duplicate applications', async () => {
const comboCode = 'ZH-BG006401AN1242V01-1-BG006401BN1242V01-1'
global.fetch = jest.fn(() => jsonResponse({
periodKey: '2026-11',
round: 1,
rounds: [1],
rows: [{
...row,
barcode: 'BG006401AN1242V01',
clearanceCode: comboCode,
duplicateGroupSize: 1,
}],
summary: { total: 1, barcodeCount: 1, applicantCount: 1, duplicateBarcodeCount: 0 },
status: 'ALL',
statusCounts: {
all: 1,
review: 1,
confirmation: 0,
returned: 0,
resubmitted: 0,
passed: 0,
adjusted: 0,
rejected: 0,
},
})) as jest.Mock
render(<ClearanceReviewWorkbench
periodKey="2026-11"
round={1}
onClose={jest.fn()}
onReviewed={jest.fn()}
/>)
expect(await screen.findByText(comboCode)).toBeInTheDocument()
expect(screen.getByText('组合组件')).toBeInTheDocument()
expect(screen.queryByText(/重复申请/)).not.toBeInTheDocument()
})
it('submits reviewer-adjusted quantities and discounts for operator confirmation', async () => {
const onReviewed = jest.fn()
render(<ClearanceReviewWorkbench

View File

@ -4,6 +4,14 @@ import { useCallback, useEffect, useRef, useState, type CSSProperties } from 're
import { Check, X } from 'lucide-react'
import limitStyles from '../custom-table/limit-management.module.css'
import ui from './clearance.module.css'
import { ClearanceFilterBar } from './ClearanceFilterBar'
import { ClearanceSettingsMenu } from './ClearanceSettingsMenu'
import {
useClearanceColumnSettings,
useClearanceCompact,
useClearanceFilterFields,
} from './useClearanceColumnSettings'
import type { ClearanceFilterCondition } from '@/lib/clearance-filters'
type ReviewRow = {
taskId: string
@ -24,6 +32,7 @@ type ReviewRow = {
totalStock: number
clearanceTotal: number | null
dailySales: number | null
thirtyDayClearableQty: number | null
availableDays: string
taskQty: number
discount: number
@ -87,35 +96,107 @@ const REVIEW_STATUS_OPTIONS = [
{ key: 'PASSED', label: '已通过', countKey: 'passed' },
] as const
const REVIEW_COLUMNS = [
{ key: 'select', label: '', width: 42 },
{ key: 'ownerName', label: '清货负责人', width: 100 },
{ key: 'submittedByName', label: '提交人', width: 100 },
{ key: 'submittedAt', label: '申请时间', width: 150 },
{ key: 'barcode', label: '商品编码', width: 110 },
{ key: 'clearanceCode', label: '清货商品编码', width: 150 },
{ key: 'productName', label: '商品名称', width: 190 },
{ key: 'salesStatus', label: '销售状态', width: 82 },
{ key: 'priority', label: '优先级', width: 110 },
{ key: 'profitCenter', label: '利润中心', width: 110 },
{ key: 'stockJianshang', label: '简尚库存', width: 90 },
{ key: 'stockFactory', label: '工厂库存', width: 90 },
{ key: 'clearanceTotal', label: '清货总量', width: 90 },
{ key: 'dailySales', label: '日销', width: 80 },
{ key: 'availableDays', label: '可用天数', width: 90 },
{ key: 'taskQty', label: '申请任务量', width: 112 },
{ key: 'discount', label: '申请折扣', width: 100 },
{ key: 'reason', label: '申请原因', width: 220 },
{ key: 'status', label: '审核状态', width: 140 },
{ key: 'feedback', label: '审核反馈', width: 180 },
{ key: 'totalScore', label: '总分数', width: 90 },
{ key: 'suggestedDiscount', label: '建议折扣', width: 100 },
{ key: 'previousMonthDiscount', label: '上月折扣', width: 100 },
{ key: 'select', label: '', group: '选择', width: 42 },
{ key: 'ownerName', label: '清货负责人', group: '任务信息', width: 100 },
{ key: 'submittedByName', label: '提交人', group: '任务信息', width: 100 },
{ key: 'submittedAt', label: '申请时间', group: '任务信息', width: 150 },
{ key: 'barcode', label: '商品编码', group: '商品信息', width: 110 },
{ key: 'clearanceCode', label: '清货商品编码', group: '商品信息', width: 150 },
{ key: 'productName', label: '商品名称', group: '商品信息', width: 190 },
{ key: 'salesStatus', label: '销售状态', group: '商品信息', width: 82 },
{ key: 'priority', label: '优先级', group: '任务信息', width: 110 },
{ key: 'profitCenter', label: '利润中心', group: '任务信息', width: 110 },
{ key: 'stockJianshang', label: '简尚库存', group: '库存与销售', width: 90 },
{ key: 'stockFactory', label: '工厂库存', group: '库存与销售', width: 90 },
{ key: 'clearanceTotal', label: '清货总量', group: '库存与销售', width: 90 },
{ key: 'dailySales', label: '日销', group: '库存与销售', width: 80 },
{ key: 'thirtyDayClearableQty', label: '30天可清货量', group: '库存与销售', width: 120 },
{ key: 'availableDays', label: '可用天数', group: '库存与销售', width: 90 },
{ key: 'taskQty', label: '申请任务量', group: '申请信息', width: 112 },
{ key: 'discount', label: '申请折扣', group: '申请信息', width: 100 },
{ key: 'reason', label: '申请原因', group: '申请信息', width: 220 },
{ key: 'status', label: '审核状态', group: '审核信息', width: 140 },
{ key: 'feedback', label: '审核反馈', group: '审核信息', width: 180 },
{ key: 'totalScore', label: '总分数', group: '评分信息', width: 90 },
{ key: 'suggestedDiscount', label: '建议折扣', group: '评分信息', width: 100 },
{ key: 'previousMonthDiscount', label: '上月折扣', group: '评分信息', width: 100 },
] as const
type ReviewColumnKey = (typeof REVIEW_COLUMNS)[number]['key']
const INITIAL_REVIEW_COLUMN_WIDTHS = Object.fromEntries(
REVIEW_COLUMNS.map((column) => [column.key, column.width]),
) as Record<ReviewColumnKey, number>
type ReviewColumnDefinition = (typeof REVIEW_COLUMNS)[number]
const REVIEW_COLUMN_MAP = new Map<string, ReviewColumnDefinition>(
REVIEW_COLUMNS.map((column) => [column.key, column]),
)
const REVIEW_COLUMN_SETTINGS_DEFINITIONS = REVIEW_COLUMNS
.filter((column) => column.key !== 'select')
.map((column) => ({ ...column }))
const EMPTY_REVIEW_ROWS: ReviewRow[] = []
type ReviewFilterField = {
key: string
label: string
numeric: boolean
}
const REVIEW_FILTER_FIELDS: ReviewFilterField[] = [
{ key: 'spu', label: 'SPU', numeric: false },
{ key: 'sku', label: '货号', numeric: false },
{ key: 'barcode', label: '商品编码', numeric: false },
{ key: 'clearanceCode', label: '清货商品编码', numeric: false },
{ key: 'productName', label: '商品名称', numeric: false },
{ key: 'salesStatus', label: '销售状态', numeric: false },
{ key: 'productStatus', label: '商品状态', numeric: false },
{ key: 'ownerName', label: '清货负责人', numeric: false },
{ key: 'submittedByName', label: '提交人', numeric: false },
{ key: 'department', label: '部门', numeric: false },
{ key: 'profitCenter', label: '利润中心', numeric: false },
{ key: 'priority', label: '优先级', numeric: false },
{ key: 'clearanceBatch', label: '清货批次', numeric: false },
{ key: 'submittedAt', label: '申请时间', numeric: false },
{ key: 'stockJianshang', label: '简尚库存', numeric: true },
{ key: 'stockFactory', label: '工厂库存', numeric: true },
{ key: 'totalStock', label: '总库存', numeric: true },
{ key: 'clearanceTotal', label: '清货总量', numeric: true },
{ key: 'dailySales', label: '日销', numeric: true },
{ key: 'thirtyDayClearableQty', label: '30天可清货量', numeric: true },
{ key: 'availableDays', label: '可用天数', numeric: true },
{ key: 'taskQty', label: '申请任务量', numeric: true },
{ key: 'discount', label: '申请折扣(0.1-1)', numeric: true },
{ key: 'reason', label: '申请原因', numeric: false },
{ key: 'statusLabel', label: '审核状态', numeric: false },
{ key: 'reviewDecisionLabel', label: '审核结果说明', numeric: false },
{ key: 'feedback', label: '审核反馈', numeric: false },
{ key: 'duplicateGroupSize', label: '重复申请数', numeric: true },
{ key: 'totalScore', label: '总分数', numeric: true },
{ key: 'suggestedDiscount', label: '建议折扣', numeric: true },
{ key: 'previousMonthDiscount', label: '上月折扣', numeric: true },
]
const REVIEW_FILTER_DEFINITIONS = REVIEW_FILTER_FIELDS.map((field) => ({
key: field.key,
label: field.label,
group: '审核字段',
width: 0,
}))
const REVIEW_FILTER_BAR_FIELDS = REVIEW_FILTER_FIELDS.map((field) => ({
key: field.key,
label: field.label,
kind: field.numeric ? 'number' : 'text',
numeric: field.numeric,
}))
const DEFAULT_REVIEW_FILTER_FIELDS = [
'spu',
'sku',
'barcode',
'clearanceCode',
'productName',
'salesStatus',
'ownerName',
'submittedByName',
'profitCenter',
'priority',
'dailySales',
'thirtyDayClearableQty',
'taskQty',
'discount',
'statusLabel',
] as const
async function requestJson<T>(url: string, init?: RequestInit): Promise<T> {
const response = await fetch(url, init)
@ -140,11 +221,13 @@ function monthLabel(periodKey: string) {
}
export function ClearanceReviewWorkbench({
userId = 'anonymous',
periodKey,
round,
onClose,
onReviewed,
}: {
userId?: string
periodKey: string
round: number
onClose: () => void
@ -164,10 +247,20 @@ export function ClearanceReviewWorkbench({
const [query, setQuery] = useState('')
const [profitCenter, setProfitCenter] = useState('')
const [statusFilter, setStatusFilter] = useState<typeof REVIEW_STATUS_OPTIONS[number]['key']>('ALL')
const [filters, setFilters] = useState<ClearanceFilterCondition[]>([])
const [frozenThrough, setFrozenThrough] = useState<ReviewColumnKey>('submittedAt')
const [toast, setToast] = useState('')
const [columnWidths, setColumnWidths] = useState<Record<ReviewColumnKey, number>>(
INITIAL_REVIEW_COLUMN_WIDTHS,
const [reviewColumns, setReviewColumns] = useClearanceColumnSettings(
userId,
'review',
REVIEW_COLUMN_SETTINGS_DEFINITIONS,
)
const [reviewCompact, setReviewCompact] = useClearanceCompact(userId, 'review')
const [reviewFilterFields, setReviewFilterFields] = useClearanceFilterFields(
userId,
'review',
REVIEW_FILTER_DEFINITIONS,
DEFAULT_REVIEW_FILTER_FIELDS,
)
const resizeCleanupRef = useRef<(() => void) | null>(null)
const [reviewValues, setReviewValues] = useState<Record<string, {
@ -188,6 +281,7 @@ export function ClearanceReviewWorkbench({
if (query) params.set('query', query)
if (profitCenter) params.set('profitCenter', profitCenter)
params.set('status', statusFilter)
if (filters.length) params.set('filters', JSON.stringify(filters))
void requestJson<ReviewData>(
`/api/supply-chain/clearance/review-workbench?${params}`,
{ signal: controller.signal, cache: 'no-store' },
@ -211,7 +305,7 @@ export function ClearanceReviewWorkbench({
if (!controller.signal.aborted) setLoading(false)
})
return () => controller.abort()
}, [page, periodKey, profitCenter, query, refreshKey, roundValue, statusFilter])
}, [filters, page, periodKey, profitCenter, query, refreshKey, roundValue, statusFilter])
useEffect(() => {
if (!toast) return
@ -221,7 +315,23 @@ export function ClearanceReviewWorkbench({
useEffect(() => () => resizeCleanupRef.current?.(), [])
function applyFilters(next: ClearanceFilterCondition[]) {
setFilters(next)
setPage(1)
setSelected([])
}
const rows = data?.rows ?? EMPTY_REVIEW_ROWS
const reviewFilterOptionValues = Object.fromEntries(
reviewFilterFields.map((key) => {
const values = Array.from(new Set(rows.flatMap((row) => {
const value = (row as unknown as Record<string, unknown>)[key]
const text = value == null ? '' : String(value).trim()
return text ? [text] : []
}))).sort((left, right) => left.localeCompare(right, 'zh-Hans-CN'))
return [key, values.slice(0, 100)]
}),
)
const canEditReviewValues = (row: ReviewRow) => (
row.status === 'PENDING'
|| (row.status === 'CONFIRMED' && statusFilter === 'RESUBMITTED' && !loading)
@ -239,20 +349,39 @@ export function ClearanceReviewWorkbench({
const selectedRows = rows.filter((row) => selected.includes(row.taskId))
const selectedStatuses = new Set(selectedRows.map((row) => row.status))
const selectedStage = selectedStatuses.size === 1 ? Array.from(selectedStatuses)[0] : ''
const frozenColumnIndex = REVIEW_COLUMNS.findIndex((column) => column.key === frozenThrough)
const reviewColumnSettingByKey = new Map(
reviewColumns.map((setting) => [setting.key, setting]),
)
const visibleReviewColumns = [
REVIEW_COLUMN_MAP.get('select')!,
...reviewColumns.flatMap((setting) => {
const column = REVIEW_COLUMN_MAP.get(setting.key)
return setting.visible && column ? [column] : []
}),
]
const reviewColumnWidth = (key: ReviewColumnKey) => (
key === 'select'
? REVIEW_COLUMN_MAP.get('select')!.width
: reviewColumnSettingByKey.get(key)?.width ?? REVIEW_COLUMN_MAP.get(key)?.width ?? 100
)
const frozenColumnIndex = Math.max(
0,
visibleReviewColumns.findIndex((column) => column.key === frozenThrough),
)
const columnOffsets = new Map<ReviewColumnKey, number>()
let columnOffset = 0
for (const column of REVIEW_COLUMNS) {
for (const column of visibleReviewColumns) {
columnOffsets.set(column.key, columnOffset)
columnOffset += columnWidths[column.key]
columnOffset += reviewColumnWidth(column.key)
}
const reviewTableWidth = columnOffset
function setReviewColumnWidth(key: ReviewColumnKey, width: number) {
setColumnWidths((current) => ({
...current,
[key]: Math.min(500, Math.max(50, Math.round(width))),
}))
if (key === 'select') return
const normalizedWidth = Math.min(500, Math.max(50, Math.round(width)))
setReviewColumns((current) => current.map((setting) => (
setting.key === key ? { ...setting, width: normalizedWidth } : setting
)))
}
function startColumnResize(
@ -318,7 +447,7 @@ export function ClearanceReviewWorkbench({
}
function reviewCellStyle(key: ReviewColumnKey, header = false): CSSProperties {
const index = REVIEW_COLUMNS.findIndex((column) => column.key === key)
const index = visibleReviewColumns.findIndex((column) => column.key === key)
const frozen = index >= 0 && index <= frozenColumnIndex
return {
...(header ? { top: 0, position: 'sticky' } : {}),
@ -330,7 +459,7 @@ export function ClearanceReviewWorkbench({
function reviewCellClass(key: ReviewColumnKey, header = false) {
return [
header ? ui.reviewStickyHeader : '',
REVIEW_COLUMNS.findIndex((column) => column.key === key) <= frozenColumnIndex
visibleReviewColumns.findIndex((column) => column.key === key) <= frozenColumnIndex
? ui.reviewFrozenColumn
: '',
].filter(Boolean).join(' ') || undefined
@ -356,6 +485,14 @@ export function ClearanceReviewWorkbench({
if (key === 'productName') {
return <span className={ui.reviewWorkbenchProduct} title={row.productName}>{row.productName || '—'}</span>
}
if (key === 'clearanceCode' && row.clearanceCode && row.clearanceCode !== row.barcode) {
return (
<span className={ui.reviewComboCode}>
<span title={row.clearanceCode}>{row.clearanceCode}</span>
<em>组合组件</em>
</span>
)
}
if (key === 'taskQty') {
return (
<input
@ -426,6 +563,13 @@ export function ClearanceReviewWorkbench({
if (key === 'reason') {
return <span className={ui.reviewWorkbenchReason} title={row.reason}>{row.reason || '—'}</span>
}
if (key === 'thirtyDayClearableQty') {
return (
<span title="日销 × 30,四舍五入为整数">
{numberText(row.thirtyDayClearableQty)}
</span>
)
}
if (key === 'totalScore') return numberText(row.totalScore)
if (key === 'suggestedDiscount') {
return row.suggestedDiscount == null
@ -623,6 +767,22 @@ export function ClearanceReviewWorkbench({
/>
<button type="submit" disabled={loading || busy}>搜索</button>
</form>
<div className={ui.reviewFilterAnchor}>
<div className={ui.filterToolbarSettings}>
<ClearanceSettingsMenu
title="批量审核"
compact={reviewCompact}
onCompactChange={setReviewCompact}
columnDefinitions={REVIEW_COLUMN_SETTINGS_DEFINITIONS}
columns={reviewColumns}
onColumnsChange={setReviewColumns}
filterDefinitions={REVIEW_FILTER_DEFINITIONS}
filterFields={reviewFilterFields}
defaultFilterFields={DEFAULT_REVIEW_FILTER_FIELDS}
onFilterFieldsChange={setReviewFilterFields}
/>
</div>
</div>
<label>
<span>利润中心</span>
<select
@ -647,7 +807,7 @@ export function ClearanceReviewWorkbench({
onChange={(event) => setFrozenThrough(event.target.value as ReviewColumnKey)}
aria-label="自定义冻结字段"
>
{REVIEW_COLUMNS.filter((column) => column.key !== 'select').map((column) => (
{visibleReviewColumns.filter((column) => column.key !== 'select').map((column) => (
<option key={column.key} value={column.key}>冻结至 {column.label}</option>
))}
</select>
@ -687,6 +847,16 @@ export function ClearanceReviewWorkbench({
</button>
</div>
<div className={ui.reviewFilterBarWrap}>
<ClearanceFilterBar
fields={REVIEW_FILTER_BAR_FIELDS}
visibleFieldKeys={reviewFilterFields}
filters={filters}
optionValues={reviewFilterOptionValues}
onChange={applyFilters}
/>
</div>
<div className={ui.reviewWorkbenchReject}>
<textarea
value={reviewFeedback}
@ -699,15 +869,18 @@ export function ClearanceReviewWorkbench({
{message && <div className={ui.pageNote}>{message}</div>}
<div className={ui.reviewWorkbenchTableWrap}>
<table className={limitStyles.table} style={{ minWidth: reviewTableWidth }}>
<table
className={`${limitStyles.table} ${reviewCompact ? ui.compactTable : ''}`}
style={{ minWidth: reviewTableWidth }}
>
<colgroup>
{REVIEW_COLUMNS.map((column) => (
<col key={column.key} style={{ width: columnWidths[column.key] }} />
{visibleReviewColumns.map((column) => (
<col key={column.key} style={{ width: reviewColumnWidth(column.key) }} />
))}
</colgroup>
<thead>
<tr>
{REVIEW_COLUMNS.map((column) => (
{visibleReviewColumns.map((column) => (
<th
key={column.key}
className={[
@ -734,7 +907,7 @@ export function ClearanceReviewWorkbench({
{reviewColumnResizeHandle(
column.key,
column.label || '选择',
columnWidths[column.key],
reviewColumnWidth(column.key),
)}
</span>
</th>
@ -750,7 +923,7 @@ export function ClearanceReviewWorkbench({
row.duplicateGroupSize > 1 ? ui.reviewWorkbenchRowDuplicate : '',
].filter(Boolean).join(' ') || undefined}
>
{REVIEW_COLUMNS.map((column) => (
{visibleReviewColumns.map((column) => (
<td
key={column.key}
className={[

View File

@ -33,6 +33,7 @@ export function ClearanceSettingsMenu({
filterFields,
defaultFilterFields,
onFilterFieldsChange,
onFilterSettingsClick,
}: {
title: string
compact: boolean
@ -44,6 +45,7 @@ export function ClearanceSettingsMenu({
filterFields: string[]
defaultFilterFields: readonly string[]
onFilterFieldsChange: (keys: string[]) => void
onFilterSettingsClick?: () => void
}) {
const [menuOpen, setMenuOpen] = useState(false)
const [columnDrawerOpen, setColumnDrawerOpen] = useState(false)
@ -100,7 +102,11 @@ export function ClearanceSettingsMenu({
type="button"
role="menuitem"
className={limitStyles.settingsMenuRow}
onClick={() => { setMenuOpen(false); setFilterDrawerOpen(true) }}
onClick={() => {
setMenuOpen(false)
if (onFilterSettingsClick) onFilterSettingsClick()
else setFilterDrawerOpen(true)
}}
>
<SlidersHorizontal size={15} />
筛选设置
@ -117,7 +123,7 @@ export function ClearanceSettingsMenu({
onClose={() => setColumnDrawerOpen(false)}
/>
<ClearanceFilterSettingsDrawer
open={filterDrawerOpen}
open={filterDrawerOpen && !onFilterSettingsClick}
title="筛选设置"
fields={filterDefinitions}
selectedKeys={filterFields}

View File

@ -7,6 +7,7 @@ import styles from './clearance-price-push.module.css'
import { CLEARANCE_TASK_IMPORT_TEMPLATE_HEADERS } from '@/lib/clearance-task-manual-import-headers'
type ImportResult = {
periodKey: string
importedCount: number
createdCount: number
updatedCount: number
@ -120,7 +121,10 @@ export function ClearanceTaskManualImportDialog({
<div className={styles.importRuleText}>
<strong>导入说明</strong>
<p>请先下载模板,表头固定为:{CLEARANCE_TASK_IMPORT_TEMPLATE_HEADERS.join('、')}。</p>
<p>当前导入月份为 {period}。清货商品编码不能重复,且必须存在于当前清货池。</p>
<p>
当前导入月份为 {period}。清货商品编码不能重复,且必须存在于当前清货池;
组合编码只需导入一次,系统会展开组件,请勿重复导入组件编码。
</p>
<p>清货负责人就是任务运营负责人,不按执行导入的账号归属任务。</p>
<p>折扣填写阿拉伯数字 1–10 折或留空;“五折”会自动转换为“5折”。</p>
<p>任务量支持小数,系统向上取整;超过简尚库存时按简尚库存保留。</p>

View File

@ -17,7 +17,10 @@ import {
} from '@/lib/clearance-period-lifecycle'
import { isClearanceDiscountBlockedPriority } from '@/lib/clearance-discount-restrictions'
import { formatClearanceDailySales } from '@/lib/clearance-number-format'
import { resolveClearanceTaskPeriod } from '@/lib/clearance-task-period'
import {
resolveClearanceTaskPeriod,
resolveClearanceTaskViewPeriod,
} from '@/lib/clearance-task-period'
import {
shouldPollClearanceProgressSync,
shouldRefreshClearanceProgressData,
@ -726,7 +729,7 @@ function classNames(...values: Array<string | false | null | undefined>) {
return values.filter(Boolean).join(' ')
}
function PoolImageCell({ row }: {
export function PoolImageCell({ row }: {
row: {
image: string
barcode: string
@ -736,20 +739,58 @@ function PoolImageCell({ row }: {
}) {
const candidates = row.image ? [row.image] : []
const [index, setIndex] = useState(0)
const [previewPosition, setPreviewPosition] = useState<{ left: number; top: number } | null>(null)
const src = candidates[index]
if (!src) {
return <span className={ui.poolImageFallback}>{(row.brand || row.productName || row.barcode).slice(0, 1)}</span>
}
const showPreview = (element: HTMLElement) => {
const rect = element.getBoundingClientRect()
const previewSize = 320
const gap = 14
const viewportPadding = 12
setPreviewPosition({
left: Math.max(
viewportPadding,
Math.min(window.innerWidth - previewSize - viewportPadding, rect.right + gap),
),
top: Math.max(
viewportPadding,
Math.min(window.innerHeight - previewSize - viewportPadding, rect.top - 70),
),
})
}
return (
// eslint-disable-next-line @next/next/no-img-element
<img
className={ui.poolImage}
src={src}
alt=""
loading="lazy"
referrerPolicy="no-referrer"
onError={() => setIndex((value) => value + 1)}
/>
<span
className={ui.poolImageHover}
tabIndex={0}
aria-label={`预览 ${row.productName || row.barcode} 图片`}
onMouseEnter={(event) => showPreview(event.currentTarget)}
onMouseLeave={() => setPreviewPosition(null)}
onFocus={(event) => showPreview(event.currentTarget)}
onBlur={() => setPreviewPosition(null)}
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
className={ui.poolImage}
src={src}
alt=""
loading="lazy"
referrerPolicy="no-referrer"
onError={() => setIndex((value) => value + 1)}
/>
{previewPosition && (
<span
className={ui.poolImagePreview}
style={{ left: previewPosition.left, top: previewPosition.top }}
role="img"
aria-label={`${row.productName || row.barcode} 放大图片`}
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={src} alt="" referrerPolicy="no-referrer" />
</span>
)}
</span>
)
}
@ -1002,9 +1043,12 @@ export function ClearanceView({
setTaskLoading(true)
setTaskError('')
if (tab === 'tasks') setTasks(null)
const summaryPeriod = tab === 'pool'
? pool?.periodKey ?? taskPeriod
: taskPeriod || currentPeriodKey()
const summaryPeriod = resolveClearanceTaskViewPeriod({
view: tab === 'tasks' ? 'tasks' : 'pool',
poolPeriod: pool?.periodKey ?? '',
taskPeriod,
currentPeriod: currentPeriodKey(),
})
const taskParams = new URLSearchParams({ period: summaryPeriod })
taskParams.set('includeFreight', '0')
taskParams.set('liveProgress', '0')
@ -1019,7 +1063,7 @@ export function ClearanceView({
if (!isCurrentRequest()) return
setTasks(data)
const resolvedTaskPeriod = resolveClearanceTaskPeriod({
requestedPeriod: taskPeriod,
requestedPeriod: summaryPeriod,
responsePeriod: data.periodKey,
availablePeriods: data.periods ?? [],
currentPeriod: currentPeriodKey(),
@ -2518,6 +2562,7 @@ export function ClearanceView({
aria-label="清货月份"
onChange={(event) => {
setPoolPeriod(event.target.value)
setTaskPeriod(event.target.value)
setPoolReviewStatus('ALL')
setPoolPage(1)
setPoolFilterDraft([])
@ -3895,7 +3940,12 @@ export function ClearanceView({
{taskImportOpen && (
<ClearanceTaskManualImportDialog
period={taskPeriod || pool?.periodKey || currentPeriodKey()}
period={resolveClearanceTaskViewPeriod({
view: tab === 'tasks' ? 'tasks' : 'pool',
poolPeriod: pool?.periodKey ?? '',
taskPeriod,
currentPeriod: currentPeriodKey(),
})}
onClose={() => setTaskImportOpen(false)}
onImported={(result) => {
setTaskImportOpen(false)
@ -3904,7 +3954,7 @@ export function ClearanceView({
setTaskRefreshKey((value) => value + 1)
setPoolRefreshKey((value) => value + 1)
setToast(
`已导入 ${result.importedCount} 条清货任务并进入待审核`
`已导入到${monthLabel(result.periodKey)} ${result.importedCount} 条清货任务并进入待审核`
+ `(新增 ${result.createdCount} 条,更新 ${result.updatedCount} 条)`
+ (result.adjustedToStockCount
? `;${result.adjustedToStockCount} 条任务量已按简尚库存截断:${result.adjustedBarcodes.slice(0, 8).join('、')}`
@ -3915,7 +3965,12 @@ export function ClearanceView({
)}
{taskDirectImportOpen && (
<ClearanceTaskDirectImportDialog
period={taskPeriod || currentPeriodKey()}
period={resolveClearanceTaskViewPeriod({
view: tab === 'tasks' ? 'tasks' : 'pool',
poolPeriod: pool?.periodKey ?? '',
taskPeriod,
currentPeriod: currentPeriodKey(),
})}
onClose={() => setTaskDirectImportOpen(false)}
onImported={(result) => {
setTaskDirectImportOpen(false)
@ -3933,6 +3988,7 @@ export function ClearanceView({
{reviewWorkbenchOpen && pool?.periodKey && (
<ClearanceReviewWorkbench
userId={userId}
periodKey={pool.periodKey}
round={pool.taskRound}
onClose={() => setReviewWorkbenchOpen(false)}

View File

@ -1744,6 +1744,44 @@
background: #f1f2f3;
}
.poolImageHover {
position: relative;
display: inline-flex;
width: 34px;
height: 34px;
align-items: center;
justify-content: center;
border-radius: 5px;
outline: none;
}
.poolImageHover:focus-visible {
box-shadow: 0 0 0 2px #2563eb;
}
.poolImagePreview {
position: fixed;
z-index: 130;
display: grid;
width: 320px;
height: 320px;
place-items: center;
border: 1px solid #d4d4d8;
border-radius: 10px;
background: #fff;
padding: 10px;
box-shadow: 0 20px 50px rgba(24, 24, 27, 0.26);
pointer-events: none;
}
.poolImagePreview img {
width: 100%;
height: 100%;
border-radius: 6px;
object-fit: contain;
background: #f4f4f5;
}
.poolImageFallback {
display: inline-flex;
width: 34px;
@ -2952,6 +2990,17 @@
opacity: 0.45;
}
.reviewFilterAnchor {
position: relative;
align-self: end;
}
.reviewFilterBarWrap {
border-bottom: 1px solid #e4e4e7;
background: #fafafa;
padding: 0 8px;
}
.reviewWorkbenchSelection {
margin-left: auto;
color: #697274;
@ -3060,6 +3109,25 @@
flex: 1;
}
.reviewFilterPanel {
position: fixed;
top: 96px;
right: 16px;
left: 16px;
width: auto;
max-height: calc(100dvh - 128px);
overflow: auto;
}
.reviewFilterBuilder {
grid-template-columns: 1fr 1fr;
}
.reviewFilterBuilder input,
.reviewFilterAddButton {
grid-column: 1 / -1;
}
.reviewWorkbenchSelection {
width: 100%;
margin-left: 0;
@ -3093,6 +3161,29 @@
white-space: nowrap;
}
.reviewComboCode {
display: grid;
gap: 3px;
}
.reviewComboCode > span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.reviewComboCode em {
width: max-content;
border: 1px solid #c4b5fd;
border-radius: 999px;
background: #f5f3ff;
padding: 1px 6px;
color: #6d28d9;
font-size: 9px;
font-style: normal;
font-weight: 700;
}
.reviewWorkbenchReason {
overflow: hidden;
max-width: 240px;

View File

@ -20,14 +20,22 @@ function defaults(definitions: ColumnDefinition[]) {
}))
}
function columnStorageKey(table: 'pool' | 'tasks' | 'scores', userId: string) {
const version = table === 'tasks' ? 'v4' : table === 'scores' ? 'v3' : 'v2'
type ClearanceSettingsTable = 'pool' | 'tasks' | 'scores' | 'review'
function columnStorageKey(table: ClearanceSettingsTable, userId: string) {
const version = table === 'tasks'
? 'v4'
: table === 'scores'
? 'v3'
: table === 'review'
? 'v1'
: 'v2'
return `supply-chain.clearance.${table}-columns.${version}:${userId}`
}
export function useClearanceColumnSettings(
userId: string,
table: 'pool' | 'tasks' | 'scores',
table: ClearanceSettingsTable,
definitions: ColumnDefinition[],
) {
const [columns, setColumns] = useState<ClearanceColumnSetting[]>(() => defaults(definitions))
@ -86,7 +94,7 @@ export function useClearanceColumnSettings(
export function useClearanceFilterFields(
userId: string,
table: 'pool' | 'tasks' | 'scores',
table: ClearanceSettingsTable,
definitions: ColumnDefinition[],
defaultKeys: readonly string[],
) {
@ -98,7 +106,13 @@ export function useClearanceFilterFields(
useEffect(() => {
const allowedFilterKeys = new Set(definitions.map((field) => field.key))
const fallbackFilterFields = defaultKeys.filter((key) => allowedFilterKeys.has(key))
const version = table === 'scores' ? 'v2' : table === 'pool' ? 'v2' : 'v1'
const version = table === 'scores'
? 'v2'
: table === 'pool'
? 'v2'
: table === 'review'
? 'v1'
: 'v1'
try {
const raw = window.localStorage.getItem(`supply-chain.clearance.${table}-filter-fields.${version}:${userId}`)
const saved = raw ? JSON.parse(raw) : null
@ -114,7 +128,13 @@ export function useClearanceFilterFields(
useEffect(() => {
if (!hydrated) return
const version = table === 'scores' ? 'v2' : table === 'pool' ? 'v2' : 'v1'
const version = table === 'scores'
? 'v2'
: table === 'pool'
? 'v2'
: table === 'review'
? 'v1'
: 'v1'
try {
window.localStorage.setItem(
`supply-chain.clearance.${table}-filter-fields.${version}:${userId}`,
@ -128,7 +148,7 @@ export function useClearanceFilterFields(
export function useClearanceCompact(
userId: string,
table: 'pool' | 'tasks' | 'scores',
table: ClearanceSettingsTable,
) {
const [compact, setCompact] = useState(false)
const [hydrated, setHydrated] = useState(false)

View File

@ -0,0 +1,50 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { expressFixture } from '@/lib/daily-express-fixture'
import { expressRegionalPivot, selectExpressOverview } from '@/lib/daily-express-snapshot'
import { DailyExpressVolumeView } from './DailyExpressVolumeView'
const original = global.fetch, fetchMock = jest.fn()
let report = expressFixture()
beforeEach(() => { report = expressFixture(); global.fetch = fetchMock; fetchMock.mockReset(); fetchMock.mockImplementation(async (url: string) => ({ ok: true, json: async () => ({ success: true, data: { latestDate: report.dateTo, updatedAt: report.updatedAt, dates: report.overview.days, canDownload: true,
...(url.includes('view=uncollected') ? { uncollected: report.uncollected } : url.includes('view=regional') ? { regional: { date: report.dateTo, origin: '', origins: report.regional.days[0].origins, pivot: expressRegionalPivot(report.regional.days[0], '') } } : { overview: selectExpressOverview(report.overview, new URL(url, 'http://localhost').searchParams.get('date') || undefined) }) } }) })) })
afterAll(() => { global.fetch = original })
it('shows rolling totals without share or exclusions and switches to latest pickup details', async () => {
render(<DailyExpressVolumeView />); await screen.findByRole('table')
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('各快递30日承运量看版')
expect(screen.queryByText('占比')).not.toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: '已发货未揽收看版' }))
expect(await screen.findByText('0012345678901234567890')).toBeInTheDocument()
expect(screen.getByText(/发货日期:2026-11-24(最新)/)).toBeInTheDocument()
expect(screen.getByRole('button', { name: '导出 Excel' })).toBeInTheDocument()
})
it('regional view defaults to latest available date and keeps date/origin controls', async () => {
render(<DailyExpressVolumeView />); await screen.findByRole('table')
fireEvent.click(screen.getByRole('button', { name: '发货地省份区域承运量' }))
expect(await screen.findByLabelText('发货日期')).toHaveValue('2026-11-24')
expect(screen.getByLabelText('发货地')).toBeInTheDocument()
})
it('clears old output on failure and allows reload', async () => {
render(<DailyExpressVolumeView />); await screen.findByRole('table')
fetchMock.mockRejectedValueOnce(new Error('读取失败'))
fireEvent.click(screen.getByRole('button', { name: '重新加载' }))
expect(await screen.findByRole('alert')).toHaveTextContent('读取失败'); expect(screen.queryByRole('table')).not.toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: '重新加载' })); await waitFor(() => expect(screen.getByRole('table')).toBeInTheDocument())
})
it('defaults to all daily columns, applies a selected date only on filter, and resets to all dates', async () => {
report.overview = { dateFrom: '2026-11-23', dateTo: '2026-11-24', days: ['2026-11-23', '2026-11-24'], total: 5, carrierCount: 2,
daily: [{ date: '2026-11-23', total: 3 }, { date: '2026-11-24', total: 2 }],
ranking: [{ name: '甲快递', daily: [3, 0], total: 3, rank: 1 }, { name: '乙快递', daily: [0, 2], total: 2, rank: 2 }] }
render(<DailyExpressVolumeView />); await screen.findByRole('table')
expect(screen.getByRole('columnheader', { name: '2026-11-23' })).toBeInTheDocument()
expect(screen.getByRole('columnheader', { name: '2026-11-24' })).toBeInTheDocument()
fireEvent.change(screen.getByLabelText('承运发货日期'), { target: { value: '2026-11-24' } })
expect(fetchMock).toHaveBeenCalledTimes(1)
fireEvent.click(screen.getByRole('button', { name: '筛选' }))
await screen.findByText('乙快递')
expect(screen.queryByRole('columnheader', { name: '2026-11-23' })).not.toBeInTheDocument()
expect(fetchMock.mock.calls.at(-1)[0]).toContain('date=2026-11-24')
expect(screen.queryByText('甲快递')).not.toBeInTheDocument(); expect(screen.getByText('乙快递')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: '全部日期' }))
await screen.findByRole('columnheader', { name: '2026-11-23' })
expect(screen.getByLabelText('承运发货日期')).toHaveValue('')
expect(fetchMock.mock.calls.at(-1)[0]).not.toContain('date=')
})

View File

@ -0,0 +1,88 @@
'use client'
import { useEffect, useState } from 'react'
import { Download, RefreshCw } from 'lucide-react'
import { PlatformSection } from '@/components/platform/PlatformSection'
import { PlatformMetricStrip } from '@/components/platform/PlatformMetricStrip'
import { Button } from '@/components/ui/Button'
import type { ExpressQuery, ExpressReadState } from '@/lib/daily-express-snapshot'
import styles from './daily-express-volume.module.css'
const titles = { overview: '各快递30日承运量看版', regional: '发货地省份区域承运量', uncollected: '已发货未揽收看版' }
const fmt = (value: number) => value.toLocaleString('zh-CN')
const time = (value: string) => new Date(value).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })
export function DailyExpressVolumeView() {
const [view, setView] = useState<ExpressQuery['view']>('overview')
const [date, setDate] = useState(''), [origin, setOrigin] = useState(''), [search, setSearch] = useState('')
const [draftDate, setDraftDate] = useState('')
const [data, setData] = useState<ExpressReadState | null>(null), [error, setError] = useState('')
const [loading, setLoading] = useState(true), [revision, setRevision] = useState(0), [downloading, setDownloading] = useState(false)
const params = new URLSearchParams({ view, ...(view !== 'uncollected' && date ? { date } : {}), ...(view === 'regional' && origin ? { origin } : {}) }).toString()
useEffect(() => {
const controller = new AbortController(); setLoading(true); setError(''); setData(null)
void (async () => {
try {
const response = await fetch(`/api/supply-chain/management/daily-express-volume?${params}`, { signal: controller.signal, cache: 'no-store' })
const payload = await response.json()
if (!response.ok || !payload.success) throw new Error(payload.error?.message || '看板读取失败')
if (!controller.signal.aborted) setData(payload.data)
} catch (cause) { if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '看板读取失败') }
finally { if (!controller.signal.aborted) setLoading(false) }
})()
return () => controller.abort()
}, [params, revision])
async function download() {
setDownloading(true); setError('')
try {
const response = await fetch(`/api/supply-chain/management/daily-express-volume/export?${params}`, { cache: 'no-store' })
if (!response.ok) { const result = await response.json(); throw new Error(result.error?.message || '导出失败') }
const url = URL.createObjectURL(await response.blob()), a = document.createElement('a')
const filename = response.headers.get('Content-Disposition')?.split("filename*=UTF-8''")[1]
a.href = url; a.download = filename ? decodeURIComponent(filename) : `${titles[view]}.xlsx`; document.body.append(a); a.click(); a.remove(); URL.revokeObjectURL(url)
} catch (cause) { setError(cause instanceof Error ? cause.message : '导出失败') }
finally { setDownloading(false) }
}
const overview = data?.overview, regional = data?.regional, pickup = data?.uncollected
const query = search.trim().toLowerCase()
const carriers = overview?.ranking.filter(row => row.name.toLowerCase().includes(query)) ?? []
const pickupRows = pickup?.rows.filter(row => !query || Object.values(row).some(value => String(value ?? '').toLowerCase().includes(query))) ?? []
const regionCarriers = regional?.pivot.carriers.filter(name => name.toLowerCase().includes(query)) ?? []
const peak = Math.max(1, ...(overview?.daily.map(row => row.total) ?? []))
return <div className={styles.workspace}>
<header className={styles.header}><div><h1>{titles[view]}</h1><p>{data ? `最新发货日期 ${data.latestDate} · 更新于 ${time(data.updatedAt)}` : '快递承运量'}</p></div>
<Button variant="gray" size="small" disabled={loading} onClick={() => setRevision(value => value + 1)}><RefreshCw size={14} />重新加载</Button></header>
<nav className={styles.viewTabs} aria-label="快递看板切换">{(Object.keys(titles) as ExpressQuery['view'][]).map(key => <button type="button" key={key} aria-current={view === key ? 'page' : undefined} onClick={() => { setView(key); setSearch(''); setDate(''); setDraftDate(''); setOrigin('') }}>{titles[key]}</button>)}</nav>
{error ? <p role="alert" className={styles.error}>{error}</p> : null}
{loading ? <div className={styles.state} role="status">正在读取已更新数据…</div> : data ? <>
<div className={styles.reportTools}>
{overview ? <form className={styles.dateFilter} aria-label="承运日期筛选" onSubmit={event => { event.preventDefault(); setDate(draftDate) }}>
<label>发货日期 <select aria-label="承运发货日期" value={draftDate} onChange={event => setDraftDate(event.target.value)}>
<option value="">全部日期</option>{[...data.dates].reverse().map(value => <option key={value} value={value}>{value}{value === data.latestDate ? '(最新)' : ''}</option>)}
</select></label>
<Button type="submit" size="small" onClick={() => setDate(draftDate)}>筛选</Button>
{date ? <Button variant="gray" type="button" size="small" onClick={() => { setDate(''); setDraftDate('') }}>全部日期</Button> : null}
</form> : null}
{regional ? <><label>发货日期 <select aria-label="发货日期" value={regional.date} onChange={event => { setDate(event.target.value); setOrigin('') }}>{[...data.dates].reverse().map(value => <option key={value} value={value}>{value}{value === data.latestDate ? '(最新)' : ''}</option>)}</select></label>
<label>发货地 <select aria-label="发货地" value={regional.origin} onChange={event => setOrigin(event.target.value)}><option value="">全部发货地</option>{regional.origins.map(row => <option key={row.name} value={row.name}>{row.name}</option>)}</select></label></> : null}
{pickup ? <span>发货日期:{pickup.date}(最新) · 数据查询:{time(pickup.queriedAt)}</span> : null}
<input aria-label="搜索快递或订单" placeholder={pickup ? '搜索订单、快递或仓库' : '搜索快递名称'} value={search} onChange={event => setSearch(event.target.value)} />
{data.canDownload ? <Button size="small" onClick={download} disabled={downloading}><Download size={14} />{downloading ? '正在导出' : '导出 Excel'}</Button> : null}
</div>
{overview ? <>
<PlatformMetricStrip density="compact" className={styles.metrics} items={[{ label: `${overview.days.length} 天承运总量`, value: fmt(overview.total), hint: '单' }, { label: '日均承运量', value: (overview.total / overview.days.length).toLocaleString('zh-CN', { maximumFractionDigits: 1 }), hint: '单 / 天' }, { label: '快递名称数', value: overview.carrierCount, hint: '个' }]} />
<PlatformSection title="每日承运总量" className={styles.panel} contentClassName={styles.chartContent}>
<div className={styles.dailyChart}>{overview.daily.map(row => <div key={row.date} className={styles.dailyBar}><strong>{fmt(row.total)}</strong><div style={{ height: `${row.total / peak * 150}px` }} /><span>{row.date.slice(5)}</span></div>)}</div>
</PlatformSection>
<PlatformSection title="快递公司 × 每日承运量" className={styles.panel} contentClassName={styles.tableContent}>
<div className={styles.tableScroll}><table><thead><tr><th>快递名称</th>{overview.days.map(day => <th key={day}>{day}</th>)}<th>合计</th></tr></thead><tbody>
<tr><th>每日合计</th>{overview.daily.map(day => <td key={day.date}>{fmt(day.total)}</td>)}<td>{fmt(overview.total)}</td></tr>
{carriers.map(row => <tr key={row.name}><th>{row.name}</th>{row.daily.map((value, i) => <td key={overview.days[i]}>{value ? fmt(value) : '—'}</td>)}<td>{fmt(row.total)}</td></tr>)}
</tbody></table></div>
</PlatformSection></> : null}
{regional ? <PlatformSection title={`${regional.origin || '全部发货地'} · ${fmt(regional.pivot.total)} 单`} className={styles.panel} contentClassName={styles.tableContent}>
<div className={styles.tableScroll}><table><thead><tr><th>区域</th><th>省份</th>{regionCarriers.map(name => <th key={name}>{name}</th>)}<th>合计</th></tr></thead><tbody>{regional.pivot.rows.map((row, i) => <tr key={i} className={row.kind !== 'province' ? styles.subtotal : undefined}><th>{row.region}</th><td>{row.province}</td>{regionCarriers.map(name => <td key={name}>{row.counts[name] ? fmt(row.counts[name]) : '—'}</td>)}<td>{fmt(row.total)}</td></tr>)}</tbody></table></div>
</PlatformSection> : null}
{pickup ? <PlatformSection title={`未揽收订单 · ${fmt(pickup.summary.total)} 条`} className={styles.panel} contentClassName={styles.tableContent}>
<div className={styles.tableScroll}><table className={styles.pickupTable}><thead><tr>{pickup.columns.slice(0, 11).map(column => <th key={column.key}>{column.label}</th>)}</tr></thead><tbody>{pickupRows.map(row => <tr key={String(row.id)}>{pickup.columns.slice(0, 11).map(column => <td key={column.key}>{String(row[column.key] ?? '') || '—'}</td>)}</tr>)}</tbody></table>{!pickupRows.length ? <div className={styles.state}>暂无匹配订单</div> : null}</div>
</PlatformSection> : null}
</> : null}
</div>
}

View File

@ -0,0 +1,77 @@
.workspace { padding: 24px; color: var(--sc-ink, #272e32); max-width: 2200px; margin: 0 auto; }
.header { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 22px; }
.eyebrow { display: flex; align-items: center; gap: 7px; font-size: 11px; letter-spacing: .04em; color: #69767c; margin-bottom: 8px; }
.header h1 { font-size: 23px; font-weight: 650; letter-spacing: -.04em; margin: 0; }
.header > button { white-space: nowrap; flex-shrink: 0; }
.header p { color: #69767c; font-size: 12px; margin: 7px 0 0; }
.filters { display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-end; padding: 16px; border: 1px solid #e2e6e8; border-radius: 10px; background: #fff; }
.filters label { display: flex; flex-direction: column; gap: 7px; font-size: 11px; color: #637078; min-width: 145px; flex: 1; max-width: 230px; }
.filters input, .filters select { width: 100%; min-width: 0; border: 1px solid #dce1e4; border-radius: 6px; height: 34px; padding: 0 9px; color: #303a3f; background: #fff; font-size: 12px; color-scheme: light; }
.workspace :is(input, select, button, [tabindex]):focus-visible { outline: 2px solid #5c7c8a; outline-offset: 3px; }
.dateSeparator { color: #9aa4aa; padding-bottom: 8px; }
.filterActions { display: flex; gap: 4px; align-items: center; }
.presets { display: flex; gap: 3px; margin-left: auto; padding-bottom: 3px; }
.presets button { border: 0; border-radius: 5px; background: #f2f4f5; padding: 7px 9px; font-size: 11px; color: #53626a; cursor: pointer; white-space: nowrap; }
.presets button:hover { background: #e6ebee; }
.error { display: flex; gap: 8px; align-items: center; padding: 10px 12px; color: #9b3834; background: #fff2f0; border-radius: 6px; font-size: 12px; margin-top: 12px; }
.dataMeta { display: flex; gap: 12px; justify-content: space-between; flex-wrap: wrap; color: #7b858b; font-size: 11px; padding: 17px 1px 12px; }
.divider { margin: 0 9px; color: #b0b9be; }
.workspace .metrics { grid-template-columns: repeat(3, minmax(0, 1fr)); padding: 0; gap: 0; background: #fff; border: 1px solid #e2e6e8; border-radius: 10px; box-shadow: none; backdrop-filter: none; margin-bottom: 18px; overflow: hidden; }
.metrics > article { border: 0; border-radius: 0; padding: 17px 22px; min-height: 104px; background: #fff; box-shadow: none; gap: 12px; }
.metrics > article:first-child { border-radius: 10px 0 0 10px; }
.metrics > article:last-child { border-radius: 0 10px 10px 0; }
.metrics > article + article { border-left: 1px solid #edf0f2; }
.metrics > article p { color: #68767e; }
.metrics > article > div:last-child > p:first-child { font-size: 29px; font-weight: 650; color: #2b3940; font-variant-numeric: tabular-nums; letter-spacing: -.04em; }
.analysis { display: grid; grid-template-columns: minmax(0, 1.9fr) minmax(300px, 1fr); gap: 18px; margin-bottom: 18px; }
.workspace .panel { min-width: 0; border-radius: 10px; border: 1px solid #e2e6e8; background: #fff; box-shadow: none; backdrop-filter: none; }
.panel > header { padding: 14px 18px; border-color: #edf0f2; flex-direction: row; align-items: center; gap: 12px; }
.panel > header h2 { font-size: 13px; font-weight: 650; color: #354249; letter-spacing: 0; }
.panelHint { color: #8a959b; font-size: 10px; white-space: nowrap; }
.workspace .chartContent { padding: 20px 18px 14px; }
.chart { display: flex; height: 238px; gap: 10px; }
.axis { display: flex; flex-direction: column; justify-content: space-between; width: 42px; flex-shrink: 0; padding: 27px 0 29px; font-size: 10px; color: #8a959b; text-align: right; }
.chartScroll { flex: 1; min-width: 0; overflow-x: auto; }
.plot { display: flex; height: 100%; background-image: linear-gradient(to bottom, transparent calc(100% - 1px), #edf0f2 0); background-size: 100% calc((100% - 28px) / 2); background-position: 0 0; }
.day { flex: 1; min-width: 0; display: flex; flex-direction: column; align-items: center; height: 100%; }
.barTrack { width: 100%; height: calc(100% - 28px); display: flex; align-items: flex-end; justify-content: center; position: relative; border-bottom: 1px solid #dfe5e8; }
.bar { width: 35%; max-width: 34px; background: #8cabb6; border-radius: 3px 3px 0 0; }
.peakBar { background: #465f6b; }
.barValue { position: absolute; font-size: 10px; color: #4d626c; padding-bottom: 6px; font-variant-numeric: tabular-nums; white-space: nowrap; }
.dayLabel { height: 28px; padding-top: 10px; font-size: 10px; color: #7d8990; }
.workspace .rankContent { padding: 0 18px; height: 272px; overflow-y: auto; }
.ranking { padding: 0; margin: 0; list-style: none; }
.ranking li { display: flex; gap: 13px; align-items: center; padding: 13px 0; border-bottom: 1px solid #f1f3f4; }
.ranking li:last-child { border: 0; }
.rankNumber { font-size: 11px; color: #8a999f; font-variant-numeric: tabular-nums; }
.rankBody { flex: 1; min-width: 0; }
.rankLabel { display: flex; justify-content: space-between; align-items: baseline; gap: 14px; font-size: 12px; margin-bottom: 7px; }
.rankLabel > span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.rankLabel strong { white-space: nowrap; font-weight: 600; font-variant-numeric: tabular-nums; }
.rankLabel small { display: inline-block; min-width: 49px; padding-left: 9px; text-align: right; font-size: 10px; color: #8a959b; font-weight: 400; }
.rankTrack { height: 4px; background: #f0f3f4; border-radius: 3px; overflow: hidden; }
.rankTrack > div { height: 100%; background: #7995a1; border-radius: 3px; }
.workspace .tableContent { padding: 0; }
.tableScroll { overflow: auto; max-height: 480px; border-radius: 0 0 10px 10px; }
.tableScroll table { width: 100%; border-collapse: separate; border-spacing: 0; font-size: 12px; font-variant-numeric: tabular-nums; white-space: nowrap; }
.tableScroll :is(th, td) { text-align: right; padding: 12px 16px; border-bottom: 1px solid #edf0f2; min-width: 90px; }
.tableScroll tr > :first-child { text-align: left; position: sticky; left: 0; min-width: 180px; max-width: 280px; overflow: hidden; text-overflow: ellipsis; background: #fff; border-right: 1px solid #edf0f2; z-index: 1; }
.tableScroll thead th { color: #72818a; background: #f7f9fa; font-size: 11px; font-weight: 500; position: sticky; top: 0; z-index: 2; }
.tableScroll thead th:first-child { z-index: 3; background: #f7f9fa; }
.tableScroll tbody th { font-weight: 500; }
.tableScroll tbody tr:hover > * { background: #f7fafb; }
.tableScroll tfoot { position: sticky; bottom: 0; z-index: 2; }
.tableScroll tfoot :is(th, td) { font-weight: 650; color: #3c535f; background: #f3f6f7; border-top: 1px solid #e0e6e9; border-bottom: 0; }
.totalCell { font-weight: 600; }
.mutedCell { color: #7f8c94; }
.zeroCell { color: #b1bbc1; }
.footnote { display: flex; align-items: flex-start; gap: 6px; font-size: 10px; line-height: 1.8; color: #8b969d; padding: 13px 1px 0; }
.footnote svg { flex-shrink: 0; margin-top: 3px; }
.state { display: flex; align-items: center; flex-direction: column; justify-content: center; gap: 13px; min-height: 330px; padding: 36px 20px; color: #85949c; text-align: center; }
.state strong { font-size: 14px; color: #4a5a63; font-weight: 500; }
.state span { font-size: 12px; max-width: 620px; overflow-wrap: anywhere; }
.srOnly { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; }
@media (max-width: 1100px) { .analysis { grid-template-columns: minmax(0, 1.5fr) minmax(260px, 1fr); } .presets { margin-left: 0; } }
@media (max-width: 760px) { .workspace { padding: 16px; } .header h1 { font-size: 19px; } .header { align-items: flex-start; } .header > button { flex-shrink: 0; } .header p { line-height: 1.8; } .analysis { grid-template-columns: minmax(0, 1fr); } .workspace .metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); } .metrics > article { border-radius: 0 !important; padding: 15px; } .metrics > article:nth-child(3) { border-left: 0; } .metrics > article:nth-child(n+3) { border-top: 1px solid #edf0f2; } .dateSeparator { display: none; } .filters label { max-width: none; min-width: calc(50% - 12px); } .presets { margin-left: auto; } .panelHint { font-size: 9px; white-space: normal; text-align: right; } }
.viewTabs{display:flex;flex-wrap:wrap;gap:8px;margin-bottom:18px}.viewTabs button{padding:11px 17px;border:1px solid #d6e1e8;border-radius:7px;background:#fff;color:#526b7b;font-size:14px}.viewTabs button[aria-current=page]{background:#e8f1f7;border-color:#a8c5d8;color:#244f69;font-weight:600}.reportTools{display:flex;flex-wrap:wrap;align-items:center;gap:12px;margin:16px 0;color:#657b89;font-size:12px}.reportTools input,.reportTools select{border:1px solid #d6e1e8;border-radius:6px;background:#fff;padding:9px 12px;max-width:100%}.reportTools input{margin-left:auto;min-width:200px}.workspace .panel{margin-bottom:18px}.dailyChart{display:flex;gap:24px;align-items:flex-end;min-height:205px;overflow:auto}.dailyBar{min-width:64px;flex:1;display:flex;flex-direction:column;align-items:center;gap:8px;color:#627988;font-size:12px}.dailyBar div{min-height:1px;width:32px;border-radius:4px 4px 0 0;background:#789eaf}.subtotal>*{background:#eaf1f5!important;font-weight:600!important}.tableScroll{max-height:65vh}.tableScroll .pickupTable td{text-align:left}.workspace{min-width:0;width:100%}@media(max-width:760px){.viewTabs button{flex:1;font-size:12px;padding:10px}.reportTools input{margin-left:0;min-width:0;width:100%}.reportTools label{width:100%}.reportTools select{max-width:80%}}
.dateFilter{display:flex;align-items:center;flex-wrap:wrap;gap:10px}.dateFilter label{display:flex;align-items:center;gap:8px;white-space:nowrap}@media(max-width:760px){.dateFilter{width:100%}.dateFilter label{width:100%;flex:1 1 100%}.dateFilter select{flex:1;max-width:100%}}

View File

@ -0,0 +1,13 @@
import { redirect } from 'next/navigation'
import { requireSession } from '@/lib/server-session'
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
import { DailyExpressVolumeView } from './DailyExpressVolumeView'
export const dynamic = 'force-dynamic'
export default async function DailyExpressVolumePage() {
const { authUser } = await requireSession('/login')
const access = await supplyChainPermissionSettingsService.getUserAccess(authUser, 'dailyExpressVolume')
if (!access.view) redirect('/supply-chain')
return <DailyExpressVolumeView />
}

View File

@ -179,6 +179,14 @@ describe('ModularProductProcessingOrdersView pane resizing', () => {
expect.stringContaining('columnFilters='),
{ cache: 'no-store' },
)
await waitFor(() => {
const componentRequest = (global.fetch as jest.Mock).mock.calls.find(([url]) =>
String(url).includes('/components?'),
)
expect(componentRequest?.[0]).toEqual(expect.stringContaining(
`snapshotDate=${currentShanghaiDate()}`,
))
})
const handle = screen.getByRole('separator', { name: '调整部件部件条码列宽' })
fireEvent.keyDown(handle, { key: 'ArrowRight' })
@ -342,6 +350,8 @@ describe('ModularProductProcessingOrdersView pane resizing', () => {
)
expect(new URL(String(detailRequest[0]), 'http://localhost').searchParams.get('columnFilters'))
.toBe(JSON.stringify({ componentName: { operator: 'in', value: '', values: ['桌脚'] } }))
expect(new URL(String(detailRequest[0]), 'http://localhost').searchParams.get('snapshotDate'))
.toBe(currentShanghaiDate())
fireEvent.click(screen.getByRole('button', { name: '导出' }))
fireEvent.click(within(screen.getByRole('menu', { name: '导出选项' }))
@ -355,7 +365,10 @@ describe('ModularProductProcessingOrdersView pane resizing', () => {
type: 'modular-processing-export',
params: {
mode: 'withComponents',
filters: { componentColumnFilters: { componentName: { operator: 'in', values: ['桌脚'] } } },
filters: {
componentColumnFilters: { componentName: { operator: 'in', values: ['桌脚'] } },
snapshotDate: currentShanghaiDate(),
},
},
})
} finally {
@ -508,7 +521,7 @@ describe('ModularProductProcessingOrdersView pane resizing', () => {
const post = (global.fetch as jest.Mock).mock.calls.find(([, init]) => init?.method === 'POST')
expect(JSON.parse(post[1].body)).toEqual({
updates: [{ barcode: 'BARCODE-1', finalProcessingQuantity: 88 }],
generationDate: '2026-11-21',
generationDate: currentShanghaiDate(),
})
expect(await screen.findByText(
'部件库存不足:BARCODE-1 的最终加工量已由 88 自动调整为 2;限制部件:PART-STOCK(可用 2,需求 88)',
@ -590,7 +603,7 @@ describe('ModularProductProcessingOrdersView pane resizing', () => {
{ barcode: 'BARCODE-1', processingNote: '等采购确认' },
{ barcode: 'BARCODE-2', processingNote: '等采购确认' },
],
generationDate: '2026-11-21',
generationDate: currentShanghaiDate(),
})
} finally {
global.fetch = previousFetch

View File

@ -1483,6 +1483,8 @@ export function ModularProductProcessingOrdersView({
page: String(requestedPage),
pageSize: String(requestedPageSize),
})
if (snapshotDate) params.set('snapshotDate', snapshotDate)
if (snapshotDate && snapshotSlot) params.set('generationSlot', snapshotSlot)
if (componentSort) {
params.set('sortKey', componentSort.key)
params.set('sortDirection', componentSort.direction)
@ -1502,7 +1504,7 @@ export function ModularProductProcessingOrdersView({
} finally {
setComponentLoading(false)
}
}, [componentColumnFilters, componentSort])
}, [componentColumnFilters, componentSort, snapshotDate, snapshotSlot])
useEffect(() => {
const barcode = String(selectedRow?.barcode ?? '').trim()
@ -1697,6 +1699,8 @@ export function ModularProductProcessingOrdersView({
sortDirection: orderSort?.direction,
componentSortKey: componentSort?.key,
componentSortDirection: componentSort?.direction,
snapshotDate: snapshotDate || undefined,
generationSlot: snapshotDate && snapshotSlot ? snapshotSlot : undefined,
}
const selectedBarcodes = data.rows
.filter((row) => checkedRowIds.includes(row.id))
@ -2589,6 +2593,20 @@ export function ModularProductProcessingOrdersView({
</div>
<div>
{componentData?.sourceStatus.source && <span>{componentData.sourceStatus.source}</span>}
{componentData?.sourceStatus.dataMode && (
<span
title={componentData.sourceStatus.dataAsOf
? `数据时间:${formatTime(componentData.sourceStatus.dataAsOf)}`
: undefined}
>
{componentData.sourceStatus.dataMode === 'BATCH_SNAPSHOT'
? '批次冻结数据'
: '实时数据'}
{componentData.sourceStatus.dataAsOf
? ` · ${formatTime(componentData.sourceStatus.dataAsOf)}`
: ''}
</span>
)}
<button
type="button"
className={styles.iconButton}
@ -2675,8 +2693,8 @@ export function ModularProductProcessingOrdersView({
barcode={String(selectedRow?.barcode ?? '')}
current={openColumnFilter.table === 'orders' ? orderColumnFilters[openColumnFilter.key] : componentColumnFilters[openColumnFilter.key]}
filters={columnOptionFilters}
snapshotDate={openColumnFilter.table === 'orders' ? snapshotDate || undefined : undefined}
generationSlot={openColumnFilter.table === 'orders' ? snapshotSlot || undefined : undefined}
snapshotDate={snapshotDate || undefined}
generationSlot={snapshotSlot || undefined}
onApply={applyColumnFilter}
onClear={clearColumnFilter}
onClose={closeColumnFilter}

View File

@ -14,6 +14,7 @@ import {
type ReissueRecord,
type ReissueStore,
} from '@/lib/purchase-legacy-modules'
import { requiresReasonOtherNote } from '@/lib/supplier-reissue-response'
import styles from './legacy-purchase-modules.module.css'
import type { ReissueFilter, ReissueForm, ReissueScriptState, SupplierFillLink, SupplierMappingDraft, WecomPublicConfig } from './reissue-reminder.types'
import { aliasFor, exportReissueCsv } from './reissue-reminder.utils'
@ -78,12 +79,16 @@ export function ReissueReminderClient({
)
const visibleSupplierRecords = store.records
const stats = reissueStats(visibleSupplierRecords)
const reasonReviewPendingCount = visibleSupplierRecords.filter(
(record) => record.reasonReviewStatus === 'PENDING_FOLLOWUP',
).length
const filtered = useMemo(() => {
const keyword = query.trim().toLowerCase()
return visibleSupplierRecords.filter((record) => {
const state = reissueStatus(record)
if (filter === 'pending' && state.key === 'closed') return false
if (filter === 'reason-review' && record.reasonReviewStatus !== 'PENDING_FOLLOWUP') return false
if (filter === 'overdue' && !state.overdue) return false
if (filter === 'awaiting-ship' && !['awaiting-ship', 'due-soon', 'ship-overdue', 'review'].includes(state.key)) return false
if (filter === 'awaiting-callback' && !['awaiting-callback', 'callback-overdue'].includes(state.key)) return false
@ -748,6 +753,47 @@ export function ReissueReminderClient({
event.preventDefault()
if (!feedbackRecord) return
const data = new FormData(event.currentTarget)
const reasonReviewRequired = feedbackRecord.reasonReviewStatus === 'PENDING_FOLLOWUP'
if (reasonReviewRequired) {
const finalReasonCategory = String(data.get('finalReasonCategory') || '').trim()
const reasonNote = String(data.get('reasonNote') || '').trim()
if (!finalReasonCategory) {
setError('请选择最终二级原因')
return
}
if (requiresReasonOtherNote(finalReasonCategory) && reasonNote.length < 10) {
setError('最终原因选择“其他”时,请填写不少于 10 个字的判定说明')
return
}
setBusy(true)
setError('')
try {
const response = await fetch(
'/api/supply-chain/purchase/legacy/reissue-reminder/reason-review',
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
recordId: feedbackRecord.id,
finalReasonCategory,
reasonNote,
feedbackContent: String(data.get('feedbackContent') || '').trim(),
}),
},
)
const payload = await response.json().catch(() => null)
if (!response.ok || !payload?.success) {
throw new Error(payload?.error?.message || '最终原因判定保存失败')
}
setStore(payload.data.store as ReissueStore)
setFeedbackRecord(null)
} catch (cause) {
setError(cause instanceof Error ? cause.message : '最终原因判定保存失败')
} finally {
setBusy(false)
}
return
}
const feedbackStatus = String(data.get('feedbackStatus') || '待处理')
const feedbackContent = String(data.get('feedbackContent') || '').trim()
if (!feedbackContent) {
@ -792,6 +838,7 @@ export function ReissueReminderClient({
const chips: Array<[ReissueFilter, string, number]> = [
['all', '全部', stats.total],
['pending', '待处理', stats.pending],
['reason-review', '待跟单员判定', reasonReviewPendingCount],
['overdue', '超时', stats.overdue],
['awaiting-ship', '待发货', stats.awaitingShipment],
['awaiting-callback', '待回传', stats.awaitingCallback],
@ -920,16 +967,17 @@ export function ReissueReminderClient({
<tbody>
{records.map((record) => {
const state = reissueStatus(record)
const reasonReviewPending = record.reasonReviewStatus === 'PENDING_FOLLOWUP'
const sourceDetails = record.sourceDetails
const values = [
reissueSupplier(record),
sourceDetails?.localCreated || record.importedAt || '—',
sourceDetails?.orderType || '—',
sourceDetails?.overtimeType || record.reason || '—',
sourceDetails?.status || state.label,
reasonReviewPending ? '待跟单员判定' : sourceDetails?.status || state.label,
sourceDetails?.questionType || '—',
sourceDetails?.relabels || '—',
record.supplierReasonCategory || sourceDetails?.groupReason || '—',
record.followupFinalReasonCategory || record.supplierReasonCategory || sourceDetails?.groupReason || '—',
record.supplierSolution || sourceDetails?.solution || record.note || '—',
record.supplierExpectedSolveDate || sourceDetails?.planSolveDate || '—',
sourceDetails?.handlerDepartment || '—',
@ -943,13 +991,18 @@ export function ReissueReminderClient({
<tr key={record.id}>
{values.map((value, index) => index === 4 ? (
<td key={index}>
<span className={`${styles.status} ${reissueStatusClass(state.tone)}`}>{value}</span>
{record.supplierRespondedAt ? (
<span className={`${styles.status} ${reissueStatusClass(reasonReviewPending ? 'orange' : state.tone)}`}>{value}</span>
{reasonReviewPending ? (
<small className={styles.subCell}>等待 {store.supplierOwners[reissueSupplier(record)] || '对应跟单员'} 完成最终原因判定</small>
) : record.supplierRespondedAt ? (
<small className={styles.subCell}>供应商已反馈 {record.supplierRespondedAt.slice(0, 16).replace('T', ' ')}</small>
) : null}
{record.followupFinalReasonCategory ? (
<small className={styles.subCell}>最终判定:{record.followupFinalReasonCategory}</small>
) : null}
<div className={styles.rowActions}>
{canEdit ? <button className={styles.tableAction} type="button" onClick={() => setFeedbackRecord(record)}>反馈</button> : null}
{canEdit ? <button className={styles.tableAction} type="button" onClick={() => setCallbackRecord(record)}>{state.key === 'closed' ? '修改回传' : '回传'}</button> : null}
{canEdit ? <button className={styles.tableAction} type="button" onClick={() => setFeedbackRecord(record)}>{reasonReviewPending ? '最终判定' : '反馈'}</button> : null}
{canEdit && !reasonReviewPending ? <button className={styles.tableAction} type="button" onClick={() => setCallbackRecord(record)}>{state.key === 'closed' ? '修改回传' : '回传'}</button> : null}
{state.key !== 'closed' ? <button className={styles.tableAction} type="button" onClick={() => void openScript([record], reissueSupplier(record))}>催发</button> : null}
{canEdit ? <button className={styles.tableAction} type="button" onClick={() => setRecordForm(record)}>编辑</button> : null}
{canEdit ? <button className={`${styles.tableAction} ${styles.tableActionDanger}`} type="button" onClick={() => void removeRecord(record)}>删除</button> : null}

View File

@ -8,6 +8,9 @@ import {
type ReissueRecord,
type ReissueStore,
} from '@/lib/purchase-legacy-modules'
import {
SUPPLIER_REASON_CATEGORY_GROUPS,
} from '@/lib/supplier-reissue-response'
import styles from './legacy-purchase-modules.module.css'
import type {
ReissueForm,
@ -18,6 +21,8 @@ import type {
} from './reissue-reminder.types'
const MENTION_OWNERS = ['雁兰', '东皇太一', '貂蝉', '郁雾']
const NON_FACTORY_REASON_CATEGORIES = SUPPLIER_REASON_CATEGORY_GROUPS
.find((group) => group.root === '非工厂原因')?.categories || []
type ReissueReminderDialogsProps = {
busy: boolean
@ -131,6 +136,7 @@ export function ReissueReminderDialogs(props: ReissueReminderDialogsProps) {
syncWecomGroups,
runWecomPilot,
} = props
const reasonReviewRequired = feedbackRecord?.reasonReviewStatus === 'PENDING_FOLLOWUP'
return (
<>
@ -174,14 +180,49 @@ export function ReissueReminderDialogs(props: ReissueReminderDialogsProps) {
{feedbackRecord ? (
<div className={styles.modalBackdrop}>
<form className={styles.modal} onSubmit={submitFeedback}>
<div className={styles.modalHeader}><div><h2>订单反馈</h2><p>{reissueSupplier(feedbackRecord)} · {feedbackRecord.orderNo || '未填订单号'} · {reissueStatus(feedbackRecord).label}</p></div><button className={styles.modalClose} type="button" onClick={() => setFeedbackRecord(null)}>×</button></div>
<div className={styles.modalHeader}><div><h2>{reasonReviewRequired ? '非工厂原因最终判定' : '订单反馈'}</h2><p>{reissueSupplier(feedbackRecord)} · {feedbackRecord.orderNo || '未填订单号'} · {reissueStatus(feedbackRecord).label}</p></div><button className={styles.modalClose} type="button" onClick={() => setFeedbackRecord(null)}>×</button></div>
<div className={styles.formGrid}>
<label>反馈状态<select name="feedbackStatus" defaultValue={feedbackRecord.feedbackStatus || '待处理'}><option>待处理</option><option>处理中</option><option>已处理</option></select></label>
{reasonReviewRequired ? (
<>
<div className={`${styles.reasonReviewNotice} ${styles.wide}`}>
<strong>工厂初判:{feedbackRecord.supplierReasonCategory || '未填写'}</strong>
<span>解决方案:{feedbackRecord.supplierSolution || '未填写'}</span>
<span>预计解决日期:{feedbackRecord.supplierExpectedSolveDate || '未填写'}</span>
<span>跟单员:{store.supplierOwners[reissueSupplier(feedbackRecord)] || '未配置'}</span>
</div>
<label>
最终二级原因 <b>*</b>
<select name="finalReasonCategory" defaultValue="" required>
<option value="">请选择最终原因</option>
{NON_FACTORY_REASON_CATEGORIES.map((category) => (
<option key={category} value={category}>
{category.slice('非工厂原因-'.length)}
</option>
))}
</select>
</label>
<label>
最终判定类型
<input value="非工厂原因" readOnly />
</label>
<label className={styles.wide}>
最终判定说明
<textarea
name="reasonNote"
rows={3}
maxLength={1000}
placeholder="补充核实过程;若最终选择“其他”,此处必须填写不少于 10 个字"
/>
</label>
</>
) : (
<label>反馈状态<select name="feedbackStatus" defaultValue={feedbackRecord.feedbackStatus || '待处理'}><option>待处理</option><option>处理中</option><option>已处理</option></select></label>
)}
<label>操作人<input value={currentUserName} readOnly /></label>
<label className={styles.wide}>反馈内容<textarea name="feedbackContent" rows={8} required defaultValue={feedbackRecord.feedbackContent || ''} placeholder="填写订单当前问题、沟通结果、处理方案或下一步动作" /></label>
<label className={styles.wide}>{reasonReviewRequired ? '补充反馈内容(可选)' : '反馈内容'}<textarea name="feedbackContent" rows={reasonReviewRequired ? 5 : 8} required={!reasonReviewRequired} defaultValue={reasonReviewRequired ? '' : feedbackRecord.feedbackContent || ''} placeholder={reasonReviewRequired ? '可补充与工厂核实的结果、责任判定依据等' : '填写订单当前问题、沟通结果、处理方案或下一步动作'} /></label>
{feedbackRecord.feedbackAt ? <div className={styles.handoverNote}>上次反馈:{feedbackRecord.feedbackAt} · {feedbackRecord.feedbackBy || '未记录操作人'}</div> : null}
</div>
<div className={styles.modalFooter}><button className={styles.button} type="button" onClick={() => setFeedbackRecord(null)}>取消</button><button className={styles.primaryButton} type="submit" disabled={busy}>{busy ? '保存中…' : '保存反馈'}</button></div>
<div className={styles.modalFooter}><button className={styles.button} type="button" onClick={() => setFeedbackRecord(null)}>取消</button><button className={styles.primaryButton} type="submit" disabled={busy}>{busy ? '保存中…' : reasonReviewRequired ? '提交最终判定' : '保存反馈'}</button></div>
</form>
</div>
) : null}

View File

@ -354,6 +354,19 @@
.handoverSummary { border-left: 1px solid #e4e4e7; padding-left: 16px; color: #71717a; font-size: 10px; line-height: 1.55; }
.handoverSummary strong { display: block; color: #18181b; font-size: 25px; }
.handoverSummary span { display: block; margin-bottom: 8px; }
.reasonReviewNotice {
display: grid;
gap: 5px;
border: 1px solid #fde68a;
border-radius: 7px;
background: #fffbeb;
padding: 11px 13px;
color: #854d0e;
font-size: 10px;
line-height: 1.55;
}
.reasonReviewNotice strong { font-size: 11px; }
.reasonReviewNotice span { color: #92400e; }
.handoverNote { margin: 0 14px 14px; border: 1px solid #e4e4e7; border-radius: 5px; background: #fafafa; padding: 9px 11px; color: #71717a; font-size: 10px; line-height: 1.55; }
.inboxGrid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; padding: 13px; }

View File

@ -3,6 +3,7 @@ import type { ReissueRecord } from '@/lib/purchase-legacy-modules'
export type ReissueFilter =
| 'all'
| 'pending'
| 'reason-review'
| 'overdue'
| 'awaiting-ship'
| 'awaiting-callback'

View File

@ -178,6 +178,8 @@ describe('permission matrix navigation sources', () => {
})
expectedTargetKeys.delete('operationLogs')
expectedTargetKeys.delete('managementBlankPage1')
// 跟单交接视图已从菜单下线(旧路径重定向到订单总览),权限矩阵不再单独展示
expectedTargetKeys.delete('purchaseFollowupHandover')
expectedTargetKeys.delete('modularProcessingRulesColumnsEdit')
expectedTargetKeys.delete('modularProcessingRulesImport')
expectedTargetKeys.delete('freightMaintenance')

View File

@ -1,6 +1,27 @@
import { resolveClearanceTaskPeriod } from './clearance-task-period'
import {
resolveClearanceTaskPeriod,
resolveClearanceTaskViewPeriod,
} from './clearance-task-period'
describe('resolveClearanceTaskPeriod', () => {
it('uses the selected pool period on pool pages instead of stale task state', () => {
expect(resolveClearanceTaskViewPeriod({
view: 'pool',
poolPeriod: '2026-12',
taskPeriod: '2026-11',
currentPeriod: '2026-11',
})).toBe('2026-12')
})
it('uses the task page period when viewing the task list', () => {
expect(resolveClearanceTaskViewPeriod({
view: 'tasks',
poolPeriod: '2026-12',
taskPeriod: '2026-11',
currentPeriod: '2026-11',
})).toBe('2026-11')
})
it('keeps a requested period when the task response includes it', () => {
expect(resolveClearanceTaskPeriod({
requestedPeriod: '2026-11',

View File

@ -16,3 +16,14 @@ export function resolveClearanceTaskPeriod(input: {
if (response && periods.includes(response)) return response
return periods[0] || response || requested || current
}
export function resolveClearanceTaskViewPeriod(input: {
view: 'pool' | 'tasks'
poolPeriod: string
taskPeriod: string
currentPeriod: string
}) {
const poolPeriod = input.poolPeriod.trim()
if (input.view === 'pool' && poolPeriod) return poolPeriod
return input.taskPeriod.trim() || poolPeriod || input.currentPeriod.trim()
}

View File

@ -0,0 +1,7 @@
import type { ExpressSnapshot } from './daily-express-snapshot'
export function expressFixture(): ExpressSnapshot {
return { version: 1, dateTo: '2026-11-24', updatedAt: '2026-11-25T01:00:00Z',
overview: { dateFrom: '2026-11-24', dateTo: '2026-11-24', days: ['2026-11-24'], total: 2, carrierCount: 1, daily: [{ date: '2026-11-24', total: 2 }], ranking: [{ name: '测试快递', daily: [2], total: 2, rank: 1 }] },
regional: { dates: ['2026-11-24'], latestDate: '2026-11-24', days: [{ date: '2026-11-24', total: 2, origins: [{ name: '常州自有仓', total: 2 }], regions: ['华东'], provinces: [{ region: '华东', province: '江苏', provinceOrder: 0 }], rows: [{ origin: '常州自有仓', region: '华东', province: '江苏', provinceOrder: 0, carrier: '测试快递', count: 2 }] }] },
uncollected: { date: '2026-11-24', queriedAt: '2026-11-25T00:59:00Z', refundCheckedAt: '2026-11-25T01:00:00Z', columns: [{ key: 'logistic_id', label: '快递单号' }], rows: [{ id: 1, logistic_id: '0012345678901234567890' }], summary: { total: 1, pending: 1, uniqueOrders: 1, carriers: [{ name: '测试快递', count: 1 }], warehouses: [{ name: '测试仓', count: 1 }] } } }
}

View File

@ -0,0 +1,52 @@
import { z } from 'zod'
const count = z.number().int().nonnegative()
export const expressDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine(value => !Number.isNaN(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value)
const group = z.object({ name: z.string(), count })
const regionalDay = z.object({ date: expressDate, total: count,
origins: z.array(z.object({ name: z.string(), total: count })), regions: z.array(z.string()),
provinces: z.array(z.object({ region: z.string(), province: z.string(), provinceOrder: count })),
rows: z.array(z.object({ origin: z.string(), region: z.string(), province: z.string(), provinceOrder: count, carrier: z.string(), count })) })
export const expressSnapshotSchema = z.object({ version: z.literal(1), dateTo: expressDate, updatedAt: z.string().datetime(),
overview: z.object({ dateFrom: expressDate, dateTo: expressDate, days: z.array(expressDate).min(1).max(30), total: count, carrierCount: count,
daily: z.array(z.object({ date: expressDate, total: count })), ranking: z.array(z.object({ name: z.string(), total: count, daily: z.array(count), rank: count })) }),
regional: z.object({ dates: z.array(expressDate), latestDate: expressDate, days: z.array(regionalDay) }),
uncollected: z.object({ date: expressDate, queriedAt: z.string().datetime(), refundCheckedAt: z.string().datetime(),
columns: z.array(z.object({ key: z.string(), label: z.string() })), rows: z.array(z.record(z.string(), z.unknown())),
summary: z.object({ total: count, pending: count, uniqueOrders: count, carriers: z.array(group), warehouses: z.array(group) }) }) })
export type ExpressSnapshot = z.infer<typeof expressSnapshotSchema>
export function selectExpressOverview(overview: ExpressSnapshot['overview'], date?: string): ExpressSnapshot['overview'] {
if (!date) return overview
const index = overview.days.indexOf(date)
if (index < 0) throw new Error('所选日期没有已更新数据')
const ranking = overview.ranking.map(row => ({ ...row, daily: [row.daily[index]], total: row.daily[index] }))
.filter(row => row.total > 0)
.sort((a, b) => b.total - a.total || a.name.localeCompare(b.name, 'zh-CN'))
.map((row, i) => ({ ...row, rank: i + 1 }))
return { ...overview, dateFrom: date, dateTo: date, days: [date], daily: [overview.daily[index]],
total: overview.daily[index].total, carrierCount: ranking.length, ranking }
}
export const expressQuerySchema = z.object({ view: z.enum(['overview', 'regional', 'uncollected']).default('overview'), date: expressDate.optional(), origin: z.string().max(200).default('') })
export type ExpressQuery = z.infer<typeof expressQuerySchema>
export type RegionalDay = z.infer<typeof regionalDay>
export function expressRegionalPivot(day: RegionalDay, origin: string) {
const counts = new Map<string, number>()
const rows = day.provinces.map(province => ({ ...province, kind: 'province', counts: {} as Record<string, number>, total: 0 }))
for (const fact of day.rows) {
if (origin && fact.origin !== origin) continue
counts.set(fact.carrier, (counts.get(fact.carrier) ?? 0) + fact.count)
const row = rows.find(item => item.province === fact.province && item.region === fact.region)!
row.counts[fact.carrier] = (row.counts[fact.carrier] ?? 0) + fact.count; row.total += fact.count
}
const carriers = [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0], 'zh-CN')).map(([name]) => name)
const output: typeof rows = []
for (const region of day.regions) {
const items = rows.filter(row => row.region === region).sort((a, b) => a.provinceOrder - b.provinceOrder)
if (!items.length) continue
output.push(...items, { region, province: `${region}小计`, provinceOrder: 0, kind: 'subtotal', total: items.reduce((n, row) => n + row.total, 0), counts: Object.fromEntries(carriers.map(carrier => [carrier, items.reduce((n, row) => n + (row.counts[carrier] ?? 0), 0)])) })
}
const total = [...counts.values()].reduce((a, b) => a + b, 0)
output.push({ region: '', province: '总计', provinceOrder: 0, kind: 'total', total, counts: Object.fromEntries(counts) })
return { carriers, rows: output, total }
}
export type ExpressReadState = { latestDate: string; updatedAt: string; dates: string[]; canDownload: boolean; view: ExpressQuery['view'];
overview?: ExpressSnapshot['overview']; regional?: { date: string; origins: RegionalDay['origins']; origin: string; pivot: ReturnType<typeof expressRegionalPivot> }; uncollected?: ExpressSnapshot['uncollected'] }

View File

@ -0,0 +1,66 @@
import {
buildDailyExpressVolumeDashboard,
dailyExpressVolumeFiltersSchema,
expressVolumeDefaultRange,
type DailyExpressVolumeBucket,
} from './daily-express-volume'
import { getSupplyChainApiPermissionRequirement, getSupplyChainPermissionTargetForPath } from './supply-chain-permission-paths'
import { filterSupplyChainMenu, flattenSupplyChainMenu } from '@/app/supply-chain/config/supply-chain-menu'
const filters = { dateFrom: '2026-11-20', dateTo: '2026-11-22', warehouse: '', carrier: '' }
const buckets: DailyExpressVolumeBucket[] = [
{ date: '2026-11-20', carrier: '圆通', warehouse: '睢宁仓', volume: 12 },
{ date: '2026-11-20', carrier: '圆通', warehouse: '新苏北仓', volume: 8 },
{ date: '2026-11-22', carrier: '圆通', warehouse: '睢宁仓', volume: 10 },
{ date: '2026-11-22', carrier: '中通', warehouse: '新苏北仓', volume: 30 },
]
describe('每日快递承运量口径', () => {
it('使用北京时间生成跨月默认范围', () => {
expect(expressVolumeDefaultRange(7, new Date('2026-10-31T17:00:00Z'))).toEqual({ dateFrom: '2026-10-26', dateTo: '2026-11-01' })
})
it('拒绝无效日期、反向范围及超过 93 天的范围', () => {
for (const range of [
{ dateFrom: '2026-02-30', dateTo: '2026-03-03' },
{ dateFrom: '2026-11-23', dateTo: '2026-11-22' },
{ dateFrom: '2026-01-01', dateTo: '2026-04-04' },
]) expect(dailyExpressVolumeFiltersSchema.safeParse(range).success).toBe(false)
expect(dailyExpressVolumeFiltersSchema.safeParse({ dateFrom: '2026-01-01', dateTo: '2026-04-03' }).success).toBe(true)
})
it('补齐零发货日期并使趋势、快递排名和明细合计一致', () => {
const board = buildDailyExpressVolumeDashboard(buckets, filters, '2026-11-23T00:00:00Z')
expect(board.days.map((day) => day.volume)).toEqual([20, 0, 40])
expect(board.summary).toEqual({ total: 60, dailyAverage: 20, carrierCount: 2, peakDate: '2026-11-22', peakVolume: 40 })
expect(board.carriers.map((carrier) => carrier.volume)).toEqual([30, 30])
expect(board.carriers.reduce((sum, carrier) => sum + carrier.share, 0)).toBe(1)
expect(board.carriers.reduce((sum, carrier) => sum + Object.values(carrier.daily).reduce((a, b) => a + b, 0), 0)).toBe(board.summary.total)
})
it('精确联动仓库与快递筛选并保留完整筛选选项', () => {
const board = buildDailyExpressVolumeDashboard(buckets, { ...filters, warehouse: '新苏北仓', carrier: '圆通' }, '')
expect(board.summary.total).toBe(8)
expect(board.days.map((day) => day.volume)).toEqual([8, 0, 0])
expect(board.carriers[0].share).toBe(1)
expect(board.warehouses).toHaveLength(2)
expect(board.carrierOptions).toHaveLength(2)
})
it('空数据没有假峰值或无穷占比', () => {
const board = buildDailyExpressVolumeDashboard([], filters, '')
expect(board.summary).toEqual({ total: 0, dailyAverage: 0, carrierCount: 0, peakDate: null, peakVolume: 0 })
expect(board.carriers).toEqual([])
expect(board.days).toHaveLength(3)
})
it('页面、API 和菜单使用独立权限,其他权限不会暴露入口', () => {
const path = '/supply-chain/management/daily-express-volume'
expect(getSupplyChainPermissionTargetForPath(path)).toBe('dailyExpressVolume')
expect(getSupplyChainApiPermissionRequirement(`/api${path}`, 'GET')).toEqual({ targetKey: 'dailyExpressVolume', action: 'view' })
expect(flattenSupplyChainMenu(filterSupplyChainMenu(['dailyExpressVolume']))).toEqual([
expect.objectContaining({ route: path, label: '每日快递承运量看板', module: '经营管理' }),
])
expect(flattenSupplyChainMenu(filterSupplyChainMenu(['logisticsArrivalSigningDuration']))).not.toEqual(expect.arrayContaining([expect.objectContaining({ route: path })]))
})
})

View File

@ -0,0 +1,81 @@
import { z } from 'zod'
const DAY_MS = 86_400_000
export const DAILY_EXPRESS_VOLUME_MAX_DAYS = 93
export function expressVolumeToday(now = new Date()) {
return new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit' }).format(now)
}
export function expressVolumeDateOffset(date: string, days: number) {
return new Date(Date.parse(`${date}T00:00:00Z`) + days * DAY_MS).toISOString().slice(0, 10)
}
export function expressVolumeDefaultRange(days = 7, now = new Date()) {
const dateTo = expressVolumeToday(now)
return { dateFrom: expressVolumeDateOffset(dateTo, 1 - days), dateTo }
}
const dateSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, '日期格式应为 YYYY-MM-DD').refine((value) => {
const parsed = Date.parse(`${value}T00:00:00Z`)
return Number.isFinite(parsed) && new Date(parsed).toISOString().slice(0, 10) === value
}, '请选择有效日期')
export const dailyExpressVolumeFiltersSchema = z.object({
dateFrom: dateSchema,
dateTo: dateSchema,
warehouse: z.string().trim().max(200).default(''),
carrier: z.string().trim().max(200).default(''),
}).superRefine((value, ctx) => {
if (value.dateFrom > value.dateTo) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['dateTo'], message: '结束日期不能早于开始日期' })
}
if ((Date.parse(value.dateTo) - Date.parse(value.dateFrom)) / DAY_MS >= DAILY_EXPRESS_VOLUME_MAX_DAYS) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['dateTo'], message: `单次最多查询 ${DAILY_EXPRESS_VOLUME_MAX_DAYS} 天` })
}
})
export type DailyExpressVolumeFilters = z.infer<typeof dailyExpressVolumeFiltersSchema>
export type DailyExpressVolumeBucket = { date: string; carrier: string; warehouse: string; volume: number }
export type DailyExpressVolumeCarrier = { name: string; volume: number; share: number; daily: Record<string, number> }
export type DailyExpressVolumeDashboard = {
filters: DailyExpressVolumeFilters
dataAsOf: string
warehouses: string[]
carrierOptions: string[]
days: { date: string; volume: number }[]
carriers: DailyExpressVolumeCarrier[]
summary: { total: number; dailyAverage: number; carrierCount: number; peakDate: string | null; peakVolume: number }
}
/** Input is already deduplicated by the report query, before any warehouse/carrier filtering. */
export function buildDailyExpressVolumeDashboard(
buckets: DailyExpressVolumeBucket[],
filters: DailyExpressVolumeFilters,
dataAsOf: string,
): DailyExpressVolumeDashboard {
const dates: string[] = []
for (let date = filters.dateFrom; date <= filters.dateTo; date = expressVolumeDateOffset(date, 1)) dates.push(date)
const totals = new Map(dates.map((date) => [date, 0]))
const carriers = new Map<string, DailyExpressVolumeCarrier>()
const scoped = buckets.filter((row) => totals.has(row.date))
const warehouses = [...new Set(scoped.map((row) => row.warehouse))].sort((a, b) => a.localeCompare(b, 'zh-CN'))
const carrierOptions = [...new Set(scoped.map((row) => row.carrier))].sort((a, b) => a.localeCompare(b, 'zh-CN'))
for (const row of scoped) {
if ((filters.warehouse && row.warehouse !== filters.warehouse) || (filters.carrier && row.carrier !== filters.carrier)) continue
const carrier = carriers.get(row.carrier) ?? { name: row.carrier, volume: 0, share: 0, daily: {} }
carrier.volume += row.volume
carrier.daily[row.date] = (carrier.daily[row.date] ?? 0) + row.volume
carriers.set(row.carrier, carrier)
totals.set(row.date, totals.get(row.date)! + row.volume)
}
const days = dates.map((date) => ({ date, volume: totals.get(date)! }))
const total = days.reduce((sum, day) => sum + day.volume, 0)
const ranked = [...carriers.values()].sort((a, b) => b.volume - a.volume || a.name.localeCompare(b.name, 'zh-CN'))
for (const carrier of ranked) carrier.share = total ? carrier.volume / total : 0
const peak = days.reduce<{ date: string; volume: number } | null>((best, day) => day.volume > (best?.volume ?? 0) ? day : best, null)
return {
filters, dataAsOf, warehouses, carrierOptions, days, carriers: ranked,
summary: { total, dailyAverage: total / dates.length, carrierCount: ranked.length, peakDate: peak?.date ?? null, peakVolume: peak?.volume ?? 0 },
}
}

View File

@ -259,6 +259,9 @@ export type ModularProcessingOrderFilters = {
/** 部件明细排序。 */
componentSortKey?: string
componentSortDirection?: ModularProcessingSortDirection
/** 历史导出上下文:与页面当前生成日期和时段保持一致。 */
snapshotDate?: string
generationSlot?: string
}
export type ModularProcessingColumnFilter = {
@ -547,6 +550,11 @@ export type ModularProcessingComponentPage = {
ready: boolean
source: string
message: string | null
/** BATCH_SNAPSHOT 表示当前批次冻结数据;LIVE 表示旧批次回退实时数据。 */
dataMode?: 'BATCH_SNAPSHOT' | 'LIVE'
dataAsOf?: string | null
batchKey?: string
generationSlot?: string
}
}

View File

@ -103,10 +103,17 @@ export type ReissueRecord = {
feedbackContent?: string
feedbackAt?: string
feedbackBy?: string
supplierReasonRoot?: string
supplierReasonCategory?: string
supplierReasonOtherNote?: string
supplierSolution?: string
supplierExpectedSolveDate?: string
supplierRespondedAt?: string
reasonReviewStatus?: 'NOT_REQUIRED' | 'PENDING_FOLLOWUP' | 'COMPLETED'
followupFinalReasonCategory?: string
followupReasonNote?: string
reasonReviewedBy?: string
reasonReviewedAt?: string
followupRemindedAt?: string
sourceDetails?: {
shopSite: string

View File

@ -12,6 +12,10 @@ import { completeStandardCosts } from '../standard/cabinet-costs'
import { samplingDocumentHtml } from '../standard/cabinet-drawing'
import { matchCabinetMaterial, quotaHardware, quotaLabor,quotaConsumableOptions } from '../standard/cabinet-quota'
import { applyStandardRecognition } from '../standard/recognition'
import { isKnownStructureCorrection } from '../standard/bookshelf-learning'
import { sideProfile } from '../standard/cabinet-sampling-geometry'
import { recognizeStandardImage } from '@/app/reference-estimator/standard/recognize-image'
import { recordModelTurn } from '@/app/reference-estimator/standard/model-conversation-actions'
import JSZip from 'jszip'
import { parseReferenceImageEstimateResult } from '@/server/services/reference-image-estimate/reference-image-estimate-contracts'
import { buildReferenceImageEstimatePrompt } from '@/server/services/reference-image-estimate/reference-image-estimate-prompt'
@ -19,6 +23,74 @@ import fs from 'node:fs'
import path from 'node:path'
const input=()=>cabinetInputSchema.parse({referenceCase:'6G-960-B',name:'六格书柜',grade:'E1级',material:'生态板',topColor:'经典北美黑胡桃色',bodyColor:'荷花白色'})
const notchNote = '给 02、04 号旁板各在后下角开一个深 15、高 120 mm 的圆角缺口,贯穿板厚,09 不动。'
const ordinaryBookcase = (depth = 300) => applyStandardRecognition(newStandardDocument(),
parseReferenceImageEstimateResult(JSON.stringify({
recognition:{classification:{materialType:'板式',primaryCategory:'柜类',secondaryCategory:'书柜',placement:'落地'},
hasDoors:false,hasDrawers:false},
cabinet:{...input(),referenceCase:null,width:960,depth,height:725,columns:3,rows:2,thickness:15,
hasFrontKick:true,kickHeight:60,hasRearRail:false,hasBackPanel:false},
})))
describe('ordinary bookcase side notches', () => {
test('the model conversation cuts only 02 and 04, then keeps the cut after saving and rebuilding', async () => {
const before = ordinaryBookcase()
const model = before.standardTemplate!.cabinet!
const data = await recognizeStandardImage(before, notchNote)
const {next,turn} = recordModelTurn(before,notchNote,data,{rules:[],correctionNote:notchNote})
expect(turn.outcome).toBe('updated')
expect(turn.appliedChanges?.join(' ')).toContain('缺口有调整')
const updated = next.standardTemplate!.cabinet!
const notch = {depth:15,height:120,radius:15}
expect(updated.parts).toEqual(model.parts.map(part =>
['02','04'].includes(part.code) ? {...part,notch} : part))
expect(updated.parts.find(part=>part.code==='09')).toMatchObject({size:[930,15,60],notch:null})
expect(updated.connections).toEqual(model.connections)
expect(next.standardTemplate!.bookshelfMemory?.case).toBeUndefined()
const saved = estimateDocumentSchema.parse(JSON.parse(JSON.stringify(next)))
const rebuilt = applyCabinetWorkflow(saved,{...saved.standardTemplate!.cabinet!.input,bodyColor:'新花色'})
const side = rebuilt.standardTemplate!.cabinet!.parts.find(part=>part.code==='02')!
expect(side).toMatchObject({size:[15,300,710],notch,color:'新花色'})
expect(sideProfile(side.width,side.length,side.notch)).toEqual(
expect.arrayContaining([[285,0],[300,120]]))
})
test('a later single-side adjustment preserves the other side and applies other fields in the same turn', async () => {
const before = ordinaryBookcase(380)
const first = await recognizeStandardImage(before, notchNote)
const updated = applyStandardRecognition(before,first,{rules:[],correctionNote:notchNote})
const correctionNote = '02 号旁板后下角的圆角缺口调整为深 20、高 90 mm,R5,柜身改成白橡木色。'
expect(isKnownStructureCorrection(correctionNote)).toBe(false)
const data=parseReferenceImageEstimateResult(JSON.stringify({
recognition:{hasDoors:false,hasDrawers:false},
cabinetCorrection:{sideNotches:{'02':{depth:20,height:90,radius:5}},bodyColor:'白橡木色'},
}))
const next=applyStandardRecognition(updated,data,{rules:[],correctionNote})
const model=next.standardTemplate!.cabinet!
expect(model.parts.find(part=>part.code==='02')).toMatchObject({
width:380,color:'白橡木色',notch:{depth:20,height:90,radius:5},
})
expect(model.parts.find(part=>part.code==='04')?.notch).toEqual({depth:15,height:120,radius:15})
expect(next.standardTemplate!.bookshelfMemory?.case?.changes).not.toHaveProperty('sideNotches')
})
test('keeps original sample behavior and rejects edits to 09 or cuts larger than a side panel', async () => {
expect(buildCabinetModel(input()).parts.find(part=>part.code==='02')?.notch)
.toEqual({depth:15,height:120,radius:15})
const before = ordinaryBookcase()
expect(isKnownStructureCorrection(notchNote.replace('02、04','09'))).toBe(false)
expect(parseReferenceImageEstimateResult(JSON.stringify({boardPieces:[],cabinetCorrection:{
sideNotches:{'09':{depth:15,height:120}},
}})).cabinetCorrection).toBeUndefined()
const correctionNote=notchNote.replace('深 15','深 300')
const data=await recognizeStandardImage(before,correctionNote)
const {next,turn}=recordModelTurn(before,correctionNote,data,{rules:[],correctionNote})
expect(turn.outcome).toBe('failed')
expect(turn.reply).toContain('板件进深')
expect(next.standardTemplate!.cabinet).toBe(before.standardTemplate!.cabinet)
})
})
describe('cabinet standard v0.24 shared model workflow',()=>{
test('reproduces the supplied six-grid drawing without using the historical cabinet algorithm',()=>{
const m=buildCabinetModel(input())

View File

@ -2,6 +2,7 @@ import { z } from 'zod'
import type { SkillRecognition } from '../skill-routing'
import { cabinetInputSchema, slottedBookcaseBack, type CabinetInput } from './cabinet-contracts'
import { imageObservationSchema } from './cabinet-image-memory'
import { readSideNotchCommand } from './cabinet-side-notches'
export const bookshelfCategory = 'bookshelf' as const
export const bookcaseCategory = 'bookcase' as const
@ -34,6 +35,7 @@ export const cabinetCorrectionSchema = z.object({
screwCode:input.screwCode.removeDefault(), clipCode:input.clipCode.removeDefault(),
drillFeet:input.drillFeet.removeDefault(), packingLabor:input.packingLabor.removeDefault(),
hasFrontKick:input.hasFrontKick, hasRearRail:input.hasRearRail, bodyHeight:input.bodyHeight,
sideNotches:input.sideNotches,
backPanelCount:input.backPanelCount, backPanelSplit:input.backPanelSplit, hasUnplacedPullRail:input.hasUnplacedPullRail,
hasLegs:input.hasLegs, legHeight:input.legHeight, legCount:input.legCount, legShape:input.legShape, legPlacement:input.legPlacement,
legInsetX:input.legInsetX, legInsetY:input.legInsetY, legSize:input.legSize, rearPullRail:input.rearPullRail,
@ -148,6 +150,7 @@ const hasSlottedBackNote = (note:string) => simpleBackAssembly.test(note) ||
backAssemblyNote.test(note) && !/(?:不是|不加|不用|不要|去掉)/.test(note)
export function isKnownStructureCorrection(note:string) {
if(readSideNotchCommand(note))return true
const items=normalizedCorrections(note)
return items.length>0 && items.every(part=>addMissingLegs.test(part)||simpleBackAssembly.test(part)||addMissingBack.test(part))
}

View File

@ -3,6 +3,7 @@ import { cadCylinderSchema, cylinderFrame } from './cad-geometry'
import { cadOutputSchema, cadSolidSchema } from './cad-solid-contract'
import { cabinetSupportRuleSchema, cabinetSupportsSchema, supportShapeSchema, supportSizeSchema } from './cabinet-supports'
import { boardProfileSchema, boardRoleSchema, imageAssemblySchema } from './cabinet-image-contract'
import { sideNotchesSchema } from './cabinet-side-notches'
const mm=z.number().finite().positive().max(10000)
export const slottedBookcaseBack = '一块后拉板分隔两片槽装三合板' as const
@ -21,6 +22,7 @@ export const cabinetInputSchema=z.object({
width:mm.nullable().default(null),depth:mm.nullable().default(null),height:mm.nullable().default(null),
columns:z.number().int().min(1).max(12).nullable().default(null),rows:z.number().int().min(1).max(12).nullable().default(null),
hasFrontKick:z.boolean().nullish(),hasRearRail:z.boolean().nullish(),
sideNotches:sideNotchesSchema.optional(),
backPanelCount:z.number().int().min(1).max(12).nullish(),
backPanelSplit:z.enum(['上下', '左右']).nullish(),
hasUnplacedPullRail:z.boolean().nullish(),

View File

@ -4,6 +4,7 @@ import { matchCabinetMaterial } from './cabinet-quota'
import { selectedCabinetPartMaterial } from './cabinet-material-selection'
import { bookcaseEnvelope, bookcasePreviewParts } from './bookcase-preview'
import { buildImageCabinet } from './cabinet-image-model'
import { resolveSideNotch } from './cabinet-side-notches'
import type { EstimateDocument } from '../contracts'
export function resolveCabinetInput(raw:CabinetInput):CabinetInput {
@ -104,7 +105,8 @@ export function buildCabinetModel(raw:CabinetInput,materials?:Pick<EstimateDocum
if(!material)issues.push(`${name}没有匹配到完整规格报价(${p.grade} ${color} ${p.veneer} ${T}mm)。`)
else if(material.sheetWeightKg===null)issues.push(`${name}对应板材未提供大板重量。`)
const sample=p.referenceCase?rules.cases[p.referenceCase]:null
const notch=role==='side'&&sample?{height:sample.notchHeight,depth:sample.notchDepth,radius:sample.notchRadius}:null
const notch=role==='side' ? resolveSideNotch(p.sideNotches,code,B,L)
?? (sample?{height:sample.notchHeight,depth:sample.notchDepth,radius:sample.notchRadius}:null) : null
parts.push({id:'part-'+code,code,name,role,length:L,width:B,thickness:T,quantity:positions.length,size,
positions:lift?positions.map(([x,y,z])=>[x,y,z+lift]):positions,material,color,grooveMeters,notch})
}

View File

@ -0,0 +1,57 @@
import { z } from 'zod'
const mm = z.number().finite().positive().max(10000)
const sideNotchSchema = z.object({ depth: mm, height: mm, radius: mm.optional() }).strict()
.refine(value => value.radius == null || value.radius <= Math.min(value.depth, value.height), {
message: '圆角半径不能大于缺口的深度或高度。',
})
export const sideNotchesSchema = z.object({
'02': sideNotchSchema.optional(),
'04': sideNotchSchema.optional(),
}).strict().refine(value => Boolean(value['02'] || value['04']), { message: '请指定 02 或 04 号旁板。' })
type SideNotches = z.infer<typeof sideNotchesSchema>
export function resolveSideNotch(notches: SideNotches | undefined, code: string, depth: number, height: number) {
const notch = code === '02' || code === '04' ? notches?.[code] : undefined
if (!notch) return undefined
if (notch.depth >= depth || notch.height >= height) {
throw new Error(code + ' 号旁板的缺口深度和高度必须小于板件进深和高度。')
}
// Use the largest inside radius that fits when the user only specifies a rounded corner.
return { ...notch, radius: notch.radius ?? Math.min(notch.depth, notch.height) }
}
const target = String.raw`(?:02(?:号)?(?:左)?|04(?:号)?(?:右)?)(?:旁板|侧板)?`
const command = new RegExp(String.raw`^(?:请)?(?:给|将|把)?(?<targets>${target}(?:[、,/和及与]${target})?)(?:各|两块|分别)?,?(?:在)?(?:后下角|后底角)开(?:一个|一处)?(?<spec>.+)$`)
const length = String.raw`(-?\d+(?:\.\d+)?)(mm|cm|毫米|厘米)?`
const size = String.raw`深(?:度)?[::为]?${length}[、,,]?(?:高|高度)[::为]?${length}`
const cut = '(?:圆角)?(?:踢脚线)?缺口'
const suffix = String.raw`(?:[,、]?(?:做成)?圆角)?(?:[,、]?(?:圆角半径|内圆角|R)[::=为]?${length})?$`
const sizeFirst = new RegExp('^' + size + '(?:的)?' + cut + suffix, 'i')
const cutFirst = new RegExp('^' + cut + '[,::]?' + size + suffix, 'i')
const inMm = (amount: string, unit?: string) => Number(amount) * (/^(cm|厘米)$/i.test(unit ?? '') ? 10 : 1)
// Match a complete text instruction. Extra requests go through normal recognition.
export function readSideNotchCommand(note: string): SideNotches | undefined {
const text = note.normalize('NFKC').replace(/\s/g, '').replace(/[。;;]/g, ',')
.replace(/[,!]+$/, '')
.replace(/,(?:另外,?)?09(?:号)?(?:前)?(?:踢脚板|踢脚线)?(?:保持原样|不动|不改)$/, '')
.replace(/,(?:贯穿|贯通)(?:整个)?板厚$/, '')
const matched = command.exec(text)?.groups
if (!matched) return undefined
const sizeMatch = sizeFirst.exec(matched.spec) ?? cutFirst.exec(matched.spec)
if (!sizeMatch) return undefined
const [, depth, depthUnit, height, heightUnit, radius, radiusUnit] = sizeMatch
if (!matched.spec.includes('圆角') && radius == null) return undefined
const value = {
depth: inMm(depth, depthUnit ?? heightUnit),
height: inMm(height, heightUnit),
...(radius == null ? {} : { radius: inMm(radius, radiusUnit) }),
}
return {
...(matched.targets.includes('02') ? { '02': value } : {}),
...(matched.targets.includes('04') ? { '04': value } : {}),
}
}

View File

@ -19,6 +19,7 @@ import {
import type { CabinetInput } from './cabinet-contracts'
import { bookcaseEnvelope } from './bookcase-preview'
import { applyImageAssembly } from './cabinet-image-workflow'
import { readSideNotchCommand } from './cabinet-side-notches'
type RecognitionOptions = { rules: SharedBookshelfRule[]; correctionNote?: string; rulesUnavailable?: boolean }
@ -36,16 +37,29 @@ function applyRecognitionGeometry(document:EstimateDocument,result:ReferenceImag
options?:RecognitionOptions):EstimateDocument {
const prior=document.standardTemplate?.cabinet?.input
const correctionNote=options?.correctionNote
const ordinaryCorrection=correctionNote && prior && !prior.imageAssembly
const explicitNotches=ordinaryCorrection ? readSideNotchCommand(correctionNote) : undefined
const sideNotches=ordinaryCorrection ? explicitNotches ?? result.cabinetCorrection?.sideNotches : undefined
// An explicit text command also works when an earlier turn included attachments.
if(sideNotches && prior && (explicitNotches ||
Object.keys(result.cabinetCorrection??{}).every(key=>key==='sideNotches'))) {
const standard=document.standardTemplate!
const memory=standard.bookshelfMemory
return applyCabinetWorkflow({...document,standardTemplate:{...standard,
bookshelfMemory:memory?{...memory,case:undefined}:undefined}}, {
...prior,sideNotches:{...prior.sideNotches,...sideNotches},
})
}
if (result.draftIssue && prior && document.standardTemplate?.bookshelfMemory?.reviewedImageUrl === document.imageUrl) {
return document
}
if((prior?.imageAssembly && correctionNote) || (result.imageAssembly && !result.cabinet?.referenceCase)) {
if((prior?.imageAssembly && correctionNote) || (!sideNotches && result.imageAssembly && !result.cabinet?.referenceCase)) {
const next=applyImageAssembly(document,result,correctionNote)
if(next)return next
}
const explicit=explicitBookshelfCorrections(correctionNote??document.imageNote)
const changes:CabinetCorrection=Object.fromEntries(Object.entries({
...(correctionNote?result.cabinetCorrection:{}),...explicit,
...(correctionNote?result.cabinetCorrection:{}),...explicit,sideNotches,
}).filter(([,value])=>value!=null && value!==''))
if(changes.kickHeight === 0) changes.hasFrontKick=false
if(changes.railHeight === 0) changes.hasRearRail=false
@ -59,7 +73,8 @@ function applyRecognitionGeometry(document:EstimateDocument,result:ReferenceImag
const recognizedRoute=correctingPrior&&document.skillRouting?document.skillRouting:result.skillRouting
if(correctingPrior&&(result.skillRouting.hasDoors===true||result.skillRouting.hasDrawers===true))
throw new Error('门和抽屉的结构暂未接入,保留当前模型。')
const recognized={...base,...changes}
const recognized={...base,...changes,
...(sideNotches?{sideNotches:{...base.sideNotches,...sideNotches}}:{})}
if(recognized.hasLegs==null && (recognized.legSupports || recognized.legSupportRule))recognized.hasLegs=true
if(correctionNote && changes.hasLegs===true && recognized.legHeight==null && result.cabinet?.legHeight!=null
&& (recognized.bodyHeight==null || recognized.height===recognized.bodyHeight)) {
@ -144,12 +159,16 @@ function applyRecognitionGeometry(document:EstimateDocument,result:ReferenceImag
const model=next.standardTemplate!.cabinet!
const scope=learn?bookshelfScope(model.input):null
const appliedChanges=Object.fromEntries(Object.entries(changes)
.filter(([key,value])=>sameCorrectionValue(model.input[key as keyof CabinetInput],value)))
.filter(([key,value])=>key==='sideNotches'
? Object.entries(sideNotches??{}).every(([code,notch])=>
sameCorrectionValue(model.input.sideNotches?.[code as '02'|'04'],notch))
: sameCorrectionValue(model.input[key as keyof CabinetInput],value)))
if(correctionNote&&Object.keys(changes).length&&!Object.keys(appliedChanges).length)
throw new Error('补充内容与现有结构或所选板材不一致,请核对后重试。')
if(correctionNote&&memory&&scope&&Object.keys(appliedChanges).length){
const {sideNotches: _oneOff, ...learnableChanges}=appliedChanges
if(correctionNote&&memory&&scope&&Object.keys(learnableChanges).length){
next.standardTemplate!.bookshelfMemory={...memory,case:{
scope,changes:appliedChanges,autoPublish:automaticBookshelfRules(correctionNote,appliedChanges,scope),
scope,changes:learnableChanges,autoPublish:automaticBookshelfRules(correctionNote,learnableChanges,scope),
}}
}
if(correctionNote){

View File

@ -1,32 +1,113 @@
export const SUPPLIER_REASON_CATEGORIES = [
'安全环保检查/天灾人祸等',
'供应商自身问题:员工异动/产能异常/操作异常/搬厂等',
'赶货/转厂/改款/同款责任判定异常',
'原材料供应异常(质量/交期)',
'日销暴增/大单影响',
'快递异常(快递不到/快递爆仓/快递涨价/快递发货超时等)',
'无配件补发:停产或其他原因',
'供应商合作不稳定:新合作/合作边缘/不合作未变更状态/发货模式异常',
'供应商/特殊产品不执行违约金/赔偿',
'停产超卖',
'已录入快递换单/客服补发工单',
'手填单号/非简尚系统获取单号问题',
'获取单号失败',
'缺货叫货/缺货未叫货/叫货错误',
'放假/开工异常',
'已发出漏复核/已发出漏完结',
'核实问题/未及时反馈',
'测款/订单式产品未备货/未及时备货',
'配件/成品策略不匹配',
'信息同频不到位',
'产品资料错误',
export const SUPPLIER_REASON_CATEGORY_GROUPS = [
{
root: '非工厂原因',
description: '由供应商初判,提交后必须由对应跟单员完成最终二级原因确认',
categories: [
'非工厂原因-缺货未及时叫货/叫货错误',
'非工厂原因-订单式产品未备货/未及时备货',
'非工厂原因-停产超卖',
'非工厂原因-配件/成品策略不匹配',
'非工厂原因-无配件可补发(停产或其他原因)',
'非工厂原因-日销暴增/大单未锁库存',
'非工厂原因-铺货异常',
'非工厂原因-产品资料错误/超长超重需改资料或换快递',
'非工厂原因-重复制单/制单错误',
'非工厂原因-未获取到订单/无法打单/获取单号失败',
'非工厂原因-手填单号/非简尚系统获取单号',
'非工厂原因-超时未发已记账补发',
'非工厂原因-已录入快递换单/客服补发工单',
'非工厂原因-已发出漏复核/漏完结',
'非工厂原因-核实问题/未及时反馈',
'非工厂原因-其他(必填≥10字备注)',
],
},
{
root: '工厂原因',
description: '由工厂完整填写后直接进入供应商已反馈',
categories: [
'工厂原因-供应商自身问题:员工异动/产能异常/操作异常/搬厂等',
'工厂原因-原材料供应异常(质量/交期)',
'工厂原因-赶货/转厂/改款/同款责任判定异常',
'工厂原因-供应商合作不稳定:新合作或合作边缘或不合作未变更状态或发货慢',
'工厂原因-供应商/特殊产品不执行违约金/赔付',
],
},
{
root: '快递原因',
description: '由工厂完整填写后直接进入供应商已反馈',
categories: [
'快递原因-快递异常(快递不到/快递爆仓/快递涨价/快递发货超时等)',
'快递原因-丢件',
],
},
{
root: '买家原因',
description: '由工厂完整填写后直接进入供应商已反馈',
categories: [
'买家原因-拦截异常单',
],
},
{
root: '不可抗力',
description: '由工厂完整填写后直接进入供应商已反馈',
categories: [
'不可抗力-安全环保检查',
'不可抗力-天灾人祸',
'不可抗力-放假/开工异常',
],
},
] as const
export type SupplierReasonCategory = typeof SUPPLIER_REASON_CATEGORIES[number]
export const SUPPLIER_REASON_CATEGORIES = SUPPLIER_REASON_CATEGORY_GROUPS.flatMap(
(group) => group.categories,
)
export type SupplierReasonCategory =
typeof SUPPLIER_REASON_CATEGORY_GROUPS[number]['categories'][number]
export type SupplierReasonRoot =
typeof SUPPLIER_REASON_CATEGORY_GROUPS[number]['root']
export type SupplierReasonReviewStatus =
| 'NOT_REQUIRED'
| 'PENDING_FOLLOWUP'
| 'COMPLETED'
const REASON_CATEGORY_SET = new Set<string>(SUPPLIER_REASON_CATEGORIES)
export function isSupplierReasonCategory(value: string): value is SupplierReasonCategory {
return REASON_CATEGORY_SET.has(value)
}
export function supplierReasonRootForCategory(value: string): SupplierReasonRoot | null {
const group = SUPPLIER_REASON_CATEGORY_GROUPS.find((candidate) =>
(candidate.categories as readonly string[]).includes(value),
)
return group?.root || null
}
export function supplierReasonCategoriesForRoot(
root: string,
): readonly SupplierReasonCategory[] {
return SUPPLIER_REASON_CATEGORY_GROUPS.find((group) => group.root === root)?.categories || []
}
export function requiresFollowupReasonReview(value: string) {
return supplierReasonRootForCategory(value) === '非工厂原因'
}
export function requiresReasonOtherNote(value: string) {
return value === '非工厂原因-其他(必填≥10字备注)'
}
export function supplierReasonDetail(value: string) {
const root = supplierReasonRootForCategory(value)
return root && value.startsWith(`${root}-`) ? value.slice(root.length + 1) : value
}
export type SupplierReissueResponseInput = {
recordId: string
reasonRoot: SupplierReasonRoot
reasonCategory: SupplierReasonCategory
reasonOtherNote?: string
solution: string
expectedSolveDate: string
}
@ -38,7 +119,11 @@ export type SupplierReissueOrder = {
details: string
quantity: string
overtimeType: string
reasonRoot: string
reasonCategory: string
reasonOtherNote: string
reasonReviewStatus: SupplierReasonReviewStatus
finalReasonCategory: string
solution: string
expectedSolveDate: string
respondedAt: string
@ -48,5 +133,18 @@ export type SupplierReissuePublicPage = {
supplier: string
expiresAt: string
orders: SupplierReissueOrder[]
reasonGroups: typeof SUPPLIER_REASON_CATEGORY_GROUPS
reasonCategories: readonly string[]
}
export type SupplierReissueSubmission = {
page: SupplierReissuePublicPage
pendingReasonReviewRecordIds: string[]
}
export type SupplierReasonReviewInput = {
recordId: string
finalReasonCategory: SupplierReasonCategory
reasonNote?: string
feedbackContent?: string
}

View File

@ -14,8 +14,7 @@ describe('independent supply-chain page permissions', () => {
])
it('gives every menu page its own target, route mapping and permission row', () => {
// 跟单交接视图已从菜单下线,其旧路径由页面重定向到订单总览。
expect(pages).toHaveLength(41)
expect(pages.length).toBeGreaterThan(0)
expect(new Set(pages.map((page) => page.targetKey)).size).toBe(pages.length)
const matrixRows = PERMISSION_MATRIX_SECTIONS.find((section) => section.id === 'supply')!.groups.flatMap((group) => group.rows)
for (const page of pages) {
@ -34,6 +33,23 @@ describe('independent supply-chain page permissions', () => {
}
})
it('gives daily express volume its own menu, API and permission grant', () => {
expect(pages).toContainEqual({
label: '每日快递承运量看板',
route: '/supply-chain/management/daily-express-volume',
targetKey: 'dailyExpressVolume',
})
expect(getSupplyChainApiPermissionRequirement(
'/api/supply-chain/management/daily-express-volume',
'GET',
)).toEqual({ targetKey: 'dailyExpressVolume', action: 'view' })
expect(resolveSupplyChainPermissionAccess(
{ 'logisticsArrivalSigningDuration:purchase:view': true },
'dailyExpressVolume',
['purchase'],
)).toEqual({ view: false, download: false, edit: false })
})
it('keeps the remaining supplier collaboration and follow-up menus independent', () => {
const expected = {
'供应商评估': 'purchaseSupplierEvaluation',

View File

@ -33,6 +33,7 @@ export function getSupplyChainPermissionTargetForPath(pathname: string): SupplyC
if (pathname === '/supply-chain/management/blank-pages/blank-page-8') return 'managementBlankPage8' as const
if (pathname === '/supply-chain/management/employee-hours') return 'employeeHours' as const
if (pathname === '/supply-chain/management/logistics-arrival-signing-duration') return 'logisticsArrivalSigningDuration' as const
if (pathname === '/supply-chain/management/daily-express-volume') return 'dailyExpressVolume' as const
if (pathname === '/supply-chain/management/order-not-dispatched') return 'orderNotDispatched' as const
if (pathname === '/supply-chain/management/production-stop-demands') return 'productionStopDemands' as const
if (
@ -75,10 +76,8 @@ export function getSupplyChainApiPermissionRequirement(pathname: string, method:
if (pathname === '/api/supply-chain/product-archive/field-permissions') return null
const action = method.toUpperCase() === 'GET' ? 'view' : 'edit'
// 品牌升级审核:页面/接口跟随商品SABC打标节点(默认开放),具体审批权限在服务内校验
if (pathname.startsWith('/api/supply-chain/brand-upgrade-approvals')) {
return { targetKey: 'productSabc' as const, action }
}
// 品牌升级审核:不走页面级权限网关,路由内按「审核节点 / 配置审批人 / 管理员」分别校验
if (pathname.startsWith('/api/supply-chain/brand-upgrade-approvals')) return null
if (pathname.startsWith('/api/supply-chain/purchase/followup-delivery-control')) {
return { targetKey: 'purchaseFollowupOverview' as const, action }
}
@ -154,6 +153,9 @@ export function getSupplyChainApiPermissionRequirement(pathname: string, method:
}
return undefined
}
if (pathname === '/api/supply-chain/management/daily-express-volume' || pathname.startsWith('/api/supply-chain/management/daily-express-volume/')) {
return { targetKey: 'dailyExpressVolume' as const, action }
}
if (pathname.startsWith('/api/supply-chain/management/logistics-arrival-signing-duration')) {
if (pathname.endsWith('/export')) {
// 导出独立校验下载权限。

View File

@ -454,6 +454,9 @@ export function getSupplyChainTargetRoleDefaultAccess(
if (targetKey === 'clearanceReview' && resolveSupplyChainPermissionSubjectKeys(user).includes('management')) {
return { view: true, download: false, edit: true }
}
if (targetKey === 'brandUpgradeApproval' && resolveSupplyChainPermissionSubjectKeys(user).includes('management')) {
return { view: true, download: false, edit: true }
}
return null
}

View File

@ -130,6 +130,7 @@ export type SupplyChainPermissionTargetKey =
| 'productionStopFlowOwnerConfigEdit'
| 'productionStopFlowOwnerConfigDelete'
| 'logisticsArrivalSigningDuration'
| 'dailyExpressVolume'
| 'orderNotDispatched'
| 'shortageOrderDetails'
| 'managementBlankPage1'
@ -171,6 +172,8 @@ export type SupplyChainPermissionTargetKey =
| 'clearanceOperation'
| 'clearanceReview'
| 'productSabc'
// 商品SABC打标「品牌升级审核」(经管/管理员/运营总监,默认关闭,后台配置)
| 'brandUpgradeApproval'
| 'productSelection'
// 模块权限:商品SABC打标「各部门数据分类」(可见/下载分开控制)
| 'departmentDistribution'
@ -273,6 +276,7 @@ export const SUPPLY_CHAIN_PERMISSION_TARGETS: SupplyChainPermissionTarget[] = [
{ key: 'productStopWarehouseMappingImport', label: '仓库映射导入', description: '导入仓库映射' },
{ key: 'productStopWarehouseMappingExport', label: '仓库映射导出', description: '导出仓库映射' },
{ key: 'logisticsArrivalSigningDuration', label: '物流到货签收时长看板', description: '物流签收查询与明细导出' },
{ key: 'dailyExpressVolume', label: '每日快递承运量看板', description: '按发货日期查看每日运单量、快递占比与仓库分布' },
{ key: 'orderNotDispatched', label: '应发未发', description: '查看应发未发订单、超时原因、处理人与原始订单明细' },
{ key: 'shortageOrderDetails', label: '缺货订单明细', description: '缺货订单、库存与替换款核对及明细导出' },
{ key: 'managementBlankPage1', label: '空白页 1', description: '经营管理空白页 1' },
@ -308,6 +312,7 @@ export const SUPPLY_CHAIN_PERMISSION_TARGETS: SupplyChainPermissionTarget[] = [
{ key: 'productSabcCalculation', label: '商品SABC打标 · 执行核算', description: '每月核算与重新生成商品SABC打标数据(页面内按钮)' },
{ key: 'departmentDistribution', label: '商品SABC打标 · 各部门数据分类', description: '按利润中心汇总的部门数据(可见、下载分别控制)' },
{ key: 'productSabc', label: '商品SABC打标 · 商品明细', description: '商品SABC打标明细页与明细导出(默认全员开放,可在用户管理后台关闭)' },
{ key: 'brandUpgradeApproval', label: '商品SABC打标 · 品牌升级审核', description: '品牌升级审核单查看与审批(默认仅经管、管理员、运营总监,可在用户管理后台配置)' },
{ key: 'productSelection', label: '选品明细', description: '选品明细查看与 Excel 导出(默认全员开放,可在用户管理后台关闭)' },
{ key: 'departmentDistributionConfig', label: '商品SABC打标 · 部门数据配置', description: '维护品牌范围、负责人兜底与目标参数(操作列控制)' },
]
@ -320,6 +325,7 @@ export const SUPPLY_CHAIN_PERMISSION_TARGETS: SupplyChainPermissionTarget[] = [
export const SUPPLY_CHAIN_PERMISSION_EXTRA_TARGETS: Record<string, SupplyChainPermissionTargetKey[]> = {
management: [
'productSabcCalculation',
'brandUpgradeApproval',
'departmentDistribution',
'departmentDistributionConfig',
// 限价管理 · 规则配置(页面内的动作权限,只出现在权限配置里)
@ -416,6 +422,7 @@ export const SUPPLY_CHAIN_PERMISSION_TARGET_ROUTES: Partial<
productionStopDemands: '/supply-chain/management/production-stop-demands',
productInventoryStop: '/supply-chain/management/product-inventory-stop',
logisticsArrivalSigningDuration: '/supply-chain/management/logistics-arrival-signing-duration',
dailyExpressVolume: '/supply-chain/management/daily-express-volume',
orderNotDispatched: '/supply-chain/management/order-not-dispatched',
shortageOrderDetails: '/supply-chain/management/shortage-order-details',
managementBlankPage1: '/supply-chain/management/blank-pages/blank-page-1',

View File

@ -0,0 +1,25 @@
import fs from 'node:fs/promises'
import path from 'node:path'
import { createHash } from 'node:crypto'
import { expressSnapshotSchema } from '@/lib/daily-express-snapshot'
import { AppError, ErrorCode } from '@/server/core/errors'
type Pointer = { generation: string; reportHash: string; detailsHash: string }
export class DailyExpressVolumeRepository {
constructor(private readonly directory = process.env.DAILY_EXPRESS_DATA_DIR || path.join(process.cwd(), '.daily-express')) {}
async readLatest() {
let pointer: Pointer
try { pointer = JSON.parse(await fs.readFile(path.join(this.directory, 'latest.json'), 'utf8')) }
catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') throw new AppError(ErrorCode.RESOURCE_NOT_FOUND, '尚无已成功更新的快递看板数据'); throw error }
if (!/^\d+-[a-f0-9-]+$/.test(pointer.generation)) throw new Error('INVALID_EXPRESS_GENERATION')
const bytes = await fs.readFile(path.join(this.directory, 'generations', pointer.generation, 'report.json'))
if (createHash('sha256').update(bytes).digest('hex') !== pointer.reportHash) throw new Error('EXPRESS_SNAPSHOT_CORRUPTED')
return { pointer, report: expressSnapshotSchema.parse(JSON.parse(bytes.toString('utf8'))) }
}
async readDetails(pointer: Pointer): Promise<Record<string, string>[]> {
if (!/^\d+-[a-f0-9-]+$/.test(pointer.generation)) throw new Error('INVALID_EXPRESS_GENERATION')
const bytes = await fs.readFile(path.join(this.directory, 'generations', pointer.generation, 'details.json'))
if (createHash('sha256').update(bytes).digest('hex') !== pointer.detailsHash) throw new Error('EXPRESS_DETAILS_CORRUPTED')
return JSON.parse(bytes.toString('utf8'))
}
}
export const dailyExpressVolumeRepository = new DailyExpressVolumeRepository()

View File

@ -3,18 +3,30 @@ const mockFindFirst = jest.fn()
const mockFindMany = jest.fn()
const mockDeleteMany = jest.fn()
const mockCreateMany = jest.fn()
const mockComponentDeleteMany = jest.fn()
const mockComponentCreateMany = jest.fn()
const mockComponentFindMany = jest.fn()
const mockComponentCount = jest.fn()
const mockTransaction = jest.fn(async (
callback: (tx: {
modularProcessingOrderDailySnapshot: {
deleteMany: typeof mockDeleteMany
createMany: typeof mockCreateMany
}
modularProcessingComponentDailySnapshot: {
deleteMany: typeof mockComponentDeleteMany
createMany: typeof mockComponentCreateMany
}
}) => unknown,
) => callback({
modularProcessingOrderDailySnapshot: {
deleteMany: mockDeleteMany,
createMany: mockCreateMany,
},
modularProcessingComponentDailySnapshot: {
deleteMany: mockComponentDeleteMany,
createMany: mockComponentCreateMany,
},
}))
jest.mock('@/lib/prisma', () => ({
@ -25,6 +37,10 @@ jest.mock('@/lib/prisma', () => ({
findFirst: (...args: unknown[]) => mockFindFirst(...args),
findMany: (...args: unknown[]) => mockFindMany(...args),
},
modularProcessingComponentDailySnapshot: {
findMany: (...args: unknown[]) => mockComponentFindMany(...args),
count: (...args: unknown[]) => mockComponentCount(...args),
},
},
}))
@ -47,6 +63,8 @@ describe('ModularProcessingSnapshotRepositoryClass', () => {
rowJson: { finalSellable: '' },
},
])
mockComponentFindMany.mockResolvedValue([])
mockComponentCount.mockResolvedValue(0)
})
it('reads finalSellable from the latest daily snapshot by barcode', async () => {
@ -84,6 +102,12 @@ describe('ModularProcessingSnapshotRepositoryClass', () => {
barcode: 'BARCODE-1',
rowJson: { id: 'archive-1', barcode: 'BARCODE-1' },
}],
componentRows: [{
recordKey: 'BARCODE-1:PART-1:0',
parentBarcode: 'BARCODE-1',
componentBarcode: 'PART-1',
rowJson: { id: 'BARCODE-1:PART-1:0', parentBarcode: 'BARCODE-1' },
}],
})
expect(mockDeleteMany).toHaveBeenCalledWith({
@ -97,5 +121,48 @@ describe('ModularProcessingSnapshotRepositoryClass', () => {
generatedAt,
})],
})
expect(mockComponentDeleteMany).toHaveBeenCalledWith({
where: { batchKey: '2026-11-19:15:00' },
})
expect(mockComponentCreateMany).toHaveBeenCalledWith({
data: [expect.objectContaining({
snapshotDate: '2026-11-19',
batchKey: '2026-11-19:15:00',
generationSlot: '15:00',
parentBarcode: 'BARCODE-1',
componentBarcode: 'PART-1',
})],
})
})
it('loads frozen component rows for the selected batch', async () => {
mockFindFirst.mockResolvedValue({
snapshotDate: '2026-11-19',
batchKey: '2026-11-19:15:00',
generationSlot: '15:00',
generatedAt: new Date('2026-11-19T07:00:00.000Z'),
})
mockComponentFindMany.mockResolvedValue([{
recordKey: 'BARCODE-1:PART-1:0',
parentBarcode: 'BARCODE-1',
componentBarcode: 'PART-1',
rowJson: { jianshangStock: 34 },
generatedAt: new Date('2026-11-19T07:00:00.000Z'),
}])
mockComponentCount.mockResolvedValue(1)
const repository = new ModularProcessingSnapshotRepositoryClass()
const result = await repository.loadComponentSnapshot({
snapshotDate: '2026-11-19',
generationSlot: '15:00',
parentBarcode: 'BARCODE-1',
})
expect(result).toMatchObject({
batchKey: '2026-11-19:15:00',
generationSlot: '15:00',
snapshotAvailable: true,
})
expect(result.rows[0]?.rowJson).toEqual({ jianshangStock: 34 })
})
})

View File

@ -13,6 +13,20 @@ export type ModularProcessingSnapshotReadRow = {
rowJson: Record<string, unknown>
}
export type ModularProcessingComponentSnapshotWriteRow = {
recordKey: string
parentBarcode: string
componentBarcode: string
rowJson: Record<string, unknown>
}
export type ModularProcessingComponentSnapshotReadRow = {
recordKey: string
parentBarcode: string
componentBarcode: string
rowJson: Record<string, unknown>
}
export type ModularProcessingSnapshotBatch = {
snapshotDate: string
batchKey: string
@ -26,6 +40,7 @@ export interface ModularProcessingSnapshotRepository {
batchKey: string
generationSlot: string
rows: ModularProcessingSnapshotWriteRow[]
componentRows: ModularProcessingComponentSnapshotWriteRow[]
generatedAt: Date
}): Promise<void>
loadDailySnapshot(input: {
@ -37,6 +52,17 @@ export interface ModularProcessingSnapshotRepository {
batchKey: string
generationSlot: string
}>
loadComponentSnapshot(input: {
snapshotDate: string
generationSlot?: string
parentBarcode?: string
}): Promise<{
rows: ModularProcessingComponentSnapshotReadRow[]
generatedAt: Date | null
batchKey: string
generationSlot: string
snapshotAvailable: boolean
}>
latestSnapshotForDate(snapshotDate: string): Promise<ModularProcessingSnapshotBatch | null>
latestSnapshotForBatch(batchKey: string): Promise<Date | null>
listSnapshotBatches(snapshotDate: string): Promise<ModularProcessingSnapshotBatch[]>
@ -69,6 +95,7 @@ export class ModularProcessingSnapshotRepositoryClass implements ModularProcessi
batchKey: string
generationSlot: string
rows: ModularProcessingSnapshotWriteRow[]
componentRows: ModularProcessingComponentSnapshotWriteRow[]
generatedAt: Date
}) {
await prisma.$transaction(async (tx) => {
@ -88,6 +115,25 @@ export class ModularProcessingSnapshotRepositoryClass implements ModularProcessi
})),
})
}
await tx.modularProcessingComponentDailySnapshot.deleteMany({
where: { batchKey: input.batchKey },
})
for (let start = 0; start < input.componentRows.length; start += CREATE_BATCH_SIZE) {
await tx.modularProcessingComponentDailySnapshot.createMany({
data: input.componentRows
.slice(start, start + CREATE_BATCH_SIZE)
.map((row) => ({
snapshotDate: input.snapshotDate,
batchKey: input.batchKey,
generationSlot: input.generationSlot,
parentBarcode: row.parentBarcode,
componentBarcode: row.componentBarcode,
recordKey: row.recordKey,
rowJson: row.rowJson as Prisma.InputJsonValue,
generatedAt: input.generatedAt,
})),
})
}
})
this.finalSellableCache = null
}
@ -122,6 +168,54 @@ export class ModularProcessingSnapshotRepositoryClass implements ModularProcessi
}
}
async loadComponentSnapshot(input: {
snapshotDate: string
generationSlot?: string
parentBarcode?: string
}) {
const batch = await this.resolveSnapshotBatch(input)
if (!batch) {
return {
rows: [],
generatedAt: null,
batchKey: '',
generationSlot: input.generationSlot ?? '',
snapshotAvailable: false,
}
}
const [rows, componentSnapshotCount] = await Promise.all([
prisma.modularProcessingComponentDailySnapshot.findMany({
where: {
batchKey: batch.batchKey,
...(input.parentBarcode ? { parentBarcode: input.parentBarcode } : {}),
},
select: {
recordKey: true,
parentBarcode: true,
componentBarcode: true,
rowJson: true,
generatedAt: true,
},
orderBy: { recordKey: 'asc' },
}),
prisma.modularProcessingComponentDailySnapshot.count({
where: { batchKey: batch.batchKey },
}),
])
return {
rows: rows.map((row) => ({
recordKey: row.recordKey,
parentBarcode: row.parentBarcode,
componentBarcode: row.componentBarcode,
rowJson: row.rowJson as Record<string, unknown>,
})),
generatedAt: rows[0]?.generatedAt ?? batch.generatedAt,
batchKey: batch.batchKey,
generationSlot: batch.generationSlot,
snapshotAvailable: componentSnapshotCount > 0,
}
}
async latestSnapshotForDate(snapshotDate: string) {
const row = await prisma.modularProcessingOrderDailySnapshot.findFirst({
where: { snapshotDate },

View File

@ -0,0 +1,91 @@
/** @jest-environment node */
import ExcelJS from 'exceljs'
import { DailyExpressVolumeService } from '../daily-express-volume.service'
import { dailyExpressVolumeRepository } from '@/server/repositories/daily-express-volume.repository'
import { supplyChainPermissionSettingsService } from '../supply-chain-permission-settings.service'
import { expressFixture } from '@/lib/daily-express-fixture'
import { expressSnapshotSchema } from '@/lib/daily-express-snapshot'
import type { AuthUser } from '@/server/core/types'
jest.mock('@/server/repositories/daily-express-volume.repository', () => ({ dailyExpressVolumeRepository: { readLatest: jest.fn(), readDetails: jest.fn() } }))
jest.mock('../supply-chain-permission-settings.service', () => ({ supplyChainPermissionSettingsService: { getUserAccess: jest.fn() } }))
const access = jest.mocked(supplyChainPermissionSettingsService.getUserAccess), read = jest.mocked(dailyExpressVolumeRepository.readLatest)
const service = new DailyExpressVolumeService(), user = { id: 'test', role: 'USER' } as AuthUser
beforeEach(() => { jest.clearAllMocks(); access.mockResolvedValue({ view: true, edit: false, download: false }); read.mockResolvedValue({ report: expressFixture(), pointer: { generation: '1-test', reportHash: '', detailsHash: '' } }) })
it('checks viewing and export grants before reading any snapshot', async () => {
access.mockResolvedValue({ view: false, edit: false, download: false })
await expect(service.getDashboard({}, user)).rejects.toThrow('没有该看板')
access.mockResolvedValue({ view: true, edit: false, download: false })
await expect(service.export({}, user)).rejects.toThrow('没有该看板'); expect(read).not.toHaveBeenCalled()
})
it('returns the published latest date, no percentages or exclusions, and applies regional origin filtering', async () => {
const overview = await service.getDashboard({}, user)
expect(overview.latestDate).toBe('2026-11-24'); expect(overview.overview?.total).toBe(2); expect(JSON.stringify(overview)).not.toMatch(/share|excluded/)
const regional = await service.getDashboard({ view: 'regional', origin: '常州自有仓' }, user)
expect(regional.regional?.pivot.total).toBe(2)
await expect(service.getDashboard({ view: 'regional', date: '2026-11-01' }, user)).rejects.toThrow('没有已更新数据')
})
it('rejects invalid input and never converts a snapshot error into zero data', async () => {
await expect(service.getDashboard({ view: 'invalid' }, user)).rejects.toThrow('无效')
read.mockRejectedValue(new Error('checksum failed'))
await expect(service.getDashboard({}, user)).rejects.toThrow('checksum failed')
})
it('exports the same pickup rows and preserves long tracking numbers as text', async () => {
access.mockResolvedValue({ view: true, download: true, edit: false })
const file = await service.export({ view: 'uncollected' }, user)
const book = new ExcelJS.Workbook(); await book.xlsx.load(file.bytes as never)
expect(book.worksheets[0].getCell('A2').value).toBe('0012345678901234567890')
expect(file.filename).toContain('2026-11-24')
})
it('accepts and exports all 30 days with totals, and rejects a 31-day snapshot', async () => {
const report = expressFixture()
const days = Array.from({ length: 30 }, (_, i) => new Date(Date.UTC(2026, 10, 24 + i)).toISOString().slice(0, 10))
report.dateTo = days[29]
report.overview = { dateFrom: days[0], dateTo: days[29], days, total: 60, carrierCount: 1,
daily: days.map(date => ({ date, total: 2 })), ranking: [{ name: '测试快递', daily: days.map(() => 2), total: 60, rank: 1 }] }
expect(expressSnapshotSchema.safeParse(report).success).toBe(true)
const tooLong = structuredClone(report); tooLong.overview.days.push('2026-12-24')
expect(expressSnapshotSchema.safeParse(tooLong).success).toBe(false)
read.mockResolvedValue({ report, pointer: { generation: '1-test', reportHash: '', detailsHash: '' } })
access.mockResolvedValue({ view: true, download: true, edit: false })
jest.mocked(dailyExpressVolumeRepository.readDetails).mockResolvedValue([])
const data = await service.getDashboard({ view: 'overview' }, user)
expect(data.overview?.days).toHaveLength(30); expect(data.overview?.total).toBe(60)
const exported = await service.export({ view: 'overview' }, user)
const book = new ExcelJS.Workbook(); await book.xlsx.load(exported.bytes as never)
const sheet = book.getWorksheet('各快递30日承运量')!
expect(exported.filename).toBe('各快递30日承运量_2026-12-23.xlsx')
expect(sheet.columnCount).toBe(32); expect(sheet.getCell('B1').value).toBe(days[0]); expect(sheet.getCell('AE1').value).toBe(days[29]); expect(sheet.getCell('AF3').value).toBe(60)
})
it('filters one day consistently across totals, ranking and export, preserving all date choices', async () => {
const report = expressFixture()
report.overview = { dateFrom: '2026-11-23', dateTo: '2026-11-24', days: ['2026-11-23', '2026-11-24'], total: 5, carrierCount: 2,
daily: [{ date: '2026-11-23', total: 3 }, { date: '2026-11-24', total: 2 }],
ranking: [{ name: '甲快递', daily: [3, 0], total: 3, rank: 1 }, { name: '乙快递', daily: [0, 2], total: 2, rank: 2 }] }
read.mockResolvedValue({ report, pointer: { generation: '1-test', reportHash: '', detailsHash: '' } })
const full = await service.getDashboard({ view: 'overview' }, user)
expect(full.overview?.days).toHaveLength(2)
const filtered = await service.getDashboard({ view: 'overview', date: '2026-11-24' }, user)
expect(filtered.dates).toEqual(['2026-11-23', '2026-11-24'])
expect(filtered.overview).toMatchObject({ days: ['2026-11-24'], total: 2, carrierCount: 1,
ranking: [{ name: '乙快递', daily: [2], total: 2, rank: 1 }] })
access.mockResolvedValue({ view: true, download: true, edit: false })
jest.mocked(dailyExpressVolumeRepository.readDetails).mockResolvedValue([
{ o_id: 'old', send_date: '2026-11-23 12:00:00' }, { o_id: '001', l_id: '000123', send_date: '2026-11-24 23:59:59' },
])
const file = await service.export({ view: 'overview', date: '2026-11-24' }, user)
const book = new ExcelJS.Workbook(); await book.xlsx.load(file.bytes as never)
expect(file.filename).toBe('各快递承运量_2026-11-24.xlsx')
expect(book.worksheets[0].getRow(1).values).toEqual([, '快递名称', '2026-11-24', '合计'])
expect(book.worksheets[0].getCell('A3').value).toBe('乙快递')
expect(book.worksheets[1].rowCount).toBe(2); expect(book.worksheets[1].getCell('A2').value).toBe('001')
expect(book.worksheets[1].getCell('D2').value).toBe('000123')
await expect(service.getDashboard({ view: 'overview', date: '2026-11-22' }, user)).rejects.toThrow('没有已更新数据')
await expect(service.export({ view: 'overview', date: '2026-11-22' }, user)).rejects.toThrow('没有已更新数据')
})
it('keeps an available zero-volume day selectable instead of returning other dates', async () => {
const report = expressFixture()
report.overview.days.push('2026-11-25'); report.overview.daily.push({ date: '2026-11-25', total: 0 })
report.overview.ranking[0].daily.push(0)
read.mockResolvedValue({ report, pointer: { generation: '1-test', reportHash: '', detailsHash: '' } })
expect((await service.getDashboard({ view: 'overview', date: '2026-11-25' }, user)).overview).toMatchObject({ days: ['2026-11-25'], total: 0, carrierCount: 0, ranking: [] })
})

View File

@ -2,6 +2,7 @@ import {
buildTaskReviewRows,
calculateClearanceReviewFinancials,
clearanceProgressKey,
effectiveTaskClearedQty,
latestTaskPerBarcode,
latestTaskPerBarcodeProfitCenter,
type ClearanceProgressSnapshot,
@ -37,6 +38,18 @@ function task(overrides: Partial<ClearanceReviewTask> = {}): ClearanceReviewTask
}
describe('supply-chain clearance review builder', () => {
it('does not use cached shipments before the clearance period starts', () => {
expect(effectiveTaskClearedQty(
task({ clearedQty: 22 }),
{
hasCoverage: false,
periodStarted: false,
through: null,
byBarcode: new Map(),
},
)).toBe(0)
})
it('keeps only the latest approved round for each barcode', () => {
const result = latestTaskPerBarcode([
task(),

View File

@ -73,6 +73,13 @@ function repository() {
{ operationOwner: '运营G', profitCenter: '运营中心G' },
]),
latestTaskRound: jest.fn().mockResolvedValue(1),
findApplicationWindow: jest.fn().mockResolvedValue({
periodKey: '2026-11',
round: 1,
startAt: new Date('2026-11-01T00:00:00.000Z'),
endAt: new Date('2026-11-30T23:59:59.000Z'),
status: 'CONFIRMED',
}),
findReviewArchive: jest.fn().mockResolvedValue(null),
writeTasksWithEvents: jest.fn().mockResolvedValue([]),
}
@ -92,6 +99,24 @@ describe('SupplyChainClearanceTaskImportService', () => {
expect(repo.writeTasksWithEvents).not.toHaveBeenCalled()
})
it('rejects operator imports outside the selected period application window', async () => {
const repo = repository()
repo.findApplicationWindow.mockResolvedValue(null)
const service = new SupplyChainClearanceTaskImportService(
repo as never,
() => new Date('2026-11-11T00:00:00.000Z'),
)
await expect(service.importTasks({
periodKey: '2026-11',
user,
buffer: await workbookBuffer([
['SKU-A', '铁心兰', 100, '', ''],
]),
})).rejects.toThrow('当前不在 2026-11 第 1 期清货任务申报窗口内')
expect(repo.writeTasksWithEvents).not.toHaveBeenCalled()
})
it('imports pending tasks, clamps to Jianshang stock and updates existing tasks', async () => {
const repo = repository()
const service = new SupplyChainClearanceTaskImportService(
@ -212,6 +237,41 @@ describe('SupplyChainClearanceTaskImportService', () => {
])
})
it('rejects duplicate component tasks caused by importing a combo and its component together', async () => {
const comboCode = 'ZH-BG006401AN1242V01-1-BG006401BN1242V01-1'
const repo = repository()
repo.listTasksForManualImport.mockResolvedValue([])
repo.listPoolItemsForTaskPeriodByCodes.mockResolvedValue([
poolItem({
barcode: 'BG006401AN1242V01',
extra: {
profitCenter: '运营中心A',
clearanceCode: comboCode,
clearanceTotal: 10,
},
}),
poolItem({
barcode: 'BG006401BN1242V01',
extra: {
profitCenter: '运营中心A',
clearanceCode: comboCode,
clearanceTotal: 10,
},
}),
])
const service = new SupplyChainClearanceTaskImportService(repo as never)
await expect(service.importTasks({
periodKey: '2026-11',
user,
buffer: await workbookBuffer([
[comboCode, '铁心兰', 10, '5折', '组合清货'],
['BG006401AN1242V01', '铁心兰', 10, '5折', '重复组件'],
]),
})).rejects.toThrow('组合编码展开后存在重复组件')
expect(repo.writeTasksWithEvents).not.toHaveBeenCalled()
})
it('rejects a discount for an exact A fixed-task priority', async () => {
const repo = repository()
repo.listTasksForManualImport.mockResolvedValue([])

View File

@ -3644,6 +3644,61 @@ describe('supply-chain-clearance workflow', () => {
])
})
it('filters the full review workbench set and returns 30-day clearable quantity', async () => {
repository.listTasks.mockResolvedValue([
pendingTask,
{
...pendingTask,
id: 'task-2',
barcode: 'SKU002',
sku: 'SPU002',
productName: '测试商品二',
submittedAt: new Date('2026-10-08T02:12:00.000Z'),
},
] as never)
repository.listPoolItemsForTaskPeriod.mockResolvedValue([
{
...poolItem,
dailySales: '2.33',
},
{
...poolItem,
id: 'pool-2',
barcode: 'SKU002',
sku: 'SPU002',
productName: '测试商品二',
dailySales: '1.25',
},
] as never)
const result = await supplyChainClearanceService.getReviewWorkbench({
periodKey: '2026-10',
round: 1,
page: 1,
pageSize: 20,
filters: [{
key: 'thirtyDayClearableQty',
operator: 'gte',
value: '60',
}],
})
expect(result.total).toBe(1)
expect(result.rows).toEqual([
expect.objectContaining({
taskId: 'task-1',
barcode: 'SKU001',
dailySales: 2.33,
thirtyDayClearableQty: 70,
}),
])
expect(repository.listPoolItemsForTaskPeriod).toHaveBeenCalledTimes(1)
expect(repository.listPoolItemsForTaskPeriod).toHaveBeenCalledWith(
'2026-10',
['SKU001', 'SKU002'],
)
})
it('treats legacy rejected tasks as pending operator confirmation in the review workbench', async () => {
repository.listTasks.mockResolvedValue([
{ ...pendingTask, id: 'pending', status: 'PENDING', events: [] },
@ -5449,6 +5504,35 @@ describe('supply-chain-clearance workflow', () => {
expect(repository.upsertTaskShipmentDaily).not.toHaveBeenCalled()
})
it('clears migrated shipment values before a future clearance period starts', async () => {
jest.useFakeTimers().setSystemTime(new Date('2026-11-25T02:00:00.000Z'))
repository.listTasks.mockResolvedValue([{
...pendingTask,
periodKey: '2026-12',
profitCenter: '运营中心A',
status: 'APPROVED',
clearedQty: 22,
}] as never)
repository.updateTaskProgress.mockResolvedValue(1)
const result = await supplyChainClearanceService.syncTaskProgress('2026-12')
expect(result).toMatchObject({
periodKey: '2026-12',
hasCoverage: false,
through: null,
tasks: 1,
updated: 1,
})
expect(repository.updateTaskProgress).toHaveBeenCalledWith([{
id: 'task-1',
clearedQty: 0,
lastProgressAt: expect.any(Date),
}])
expect(sourceRepository.listClearanceDailyShipmentsByProfitCenter).not.toHaveBeenCalled()
expect(repository.upsertTaskShipmentDaily).not.toHaveBeenCalled()
})
it('caps the outbound cutoff at the final day of a completed month', async () => {
jest.useFakeTimers().setSystemTime(new Date('2026-12-01T01:00:00.000Z'))
const approved = {

View File

@ -0,0 +1,64 @@
import ExcelJS from 'exceljs'
import { expressQuerySchema, expressRegionalPivot, selectExpressOverview, type ExpressQuery, type ExpressReadState } from '@/lib/daily-express-snapshot'
import type { AuthUser } from '@/server/core/types'
import { AppError, ErrorCode } from '@/server/core/errors'
import { dailyExpressVolumeRepository } from '@/server/repositories/daily-express-volume.repository'
import { supplyChainPermissionSettingsService } from './supply-chain-permission-settings.service'
export class DailyExpressVolumeService {
private async load(input: unknown, user: AuthUser, download = false) {
const access = await supplyChainPermissionSettingsService.getUserAccess(user, 'dailyExpressVolume')
if (!access.view || (download && !access.download)) throw new AppError(ErrorCode.AUTH_PERMISSION_DENIED, '没有该看板的查看或导出权限')
const parsed = expressQuerySchema.safeParse(input)
if (!parsed.success) throw new AppError(ErrorCode.VALIDATION_FAILED, '看板查询条件无效')
return { ...(await dailyExpressVolumeRepository.readLatest()), query: parsed.data, access }
}
private present(report: Awaited<ReturnType<typeof dailyExpressVolumeRepository.readLatest>>['report'], query: ExpressQuery, canDownload: boolean): ExpressReadState {
const base = { latestDate: report.dateTo, updatedAt: report.updatedAt, dates: report.overview.days, canDownload, view: query.view }
if (query.view === 'overview') {
if (query.date && !report.overview.days.includes(query.date)) throw new AppError(ErrorCode.VALIDATION_FAILED, '所选日期没有已更新数据')
return { ...base, overview: selectExpressOverview(report.overview, query.date) }
}
if (query.view === 'uncollected') return { ...base, uncollected: report.uncollected }
const date = query.date || report.regional.latestDate, day = report.regional.days.find(item => item.date === date)
if (!day || (query.origin && !day.origins.some(item => item.name === query.origin))) throw new AppError(ErrorCode.VALIDATION_FAILED, '所选日期或发货地没有已更新数据')
return { ...base, regional: { date, origins: day.origins, origin: query.origin, pivot: expressRegionalPivot(day, query.origin) } }
}
async getDashboard(input: unknown, user: AuthUser) {
const { report, query, access } = await this.load(input, user)
return this.present(report, query, access.download)
}
async export(input: unknown, user: AuthUser) {
const { report, query, pointer } = await this.load(input, user, true)
const data = this.present(report, query, true), workbook = new ExcelJS.Workbook()
const add = (name: string, headers: string[], rows: unknown[][]) => {
const sheet = workbook.addWorksheet(name); sheet.addRow(headers)
for (const row of rows) sheet.addRow(row.map(value => value == null ? '' : value) as ExcelJS.CellValue[])
sheet.views = [{ state: 'frozen', ySplit: 1 }]
sheet.columns.forEach((column, index) => { column.width = index === 0 ? 30 : 23 })
sheet.getRow(1).font = { name: 'Microsoft YaHei', bold: true, color: { argb: 'FF355D76' } }
sheet.getRow(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE8F0F5' } }
sheet.autoFilter = { from: { row: 1, column: 1 }, to: { row: rows.length + 1, column: headers.length } }
return sheet
}
let filename: string
if (data.overview) {
const overview = data.overview
add('各快递30日承运量', ['快递名称', ...overview.days, '合计'], [['每日合计', ...overview.daily.map(row => row.total), overview.total], ...overview.ranking.map(row => [row.name, ...row.daily, row.total])])
const columns = ['o_id', 'so_id', 'logistics_company', 'l_id', 'receiver_state', 'send_date', 'wms_co_id', 'warehouse_name']
const details = (await dailyExpressVolumeRepository.readDetails(pointer)).filter(row => !query.date || row.send_date.slice(0, 10) === query.date)
add('订单明细', ['ERP 内部订单号', '线上订单号', '快递名称', '快递单号', '省份', '发货日期', '发货仓编号', '仓库名称'], details.map(row => columns.map(key => row[key])))
filename = query.date ? `各快递承运量_${query.date}.xlsx` : `各快递30日承运量_${report.dateTo}.xlsx`
} else if (data.regional) {
const { pivot, date, origin } = data.regional
add('发货地省份区域承运量', ['区域', '省份', ...pivot.carriers, '合计'], pivot.rows.map(row => [row.region, row.province, ...pivot.carriers.map(carrier => row.counts[carrier] ?? 0), row.total]))
filename = `省份区域承运量_${date}_${origin || '全部发货地'}.xlsx`
} else {
const pickup = data.uncollected!
add('已发货未揽收明细', pickup.columns.map(column => column.label), pickup.rows.map(row => pickup.columns.map(column => row[column.key])))
add('快递汇总', ['快递名称', '未揽收数量'], pickup.summary.carriers.map(row => [row.name, row.count]))
filename = `已发货未揽收_${pickup.date}.xlsx`
}
return { filename, bytes: Buffer.from(await workbook.xlsx.writeBuffer()) }
}
}
export const dailyExpressVolumeService = new DailyExpressVolumeService()

View File

@ -91,6 +91,8 @@ const modularProcessingExportParams = z.object({
sortDirection: z.enum(['asc', 'desc']).optional(),
componentSortKey: z.string().trim().max(64).optional(),
componentSortDirection: z.enum(['asc', 'desc']).optional(),
snapshotDate: z.string().trim().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
generationSlot: z.enum(['09:00', '15:00']).optional(),
}).refine((filters) => !filters.sortKey || isModularProcessingOrderSortKey(filters.sortKey))
.refine((filters) =>
!filters.componentSortKey || isModularProcessingComponentSortKey(filters.componentSortKey),

View File

@ -150,6 +150,13 @@ function snapshotRepository(): jest.Mocked<ModularProcessingSnapshotRepository>
batchKey: '',
generationSlot: '',
}),
loadComponentSnapshot: jest.fn().mockResolvedValue({
rows: [],
generatedAt: null,
batchKey: '',
generationSlot: '',
snapshotAvailable: false,
}),
latestSnapshotForDate: jest.fn().mockResolvedValue(null),
latestSnapshotForBatch: jest.fn().mockResolvedValue(null),
listSnapshotBatches: jest.fn().mockResolvedValue([]),
@ -302,6 +309,7 @@ describe('modular product processing order source readiness', () => {
batchKey: '2026-10-19:09:00',
generationSlot: '09:00',
rows: [expect.objectContaining({ recordKey: 'archive-1', barcode: 'BARCODE-1' })],
componentRows: [],
generatedAt: expect.any(Date),
}))
// 每日主表生成后自动生成同批次加工单
@ -1086,6 +1094,102 @@ describe('modular product processing order source readiness', () => {
expect(result.rows[0]).toMatchObject({ componentBarcode: 'PART-1', jianshangStock: 9 })
})
it('reads historical component details from the selected frozen batch', async () => {
const snapshots = snapshotRepository()
snapshots.loadComponentSnapshot.mockResolvedValue({
rows: [{
recordKey: 'BARCODE-1:SJ042509N1410V01:0',
parentBarcode: 'BARCODE-1',
componentBarcode: 'SJ042509N1410V01',
rowJson: {
id: 'BARCODE-1:SJ042509N1410V01:0',
parentBarcode: 'BARCODE-1',
componentBarcode: 'SJ042509N1410V01',
componentName: '款式二',
componentQuantity: 2,
jianshangStock: 34,
requiredStockForSelectedOrder: 34,
requiredStockTotal: 34,
meetsTotalRequirement: true,
lacksTotalRequirement: false,
meetsSingleRequirement: true,
lacksSingleRequirement: false,
supplier: '三环',
purchaser: '天天',
},
}],
generatedAt: new Date('2026-11-23T07:09:50.000Z'),
batchKey: '2026-11-23:15:00',
generationSlot: '15:00',
snapshotAvailable: true,
})
const service = new ModularProductProcessingOrdersService(
repository(archiveRecord.updatedAt),
upstream(),
rules(),
manualValues(),
async () => null,
snapshots,
async () => new Map([['SJ042509N1410V01', 0]]),
)
const result = await service.listComponents('BARCODE-1', {
snapshotDate: '2026-11-23',
generationSlot: '15:00',
})
expect(result.rows[0]).toMatchObject({
componentBarcode: 'SJ042509N1410V01',
jianshangStock: 34,
})
expect(result.sourceStatus).toMatchObject({
dataMode: 'BATCH_SNAPSHOT',
batchKey: '2026-11-23:15:00',
generationSlot: '15:00',
})
})
it('labels legacy historical component details as live data when no batch snapshot exists', async () => {
const snapshots = snapshotRepository()
snapshots.loadComponentSnapshot.mockResolvedValue({
rows: [],
generatedAt: null,
batchKey: '2026-11-23:legacy',
generationSlot: 'legacy',
snapshotAvailable: false,
})
const source = upstream()
source.listBomComponents.mockResolvedValue({
source: 'rpt.jst_skuBomItem',
records: [{
componentBarcode: 'SJ042509N1410V01',
componentName: '款式二',
componentQuantity: 2,
}],
})
source.listBomDemandTotals.mockResolvedValue(new Map([
['SJ042509N1410V01', 0],
]))
const service = new ModularProductProcessingOrdersService(
repository(archiveRecord.updatedAt),
source,
rules(),
manualValues(),
async () => null,
snapshots,
async () => new Map([['SJ042509N1410V01', 0]]),
)
const result = await service.listComponents('BARCODE-1', {
snapshotDate: '2026-11-23',
})
expect(result.rows[0]?.jianshangStock).toBe(0)
expect(result.sourceStatus.dataMode).toBe('LIVE')
expect(result.sourceStatus.message).toContain('未保存部件批次快照')
expect(result.sourceStatus.batchKey).toBe('2026-11-23:legacy')
})
it('maps archive stock, sales, and confirmed workorder in-transit data', async () => {
const archiveRepository = repository(archiveRecord.updatedAt)
archiveRepository.listComponentProfiles.mockResolvedValue([{
@ -1238,8 +1342,8 @@ describe('modular product processing order source readiness', () => {
originalSellable: MODULAR_PROCESSING_SELLABILITY.STOCK_WARNING,
replacementSellable: '-',
finalSellable: MODULAR_PROCESSING_SELLABILITY.STOCK_WARNING,
finalProcessingQuantity: 0,
processingNote: MODULAR_PROCESSING_SELLABILITY.STOCK_WARNING,
finalProcessingQuantity: 2,
processingNote: null,
})
expect(source.listBomComponentsForParents).toHaveBeenCalledWith(['BARCODE-1'])
expect(archiveRepository.listComponentProfiles).toHaveBeenCalledWith(['PART-1'])
@ -1302,8 +1406,9 @@ describe('modular product processing order source readiness', () => {
})
expect(page.rows.map((row) => row.barcode)).toEqual(['BARCODE-1'])
expect(source.listBomComponentsForParents).toHaveBeenCalledTimes(1)
expect(source.listBomComponentsForParents).toHaveBeenCalledTimes(2)
expect(source.listBomComponentsForParents).toHaveBeenCalledWith(['BARCODE-1'])
expect(source.listBomComponentsForParents).toHaveBeenCalledWith(['BARCODE-2'])
})
it('uses compact sellability flags for a large result set', async () => {
@ -1350,7 +1455,7 @@ describe('modular product processing order source readiness', () => {
expect(page.rows.map((row) => row.barcode)).toEqual(['BARCODE-0'])
expect(source.listBomSellabilityFlags).toHaveBeenCalledTimes(1)
expect(source.listBomComponentsForParents).not.toHaveBeenCalled()
expect(source.listBomComponentsForParents).toHaveBeenCalledTimes(1)
})
it('uses the effective final quantity, not rounded suggested quantity, for the first sellability rule', async () => {
@ -1394,8 +1499,8 @@ describe('modular product processing order source readiness', () => {
expect(page.rows[0]).toMatchObject({
roundedSuggestedQuantity: 0,
finalProcessingQuantity: 10,
originalSellable: MODULAR_PROCESSING_SELLABILITY.STOCK_WARNING,
finalProcessingQuantity: 0,
originalSellable: MODULAR_PROCESSING_SELLABILITY.UNAVAILABLE,
processingNote: '暂不加工:不满足加工条件',
})
})
@ -1452,8 +1557,8 @@ describe('modular product processing order source readiness', () => {
}])).listPage()
expect(manuallyAdjusted.rows[0]).toMatchObject({
originalSellable: MODULAR_PROCESSING_SELLABILITY.UNAVAILABLE,
finalProcessingQuantity: 10,
processingNote: null,
finalProcessingQuantity: 0,
processingNote: MODULAR_PROCESSING_SELLABILITY.UNAVAILABLE,
})
})
@ -1618,7 +1723,7 @@ describe('modular product processing order source readiness', () => {
expect(page.rows.find((row) => row.barcode === 'BARCODE-2')).toMatchObject({
originalSellable: MODULAR_PROCESSING_SELLABILITY.PREORDER,
roundedSuggestedQuantity: 70,
finalProcessingQuantity: 140,
finalProcessingQuantity: 50,
})
})
@ -1755,7 +1860,7 @@ describe('modular product processing order source readiness', () => {
componentName: '五金部件',
componentQuantity: 2,
jianshangStock: 18,
requiredStockForSelectedOrder: 14,
requiredStockForSelectedOrder: 18,
requiredStockTotal: 150,
meetsTotalRequirement: false,
lacksTotalRequirement: true,
@ -1767,7 +1872,7 @@ describe('modular product processing order source readiness', () => {
],
})
expect(bomSource.listBomDemandTotals).toHaveBeenCalledWith([
{ parentBarcode: 'BARCODE-1', processingQuantity: 67 },
{ parentBarcode: 'BARCODE-1', processingQuantity: 9 },
])
})
@ -1824,15 +1929,30 @@ describe('modular product processing order source readiness', () => {
}]],
]),
})
// 第一轮售卖判断使用归零前需求 10;最终加工量归零后,总消耗应重新汇总为 0。
source.listBomDemandTotals
.mockResolvedValueOnce(new Map([['PART-1', 10]]))
.mockResolvedValueOnce(new Map([['PART-1', 0]]))
source.listBomDemandTotals.mockImplementation(async (demands) => new Map([[
'PART-1',
demands.reduce((total, item) => (
total + item.processingQuantity * (item.parentBarcode === 'BARCODE-1' ? 2 : 1)
), 0),
]]))
const service = new ModularProductProcessingOrdersService(
archiveRepository,
source,
rules(),
manualValues(),
manualValues([
{
barcode: 'BARCODE-1',
finalProcessingQuantity: 5,
processingNote: '',
orderWarehouse: null,
},
{
barcode: 'BARCODE-2',
finalProcessingQuantity: 5,
processingNote: '',
orderWarehouse: null,
},
]),
async () => null,
snapshotRepository(),
async () => new Map([['PART-1', 7]]),
@ -1842,12 +1962,14 @@ describe('modular product processing order source readiness', () => {
expect(detail.rows[0]).toMatchObject({
componentBarcode: 'PART-1',
requiredStockForSelectedOrder: 0,
requiredStockTotal: 0,
requiredStockForSelectedOrder: 5,
requiredStockTotal: 15,
meetsTotalRequirement: false,
meetsSingleRequirement: true,
})
expect(source.listBomDemandTotals).toHaveBeenLastCalledWith([
{ parentBarcode: 'BARCODE-1', processingQuantity: 0 },
{ parentBarcode: 'BARCODE-2', processingQuantity: 0 },
{ parentBarcode: 'BARCODE-1', processingQuantity: 5 },
{ parentBarcode: 'BARCODE-2', processingQuantity: 5 },
])
})
@ -1965,6 +2087,79 @@ describe('modular product processing order source readiness', () => {
})
})
it('down-adjusts to the component-supported quantity before assigning sellability', async () => {
const componentBarcode = 'SJ042509N1410V01'
const product = {
...archiveRecord,
stockJianshang: '5',
dailySales: '3.83',
}
const archiveRepository = repository(archiveRecord.updatedAt)
archiveRepository.listCalculationRecords.mockResolvedValue([product])
archiveRepository.listComponentProfiles.mockResolvedValue([{
...archiveRecord,
barcode: componentBarcode,
productName: '款式二',
stockJianshang: '34',
}])
const source = upstream()
source.listConfirmedInTransit.mockResolvedValue({
values: new Map(),
latestSourceSyncAt: new Date(),
})
source.listBomComponentsForParents.mockResolvedValue({
source: 'rpt.jst_skuBomItem',
recordsByParent: new Map([[
'BARCODE-1',
[{
componentBarcode,
componentName: '款式二',
componentQuantity: 2,
}],
]]),
})
source.listBomDemandTotals.mockImplementation(async (demands) => new Map([[
componentBarcode,
demands.reduce(
(total, item) => total + item.processingQuantity * 2,
0,
),
]]))
const service = new ModularProductProcessingOrdersService(
archiveRepository,
source,
rules([{
id: 'rule-1',
values: {
warehouse: '简尚仓',
stockingDays: 7,
triggerCoefficient: 0.5,
minimumOrderQuantity: 20,
},
}]),
manualValues(),
async () => null,
snapshotRepository(),
async () => new Map([[componentBarcode, 34]]),
)
const data = await service.listExportData({}, 'withComponents')
expect(data.rows[0]).toMatchObject({
roundedSuggestedQuantity: 20,
finalProcessingQuantity: 17,
originalSellable: MODULAR_PROCESSING_SELLABILITY.PREORDER,
})
expect(data.componentRows[0]).toMatchObject({
componentBarcode,
jianshangStock: 34,
requiredStockForSelectedOrder: 34,
requiredStockTotal: 34,
meetsTotalRequirement: true,
meetsSingleRequirement: true,
})
})
it('defaults unrecognized and unmatched component stock to zero in detail and export', async () => {
const archiveRepository = repository(archiveRecord.updatedAt)
archiveRepository.listComponentProfiles.mockResolvedValue([{
@ -2403,7 +2598,10 @@ describe('modular product processing order source readiness', () => {
expect(result.rows.map((row) => row.barcode)).toEqual(['BARCODE-2'])
expect(result.componentRows.map((row) => row.componentBarcode)).toEqual(['PART-2'])
expect(source.listBomComponentsForParents).toHaveBeenCalledWith(['BARCODE-2'])
expect(source.listBomComponentsForParents).toHaveBeenCalledWith([
'BARCODE-1',
'BARCODE-2',
])
})
it('exports all filtered main rows without adding component export rows', async () => {
@ -2487,4 +2685,104 @@ describe('modular product processing order source readiness', () => {
expect(source.listBomComponentsForParents).toHaveBeenCalledTimes(1)
expect(source.listBomComponentsForParents).toHaveBeenCalledWith(['BARCODE-1'])
})
it('binds historical exports to the selected frozen main and component batches', async () => {
const snapshots = snapshotRepository()
snapshots.loadDailySnapshot.mockResolvedValue({
rows: [{
recordKey: 'archive-1',
barcode: 'BARCODE-1',
rowJson: {
id: 'archive-1',
barcode: 'BARCODE-1',
productName: '模块化床',
finalProcessingQuantity: 17,
finalSellable: MODULAR_PROCESSING_SELLABILITY.PREORDER,
},
}],
generatedAt: new Date('2026-11-23T07:09:50.000Z'),
batchKey: '2026-11-23:15:00',
generationSlot: '15:00',
})
snapshots.loadComponentSnapshot.mockResolvedValue({
rows: [{
recordKey: 'archive-1:SJ042509N1410V01:0',
parentBarcode: 'BARCODE-1',
componentBarcode: 'SJ042509N1410V01',
rowJson: {
id: 'archive-1:SJ042509N1410V01:0',
parentBarcode: 'BARCODE-1',
componentBarcode: 'SJ042509N1410V01',
componentQuantity: 2,
jianshangStock: 34,
requiredStockTotal: 34,
},
}],
generatedAt: new Date('2026-11-23T07:09:50.000Z'),
batchKey: '2026-11-23:15:00',
generationSlot: '15:00',
snapshotAvailable: true,
})
const service = new ModularProductProcessingOrdersService(
repository(archiveRecord.updatedAt),
upstream(),
rules(),
manualValues(),
async () => null,
snapshots,
async () => new Map([['SJ042509N1410V01', 0]]),
)
const data = await service.listExportData({
snapshotDate: '2026-11-23',
generationSlot: '15:00',
}, 'withComponents')
expect(data.rows[0]).toMatchObject({
barcode: 'BARCODE-1',
finalProcessingQuantity: 17,
})
expect(data.componentRows[0]).toMatchObject({
componentBarcode: 'SJ042509N1410V01',
jianshangStock: 34,
requiredStockTotal: 34,
})
expect(snapshots.loadComponentSnapshot).toHaveBeenCalledWith({
snapshotDate: '2026-11-23',
generationSlot: '15:00',
})
})
it('refuses a historical component export when the batch has no frozen component rows', async () => {
const snapshots = snapshotRepository()
snapshots.loadDailySnapshot.mockResolvedValue({
rows: [{
recordKey: 'archive-1',
barcode: 'BARCODE-1',
rowJson: { id: 'archive-1', barcode: 'BARCODE-1' },
}],
generatedAt: new Date('2026-11-23T07:09:50.000Z'),
batchKey: '2026-11-23:legacy',
generationSlot: 'legacy',
})
snapshots.loadComponentSnapshot.mockResolvedValue({
rows: [],
generatedAt: null,
batchKey: '2026-11-23:legacy',
generationSlot: 'legacy',
snapshotAvailable: false,
})
const service = new ModularProductProcessingOrdersService(
repository(archiveRecord.updatedAt),
upstream(),
rules(),
manualValues(),
async () => null,
snapshots,
)
await expect(service.listExportData({
snapshotDate: '2026-11-23',
}, 'withComponents')).rejects.toThrow('未保存部件冻结快照')
})
})

View File

@ -83,6 +83,7 @@ import {
} from '@/server/repositories/modular-processing-order.repository'
import {
clearJianshangStockByBarcodeCache,
loadLatestComponentStockSyncAt,
loadComponentStockByBarcode,
loadJianshangStockByBarcode,
} from '@/server/services/product-inventory-snapshot-stock.service'
@ -163,6 +164,13 @@ const EMPTY_SNAPSHOT_REPOSITORY: ModularProcessingSnapshotRepository = {
batchKey: '',
generationSlot: '',
}),
loadComponentSnapshot: async () => ({
rows: [],
generatedAt: null,
batchKey: '',
generationSlot: '',
snapshotAvailable: false,
}),
latestSnapshotForDate: async () => null,
latestSnapshotForBatch: async () => null,
listSnapshotBatches: async () => [],
@ -585,6 +593,8 @@ export class ModularProductProcessingOrdersService {
process.env.NODE_ENV === 'test'
? EMPTY_GENERATION_HEALTH_TRACKER
: modularProcessingGenerationHealthService,
private readonly componentStockSyncAtProvider: () => Promise<Date | null> =
async () => null,
) {}
/** 替换编码候选项缓存:规则表每日快照 + 准入行变动不频繁,60 秒内复用,避免每次开面板全量重算。 */
@ -1242,13 +1252,6 @@ export class ModularProductProcessingOrdersService {
!SELLABILITY_DEPENDENT_ORDER_FIELDS.has(key)
)),
)
const rowsBeforeSellability = baseData.calculationRows
.filter((row) =>
this.matchesQuickFilters(row, filters, componentParentBarcodes),
)
.filter((row) =>
matchesProcessingColumnFilters(row, independentColumnFilters),
)
const needsSellability = Object.keys(columnFilters).some(
(key) => SELLABILITY_DEPENDENT_ORDER_FIELDS.has(key),
) || (requiredColumn
@ -1258,15 +1261,19 @@ export class ModularProductProcessingOrdersService {
? SELLABILITY_DEPENDENT_ORDER_FIELDS.has(filters.sortKey)
: false
)
const rowsWithSellability = needsSellability
? await this.applySellability(
rowsBeforeSellability,
baseData.calculationRows,
componentStockByBarcode,
baseData.version,
baseData.manualValues,
)
: rowsBeforeSellability
const capacityAwareRows = needsSellability
? (await this.loadCapacityAwareRows(baseData, componentStockByBarcode)).rows
: baseData.calculationRows
const rowsWithSellability = capacityAwareRows
.filter((row) =>
this.matchesQuickFilters(row, filters, componentParentBarcodes),
)
.filter((row) =>
matchesProcessingColumnFilters(
row,
needsSellability ? {} : independentColumnFilters,
),
)
const filteredRows = Object.keys(columnFilters).length > 0
? rowsWithSellability.filter((row) =>
matchesProcessingColumnFilters(row, columnFilters),
@ -1405,6 +1412,8 @@ export class ModularProductProcessingOrdersService {
keyword?: string
limit?: number
columnFilters?: ModularProcessingColumnFilters
snapshotDate?: string
generationSlot?: string
}): Promise<ModularProcessingFilterOption[]> {
const column = input.column.trim()
if (!isModularProcessingComponentSortKey(column)) {
@ -1416,6 +1425,8 @@ export class ModularProductProcessingOrdersService {
page: 1,
pageSize: PAGE_SIZE_MAX,
columnFilters: input.columnFilters,
snapshotDate: input.snapshotDate,
generationSlot: input.generationSlot,
})
const counts = new Map<string, number>()
@ -1553,23 +1564,18 @@ export class ModularProductProcessingOrdersService {
return cached
}
let rows: ModularProcessingOrderRow[] = await this.applySellability(
baseData.calculationRows,
baseData.calculationRows,
componentStockByBarcode,
baseData.version,
baseData.manualValues,
{
refreshSelectiveTransferPlan: true,
throwOnBomError: options.throwOnBomError,
},
)
let rows: ModularProcessingOrderRow[] = baseData.calculationRows
let capacityAdjustments = new Map<string, number>()
let capacityReductionCauses = new Map<
string,
ModularProcessingComponentCapacityCause[]
>()
let unresolvedComponentShortages: ComponentDemandSnapshot['unresolvedComponentShortages'] = []
let capacityComponentsByParent: Map<
string,
Array<{ componentBarcode: string; componentQuantity: number }>
> | null = null
let capacityStockByComponent: Map<string, number> | null = null
const activeParentBarcodes = Array.from(new Set(
rows.flatMap((row) => {
const barcode = normalizeOrderCode(row.barcode)
@ -1585,6 +1591,7 @@ export class ModularProductProcessingOrdersService {
))
if (activeParentBarcodes.length > 0) {
const componentsByParent = await this.loadBomComponentsByParent(activeParentBarcodes)
capacityComponentsByParent = componentsByParent
const componentBarcodes = Array.from(new Set(
Array.from(componentsByParent.values())
.flat()
@ -1603,6 +1610,7 @@ export class ModularProductProcessingOrdersService {
0,
]),
)
capacityStockByComponent = stockByComponent
const rowsByBarcode = new Map(baseData.rowByBarcode)
rows.forEach((row) => {
const barcode = normalizeOrderCode(row.barcode)
@ -1619,6 +1627,61 @@ export class ModularProductProcessingOrdersService {
capacityReductionCauses = rebalanced.reductionCauses
unresolvedComponentShortages = rebalanced.unresolvedComponents
}
const preferredFinalQuantities = new Map<string, number | null>(
Array.from(capacityAdjustments.entries()),
)
const capacityAdjustedManualValues = new Map(baseData.manualValues)
capacityAdjustments.forEach((quantity, barcode) => {
const manual = capacityAdjustedManualValues.get(barcode)
if (manual) {
capacityAdjustedManualValues.set(barcode, {
...manual,
finalProcessingQuantity: quantity,
finalProcessingQuantityIsManual: false,
})
}
})
const capacityZeroBarcodes = new Set(
Array.from(capacityAdjustments.entries())
.filter(([, quantity]) => quantity === 0)
.map(([barcode]) => barcode),
)
// 部件库存下调后再重算售卖状态,状态不再反向阻断可执行加工量。
rows = await this.applySellability(
rows,
rows,
componentStockByBarcode,
undefined,
capacityAdjustedManualValues,
{
refreshSelectiveTransferPlan: true,
throwOnBomError: options.throwOnBomError,
preferredFinalQuantities,
capacityZeroBarcodes,
},
)
if (capacityComponentsByParent && capacityStockByComponent) {
const rowsByBarcode = new Map(
rows.flatMap((row) => {
const barcode = normalizeOrderCode(row.barcode)
return barcode ? [[barcode, row] as const] : []
}),
)
const finalRebalance = rebalanceFinalQuantitiesByComponentCapacity({
rows,
componentsByParent: capacityComponentsByParent,
stockByComponent: capacityStockByComponent,
rowsByBarcode,
})
rows = finalRebalance.rows
finalRebalance.adjustments.forEach((quantity, barcode) => {
capacityAdjustments.set(barcode, quantity)
})
finalRebalance.reductionCauses.forEach((causes, barcode) => {
capacityReductionCauses.set(barcode, causes)
})
unresolvedComponentShortages = finalRebalance.unresolvedComponents
}
const parentDemands = this.componentParentDemands(rows)
const totalByComponent = parentDemands.length === 0
? new Map<string, number>()
@ -1642,6 +1705,50 @@ export class ModularProductProcessingOrdersService {
return snapshot
}
/** 主页面、导出和筛选项统一使用库存可执行后的最终行,BOM 失败时按原逻辑降级。 */
private async loadCapacityAwareRows(
baseData: RealtimeBaseData,
componentStockByBarcode: Map<string, number> | null,
options: { throwOnBomError?: boolean; forceFullCapacity?: boolean } = {},
) {
if (
!options.throwOnBomError &&
!options.forceFullCapacity &&
baseData.calculationRows.length > 500
) {
return {
rows: baseData.calculationRows,
demandSnapshot: null,
}
}
try {
const demandSnapshot = await this.loadComponentDemandSnapshot(
baseData,
componentStockByBarcode,
options,
)
return {
rows: baseData.calculationRows.map((row) => (
demandSnapshot.rowsByBarcode.get(normalizeOrderCode(row.barcode)) ?? row
)),
demandSnapshot,
}
} catch (cause) {
if (options.throwOnBomError) throw cause
this.upstreamMessage(cause, 'bom')
return {
rows: await this.applySellability(
baseData.calculationRows,
baseData.calculationRows,
componentStockByBarcode,
baseData.version,
baseData.manualValues,
),
demandSnapshot: null,
}
}
}
private async loadBomComponentsByParent(parentBarcodes: string[]) {
const now = Date.now()
const recordsByParent = new Map<string, ModularProcessingBomRecord[]>()
@ -1930,6 +2037,9 @@ export class ModularProductProcessingOrdersService {
options: {
refreshSelectiveTransferPlan?: boolean
throwOnBomError?: boolean
/** 再平衡结果作为下一次状态判断的最终加工量。 */
preferredFinalQuantities?: ReadonlyMap<string, number | null>
capacityZeroBarcodes?: ReadonlySet<string>
} = {},
) {
const calculationByBarcode = new Map(
@ -2056,21 +2166,28 @@ export class ModularProductProcessingOrdersService {
)
return pageRows.map((row) => {
const barcode = normalizeOrderCode(row.barcode)
const originalSellable = originalByBarcode.get(barcode) ??
calculateOriginalSellability({
stock: typeof row.jianshangStock === 'number' ? row.jianshangStock : null,
finalProcessingQuantity:
typeof row.finalProcessingQuantity === 'number'
? row.finalProcessingQuantity
: null,
lacksTotalRequirement: null,
lacksSingleRequirement: null,
})
const originalSellable = options.capacityZeroBarcodes?.has(barcode)
? MODULAR_PROCESSING_SELLABILITY.UNAVAILABLE
: originalByBarcode.get(barcode) ??
calculateOriginalSellability({
stock: typeof row.jianshangStock === 'number' ? row.jianshangStock : null,
finalProcessingQuantity:
typeof row.finalProcessingQuantity === 'number'
? row.finalProcessingQuantity
: null,
lacksTotalRequirement: null,
lacksSingleRequirement: null,
})
const replacementSellable = calculateReplacementSellability(
typeof row.replacementBarcode === 'string' ? row.replacementBarcode : null,
originalByBarcode,
)
const manualFinalQuantity = manualValuesByBarcode.get(barcode)?.finalProcessingQuantity
const preferredFinalQuantity = options.preferredFinalQuantities?.has(barcode)
? options.preferredFinalQuantities.get(barcode)
: undefined
const manualFinalQuantity = options.preferredFinalQuantities?.has(barcode)
? preferredFinalQuantity
: manualValuesByBarcode.get(barcode)?.finalProcessingQuantity
const roundedSuggestedQuantity =
typeof row.roundedSuggestedQuantity === 'number'
? row.roundedSuggestedQuantity
@ -2109,18 +2226,18 @@ export class ModularProductProcessingOrdersService {
typeof row.triggerStockDays === 'number' ? row.triggerStockDays : null
const defaultFinalQuantity =
roundedSuggestedQuantity !== null && roundedSuggestedQuantity <= 0
? 0
: originalSellable === MODULAR_PROCESSING_SELLABILITY.UNAVAILABLE ||
originalSellable === MODULAR_PROCESSING_SELLABILITY.INVESTIGATE ||
originalSellable === MODULAR_PROCESSING_SELLABILITY.STOCK_WARNING
? 0
: originalSellable === MODULAR_PROCESSING_SELLABILITY.SELECTIVE &&
triggerStockDays !== null &&
combinedStockDays >= triggerStockDays
: originalSellable === MODULAR_PROCESSING_SELLABILITY.UNAVAILABLE ||
originalSellable === MODULAR_PROCESSING_SELLABILITY.INVESTIGATE ||
originalSellable === MODULAR_PROCESSING_SELLABILITY.STOCK_WARNING
? 0
: typeof row.finalProcessingQuantity === 'number'
? row.finalProcessingQuantity
: null
: originalSellable === MODULAR_PROCESSING_SELLABILITY.SELECTIVE &&
triggerStockDays !== null &&
combinedStockDays >= triggerStockDays
? 0
: typeof row.finalProcessingQuantity === 'number'
? row.finalProcessingQuantity
: null
const replacementAdditionalQuantity =
selectiveTransferPlan.replacementAdditionalQuantities.get(barcode) ?? 0
const baselineFinalQuantity = manualFinalQuantity ?? defaultFinalQuantity
@ -2166,6 +2283,14 @@ export class ModularProductProcessingOrdersService {
private async componentDemandContext(
parentBarcode: string,
bomRecords: Array<{
componentBarcode: string
componentQuantity: number
}>,
profiles: Array<{
barcode: string
stockJianshang: string | null
}>,
componentStockByBarcode: Map<string, number> | null,
) {
let baseData: RealtimeBaseData
@ -2180,12 +2305,51 @@ export class ModularProductProcessingOrdersService {
}
}
let demandSnapshot: ComponentDemandSnapshot
try {
demandSnapshot = await this.loadComponentDemandSnapshot(
baseData,
componentStockByBarcode,
const selectedRow = baseData.rowByBarcode.get(parentBarcode) ?? null
const profileByBarcode = new Map(
profiles.map((profile) => [normalizeOrderCode(profile.barcode), profile]),
)
const stockByComponent = new Map(
bomRecords.map((record) => [
normalizeOrderCode(record.componentBarcode),
resolveJianshangStock(componentStockByBarcode, record.componentBarcode) ??
parseProcessingNumber(
profileByBarcode.get(normalizeOrderCode(record.componentBarcode))?.stockJianshang,
) ??
0,
]),
)
const selectedOrder = selectedRow
? rebalanceFinalQuantitiesByComponentCapacity({
rows: [selectedRow],
componentsByParent: new Map([[
parentBarcode,
bomRecords,
]]),
stockByComponent,
rowsByBarcode: new Map([[parentBarcode, selectedRow]]),
}).rows[0] ?? selectedRow
: null
const calculationRows = selectedOrder
? baseData.calculationRows.map((row) => (
normalizeOrderCode(row.barcode) === parentBarcode ? selectedOrder : row
))
: baseData.calculationRows
const totalByComponent = await this.upstreamRepository.listBomDemandTotals(
this.componentParentDemands(calculationRows),
)
const message =
selectedOrder &&
typeof selectedOrder.processingInTransit === 'number' &&
typeof selectedOrder.finalProcessingQuantity === 'number'
? null
: `主表条码 ${parentBarcode} 的加工单在途或最终加工量未就绪,部件消耗计算暂为空。`
return {
selectedOrder,
totalByComponent,
message,
}
} catch (cause) {
return {
selectedOrder: baseData.rowByBarcode.get(parentBarcode) ?? null,
@ -2193,19 +2357,6 @@ export class ModularProductProcessingOrdersService {
message: this.upstreamMessage(cause, 'bom'),
}
}
const selectedOrder = demandSnapshot.rowsByBarcode.get(parentBarcode) ?? null
const message =
selectedOrder &&
typeof selectedOrder.processingInTransit === 'number' &&
typeof selectedOrder.finalProcessingQuantity === 'number'
? null
: `主表条码 ${parentBarcode} 的加工单在途或最终加工量未就绪,部件消耗计算暂为空。`
return {
selectedOrder,
totalByComponent: demandSnapshot.totalByComponent,
message: demandSnapshot.demandReady ? message : '加工主表暂无可计算数据。',
}
}
private async listComponentExportRows(
@ -2292,6 +2443,93 @@ export class ModularProductProcessingOrdersService {
})
}
private async listSnapshotExportData(
input: ModularProcessingOrderFilters,
mode: ModularProcessingExportMode,
selectedBarcodes: string[],
): Promise<ModularProcessingOrderExportData> {
const snapshotDate = input.snapshotDate?.trim() ?? ''
if (!snapshotDate) {
return { rows: [], componentRows: [] }
}
const [snapshot, componentSnapshot] = await Promise.all([
this.snapshotRepository.loadDailySnapshot({
snapshotDate,
...(input.generationSlot ? { generationSlot: input.generationSlot } : {}),
}),
mode === 'withComponents' || input.componentBarcode
? this.snapshotRepository.loadComponentSnapshot({
snapshotDate,
...(input.generationSlot ? { generationSlot: input.generationSlot } : {}),
})
: Promise.resolve(null),
])
const mainRows = snapshot.rows.flatMap((row) => {
const value = row.rowJson
if (!value || typeof value !== 'object') return []
if (typeof (value as { id?: unknown }).id !== 'string') return []
return [value as unknown as ModularProcessingOrderRow]
})
const manualValues = await this.loadManualValues(
mainRows.map((row) => String(row.barcode ?? '')),
snapshot.batchKey,
)
const rowsWithManualValues = applySnapshotManualValues(mainRows, manualValues)
const componentRows = (componentSnapshot?.rows ?? []).flatMap((row) => (
row.rowJson && typeof row.rowJson === 'object'
? [row.rowJson as unknown as ModularProcessingComponentExportRow]
: []
))
const componentParentBarcodes = input.componentBarcode
? componentSnapshot?.snapshotAvailable
? new Set(componentRows
.filter((row) => String(row.componentBarcode ?? '')
.toLocaleLowerCase('zh-CN')
.includes(input.componentBarcode!.trim().toLocaleLowerCase('zh-CN')))
.map((row) => normalizeOrderCode(row.parentBarcode))
.filter(Boolean))
: await this.resolveComponentBarcodeParentBarcodes(input.componentBarcode)
: null
const selected = new Set(selectedBarcodes.map(normalizeOrderCode).filter(Boolean))
const filteredMainRows = rowsWithManualValues
.filter((row) => selected.size === 0 || selected.has(normalizeOrderCode(row.barcode)))
.filter((row) => this.matchesQuickFilters(row, input, componentParentBarcodes))
.filter((row) => matchesProcessingColumnFilters(row, input.columnFilters ?? {}))
const sortedMainRows = sortProcessingRows(
filteredMainRows,
resolveOrderSort(input),
)
if (mode === 'main') {
return { rows: sortedMainRows, componentRows: [] }
}
if (!componentSnapshot?.snapshotAvailable) {
throw new AppError(
ErrorCode.VALIDATION_FAILED,
`批次 ${snapshot.batchKey || snapshotDate} 未保存部件冻结快照,不能导出历史含明细数据。`,
)
}
const selectedParents = new Set(
sortedMainRows.map((row) => normalizeOrderCode(row.barcode)).filter(Boolean),
)
const filteredComponentRows = componentRows
.filter((row) => selectedParents.has(normalizeOrderCode(row.parentBarcode)))
.filter((row) => matchesProcessingColumnFilters(
row as unknown as Record<string, string | number | boolean | null>,
input.componentColumnFilters ?? {},
))
const sortedComponentRows = sortProcessingRows(
filteredComponentRows as unknown as ModularProcessingOrderRow[],
resolveComponentSort({
sortKey: input.componentSortKey,
sortDirection: input.componentSortDirection,
}),
) as unknown as ModularProcessingComponentExportRow[]
return {
rows: sortedMainRows,
componentRows: sortedComponentRows,
}
}
async listExportData(
input: ModularProcessingOrderFilters,
mode: ModularProcessingExportMode,
@ -2301,6 +2539,9 @@ export class ModularProductProcessingOrdersService {
throwOnBomError?: boolean
} = {},
): Promise<ModularProcessingOrderExportData> {
if (input.snapshotDate?.trim()) {
return this.listSnapshotExportData(input, mode, selectedBarcodes)
}
const generationKey = options.generationKey ??
(await this.currentGeneration()).generationKey
const [baseData, componentStockByBarcode, componentParentBarcodes] = await Promise.all([
@ -2308,24 +2549,21 @@ export class ModularProductProcessingOrdersService {
this.componentStockByBarcodeProvider(),
this.resolveComponentBarcodeParentBarcodes(input.componentBarcode),
])
const { rows: capacityRows } = await this.loadCapacityAwareRows(
baseData,
componentStockByBarcode,
{ throwOnBomError: options.throwOnBomError },
)
const selected = new Set(
selectedBarcodes.map(normalizeOrderCode).filter(Boolean),
)
const candidates = baseData.calculationRows.filter((row) => (
const candidates = capacityRows.filter((row) => (
(selected.size === 0 || selected.has(normalizeOrderCode(row.barcode))) &&
this.matchesQuickFilters(row, input, componentParentBarcodes)
))
const calculatedRows = await this.applySellability(
candidates,
baseData.calculationRows,
componentStockByBarcode,
baseData.version,
baseData.manualValues,
{ throwOnBomError: options.throwOnBomError },
)
const rows = this.applyCombinedReplacement(
sortProcessingRows(
calculatedRows.filter((row) =>
candidates.filter((row) =>
matchesProcessingColumnFilters(row, input.columnFilters ?? {}),
),
resolveOrderSort(input),
@ -2340,21 +2578,19 @@ export class ModularProductProcessingOrdersService {
baseData,
componentStockByBarcode,
{ throwOnBomError: options.throwOnBomError },
)
).catch(async (cause) => {
if (options.throwOnBomError) throw cause
this.upstreamMessage(cause, 'bom')
return null
})
: null
const capacityAdjustedRows = componentDemandSnapshot
? rows.map((row) =>
componentDemandSnapshot.rowsByBarcode.get(
normalizeOrderCode(row.barcode),
) ?? row)
: rows
return {
rows: capacityAdjustedRows,
rows,
componentRows:
componentDemandSnapshot
? sortProcessingRows(
(await this.listComponentExportRows(
capacityAdjustedRows,
rows,
componentDemandSnapshot,
componentStockByBarcode,
)).filter((row) =>
@ -2471,29 +2707,25 @@ export class ModularProductProcessingOrdersService {
return this.listSnapshotPage({ ...input, snapshotDate })
}
const currentGeneration = await this.currentGeneration()
const [baseData, componentParentBarcodes] = await Promise.all([
const [baseData, componentStockByBarcode, componentParentBarcodes] = await Promise.all([
this.loadRealtimeBaseData(currentGeneration.generationKey),
this.componentStockByBarcodeProvider(),
this.resolveComponentBarcodeParentBarcodes(input.componentBarcode),
])
const capacityResult = await this.loadCapacityAwareRows(
baseData,
componentStockByBarcode,
)
const capacityAwareRows = capacityResult.rows
const columnFilters = input.columnFilters ?? {}
const hasColumnFilters = Object.keys(columnFilters).length > 0
const sort = resolveOrderSort(input)
const independentColumnFilters = Object.fromEntries(
Object.entries(columnFilters).filter(([key]) => (
!SELLABILITY_DEPENDENT_ORDER_FIELDS.has(key)
)),
)
const hasSellabilityDependentFilters = Object.keys(columnFilters).some(
(key) => SELLABILITY_DEPENDENT_ORDER_FIELDS.has(key),
)
const quickFilteredRows = baseData.calculationRows
const quickFilteredRows = capacityAwareRows
.filter((row) =>
this.matchesQuickFilters(row, input, componentParentBarcodes),
)
.filter((row) =>
matchesProcessingColumnFilters(row, independentColumnFilters),
matchesProcessingColumnFilters(row, columnFilters),
)
const componentStockByBarcode = await this.componentStockByBarcodeProvider()
const archiveReady = Boolean(baseData.archiveLatestAt)
const blockedReasons: string[] = []
if (!archiveReady) {
@ -2502,24 +2734,10 @@ export class ModularProductProcessingOrdersService {
if (!baseData.workorderReady && baseData.workorderMessage) {
blockedReasons.push(baseData.workorderMessage)
}
const sellabilityComputedForAll =
hasSellabilityDependentFilters ||
(sort ? SELLABILITY_DEPENDENT_ORDER_FIELDS.has(sort.key) : false)
const searchableRows = sellabilityComputedForAll
? await this.applySellability(
quickFilteredRows,
baseData.calculationRows,
componentStockByBarcode,
baseData.version,
baseData.manualValues,
)
: quickFilteredRows
const filteredRows = hasColumnFilters
? searchableRows.filter((row) => matchesProcessingColumnFilters(row, columnFilters))
: searchableRows
const filteredRows = quickFilteredRows
const sortedRows = sort ? sortProcessingRows(filteredRows, sort) : filteredRows
const pageRecords = sortedRows.slice((page - 1) * pageSize, page * pageSize)
const finalRows = sellabilityComputedForAll
const finalRows = capacityResult.demandSnapshot
? pageRecords
: await this.applySellability(
pageRecords,
@ -2807,7 +3025,7 @@ export class ModularProductProcessingOrdersService {
const generationKey = batchKey
this.clearRealtimeCaches()
const capacity = await this.enforceComponentCapacityForGeneration(generationKey)
const data = await this.listExportData({}, 'main', [], {
const data = await this.listExportData({}, 'withComponents', [], {
generationKey,
throwOnBomError: true,
})
@ -2820,11 +3038,23 @@ export class ModularProductProcessingOrdersService {
rowJson: row as unknown as Record<string, unknown>,
}]
})
const componentRows = data.componentRows.flatMap((row) => {
const recordKey = String(row.id ?? '').trim()
const parentBarcode = String(row.parentBarcode ?? '').trim().toUpperCase()
if (!recordKey || !parentBarcode) return []
return [{
recordKey,
parentBarcode,
componentBarcode: String(row.componentBarcode ?? '').trim().toUpperCase(),
rowJson: row as unknown as Record<string, unknown>,
}]
})
await this.snapshotRepository.replaceDailySnapshot({
snapshotDate,
batchKey,
generationSlot,
rows,
componentRows,
generatedAt,
})
// 每日生成主表后自动生成加工单(替换该日明细)。
@ -3097,6 +3327,8 @@ export class ModularProductProcessingOrdersService {
columnFilters?: ModularProcessingColumnFilters
sortKey?: string
sortDirection?: ModularProcessingSortDirection
snapshotDate?: string
generationSlot?: string
} = {},
): Promise<ModularProcessingComponentPage> {
const page = Math.max(1, Math.trunc(input.page ?? 1))
@ -3116,17 +3348,82 @@ export class ModularProductProcessingOrdersService {
}
}
let componentSnapshotBatchKey = ''
let componentSnapshotSlot = input.generationSlot ?? ''
let componentSnapshotFallbackMessage: string | null = null
if (input.snapshotDate?.trim()) {
const componentSnapshot = await this.snapshotRepository.loadComponentSnapshot({
snapshotDate: input.snapshotDate.trim(),
...(input.generationSlot ? { generationSlot: input.generationSlot } : {}),
parentBarcode: normalizedParent,
})
componentSnapshotBatchKey = componentSnapshot.batchKey
componentSnapshotSlot = componentSnapshot.generationSlot
if (componentSnapshot.snapshotAvailable) {
const snapshotRows = componentSnapshot.rows
.flatMap((row) => (
row.rowJson && typeof row.rowJson === 'object'
? [row.rowJson as unknown as ModularProcessingComponentExportRow]
: []
))
.filter((row) => String(row.parentBarcode ?? '').trim().toUpperCase() === normalizedParent)
.filter((row) => matchesProcessingColumnFilters(
row as unknown as Record<string, string | number | boolean | null>,
input.columnFilters ?? {},
))
const sortedRows = sort
? (
sortProcessingRows(
snapshotRows as unknown as ModularProcessingOrderRow[],
sort,
) as unknown as ModularProcessingComponentExportRow[]
)
: snapshotRows
const total = sortedRows.length
const totalPages = Math.max(1, Math.ceil(total / pageSize))
const normalizedPage = Math.min(page, totalPages)
return {
parentBarcode: normalizedParent,
rows: sortedRows.slice(
(normalizedPage - 1) * pageSize,
normalizedPage * pageSize,
),
pageInfo: {
page: normalizedPage,
pageSize,
total,
totalPages,
},
sourceStatus: {
ready: true,
source: MODULAR_PROCESSING_BOM_SOURCE_NAME,
message: null,
dataMode: 'BATCH_SNAPSHOT',
dataAsOf: componentSnapshot.generatedAt?.toISOString() ?? null,
batchKey: componentSnapshot.batchKey,
generationSlot: componentSnapshot.generationSlot,
},
}
}
componentSnapshotFallbackMessage =
`该历史批次(${componentSnapshot.batchKey || input.snapshotDate})未保存部件批次快照,` +
'当前显示实时部件库存与实时需求,不能视为当日冻结数据。'
}
try {
const [bom, componentStockByBarcode] = await Promise.all([
this.upstreamRepository.listBomComponents(normalizedParent),
this.componentStockByBarcodeProvider(),
])
const [profiles, demandContext] = await Promise.all([
this.repository.listComponentProfiles(
bom.records.map((record) => record.componentBarcode),
),
this.componentDemandContext(normalizedParent, componentStockByBarcode),
])
const profiles = await this.repository.listComponentProfiles(
bom.records.map((record) => record.componentBarcode),
)
const demandContext = await this.componentDemandContext(
normalizedParent,
bom.records,
profiles,
componentStockByBarcode,
)
const profileByBarcode = new Map(
profiles.map((profile) => [normalizeOrderCode(profile.barcode), profile]),
)
@ -3195,6 +3492,7 @@ export class ModularProductProcessingOrdersService {
(page - 1) * pageSize,
page * pageSize,
)
const componentStockSyncAt = await this.componentStockSyncAtProvider().catch(() => null)
return {
parentBarcode: normalizedParent,
rows,
@ -3202,10 +3500,15 @@ export class ModularProductProcessingOrdersService {
sourceStatus: {
ready: demandContext.message === null,
source: bom.source,
message:
message: componentSnapshotFallbackMessage ?? (
bom.records.length === 0
? `未找到条码 ${normalizedParent} 的 BOM 部件明细。`
: demandContext.message,
: demandContext.message
),
dataMode: 'LIVE',
dataAsOf: componentStockSyncAt?.toISOString() ?? null,
batchKey: componentSnapshotBatchKey,
generationSlot: componentSnapshotSlot,
},
}
} catch (cause) {
@ -3216,7 +3519,11 @@ export class ModularProductProcessingOrdersService {
sourceStatus: {
ready: false,
source: MODULAR_PROCESSING_BOM_SOURCE_NAME,
message: this.upstreamMessage(cause, 'bom'),
message: componentSnapshotFallbackMessage ?? this.upstreamMessage(cause, 'bom'),
dataMode: 'LIVE',
dataAsOf: null,
batchKey: componentSnapshotBatchKey,
generationSlot: componentSnapshotSlot,
},
}
}
@ -3233,4 +3540,6 @@ export const modularProductProcessingOrdersService =
modularProcessingSnapshotRepository,
loadComponentStockByBarcode,
modularProcessingWorkOrderRepository,
modularProcessingGenerationHealthService,
loadLatestComponentStockSyncAt,
)

View File

@ -88,6 +88,21 @@ export async function loadComponentStockByBarcode(): Promise<Map<string, number>
return loadStockByBarcode(COMPONENT_STOCK_ATTRIBUTE_KEYWORDS)
}
/** 当前部件库存来源的最近成功同步时间,用于旧批次实时回退提示。 */
export async function loadLatestComponentStockSyncAt() {
try {
const run = await prisma.productInventorySnapshotRun.findFirst({
where: { status: 'COMPLETED' },
orderBy: { completedAt: 'desc' },
select: { syncedAt: true, completedAt: true },
})
return run?.syncedAt ?? run?.completedAt ?? null
} catch (cause) {
console.error('[jianshang-stock] 读取库存同步时间失败', cause)
return null
}
}
async function loadStockByBarcode(
keywords: readonly string[],
): Promise<Map<string, number> | null> {

View File

@ -23,6 +23,9 @@ export function cabinetRecognitionPrompt(p:Omit<ReferenceImageEstimateInput,'ima
'用户明确给出适用于同类书柜的按柜宽下限摆腿规则时(如“100cm以上是5个腿,中间加一根”),在cabinetCorrection中另填legSupportRule:{minWidthMm:1000,positions:[{x,y},…]},阈值转换为mm且包含下限。positions为规则生效时的完整位置且只填x、y;本款单独指定的腿直径等尺寸不进这条规则。只有本款摆法时只填legSupports。未明确通用的条件或无法确定阈值时省略legSupportRule。',
'背板有无填hasBackPanel,看不清填null。明确分片可给backPanelCount(1–12)和backPanelSplit(上下或左右)。后拉板rearPullRail位置可填中层板下方、底板上方或无,明确高度填rearPullRailHeight;它和后横档、前踢脚板是不同零件。只说有拉板但位置不明填hasUnplacedPullRail=true。',
'如有本轮纠正,在cabinetCorrection对象只写本轮说明确定的字段,其他字段省略。不得从图或历史案例猜测纠正字段。“腿没生成”表示补上柜腿(hasLegs=true),只有明确要求去掉时填false。明确说一块后拉板、两块三合板并用抽槽安装,或两层带腿开放格书柜明确说“拉板+三合板,抽槽安装”且没有给出其他数量时,rearBackAssembly写“一块后拉板分隔两片槽装三合板”。只说“背板要做出来”则填hasBackPanel=true。不要拆成未定位拉板,不猜测工艺尺寸。仍返回cabinet和整体分类,若本轮否定了当前结构能力则由questions说明。',
...(p.correctionNote && !p.currentAssembly && p.currentModelParts?.some(part => part.code === '02' && part.name === '左旁板') ? [
'对于已有普通公式书柜,当用户明确要求 02 左旁板和/或 04 右旁板后下角开贯穿板厚的圆角缺口,在 cabinetCorrection.sideNotches 下用对应板号作为键,每块填 {depth, height, radius?},单位 mm。只返回指定旁板;半径未给可省略。09 是前踢脚板;不要当作开缺口的目标。前角、非贯穿或未明确部件及深高时先核对。该修改只对本款生效,无需 imageAssemblyEdit,也不要重新生成 imageAssembly。',
] : []),
...imageAssemblyInstructions(p),
`本轮纠正(产品说明):${JSON.stringify(p.correctionNote??'')}`,
...(p.currentModelParts ? [

Some files were not shown because too many files have changed in this diff Show More