Merge remote-tracking branch 'origin/codex/xuxiake-mainline' into codex/wuyongjie-production-stop-skip-liujinggang-20261126
This commit is contained in:
commit
a48d1e6682
@ -62,3 +62,17 @@ node scripts/daily-express-dashboard/run.mjs
|
||||
验证:11项页面/服务测试通过,覆盖默认全部日期、点击后应用筛选、恢复、零发货日、无效日期和同日 Excel 明细;相关生产文件 ESLint 通过。本地日期选择/发布测试3项通过。实际组件浏览器验证多日切换、恢复、零发货日及 1920×1080 / 390×844 布局;本地看板同样验证通过,现有已核对数据仍为 2026-11-24、7,908 单。
|
||||
|
||||
规范自审:passed。这是自审,不是独立复审。架构边界保留、控件沿用组件库、日期筛选和导出共用数据投影;筛选直接作用于日期数据,未用页面隐藏替代统计计算。线上生效须随共享主线变更合入生产 main 后部署。
|
||||
|
||||
## 2026-11-26:自动更新与未揽收异常分离
|
||||
|
||||
排查发现本机09:00任务在订单取数完成后因桌面仓库映射文件缺失失败,服务器原先仅迁入快照,尚未安装日更timer。现已安装并启用服务器 `furniture-daily-express.timer`,每日北京时间09:00执行,使用持久化映射,不依赖电脑桌面文件。确认服务器成功接管后停用旧Windows任务,避免重复发送。
|
||||
|
||||
用户确认新口径:承运量和区域正常更新;未揽收逐单核对,仅将本次核对成功且符合筛选条件的订单用于列表、导出及正常通知。缺少主表/明细、关联不一致或明细重复的候选进入独立异常清单,不视作无退款、不混入正常数据。正常通知和异常通知使用不同的每日发送记录,重试不会重复发送。
|
||||
|
||||
承运量先独立校验,再处理未揽收。个别订单异常时发布本次成功记录及异常摘要;整个未揽收查询失败时仍发布有效承运量,页面明确无本次已核对数据,不展示旧数据冒充本次;内部保留上次已校验快照仅供恢复。异常页不展示凭据或SQL。退款成功继续整单排除。
|
||||
|
||||
2026-11-25主承运量快照已在本机09:27完成且通过服务端规则校验,共7,365单(普通3,271、奇门4,094);和11月24日7,908单累计15,273单。首次服务器补跑因奇门订单10366147缺少商品明细被旧逻辑阻止;未改变源数据库,按上述新口径单独处理异常。
|
||||
|
||||
验证:39项数据/通知测试、13项页面/服务测试及TypeScript、相关ESLint通过;新增逐单隔离、退款成功仍剔除、完整审计损坏阻止读取、正常/异常通知独立去重等检查。实际组件桌面1920×1080、手机390×844验证本次记录与异常提示共存。
|
||||
|
||||
规范自审:passed。这是自审,不是独立复审。规则仍位于共享计算与服务层,数据权限及严格退款判断保留;页面沿用平台控件,只增加必要异常状态,修复单个异常阻断无关看板更新的问题。
|
||||
|
||||
@ -0,0 +1,8 @@
|
||||
ALTER TABLE "SupplyChainClearanceTask"
|
||||
ADD COLUMN "inventoryStockJianshang" INTEGER,
|
||||
ADD COLUMN "inventoryStockFactory" INTEGER,
|
||||
ADD COLUMN "inventoryTotalStock" INTEGER,
|
||||
ADD COLUMN "inventoryDailySales" DECIMAL(18, 4),
|
||||
ADD COLUMN "inventoryAvailableDays" TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN "inventoryBreakdown" JSONB,
|
||||
ADD COLUMN "inventoryUpdatedAt" TIMESTAMP(3);
|
||||
@ -0,0 +1,11 @@
|
||||
DROP INDEX IF EXISTS "SCClearanceTask_period_round_barcode_center_applicant_key";
|
||||
|
||||
CREATE UNIQUE INDEX "SCClearanceTask_period_round_barcode_center_applicant_owner_key"
|
||||
ON "SupplyChainClearanceTask"(
|
||||
"periodKey",
|
||||
"round",
|
||||
"barcode",
|
||||
"profitCenter",
|
||||
"submittedById",
|
||||
"ownerName"
|
||||
);
|
||||
@ -6538,6 +6538,13 @@ model SupplyChainClearanceTask {
|
||||
reviewedAt DateTime?
|
||||
rejectReason String @default("") @db.Text
|
||||
priorityOverride String @default("") @db.VarChar(50)
|
||||
inventoryStockJianshang Int?
|
||||
inventoryStockFactory Int?
|
||||
inventoryTotalStock Int?
|
||||
inventoryDailySales Decimal? @db.Decimal(18, 4)
|
||||
inventoryAvailableDays String @default("")
|
||||
inventoryBreakdown Json?
|
||||
inventoryUpdatedAt DateTime?
|
||||
clearedQty Int @default(0)
|
||||
lastProgressAt DateTime?
|
||||
revision Int @default(1)
|
||||
@ -6546,7 +6553,7 @@ model SupplyChainClearanceTask {
|
||||
events SupplyChainClearanceTaskEvent[]
|
||||
shipmentDaily SupplyChainClearanceTaskShipmentDaily[]
|
||||
|
||||
@@unique([periodKey, round, barcode, profitCenter, submittedById], map: "SCClearanceTask_period_round_barcode_center_applicant_key")
|
||||
@@unique([periodKey, round, barcode, profitCenter, submittedById, ownerName], map: "SCClearanceTask_period_round_barcode_center_applicant_owner_key")
|
||||
@@index([periodKey, status])
|
||||
@@index([barcode])
|
||||
@@index([profitCenter])
|
||||
|
||||
@ -29,9 +29,8 @@ const {pool,sql,schema}=require('./report-db-readonly.cjs');
|
||||
}
|
||||
}
|
||||
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);
|
||||
const {partitionRefundChecks}=await import('./refund.mjs');
|
||||
const {checked,exceptions}=partitionRefundChecks(snapshot.rows,audit,snapshot.summary.date);
|
||||
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}))}));
|
||||
console.log(JSON.stringify({stage:'refund_checks_complete',candidates:candidates.length,checked:checked.length,exceptions:exceptions.length,refundSuccess:checked.filter(row=>row.refund_success).length,retained:checked.filter(row=>!row.refund_success).length}));
|
||||
}catch(error){console.error(JSON.stringify({errorCode:error.code||error.message||error.name,number:error.number||null}));process.exitCode=1;}finally{await pool.close();}})();
|
||||
|
||||
@ -26,3 +26,18 @@ export function attachRefundChecks(rows,audit,date){
|
||||
}
|
||||
return rows.map(row=>checked.get(String(row.id))||row);
|
||||
}
|
||||
|
||||
export function partitionRefundChecks(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=[],exceptions=[];
|
||||
for(const row of candidates){
|
||||
try{checked.push(...attachRefundChecks([row],{...audit,candidates:[identity(row)]},date));}
|
||||
catch(error){
|
||||
if(!/^(?:REFUND_ORDER_NOT_FOUND_|REFUND_ITEMS_NOT_FOUND_|REFUND_ORDER_IDENTITY_MISMATCH_|INVALID_REFUND_ITEM|DUPLICATE_REFUND_ITEM)/.test(error.message))throw error;
|
||||
exceptions.push({id:String(row.id),inner_order_id:text(row.inner_order_id),logistic_id:text(row.logistic_id),logistic_company_name:text(row.logistic_company_name),warehouse_name:text(row.warehouse_name),errorCode:error.message});
|
||||
}
|
||||
}
|
||||
return {checked,exceptions};
|
||||
}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {attachRefundChecks} from './refund.mjs';
|
||||
import {attachRefundChecks,partitionRefundChecks} 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'}]});
|
||||
@ -23,3 +23,16 @@ 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'),[]);
|
||||
});
|
||||
|
||||
test('one missing item is isolated while current successful and refunded records remain correctly classified',()=>{
|
||||
const records=[...rows,{...rows[0],id:2,inner_order_id:'2',so_id:'S2',logistic_id:'L2'},{...rows[0],id:3,inner_order_id:'3',so_id:'S3',logistic_id:'L3'}];
|
||||
const data=audit();data.items[0].refund_status='';
|
||||
data.candidates.push({id:'2',o_id:'2',so_id:'S2',l_id:'L2'},{id:'3',o_id:'3',so_id:'S3',l_id:'L3'});
|
||||
data.masters.push({source:'jst_qmcust_orderlist',o_id:'2',so_id:'S2',l_id:'L2'},{source:'jst_Orders',o_id:'3',so_id:'S3',l_id:'L3'});
|
||||
data.items.push({source:'jst_OrderItem',o_id:'3',oi_id:'I3',refund_status:'success'});
|
||||
const result=partitionRefundChecks(records,data,'2026-11-24');
|
||||
assert.equal(result.exceptions.length,1);assert.equal(result.exceptions[0].inner_order_id,'2');assert.match(result.exceptions[0].errorCode,/ITEMS_NOT_FOUND/);
|
||||
assert.deepEqual(applyUncollectedRules(result.checked).map(row=>row.id),[1]);
|
||||
assert.throws(()=>attachRefundChecks(records,data,'2026-11-24'),/ITEMS_NOT_FOUND/);
|
||||
const corrupt=structuredClone(data);corrupt.candidates.pop();assert.throws(()=>partitionRefundChecks(records,corrupt,'2026-11-24'),/CANDIDATE_MISMATCH/);
|
||||
});
|
||||
|
||||
@ -6,8 +6,8 @@ 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';
|
||||
import {buildSnapshot,buildCarrierSnapshot,buildUncollectedSnapshot,readPreviousUncollected,retainPreviousUncollected,publishSnapshot} from './snapshot.mjs';
|
||||
import {deliverNotification,deliverExceptionNotification,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'));
|
||||
@ -43,25 +43,40 @@ try{
|
||||
}
|
||||
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});
|
||||
let built;
|
||||
if(seed)built=buildSnapshot(snapshots,await read(path.join(stage,'uncollected-source.json')),await read(path.join(stage,'uncollected-refund-checks.json')),mappings);
|
||||
else{
|
||||
const carrier=buildCarrierSnapshot(snapshots,mappings);
|
||||
try{
|
||||
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 {uncollected,uncollectedRefresh}=buildUncollectedSnapshot(await read(path.join(stage,'uncollected-source.json')),await read(path.join(stage,'uncollected-refund-checks.json')),target);
|
||||
validateNotificationReport(uncollected,{target,refreshedAfter:startedAt});
|
||||
built={...carrier,report:{...carrier.report,uncollected,...(uncollectedRefresh?{uncollectedRefresh}:{})}};
|
||||
}catch(error){
|
||||
built=retainPreviousUncollected(carrier,await readPreviousUncollected(directory),error);
|
||||
}
|
||||
}
|
||||
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'};
|
||||
let notification={status:'seed_not_sent'},exceptionNotification={status:'not_required'};
|
||||
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 refresh=built.report.uncollectedRefresh;
|
||||
if(refresh?.status!=='failed')notification=await deliverNotification({directory:path.join(directory,'notifications'),report:{...built.report.uncollected,exceptionCount:refresh?.exceptions.length||0},config});
|
||||
else notification={status:'not_sent_refresh_failed'};
|
||||
if(refresh)exceptionNotification=await deliverExceptionNotification({directory:path.join(directory,'notifications'),refresh,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()};
|
||||
const status={status:built.report.uncollectedRefresh?'partial':'success',date:target,generation:pointer.generation,total:built.report.overview.total,uncollected:built.report.uncollectedRefresh?.status==='failed'?null:built.report.uncollected.summary.total,uncollectedDate:built.report.uncollectedRefresh?.status==='failed'?null:built.report.uncollected.date,...(built.report.uncollectedRefresh?{errorCode:built.report.uncollectedRefresh.errorCode,exceptions:built.report.uncollectedRefresh.exceptions.length}:{}),notification,exceptionNotification,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));
|
||||
if(built.report.uncollectedRefresh?.status==='failed')process.exitCode=1;
|
||||
}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'));}}
|
||||
|
||||
@ -1,23 +1,54 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import {createHash,randomUUID} from 'node:crypto';
|
||||
import assert from 'node:assert/strict';
|
||||
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';
|
||||
import {partitionRefundChecks} 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 carrier=buildCarrierSnapshot(days,mappings);
|
||||
const {uncollected,uncollectedRefresh}=buildUncollectedSnapshot(source,refund,latest);
|
||||
return {...carrier,report:{...carrier.report,uncollected,...(uncollectedRefresh?{uncollectedRefresh}:{})}};
|
||||
}
|
||||
export function buildCarrierSnapshot(days,mappings){
|
||||
days.forEach(validateDayDetails);
|
||||
const latest=days.at(-1).date;
|
||||
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}};
|
||||
regional:{dates:facts.days,latestDate:latest,days:days.map(day=>buildRegionalDay(day,mappings))}};
|
||||
return {report,details};
|
||||
}
|
||||
export function buildUncollectedSnapshot(source,refund,latest){
|
||||
validateUncollected(source);
|
||||
if(source.summary.date!==latest||refund.sourceQueriedAt!==source.summary.queriedAt)throw new Error('SNAPSHOT_SOURCE_MISMATCH');
|
||||
const {checked,exceptions}=partitionRefundChecks(source.rows,refund,latest),rows=applyUncollectedRules(checked);
|
||||
return {uncollected:{date:latest,queriedAt:source.summary.queriedAt,refundCheckedAt:refund.completedAt,summary:summarizeUncollected(rows),columns:UNCOLLECTED_COLUMNS.map(([key,label])=>({key,label})),rows},
|
||||
...(exceptions.length?{uncollectedRefresh:{status:'partial',date:latest,attemptedAt:refund.completedAt,errorCode:'REFUND_RECORD_EXCEPTIONS',exceptions}}:{})};
|
||||
}
|
||||
export async function readPreviousUncollected(directory){
|
||||
const pointer=JSON.parse(await fs.readFile(path.join(directory,'latest.json'),'utf8'));
|
||||
if(!/^\d+-[a-f0-9-]+$/.test(pointer.generation))throw new Error('INVALID_PREVIOUS_GENERATION');
|
||||
const bytes=await fs.readFile(path.join(directory,'generations',pointer.generation,'report.json'));
|
||||
if(hash(bytes)!==pointer.reportHash)throw new Error('PREVIOUS_SNAPSHOT_CORRUPTED');
|
||||
const previous=JSON.parse(bytes).uncollected;
|
||||
validateUncollected({summary:{date:previous.date,queriedAt:previous.queriedAt,rowCount:previous.rows.length},rows:previous.rows});
|
||||
if(!Number.isFinite(Date.parse(previous.refundCheckedAt))||Date.parse(previous.refundCheckedAt)<Date.parse(previous.queriedAt)||!Array.isArray(previous.columns))throw new Error('INVALID_PREVIOUS_UNCOLLECTED');
|
||||
assert.deepEqual(applyUncollectedRules(previous.rows),previous.rows);
|
||||
assert.deepEqual(summarizeUncollected(previous.rows),previous.summary);
|
||||
return previous;
|
||||
}
|
||||
export function retainPreviousUncollected(carrier,previous,error){
|
||||
if(previous.date>carrier.report.dateTo)throw new Error('PREVIOUS_UNCOLLECTED_FROM_FUTURE');
|
||||
const code=String(error.code||error.message||error.name);
|
||||
return {...carrier,report:{...carrier.report,uncollected:previous,
|
||||
uncollectedRefresh:{status:'failed',date:carrier.report.dateTo,attemptedAt:new Date().toISOString(),errorCode:/^[A-Z0-9_]{1,160}$/.test(code)?code:'UNCOLLECTED_REFRESH_FAILED',exceptions:[]}}};
|
||||
}
|
||||
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;}
|
||||
|
||||
@ -5,7 +5,7 @@ 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';
|
||||
import {buildSnapshot,buildCarrierSnapshot,retainPreviousUncollected,readPreviousUncollected,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:[]};
|
||||
@ -17,3 +17,38 @@ test('published snapshots reconcile all views and refuse older dates',async()=>{
|
||||
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});}
|
||||
});
|
||||
|
||||
test('a failed pickup refresh preserves verified prior pickup while advancing carrier and regional dates',async()=>{
|
||||
const mapping={provinces:[{province:'江苏',region:'华东'}],warehouses:[{warehouse:'测试仓',origin:'常州自有仓'}]};
|
||||
const warehouse=[{co_id:'1',wms_co_id:'2',name:'测试仓'}];
|
||||
const day=date=>aggregateDay(date,[{o_id:date,so_id:'001',source:'jst_Orders',status:'Sent',send_date:date+' 10:00:00',l_id:'001234',logistics_company:'测试快递',receiver_state:'江苏',co_id:'1',wms_co_id:'2'}],warehouse);
|
||||
const first=day('2026-11-24'),second=day('2026-11-25'),queriedAt='2026-11-25T01:00:00Z';
|
||||
const initial=buildSnapshot([first],{summary:{date:first.date,queriedAt,rowCount:0},rows:[]},{version:'item-refund-success-v1',date:first.date,sourceQueriedAt:queriedAt,completedAt:queriedAt,candidates:[],masters:[],items:[]},mapping);
|
||||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'express-partial-'));
|
||||
try{
|
||||
await publishSnapshot(root,initial);
|
||||
const previous=await readPreviousUncollected(root);
|
||||
const next=retainPreviousUncollected(buildCarrierSnapshot([first,second],mapping),previous,new Error('REFUND_ITEMS_NOT_FOUND_10366147'));
|
||||
assert.deepEqual(next.report.overview.days,['2026-11-24','2026-11-25']);assert.equal(next.report.overview.total,2);
|
||||
assert.equal(next.report.regional.latestDate,'2026-11-25');assert.deepEqual(next.report.uncollected,initial.report.uncollected);
|
||||
assert.equal(next.report.uncollectedRefresh.date,'2026-11-25');assert.equal(next.report.uncollectedRefresh.errorCode,'REFUND_ITEMS_NOT_FOUND_10366147');
|
||||
await publishSnapshot(root,next);
|
||||
assert.deepEqual(await readPreviousUncollected(root),previous);
|
||||
assert.throws(()=>retainPreviousUncollected(buildCarrierSnapshot([first],mapping),{...previous,date:'2026-11-26'},new Error('FAIL')),/FROM_FUTURE/);
|
||||
const pointer=JSON.parse(await fs.readFile(path.join(root,'latest.json'),'utf8'));
|
||||
await fs.appendFile(path.join(root,'generations',pointer.generation,'report.json'),' ');
|
||||
await assert.rejects(()=>readPreviousUncollected(root),/CORRUPTED/);
|
||||
}finally{assert.equal(path.dirname(root),os.tmpdir());await fs.rm(root,{recursive:true,force:true});}
|
||||
});
|
||||
|
||||
test('the published current pickup includes verified rows and separately records incomplete orders',()=>{
|
||||
const date='2026-11-25',queriedAt='2026-11-26T01:00:00Z';
|
||||
const day=aggregateDay(date,[],[]);
|
||||
const records=[1,2].map(id=>({id,inner_order_id:String(id),so_id:'S'+id,logistic_id:'L'+id,logistic_company_name:'测试快递',warehouse_name:'测试仓',send_time:date+' 10:00:00',fetch_time:null,logistic_status_name:'未揽收',first_question_type:null,order_labels:null,remark:null}));
|
||||
const source={summary:{date,queriedAt,rowCount:2},rows:records};
|
||||
const audit={version:'item-refund-success-v1',date,sourceQueriedAt:queriedAt,completedAt:queriedAt,candidates:records.map(row=>({id:String(row.id),o_id:row.inner_order_id,so_id:row.so_id,l_id:row.logistic_id})),masters:records.map(row=>({source:'jst_qmcust_orderlist',o_id:row.inner_order_id,so_id:row.so_id,l_id:row.logistic_id})),items:[{source:'jst_qmcust_orderlist_item',o_id:'1',oi_id:'I1',refund_status:''}]};
|
||||
const built=buildSnapshot([aggregateDay('2026-11-24',[],[]),day],source,audit,{provinces:[{province:'江苏',region:'华东'}],warehouses:[{warehouse:'测试仓',origin:'常州'}]});
|
||||
assert.equal(built.report.uncollected.date,date);assert.deepEqual(built.report.uncollected.rows.map(row=>row.id),[1]);
|
||||
assert.equal(built.report.uncollected.summary.total,1);assert.equal(built.report.uncollectedRefresh.status,'partial');
|
||||
assert.equal(built.report.uncollectedRefresh.exceptions[0].inner_order_id,'2');assert.equal(built.report.overview.dateTo,date);
|
||||
});
|
||||
|
||||
@ -50,7 +50,7 @@ export async function readNotificationReport({root,output,target,now=new Date(),
|
||||
}
|
||||
|
||||
export function buildNotificationTexts(report,{keyword='',reviewedSnapshot=false}={}){
|
||||
const header=[`昨日未揽收订单提醒${reviewedSnapshot?'(已核对快照)':''}`,`发货日期:${report.date}`,`数据查询:${localTime(report.queriedAt)}(北京时间)`,`退款核对:${localTime(report.refundCheckedAt)}(北京时间)`,`未揽收:${report.rows.length} 单`].join('\n');
|
||||
const header=[`昨日未揽收订单提醒${reviewedSnapshot?'(已核对快照)':''}`,`发货日期:${report.date}`,`数据查询:${localTime(report.queriedAt)}(北京时间)`,`退款核对:${localTime(report.refundCheckedAt)}(北京时间)`,`${report.exceptionCount?'已核对成功的未揽收':'未揽收'}:${report.rows.length} 单`,...(report.exceptionCount?[`另有 ${report.exceptionCount} 条核对异常,单独推送。`]:[])].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;
|
||||
@ -84,7 +84,31 @@ export function buildNotificationTexts(report,{keyword='',reviewedSnapshot=false
|
||||
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'):'昨日无符合条件的未揽收订单。'));
|
||||
return groups.map((group,index)=>header+(groups.length>1?`\n第 ${index+1}/${groups.length} 条消息`:'')+'\n\n'+(group.length?group.join('\n\n'):(report.exceptionCount?'本次暂无已核对成功的未揽收订单。':'昨日无符合条件的未揽收订单。')));
|
||||
}
|
||||
|
||||
export function exceptionReason(code){
|
||||
if(code.startsWith('REFUND_ITEMS_NOT_FOUND_'))return '缺少商品明细,退款状态未核实';
|
||||
if(code.startsWith('REFUND_ORDER_NOT_FOUND_'))return '未找到源订单,退款状态未核实';
|
||||
if(code.startsWith('REFUND_ORDER_IDENTITY_MISMATCH_'))return '源订单与物流信息不一致';
|
||||
if(code==='INVALID_REFUND_ITEM')return '商品明细缺少退款核对字段';
|
||||
if(code==='DUPLICATE_REFUND_ITEM')return '商品明细重复,需核对';
|
||||
return '本次数据查询或校验未完成';
|
||||
}
|
||||
export function buildExceptionTexts(report,{keyword=''}={}){
|
||||
const header=`未揽收数据核对异常\n发货日期:${report.date}\n核对时间:${localTime(report.queriedAt)}(北京时间)\n${report.rows.length?`异常:${report.rows.length} 条,未计入正常未揽收明细。`:'本次数据更新未完成,未发送正常未揽收明细。'}`;
|
||||
const blocks=report.rows.map((row,index)=>`${index+1}. ERP内部订单号:${singleLine(row.inner_order_id)}\n快递单号:${singleLine(row.logistic_id)}\n快递名称:${singleLine(row.logistic_company_name)}\n发货仓库:${singleLine(row.warehouse_name)}\n异常原因:${exceptionReason(row.errorCode)}`);
|
||||
if(!blocks.length)blocks.push(exceptionReason(report.errorCode));
|
||||
const messages=[];let current=[];
|
||||
const fits=body=>Buffer.byteLength(header+'\n第 999999/999999 条消息\n\n'+body,'utf8')<=14000-Buffer.byteLength(keyword,'utf8');
|
||||
for(const block of blocks){if(!fits(block))throw fail('NOTIFICATION_ROW_TOO_LONG');if(current.length&&!fits([...current,block].join('\n\n'))){messages.push(current);current=[];}current.push(block);}
|
||||
if(current.length)messages.push(current);
|
||||
return messages.map((parts,i)=>header+(messages.length>1?`\n第 ${i+1}/${messages.length} 条消息`:'')+'\n\n'+parts.join('\n\n'));
|
||||
}
|
||||
export async function deliverExceptionNotification({refresh,now=new Date(),...options}){
|
||||
if(refresh.date!==businessYesterday(now)||!Number.isFinite(Date.parse(refresh.attemptedAt))||!Array.isArray(refresh.exceptions))throw fail('INVALID_EXCEPTION_REPORT');
|
||||
for(const row of refresh.exceptions)if(!row.id||!row.inner_order_id||!row.errorCode)throw fail('INVALID_EXCEPTION_ROW');
|
||||
return deliverNotification({...options,kind:'exceptions',deliveryRevision:'exceptions-v1',report:{date:refresh.date,queriedAt:refresh.attemptedAt,refundCheckedAt:refresh.attemptedAt,errorCode:refresh.errorCode,rows:refresh.exceptions}});
|
||||
}
|
||||
|
||||
export function validateRobotConfig(config){
|
||||
@ -142,8 +166,9 @@ async function lockDelivery(directory){
|
||||
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))}){
|
||||
export async function deliverNotification({directory,report,config,reviewedSnapshot=false,deliveryRevision='',kind='uncollected',transport=sendRobotText,pause=ms=>new Promise(resolve=>setTimeout(resolve,ms))}){
|
||||
validateRobotConfig(config);
|
||||
if(!['uncollected','exceptions'].includes(kind))throw fail('INVALID_NOTIFICATION_KIND');
|
||||
if(deliveryRevision&&!/^[a-z][a-z0-9-]{0,40}$/.test(deliveryRevision))throw fail('INVALID_NOTIFICATION_REVISION');
|
||||
const release=await lockDelivery(directory);
|
||||
try{
|
||||
@ -154,7 +179,7 @@ export async function deliverNotification({directory,report,config,reviewedSnaps
|
||||
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}))};
|
||||
state={version:1,format:kind==='exceptions'?'exceptions-v1':'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:(kind==='exceptions'?buildExceptionTexts: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.
|
||||
|
||||
@ -5,7 +5,7 @@ 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';
|
||||
import {validateNotificationReport,buildNotificationTexts,buildExceptionTexts,buildRobotRequest,deliverNotification,deliverExceptionNotification} 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});
|
||||
@ -14,6 +14,24 @@ const gate={target:'2026-11-24',now:new Date('2026-11-25T01:05:00Z'),refreshedAf
|
||||
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('successful current rows and exceptions use separate idempotent messages and receipts',async()=>{
|
||||
const value=report(1);value.exceptionCount=1;
|
||||
const refresh={status:'partial',date:value.date,attemptedAt:value.refundCheckedAt,errorCode:'REFUND_RECORD_EXCEPTIONS',exceptions:[{id:'2',inner_order_id:'10366147',logistic_id:'773453795323647',logistic_company_name:'异常测试快递',warehouse_name:'异常测试仓',errorCode:'REFUND_ITEMS_NOT_FOUND_10366147'}]};
|
||||
assert.match(buildNotificationTexts(value)[0],/已核对成功的未揽收:1 单/);
|
||||
assert.doesNotMatch(buildNotificationTexts(value)[0],/773453795323647/);
|
||||
const errorText=buildExceptionTexts({date:value.date,queriedAt:value.refundCheckedAt,rows:refresh.exceptions})[0];
|
||||
assert.match(errorText,/10366147/);assert.match(errorText,/缺少商品明细/);assert.match(errorText,/未计入正常未揽收明细/);
|
||||
await fixture(async directory=>{
|
||||
const messages=[],transport=async(_,text)=>{messages.push(text);return accepted();};
|
||||
await deliverNotification({directory,report:value,config,transport});
|
||||
await deliverExceptionNotification({directory,refresh,config,transport,now:gate.now});
|
||||
await deliverNotification({directory,report:value,config,transport});
|
||||
await deliverExceptionNotification({directory,refresh,config,transport,now:gate.now});
|
||||
assert.equal(messages.length,2);assert.match(messages[0],/昨日未揽收订单提醒/);assert.match(messages[1],/未揽收数据核对异常/);
|
||||
assert.deepEqual((await fs.readdir(directory)).sort(),['2026-11-24.exceptions-v1.json','2026-11-24.json']);
|
||||
});
|
||||
});
|
||||
|
||||
test('same carrier and warehouse share one tracking list, name and warehouse label',()=>{
|
||||
const value=report();validateNotificationReport(value,gate);
|
||||
const texts=buildNotificationTexts(value);
|
||||
|
||||
@ -113,9 +113,9 @@ async function main() {
|
||||
} finally {
|
||||
await pool.end()
|
||||
}
|
||||
console.log(`[clearance-daily] ${today} 前置数据已就绪,开始刷新清货库存和任务进度`)
|
||||
console.log(`[clearance-daily] ${today} 前置数据已就绪,开始刷新清货任务库存和任务进度`)
|
||||
await runClearanceProgress()
|
||||
console.log(`[clearance-daily] ${today} 清货库存和任务进度刷新完成`)
|
||||
console.log(`[clearance-daily] ${today} 清货任务库存和任务进度刷新完成`)
|
||||
}
|
||||
|
||||
void main().catch((error) => {
|
||||
|
||||
@ -16,9 +16,6 @@ async function main() {
|
||||
const dispatch = mode === 'followup-14'
|
||||
? await wecomReissueService.dispatchUnrespondedFollowup()
|
||||
: await wecomReissueService.dispatchDue(true)
|
||||
const deliveryAlerts = await wecomReissueService.dispatchDeliveryNodeAlerts({
|
||||
includeQa: mode === 'initial',
|
||||
})
|
||||
console.log(JSON.stringify({
|
||||
mode,
|
||||
syncedAt: sync.syncedAt,
|
||||
@ -31,7 +28,6 @@ async function main() {
|
||||
attempted: dispatch.attempted,
|
||||
created: dispatch.created,
|
||||
failures: dispatch.failures,
|
||||
deliveryNodeAlerts: deliveryAlerts,
|
||||
}))
|
||||
await prisma.$disconnect()
|
||||
}
|
||||
|
||||
@ -29,11 +29,11 @@ async function main() {
|
||||
))
|
||||
const results = []
|
||||
for (const periodKey of periods) {
|
||||
const poolMetrics = await supplyChainClearanceService.refreshClearanceDailyMetrics(
|
||||
const taskMetrics = await supplyChainClearanceService.refreshClearanceTaskDailyMetrics(
|
||||
periodKey,
|
||||
)
|
||||
const taskProgress = await supplyChainClearanceService.syncTaskProgress(periodKey)
|
||||
results.push({ ...taskProgress, poolMetrics })
|
||||
results.push({ ...taskProgress, taskMetrics })
|
||||
}
|
||||
console.log(JSON.stringify({ results }, null, 2))
|
||||
}
|
||||
|
||||
25
furniture-3d-system/src/app/s/[code]/route.ts
Normal file
25
furniture-3d-system/src/app/s/[code]/route.ts
Normal file
@ -0,0 +1,25 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { ErrorCode } from '@/server/core/errors'
|
||||
import { handleRequest, jsonError } from '@/server/core/response'
|
||||
import { checkShareAccessRateLimit } from '@/server/services/share-rate-limit.service'
|
||||
import { supplierReissueResponseService } from '@/server/services/supplier-reissue-response.service'
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
context: { params: Promise<{ code: string }> },
|
||||
) {
|
||||
return handleRequest(request, async (ctx) => {
|
||||
const { code } = await context.params
|
||||
const rateLimit = checkShareAccessRateLimit({
|
||||
token: `supplier-short-response:${code}`,
|
||||
forwardedFor: request.headers.get('x-forwarded-for'),
|
||||
realIp: request.headers.get('x-real-ip'),
|
||||
userAgent: request.headers.get('user-agent'),
|
||||
})
|
||||
if (rateLimit.limited) {
|
||||
return jsonError(ErrorCode.SYSTEM_RATE_LIMIT, '访问过于频繁,请稍后重试', 429, ctx.requestId)
|
||||
}
|
||||
const resolved = await supplierReissueResponseService.resolveShortPath(code)
|
||||
return NextResponse.redirect(new URL(resolved.path, request.nextUrl.origin), 307)
|
||||
}, { requireAuth: false })
|
||||
}
|
||||
@ -5,7 +5,7 @@ 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) }) } }) })) })
|
||||
...(url.includes('view=uncollected') ? { uncollected: report.uncollected, ...(report.uncollectedRefresh ? { uncollectedRefresh: { status: report.uncollectedRefresh.status, date: report.uncollectedRefresh.date, exceptions: report.uncollectedRefresh.exceptions.length, message: '本次有 1 条订单核对异常,列表展示本次已核对成功的数据,异常另行通知。' } } : {}) } : 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')
|
||||
@ -16,6 +16,18 @@ it('shows rolling totals without share or exclusions and switches to latest pick
|
||||
expect(screen.getByText(/发货日期:2026-11-24(最新)/)).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: '导出 Excel' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows this refresh successful rows with an explicit separate-exception notice', async () => {
|
||||
report.uncollectedRefresh = { status: 'partial', date: '2026-11-25', attemptedAt: '2026-11-26T01:00:00Z', errorCode: 'REFUND_RECORD_EXCEPTIONS', exceptions: [{ id: '2', inner_order_id: '10366147', logistic_id: '773453795323647', logistic_company_name: '测试快递', warehouse_name: '测试仓', errorCode: 'REFUND_ITEMS_NOT_FOUND_10366147' }] }
|
||||
report.uncollected.date = '2026-11-25'
|
||||
render(<DailyExpressVolumeView />); await screen.findByRole('table')
|
||||
expect(screen.queryByText(/订单核对异常/)).not.toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: '已发货未揽收看版' }))
|
||||
await screen.findByText(/订单核对异常/)
|
||||
expect(screen.getByRole('status')).toHaveTextContent('本次已核对成功的数据')
|
||||
expect(screen.getByRole('status')).toHaveTextContent('异常另行通知')
|
||||
expect(await screen.findByText('0012345678901234567890')).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: '发货地省份区域承运量' }))
|
||||
|
||||
@ -47,7 +47,7 @@ export function DailyExpressVolumeView() {
|
||||
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>
|
||||
<header className={styles.header}><div><h1>{titles[view]}</h1><p>{data ? `${data.uncollectedRefresh?.status === 'failed' ? '目标发货日期' : '最新发货日期'} ${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}
|
||||
@ -64,8 +64,9 @@ export function DailyExpressVolumeView() {
|
||||
<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}
|
||||
{data.canDownload ? <Button size="small" onClick={download} disabled={downloading || data.uncollectedRefresh?.status === 'failed'}><Download size={14} />{downloading ? '正在导出' : '导出 Excel'}</Button> : null}
|
||||
</div>
|
||||
{data.uncollectedRefresh ? <p role="status" className={styles.refreshWarning}>{data.uncollectedRefresh.date}:{data.uncollectedRefresh.message}</p> : null}
|
||||
{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}>
|
||||
|
||||
@ -75,3 +75,4 @@
|
||||
@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%}}
|
||||
.refreshWarning{padding:12px 14px;margin:0 0 16px;border:1px solid #e5d7b4;border-radius:7px;background:#fffaf0;color:#796037;font-size:12px;line-height:1.8}
|
||||
|
||||
@ -2,6 +2,8 @@
|
||||
|
||||
import type { Dispatch, FormEventHandler, SetStateAction } from 'react'
|
||||
import {
|
||||
DEFAULT_REISSUE_FALLBACK_OWNER,
|
||||
REISSUE_SUPPLIER_OWNER_GROUPS,
|
||||
reissueHasCallback,
|
||||
reissueStatus,
|
||||
reissueSupplier,
|
||||
@ -20,7 +22,10 @@ import type {
|
||||
WecomPublicConfig,
|
||||
} from './reissue-reminder.types'
|
||||
|
||||
const MENTION_OWNERS = ['雁兰', '东皇太一', '貂蝉', '郁雾']
|
||||
const MENTION_OWNERS = [
|
||||
...REISSUE_SUPPLIER_OWNER_GROUPS.map(([owner]) => owner),
|
||||
DEFAULT_REISSUE_FALLBACK_OWNER,
|
||||
]
|
||||
const NON_FACTORY_REASON_CATEGORIES = SUPPLIER_REASON_CATEGORY_GROUPS
|
||||
.find((group) => group.root === '非工厂原因')?.categories || []
|
||||
|
||||
@ -479,7 +484,7 @@ export function ReissueReminderDialogs(props: ReissueReminderDialogsProps) {
|
||||
rows={3}
|
||||
value={ownerUserIds}
|
||||
onChange={(event) => setOwnerUserIds(event.target.value)}
|
||||
placeholder="不知道可留空,系统会尝试按“雁兰、东皇太一、貂蝉”通讯录姓名自动查找"
|
||||
placeholder="不知道可留空,系统会尝试按跟单员通讯录姓名自动查找"
|
||||
/>
|
||||
</label>
|
||||
<div className={`${styles.handoverNote} ${styles.wide}`}>
|
||||
|
||||
@ -20,12 +20,12 @@ describe('clearance period lifecycle', () => {
|
||||
)).toBe(true)
|
||||
})
|
||||
|
||||
it('refreshes the previous and current period during the monthly settlement window', () => {
|
||||
it('refreshes previous, current and pre-generated next task periods', () => {
|
||||
expect(clearanceDailyRefreshPeriods(
|
||||
new Date('2026-12-02T02:45:00.000Z'),
|
||||
)).toEqual(['2026-11', '2026-12'])
|
||||
)).toEqual(['2026-11', '2026-12', '2027-01'])
|
||||
expect(clearanceDailyRefreshPeriods(
|
||||
new Date('2027-01-01T02:45:00.000Z'),
|
||||
)).toEqual(['2026-12', '2027-01'])
|
||||
)).toEqual(['2026-12', '2027-01', '2027-02'])
|
||||
})
|
||||
})
|
||||
|
||||
@ -47,5 +47,9 @@ export function clearanceDailyRefreshPeriods(now = new Date()) {
|
||||
const previousPeriod = `${previousMonth.getUTCFullYear()}-${String(
|
||||
previousMonth.getUTCMonth() + 1,
|
||||
).padStart(2, '0')}`
|
||||
return [previousPeriod, currentPeriod]
|
||||
const nextMonth = new Date(Date.UTC(year, month, 1))
|
||||
const nextPeriod = `${nextMonth.getUTCFullYear()}-${String(
|
||||
nextMonth.getUTCMonth() + 1,
|
||||
).padStart(2, '0')}`
|
||||
return [previousPeriod, currentPeriod, nextPeriod]
|
||||
}
|
||||
|
||||
@ -7,6 +7,8 @@ const regionalDay = z.object({ date: expressDate, total: count,
|
||||
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(),
|
||||
uncollectedRefresh: z.object({ status: z.enum(['partial', 'failed']), date: expressDate, attemptedAt: z.string().datetime(), errorCode: z.string(),
|
||||
exceptions: z.array(z.object({ id: z.string(), inner_order_id: z.string(), logistic_id: z.string(), logistic_company_name: z.string(), warehouse_name: z.string(), errorCode: z.string() })) }).optional(),
|
||||
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) }),
|
||||
@ -49,4 +51,5 @@ export function expressRegionalPivot(day: RegionalDay, origin: string) {
|
||||
return { carriers, rows: output, total }
|
||||
}
|
||||
export type ExpressReadState = { latestDate: string; updatedAt: string; dates: string[]; canDownload: boolean; view: ExpressQuery['view'];
|
||||
uncollectedRefresh?: { status: 'partial' | 'failed'; date: string; message: string; exceptions: number };
|
||||
overview?: ExpressSnapshot['overview']; regional?: { date: string; origins: RegionalDay['origins']; origin: string; pivot: ReturnType<typeof expressRegionalPivot> }; uncollected?: ExpressSnapshot['uncollected'] }
|
||||
|
||||
@ -1,12 +1,16 @@
|
||||
import {
|
||||
handoverOrders,
|
||||
DEFAULT_REISSUE_FALLBACK_OWNER,
|
||||
DEFAULT_REISSUE_SUPPLIER_OWNERS,
|
||||
REISSUE_SUPPLIER_OWNER_GROUPS,
|
||||
handoverOrders,
|
||||
REISSUE_PILOT_SUPPLIERS,
|
||||
REISSUE_QUALIFYING_OVERTIME_TYPES,
|
||||
reissueOwnerForSupplier,
|
||||
reissueSupplierNames,
|
||||
reissueStatus,
|
||||
followupState,
|
||||
followupDashboardStats,
|
||||
reissueHasSupplierFeedback,
|
||||
samePersonName,
|
||||
type FollowupRecord,
|
||||
type ReissueRecord,
|
||||
@ -28,6 +32,24 @@ describe('purchase legacy module rules', () => {
|
||||
))
|
||||
})
|
||||
|
||||
it('uses the requested owner groups and assigns unknown suppliers to 昭君', () => {
|
||||
expect(Object.fromEntries(
|
||||
REISSUE_SUPPLIER_OWNER_GROUPS.map(([owner, suppliers]) => [owner, suppliers.length]),
|
||||
)).toMatchObject({
|
||||
雁兰: 36,
|
||||
东皇太一: 40,
|
||||
徐祯卿: 26,
|
||||
貂蝉: 26,
|
||||
千里眼: 18,
|
||||
})
|
||||
expect(DEFAULT_REISSUE_FALLBACK_OWNER).toBe('昭君')
|
||||
expect(DEFAULT_REISSUE_SUPPLIER_OWNERS['沐蕴佳']).toBe('东皇太一')
|
||||
expect(DEFAULT_REISSUE_SUPPLIER_OWNERS['河北浚璐']).toBe('千里眼')
|
||||
expect(DEFAULT_REISSUE_SUPPLIER_OWNERS['徐州苏夏世纪商']).toBe('千里眼')
|
||||
expect(Object.values(DEFAULT_REISSUE_SUPPLIER_OWNERS)).not.toContain('郁雾')
|
||||
expect(reissueOwnerForSupplier('不在名单供应商', DEFAULT_REISSUE_SUPPLIER_OWNERS)).toBe('昭君')
|
||||
})
|
||||
|
||||
it('calculates reminder status from the migrated 48h and 24h rules', () => {
|
||||
const base: ReissueRecord = {
|
||||
id: 'rr-1',
|
||||
@ -47,6 +69,25 @@ describe('purchase legacy module rules', () => {
|
||||
expect(followupState({ ...base, dueDate: '2026-11-30' }, '2026-11-16').key).toBe('green')
|
||||
})
|
||||
|
||||
it('recognizes legacy and current supplier feedback fields as already filled', () => {
|
||||
expect(reissueHasSupplierFeedback({
|
||||
id: 'legacy',
|
||||
supplierReasonCategory: '工厂原因-原材料供应异常(质量/交期)',
|
||||
})).toBe(true)
|
||||
expect(reissueHasSupplierFeedback({
|
||||
id: 'pending-review',
|
||||
feedbackStatus: '待跟单员判定',
|
||||
})).toBe(true)
|
||||
expect(reissueHasSupplierFeedback({
|
||||
id: 'solution-only',
|
||||
supplierSolution: '已安排补发',
|
||||
})).toBe(true)
|
||||
expect(reissueHasSupplierFeedback({
|
||||
id: 'unfilled',
|
||||
feedbackStatus: '待处理',
|
||||
})).toBe(false)
|
||||
})
|
||||
|
||||
it('includes unfinished orders due before the handover return date', () => {
|
||||
const records: FollowupRecord[] = [
|
||||
{ id: '1', owner: '昭君', orderNo: 'A', dueDate: '2026-11-18' },
|
||||
|
||||
@ -15,8 +15,9 @@ export const REISSUE_PILOT_SUPPLIERS = [
|
||||
'博曼特',
|
||||
'欣亿航家居',
|
||||
] as const
|
||||
export const DEFAULT_REISSUE_FALLBACK_OWNER = '昭君'
|
||||
|
||||
const REISSUE_SUPPLIER_OWNER_GROUPS: Array<[string, string[]]> = [
|
||||
export const REISSUE_SUPPLIER_OWNER_GROUPS: Array<[string, string[]]> = [
|
||||
['雁兰', [
|
||||
'双爱家私', '临沂恒思', '浩林木业', '恒菏', '嘉木盛源', '兰考华兰家具',
|
||||
'铭星智能家居', '木町工艺品', '青岛华泽', '青岛弢森', '三洋木业', '森百禾',
|
||||
@ -29,12 +30,12 @@ const REISSUE_SUPPLIER_OWNER_GROUPS: Array<[string, string[]]> = [
|
||||
'海格', '金太阳', '双伟办公', '优创包装', '河北顾顾家居', '众隆包装',
|
||||
'博曼特', '常州安裕', '格林家具', '曹县天山', '曹县鑫顺', '曹县玥畅涵',
|
||||
'山东成武三木', '山东瑞敏', '曹县汉信', '曹县松达', '曹县玥涵', '菏泽顺杰',
|
||||
'山东精尚', '智杰家居', '金尔威', '淼缘家具', '源沃家具', '春霖木制品',
|
||||
'山东精尚', '智杰家居', '金尔威', '森缘家具', '淼缘家具', '源沃家具', '春霖木制品',
|
||||
'菏泽荣淼', '曹县宇诺', '曹县久力', '曹县君御阁', '定陶中亿', '菏泽艺居阁',
|
||||
'曹县鼎端', '曹县鑫鑫', '曹县优润', '定陶琴韵', '定陶森特', '菏泽金信',
|
||||
'菏泽钦诺', '泉隆家居',
|
||||
'曹县鼎端', '曹县鑫鑫', '曹县优润', '定陶琴韵', '定陶森特', '沐蕴佳',
|
||||
'菏泽金信', '菏泽钦诺', '泉隆家居',
|
||||
]],
|
||||
['郁雾', [
|
||||
['徐祯卿', [
|
||||
'弘远', '凯罗', '闻其', '翧盛家具', '恒基', '恒鑫', '铭远', '木缘居',
|
||||
'三鑫', '盈志', '公牛电器', '合创家具', '上海恩幽', '许世家具', '曹县露娜',
|
||||
'艾家源木', '大志', '河南乐达', '河南宁基', '横林松法', '虎帝', '佳印图文',
|
||||
@ -47,6 +48,11 @@ const REISSUE_SUPPLIER_OWNER_GROUPS: Array<[string, string[]]> = [
|
||||
'河北雅柏', '菏泽顺帆', '简阔', '杰越', '苏州贝格迪派', '临沂卿德客',
|
||||
'郯城祥和', '欣亿航家居', '越子涵', '浙江茗悦',
|
||||
]],
|
||||
['千里眼', [
|
||||
'霸州浩浦', '霸州四强', '浩远', '河北森卓/霸州四强', '文昊', '亿之航',
|
||||
'霸州锦辉', '常州缔格', '常州富来居', '常州金艺来', '福建顺安', '河北江三',
|
||||
'河北浚璐', '河北鑫木', '江西迈当家具', '江西名屋居', '韦尔勒斯', '徐州苏夏世纪商',
|
||||
]],
|
||||
]
|
||||
|
||||
export const DEFAULT_REISSUE_SUPPLIER_OWNERS = Object.freeze(
|
||||
@ -291,6 +297,25 @@ export function reissueHasCallback(record: ReissueRecord) {
|
||||
return Boolean(textValue(record.supplierReissueNo || record.trackingNo || record.callbackAt || record.repliedAt))
|
||||
}
|
||||
|
||||
export function reissueHasSupplierFeedback(record: ReissueRecord) {
|
||||
const feedbackStatus = textValue(record.feedbackStatus)
|
||||
return Boolean(
|
||||
textValue(record.supplierRespondedAt)
|
||||
|| textValue(record.supplierReasonCategory)
|
||||
|| textValue(record.supplierSolution)
|
||||
|| textValue(record.supplierExpectedSolveDate)
|
||||
|| ['供应商已反馈', '待跟单员判定', '跟单员已判定'].includes(feedbackStatus),
|
||||
)
|
||||
}
|
||||
|
||||
export function reissueOwnerForSupplier(
|
||||
supplier: string,
|
||||
supplierOwners: Record<string, string>,
|
||||
) {
|
||||
const normalizedSupplier = textValue(supplier)
|
||||
return textValue(supplierOwners[normalizedSupplier]) || DEFAULT_REISSUE_FALLBACK_OWNER
|
||||
}
|
||||
|
||||
export function reissueSupplierNames(
|
||||
records: readonly ReissueRecord[],
|
||||
additionalSuppliers: readonly string[] = [],
|
||||
|
||||
75
furniture-3d-system/src/lib/wecom-reissue-message.test.ts
Normal file
75
furniture-3d-system/src/lib/wecom-reissue-message.test.ts
Normal file
@ -0,0 +1,75 @@
|
||||
import {
|
||||
buildFollowupSupplierMessages,
|
||||
buildInitialSupplierDigestMessages,
|
||||
} from './wecom-reissue-message'
|
||||
|
||||
describe('wecom reissue message formatting', () => {
|
||||
it('groups supplier links under one follow-up owner and paginates without splitting links', () => {
|
||||
const suppliers = Array.from({ length: 18 }, (_, index) => ({
|
||||
supplier: `供应商${String(index + 1).padStart(2, '0')}`,
|
||||
count: index + 1,
|
||||
link: `https://cp.jiansun.vip/s/LINK${String(index + 1).padStart(6, '0')}`,
|
||||
}))
|
||||
const messages = buildInitialSupplierDigestMessages({
|
||||
owner: '雁兰',
|
||||
suppliers,
|
||||
maxBytes: 900,
|
||||
})
|
||||
|
||||
expect(messages.length).toBeGreaterThan(1)
|
||||
expect(messages[0]).toContain('【10:00|供应商填报 · 1/')
|
||||
expect(messages.join('\n')).toContain('跟单员:@雁兰')
|
||||
suppliers.forEach((supplier) => {
|
||||
expect(messages.join('\n')).toContain(supplier.link)
|
||||
})
|
||||
messages.forEach((message) => {
|
||||
expect(Buffer.byteLength(message, 'utf8')).toBeLessThanOrEqual(900)
|
||||
expect(message).not.toMatch(/https:\/\/cp\.jiansun\.vip\/s\/\n/)
|
||||
})
|
||||
})
|
||||
|
||||
it('omits order details by default and shows only supplier-level totals', () => {
|
||||
const messages = buildFollowupSupplierMessages({
|
||||
owner: '貂蝉',
|
||||
excludedCount: 12,
|
||||
suppliers: [{
|
||||
supplier: '双爱家私',
|
||||
link: 'https://cp.jiansun.vip/s/ABCDEFGHJK',
|
||||
orders: Array.from({ length: 13 }, (_, index) => ({
|
||||
orderNo: `SO-${index + 1}`,
|
||||
overtimeType: '超平台时效',
|
||||
})),
|
||||
}],
|
||||
maxOrdersPerSection: 10,
|
||||
maxBytes: 1_200,
|
||||
})
|
||||
|
||||
expect(messages.join('\n')).toContain('未填写:13 条')
|
||||
expect(messages.join('\n')).toContain('已填写剔除:12 条')
|
||||
expect(messages.join('\n')).toContain('双爱家私|未填 13 条')
|
||||
expect(messages.join('\n')).not.toContain('SO-1')
|
||||
})
|
||||
|
||||
it('can include order details with ten orders per section when explicitly enabled', () => {
|
||||
const messages = buildFollowupSupplierMessages({
|
||||
owner: '貂蝉',
|
||||
excludedCount: 12,
|
||||
suppliers: [{
|
||||
supplier: '双爱家私',
|
||||
link: 'https://cp.jiansun.vip/s/ABCDEFGHJK',
|
||||
orders: Array.from({ length: 13 }, (_, index) => ({
|
||||
orderNo: `SO-${index + 1}`,
|
||||
overtimeType: '超平台时效',
|
||||
})),
|
||||
}],
|
||||
showOrderDetails: true,
|
||||
maxOrdersPerSection: 10,
|
||||
maxBytes: 1_200,
|
||||
})
|
||||
|
||||
expect(messages.join('\n')).toContain('双爱家私(1/2)')
|
||||
expect(messages.join('\n')).toContain('双爱家私(2/2)')
|
||||
expect(messages.join('\n')).toContain('10. SO-10|超平台时效')
|
||||
expect(messages.join('\n')).toContain('11. SO-11|超平台时效')
|
||||
})
|
||||
})
|
||||
154
furniture-3d-system/src/lib/wecom-reissue-message.ts
Normal file
154
furniture-3d-system/src/lib/wecom-reissue-message.ts
Normal file
@ -0,0 +1,154 @@
|
||||
const DEFAULT_MAX_BYTES = 1_750
|
||||
|
||||
export type InitialSupplierDigestItem = {
|
||||
supplier: string
|
||||
count: number
|
||||
link: string
|
||||
}
|
||||
|
||||
export type FollowupOrderItem = {
|
||||
orderNo: string
|
||||
overtimeType: string
|
||||
}
|
||||
|
||||
export type FollowupSupplierItem = {
|
||||
supplier: string
|
||||
orders: FollowupOrderItem[]
|
||||
link: string
|
||||
}
|
||||
|
||||
type PageSection = {
|
||||
text: string
|
||||
}
|
||||
|
||||
function byteLength(value: string) {
|
||||
return Buffer.byteLength(value, 'utf8')
|
||||
}
|
||||
|
||||
function paginateSections(
|
||||
sections: PageSection[],
|
||||
buildHeader: (page: number, total: number) => string,
|
||||
maxBytes: number,
|
||||
) {
|
||||
if (!sections.length) return []
|
||||
const pages: PageSection[][] = []
|
||||
let current: PageSection[] = []
|
||||
for (const section of sections) {
|
||||
const candidate = [...current, section]
|
||||
const candidateText = [
|
||||
buildHeader(99, 99),
|
||||
...candidate.map((item) => item.text),
|
||||
].join('\n\n')
|
||||
if (current.length && byteLength(candidateText) > maxBytes) {
|
||||
pages.push(current)
|
||||
current = [section]
|
||||
continue
|
||||
}
|
||||
current = candidate
|
||||
}
|
||||
if (current.length) pages.push(current)
|
||||
|
||||
return pages.map((page, index) => {
|
||||
const text = [
|
||||
buildHeader(index + 1, pages.length),
|
||||
...page.map((item) => item.text),
|
||||
].join('\n\n')
|
||||
if (byteLength(text) > maxBytes) {
|
||||
throw new Error(`企业微信消息分页超出 ${maxBytes} 字节限制`)
|
||||
}
|
||||
return text
|
||||
})
|
||||
}
|
||||
|
||||
export function buildInitialSupplierDigestMessages(input: {
|
||||
owner: string
|
||||
suppliers: InitialSupplierDigestItem[]
|
||||
maxBytes?: number
|
||||
}) {
|
||||
const owner = input.owner.trim() || '未分配跟单员'
|
||||
const suppliers = input.suppliers
|
||||
.filter((item) => item.supplier && item.count > 0 && item.link)
|
||||
.slice()
|
||||
.sort((left, right) => left.supplier.localeCompare(right.supplier, 'zh-CN'))
|
||||
if (!suppliers.length) return []
|
||||
const totalOrders = suppliers.reduce((sum, item) => sum + item.count, 0)
|
||||
const sections = suppliers.map((item, index) => ({
|
||||
text: [
|
||||
`${index + 1}/${suppliers.length} ${item.supplier}(${item.count} 条)`,
|
||||
`填写链接:${item.link}`,
|
||||
].join('\n'),
|
||||
}))
|
||||
return paginateSections(
|
||||
sections,
|
||||
(page, total) => [
|
||||
`【10:00|供应商填报 · ${page}/${total}】`,
|
||||
`跟单员:@${owner}`,
|
||||
`供应商:${suppliers.length} 家|待填明细:${totalOrders} 条`,
|
||||
].join('\n'),
|
||||
input.maxBytes || DEFAULT_MAX_BYTES,
|
||||
)
|
||||
}
|
||||
|
||||
export function buildFollowupSupplierMessages(input: {
|
||||
owner: string
|
||||
suppliers: FollowupSupplierItem[]
|
||||
excludedCount: number
|
||||
includeWeekend?: boolean
|
||||
maxOrdersPerSection?: number
|
||||
maxBytes?: number
|
||||
showOrderDetails?: boolean
|
||||
}) {
|
||||
const owner = input.owner.trim() || '未分配跟单员'
|
||||
const suppliers = input.suppliers
|
||||
.filter((item) => item.supplier && item.orders.length > 0 && item.link)
|
||||
.slice()
|
||||
.sort((left, right) => left.supplier.localeCompare(right.supplier, 'zh-CN'))
|
||||
if (!suppliers.length) return []
|
||||
|
||||
const totalOrders = suppliers.reduce((sum, item) => sum + item.orders.length, 0)
|
||||
const maxOrdersPerSection = Math.max(1, input.maxOrdersPerSection || 10)
|
||||
const sections: PageSection[] = []
|
||||
suppliers.forEach((supplier) => {
|
||||
if (!input.showOrderDetails) {
|
||||
sections.push({
|
||||
text: [
|
||||
`${supplier.supplier}|未填 ${supplier.orders.length} 条`,
|
||||
`填写链接:${supplier.link}`,
|
||||
].join('\n'),
|
||||
})
|
||||
return
|
||||
}
|
||||
const chunks = Array.from(
|
||||
{ length: Math.ceil(supplier.orders.length / maxOrdersPerSection) },
|
||||
(_, index) => supplier.orders.slice(
|
||||
index * maxOrdersPerSection,
|
||||
(index + 1) * maxOrdersPerSection,
|
||||
),
|
||||
)
|
||||
chunks.forEach((orders, chunkIndex) => {
|
||||
const continuation = chunks.length > 1
|
||||
? `(${chunkIndex + 1}/${chunks.length})`
|
||||
: ''
|
||||
sections.push({
|
||||
text: [
|
||||
`${supplier.supplier}${continuation}|未填 ${supplier.orders.length} 条`,
|
||||
...orders.map((order, index) =>
|
||||
`${chunkIndex * maxOrdersPerSection + index + 1}. ${order.orderNo || '未填订单号'}|${order.overtimeType || '未填超时类型'}`,
|
||||
),
|
||||
`填写链接:${supplier.link}`,
|
||||
].join('\n'),
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
return paginateSections(
|
||||
sections,
|
||||
(page, total) => [
|
||||
`【14:00|未填写催办 · ${page}/${total}】`,
|
||||
`跟单员:@${owner}`,
|
||||
`待催供应商:${suppliers.length} 家|未填写:${totalOrders} 条|已填写剔除:${input.excludedCount} 条`,
|
||||
...(input.includeWeekend ? ['说明:本清单已补入周六、周日异常订单。'] : []),
|
||||
].join('\n'),
|
||||
input.maxBytes || DEFAULT_MAX_BYTES,
|
||||
)
|
||||
}
|
||||
@ -6,6 +6,11 @@ describe('proxy public path guard', () => {
|
||||
expect(isPublicPath('/internal/asset-thumbnail?foo=bar')).toBe(true)
|
||||
})
|
||||
|
||||
it('allows supplier short response links without login', () => {
|
||||
expect(isPublicPath('/s/ABCDEFGHJK')).toBe(true)
|
||||
expect(isPublicPath('/s/ABCDEFGHJK?source=wecom')).toBe(true)
|
||||
})
|
||||
|
||||
it('does not treat the legacy non-integrated asset prefix as a public route', () => {
|
||||
expect(isPublicPath('/non-integrated-test-assets')).toBe(false)
|
||||
expect(isPublicPath('/non-integrated-test-assets/demo.pdf')).toBe(false)
|
||||
|
||||
@ -28,6 +28,7 @@ export const publicPaths = [
|
||||
'/share',
|
||||
'/installation-demo-share',
|
||||
'/supplier-response',
|
||||
'/s',
|
||||
'/internal/asset-thumbnail',
|
||||
'/api/auth/login',
|
||||
'/api/auth/register',
|
||||
|
||||
@ -181,6 +181,7 @@ describe('supply-chain-discontinuation-source repository', () => {
|
||||
barcode: 'CTG003028N277V01',
|
||||
qty: 1,
|
||||
orderLock: 0,
|
||||
cloudAvailable: 0,
|
||||
warehouseName: '简尚-新苏北仓',
|
||||
warehouseType: '成品发货仓-真实库存',
|
||||
},
|
||||
@ -188,6 +189,7 @@ describe('supply-chain-discontinuation-source repository', () => {
|
||||
barcode: 'CTG003028N277V01',
|
||||
qty: 152,
|
||||
orderLock: 0,
|
||||
cloudAvailable: 0,
|
||||
warehouseName: '简尚-运营G新苏北专用仓',
|
||||
warehouseType: '成品专用仓-真实库存(不可释放)',
|
||||
},
|
||||
@ -195,6 +197,7 @@ describe('supply-chain-discontinuation-source repository', () => {
|
||||
barcode: 'CTG003028N277V01',
|
||||
qty: 9,
|
||||
orderLock: 2,
|
||||
cloudAvailable: 0,
|
||||
warehouseName: '简尚-运营A可释放仓',
|
||||
warehouseType: '成品专用仓-真实库存(可释放)',
|
||||
},
|
||||
@ -202,6 +205,7 @@ describe('supply-chain-discontinuation-source repository', () => {
|
||||
barcode: 'CTG003028N277V01',
|
||||
qty: 100,
|
||||
orderLock: 0,
|
||||
cloudAvailable: 0,
|
||||
warehouseName: '云仓-示例仓',
|
||||
warehouseType: '开通云仓',
|
||||
},
|
||||
@ -232,6 +236,41 @@ describe('supply-chain-discontinuation-source repository', () => {
|
||||
expect(String(request.query.mock.calls[0][0])).not.toContain('OPENQUERY')
|
||||
})
|
||||
|
||||
it('subtracts cloud available stock from the matching actual warehouse', async () => {
|
||||
const request = {
|
||||
input: jest.fn().mockReturnThis(),
|
||||
query: jest.fn().mockResolvedValue({
|
||||
recordset: [{
|
||||
barcode: 'CTG003027N277V01',
|
||||
qty: 134,
|
||||
orderLock: 0,
|
||||
cloudAvailable: 100,
|
||||
warehouseName: '简尚-新苏北仓',
|
||||
warehouseType: '成品发货仓-真实库存',
|
||||
}],
|
||||
}),
|
||||
}
|
||||
const pool = {
|
||||
request: jest.fn(() => request),
|
||||
}
|
||||
;(repository as unknown as {
|
||||
getPool: () => Promise<typeof pool>
|
||||
}).getPool = jest.fn().mockResolvedValue(pool)
|
||||
|
||||
await expect(repository.listClearanceWarehouseInventoryByBarcodes([
|
||||
'CTG003027N277V01',
|
||||
])).resolves.toEqual([{
|
||||
barcode: 'CTG003027N277V01',
|
||||
bigWarehouseStock: 34,
|
||||
frontWarehouseStock: 0,
|
||||
dedicatedWarehouseStock: 0,
|
||||
dropshipStock: 0,
|
||||
}])
|
||||
const query = String(request.query.mock.calls[0][0])
|
||||
expect(query).toContain('jst_virtualstockStocksInfo')
|
||||
expect(query).toContain('order_able_qty')
|
||||
})
|
||||
|
||||
it('keeps non-releasable attributes in discontinuation inventory SQL', async () => {
|
||||
const request = {
|
||||
input: jest.fn().mockReturnThis(),
|
||||
|
||||
@ -1944,6 +1944,54 @@ class SupplyChainClearanceRepository {
|
||||
return updates.length
|
||||
}
|
||||
|
||||
async updateTaskDailyMetrics(input: {
|
||||
periodKey: string
|
||||
updates: Array<{
|
||||
barcode: string
|
||||
stockJianshang: number
|
||||
stockFactory: number
|
||||
totalStock: number
|
||||
dailySales: string | null
|
||||
availableDays: string
|
||||
breakdown: Record<string, unknown>
|
||||
updatedAt: Date
|
||||
}>
|
||||
}) {
|
||||
if (!input.updates.length) return 0
|
||||
let updated = 0
|
||||
for (let offset = 0; offset < input.updates.length; offset += 1000) {
|
||||
const rows = input.updates.slice(offset, offset + 1000).map((update) => ({
|
||||
...update,
|
||||
updatedAt: update.updatedAt.toISOString(),
|
||||
}))
|
||||
updated += await prisma.$executeRaw(Prisma.sql`
|
||||
UPDATE "SupplyChainClearanceTask" AS task
|
||||
SET
|
||||
"inventoryStockJianshang" = metrics."stockJianshang",
|
||||
"inventoryStockFactory" = metrics."stockFactory",
|
||||
"inventoryTotalStock" = metrics."totalStock",
|
||||
"inventoryDailySales" = metrics."dailySales"::numeric,
|
||||
"inventoryAvailableDays" = metrics."availableDays",
|
||||
"inventoryBreakdown" = metrics."breakdown",
|
||||
"inventoryUpdatedAt" = metrics."updatedAt"::timestamp(3),
|
||||
"updatedAt" = CURRENT_TIMESTAMP
|
||||
FROM jsonb_to_recordset(${JSON.stringify(rows)}::jsonb) AS metrics(
|
||||
"barcode" text,
|
||||
"stockJianshang" integer,
|
||||
"stockFactory" integer,
|
||||
"totalStock" integer,
|
||||
"dailySales" text,
|
||||
"availableDays" text,
|
||||
"breakdown" jsonb,
|
||||
"updatedAt" text
|
||||
)
|
||||
WHERE task."periodKey" = ${input.periodKey}
|
||||
AND task."barcode" = metrics."barcode"
|
||||
`)
|
||||
}
|
||||
return updated
|
||||
}
|
||||
|
||||
async listTaskShipmentCoverage(taskIds: string[]) {
|
||||
const ids = Array.from(new Set(taskIds.map((id) => id.trim()).filter(Boolean)))
|
||||
if (!ids.length) return []
|
||||
|
||||
@ -423,7 +423,8 @@ class SupplyChainDiscontinuationSourceRepository {
|
||||
}
|
||||
|
||||
/**
|
||||
* 清货池库存拆项。四类仓库互斥,全部使用公有可用数(qty - order_lock);
|
||||
* 清货池库存拆项。四类仓库互斥,全部使用公有可用数
|
||||
* (qty - order_lock - 同实际仓的云仓 order_able_qty);
|
||||
* 大货、前置、专用仓保留负数参与汇总,代发仓负数按 0:
|
||||
* 数据源:JianSun_Old.JianSun.dbo.jst_inventoryInfo_view,避免报表库同步延迟。
|
||||
* - 前置仓:南昌樵舍仓
|
||||
@ -444,24 +445,53 @@ class SupplyChainDiscontinuationSourceRepository {
|
||||
barcode: string
|
||||
qty: number | null
|
||||
orderLock: number | null
|
||||
cloudAvailable: number | null
|
||||
warehouseName: string | null
|
||||
warehouseType: string | null
|
||||
}>(`
|
||||
WITH input_codes AS (
|
||||
SELECT UPPER(LTRIM(RTRIM([value]))) AS barcode
|
||||
FROM OPENJSON(@codes)
|
||||
),
|
||||
inventory_rows AS (
|
||||
SELECT
|
||||
UPPER(LTRIM(RTRIM(CAST(inventory.sku_id AS varchar(200))))) AS barcode,
|
||||
inventory.wms_co_id AS warehouseId,
|
||||
SUM(CAST(ISNULL(inventory.qty, 0) AS int)) AS qty,
|
||||
SUM(CAST(ISNULL(inventory.order_lock, 0) AS int)) AS orderLock
|
||||
FROM [JianSun_Old].[JianSun].[dbo].[jst_inventoryInfo_view] inventory
|
||||
INNER JOIN input_codes codes
|
||||
ON codes.barcode = UPPER(LTRIM(RTRIM(CAST(inventory.sku_id AS varchar(200)))))
|
||||
GROUP BY
|
||||
UPPER(LTRIM(RTRIM(CAST(inventory.sku_id AS varchar(200))))),
|
||||
inventory.wms_co_id
|
||||
),
|
||||
cloud_rows AS (
|
||||
SELECT
|
||||
UPPER(LTRIM(RTRIM(CAST(virtualStock.sku_id AS varchar(200))))) AS barcode,
|
||||
virtualStock.wms_co_id AS warehouseId,
|
||||
SUM(CAST(ISNULL(virtualStock.order_able_qty, 0) AS int)) AS cloudAvailable
|
||||
FROM [JianSun_Old].[JianSun].[dbo].[jst_virtualstockStocksInfo] virtualStock
|
||||
INNER JOIN input_codes codes
|
||||
ON codes.barcode = UPPER(LTRIM(RTRIM(CAST(virtualStock.sku_id AS varchar(200)))))
|
||||
WHERE CAST(ISNULL(virtualStock.qty, 0) AS int) > 0
|
||||
GROUP BY
|
||||
UPPER(LTRIM(RTRIM(CAST(virtualStock.sku_id AS varchar(200))))),
|
||||
virtualStock.wms_co_id
|
||||
)
|
||||
SELECT
|
||||
UPPER(LTRIM(RTRIM(CAST(inventory.sku_id AS varchar(200))))) AS barcode,
|
||||
inventory.qty,
|
||||
inventory.order_lock AS orderLock,
|
||||
inventory_rows.barcode,
|
||||
inventory_rows.qty,
|
||||
inventory_rows.orderLock,
|
||||
ISNULL(cloud_rows.cloudAvailable, 0) AS cloudAvailable,
|
||||
warehouse.name AS warehouseName,
|
||||
warehouse.remark2 AS warehouseType
|
||||
FROM [JianSun_Old].[JianSun].[dbo].[jst_inventoryInfo_view] inventory
|
||||
INNER JOIN input_codes codes
|
||||
ON codes.barcode = UPPER(LTRIM(RTRIM(CAST(inventory.sku_id AS varchar(200)))))
|
||||
FROM inventory_rows
|
||||
LEFT JOIN rpt.jst_warehouseInfo warehouse
|
||||
ON warehouse.wms_co_id = inventory.wms_co_id
|
||||
ON warehouse.wms_co_id = inventory_rows.warehouseId
|
||||
LEFT JOIN cloud_rows
|
||||
ON cloud_rows.barcode = inventory_rows.barcode
|
||||
AND cloud_rows.warehouseId = inventory_rows.warehouseId
|
||||
`)
|
||||
const codeSet = new Set(codes)
|
||||
const profileByBarcode = new Map<string, DiscontinuationClearanceWarehouseProfile>()
|
||||
@ -476,7 +506,9 @@ class SupplyChainDiscontinuationSourceRepository {
|
||||
dropshipStock: 0,
|
||||
}
|
||||
const publicAvailable = Math.trunc(
|
||||
Number(row.qty ?? 0) - Number(row.orderLock ?? 0),
|
||||
Number(row.qty ?? 0)
|
||||
- Number(row.orderLock ?? 0)
|
||||
- Number(row.cloudAvailable ?? 0),
|
||||
)
|
||||
const warehouseName = String(row.warehouseName ?? '').trim()
|
||||
const warehouseType = String(row.warehouseType ?? '').trim()
|
||||
|
||||
@ -89,3 +89,22 @@ it('keeps an available zero-volume day selectable instead of returning other dat
|
||||
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: [] })
|
||||
})
|
||||
|
||||
it('shows a pickup-specific stale-data warning without blocking current carrier data', async () => {
|
||||
const report = expressFixture(); report.dateTo = '2026-11-25'
|
||||
report.uncollectedRefresh = { status: 'partial', date: '2026-11-25', attemptedAt: '2026-11-26T01:00:00Z', errorCode: 'REFUND_RECORD_EXCEPTIONS', exceptions: [{ id: '2', inner_order_id: '10366147', logistic_id: '773453795323647', logistic_company_name: '测试快递', warehouse_name: '测试仓', errorCode: 'REFUND_ITEMS_NOT_FOUND_10366147' }] }
|
||||
report.uncollected.date = '2026-11-25'
|
||||
read.mockResolvedValue({ report, pointer: { generation: '1-test', reportHash: '', detailsHash: '' } })
|
||||
const overview = await service.getDashboard({ view: 'overview' }, user)
|
||||
expect(overview.latestDate).toBe('2026-11-25'); expect(overview.uncollectedRefresh).toBeUndefined()
|
||||
const pickup = await service.getDashboard({ view: 'uncollected' }, user)
|
||||
expect(pickup.latestDate).toBe('2026-11-25')
|
||||
expect(pickup.uncollectedRefresh).toMatchObject({ status: 'partial', date: '2026-11-25', exceptions: 1 })
|
||||
expect(pickup.uncollected?.rows).toEqual(report.uncollected.rows)
|
||||
expect(expressSnapshotSchema.safeParse(report).success).toBe(true)
|
||||
report.uncollectedRefresh.status = 'failed'
|
||||
const failed = await service.getDashboard({ view: 'uncollected' }, user)
|
||||
expect(failed.uncollected).toBeUndefined()
|
||||
access.mockResolvedValue({ view: true, edit: false, download: true })
|
||||
await expect(service.export({ view: 'uncollected' }, user)).rejects.toThrow('暂不能导出')
|
||||
})
|
||||
|
||||
@ -65,6 +65,7 @@ function repository() {
|
||||
reason: '原原因',
|
||||
status: 'APPROVED',
|
||||
ownerName: '铁心兰',
|
||||
submittedById: user.id,
|
||||
priorityOverride: '普通任务',
|
||||
revision: 1,
|
||||
}]),
|
||||
@ -170,6 +171,80 @@ describe('SupplyChainClearanceTaskImportService', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('creates a separate task when the imported clearance owner changed', async () => {
|
||||
const repo = repository()
|
||||
repo.listTasksForManualImport.mockResolvedValue([{
|
||||
id: 'task-existing',
|
||||
periodKey: '2026-11',
|
||||
round: 1,
|
||||
barcode: 'SKU-A',
|
||||
profitCenter: '运营中心A',
|
||||
taskQty: 50,
|
||||
discount: '0.70',
|
||||
reason: '原任务',
|
||||
status: 'APPROVED',
|
||||
ownerName: '原负责人',
|
||||
submittedById: user.id,
|
||||
priorityOverride: '',
|
||||
revision: 1,
|
||||
}])
|
||||
const service = new SupplyChainClearanceTaskImportService(repo as never)
|
||||
|
||||
await expect(service.importTasks({
|
||||
periodKey: '2026-11',
|
||||
user,
|
||||
buffer: await workbookBuffer([
|
||||
['SKU-A', '铁心兰', 20, '5折', '调整负责人'],
|
||||
]),
|
||||
})).resolves.toMatchObject({
|
||||
importedCount: 1,
|
||||
createdCount: 1,
|
||||
updatedCount: 0,
|
||||
})
|
||||
expect(repo.writeTasksWithEvents).toHaveBeenCalledWith([
|
||||
expect.objectContaining({
|
||||
create: expect.objectContaining({
|
||||
ownerName: '铁心兰',
|
||||
submittedById: user.id,
|
||||
barcode: 'SKU-A',
|
||||
}),
|
||||
}),
|
||||
])
|
||||
})
|
||||
|
||||
it('allows one import account to create tasks for multiple clearance owners', async () => {
|
||||
const repo = repository()
|
||||
repo.listTasksForManualImport.mockResolvedValue([])
|
||||
const service = new SupplyChainClearanceTaskImportService(repo as never)
|
||||
|
||||
await expect(service.importTasks({
|
||||
periodKey: '2026-11',
|
||||
user,
|
||||
buffer: await workbookBuffer([
|
||||
['SKU-A', '铁心兰', 10, '', ''],
|
||||
['SKU-A', '运营G', 20, '', ''],
|
||||
]),
|
||||
})).resolves.toMatchObject({
|
||||
importedCount: 2,
|
||||
createdCount: 2,
|
||||
updatedCount: 0,
|
||||
})
|
||||
})
|
||||
|
||||
it('returns a refreshable validation error for a concurrent unique-key conflict', async () => {
|
||||
const repo = repository()
|
||||
repo.writeTasksWithEvents.mockRejectedValue({ code: 'P2002' })
|
||||
const service = new SupplyChainClearanceTaskImportService(repo as never)
|
||||
|
||||
await expect(service.importTasks({
|
||||
periodKey: '2026-11',
|
||||
user,
|
||||
buffer: await workbookBuffer([
|
||||
['SKU-A', '铁心兰', 10, '', ''],
|
||||
]),
|
||||
})).rejects.toThrow('清货任务在导入过程中已被其他操作更新,请刷新后重新导入')
|
||||
})
|
||||
|
||||
it('resolves a combined clearance code and creates its component tasks', async () => {
|
||||
const comboCode = 'ZH-BG006401AN1242V01-1-BG006401BN1242V01-1'
|
||||
const repo = repository()
|
||||
@ -433,6 +508,7 @@ describe('SupplyChainClearanceTaskImportService', () => {
|
||||
reason: '不再提交',
|
||||
status: 'REMOVED',
|
||||
ownerName: '铁心兰',
|
||||
submittedById: user.id,
|
||||
department: '事业一部',
|
||||
sku: 'SPU-A',
|
||||
productName: '商品A',
|
||||
|
||||
@ -113,6 +113,7 @@ jest.mock('@/server/repositories/supply-chain-clearance.repository', () => ({
|
||||
updateTaskCostPrices: jest.fn(),
|
||||
updateTaskAuditSnapshots: jest.fn(),
|
||||
updateTaskOwnerSnapshots: jest.fn(),
|
||||
updateTaskDailyMetrics: jest.fn(),
|
||||
findDraftTask: jest.fn(),
|
||||
findActiveTask: jest.fn(),
|
||||
listTaskApplicationsForReview: jest.fn(),
|
||||
@ -2484,6 +2485,134 @@ describe('supply-chain-clearance workflow', () => {
|
||||
expect(repository.findClearanceConfig).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refreshes task inventory daily without changing the generated pool snapshot', async () => {
|
||||
repository.listTasks.mockResolvedValue([{
|
||||
...pendingTask,
|
||||
status: 'APPROVED',
|
||||
}] as never)
|
||||
repository.listProductArchiveTaskValuesByBarcodes.mockResolvedValue([{
|
||||
barcode: 'SKU001',
|
||||
spu: 'SPU001',
|
||||
productTag: '',
|
||||
inOutWarehouse: '',
|
||||
weight: null,
|
||||
length: null,
|
||||
width: null,
|
||||
height: null,
|
||||
volume: null,
|
||||
costPrice: '12.50',
|
||||
sales3d: '10',
|
||||
sales7d: '5',
|
||||
sales15d: '2',
|
||||
stockJianshang: '0',
|
||||
stockFactory: '0',
|
||||
}] as never)
|
||||
sourceRepository.listClearanceWarehouseInventoryByBarcodes.mockResolvedValue([{
|
||||
barcode: 'SKU001',
|
||||
bigWarehouseStock: 34,
|
||||
frontWarehouseStock: 0,
|
||||
dedicatedWarehouseStock: 0,
|
||||
dropshipStock: 0,
|
||||
}])
|
||||
sourceRepository.listSupplierClearanceByBarcodes.mockResolvedValue([{
|
||||
barcode: 'SKU001',
|
||||
supplierRemainingStock: 531,
|
||||
hasPlmRecord: true,
|
||||
hasActivePlmRecord: true,
|
||||
sourceRecordId: 'plm-1',
|
||||
sourceRecordedAt: new Date(),
|
||||
}])
|
||||
repository.updateTaskDailyMetrics.mockResolvedValue(1)
|
||||
|
||||
await expect(supplyChainClearanceService.refreshClearanceTaskDailyMetrics(
|
||||
'2026-12',
|
||||
new Date('2026-11-26T02:45:00.000Z'),
|
||||
)).resolves.toMatchObject({
|
||||
periodKey: '2026-12',
|
||||
tasks: 1,
|
||||
updated: 1,
|
||||
metricsDate: '2026-11-26',
|
||||
})
|
||||
|
||||
expect(repository.updateTaskDailyMetrics).toHaveBeenCalledWith({
|
||||
periodKey: '2026-12',
|
||||
updates: [{
|
||||
barcode: 'SKU001',
|
||||
stockJianshang: 34,
|
||||
stockFactory: 531,
|
||||
totalStock: 565,
|
||||
dailySales: '6.90',
|
||||
availableDays: '81',
|
||||
breakdown: {
|
||||
bigWarehouseStock: 34,
|
||||
frontWarehouseStock: 0,
|
||||
dedicatedWarehouseStock: 0,
|
||||
dropshipStock: 0,
|
||||
supplierRemainingStock: 531,
|
||||
factoryTotalStock: 531,
|
||||
},
|
||||
updatedAt: new Date('2026-11-26T02:45:00.000Z'),
|
||||
}],
|
||||
})
|
||||
expect(repository.updatePoolDailyMetrics).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('skips task daily inventory after the period archive is frozen', async () => {
|
||||
repository.findReviewArchive.mockResolvedValue({
|
||||
id: 'archive-1',
|
||||
generatedAt: new Date('2026-12-02T02:00:00.000Z'),
|
||||
} as never)
|
||||
|
||||
await expect(supplyChainClearanceService.refreshClearanceTaskDailyMetrics(
|
||||
'2026-11',
|
||||
new Date('2026-12-03T02:45:00.000Z'),
|
||||
)).resolves.toMatchObject({
|
||||
periodKey: '2026-11',
|
||||
tasks: 0,
|
||||
updated: 0,
|
||||
frozen: true,
|
||||
})
|
||||
expect(repository.updateTaskDailyMetrics).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('prefers the task daily inventory snapshot over the frozen pool inventory', async () => {
|
||||
repository.listTasks.mockResolvedValue([{
|
||||
...pendingTask,
|
||||
periodKey: '2026-12',
|
||||
status: 'APPROVED',
|
||||
inventoryStockJianshang: 34,
|
||||
inventoryStockFactory: 531,
|
||||
inventoryTotalStock: 565,
|
||||
inventoryDailySales: '6.90',
|
||||
inventoryAvailableDays: '82',
|
||||
inventoryUpdatedAt: new Date('2026-11-26T02:45:00.000Z'),
|
||||
}] as never)
|
||||
repository.listPoolItemsForTaskPeriod.mockResolvedValue([{
|
||||
...poolItem,
|
||||
stockJianshang: 105,
|
||||
stockFactory: 531,
|
||||
totalStock: 636,
|
||||
dailySales: '4.00',
|
||||
availableDays: '159',
|
||||
}] as never)
|
||||
repository.listTaskShipmentCoverage.mockResolvedValue([])
|
||||
repository.listReviewMonths.mockResolvedValue([])
|
||||
repository.listTaskPeriods.mockResolvedValue(['2026-12'])
|
||||
|
||||
const result = await supplyChainClearanceService.getTasks('2026-12', {
|
||||
includeFreight: false,
|
||||
liveProgress: false,
|
||||
})
|
||||
|
||||
expect(result.tasks[0]).toMatchObject({
|
||||
stockJianshang: 34,
|
||||
stockFactory: 531,
|
||||
totalStock: 565,
|
||||
dailySales: 6.9,
|
||||
availableDays: '82',
|
||||
})
|
||||
})
|
||||
|
||||
it('backfills a pool inventory row for a task barcode missing from the generated pool', async () => {
|
||||
repository.findPoolGeneration.mockResolvedValue({
|
||||
id: 'generation-1',
|
||||
|
||||
@ -18,7 +18,14 @@ export class DailyExpressVolumeService {
|
||||
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 }
|
||||
if (query.view === 'uncollected') {
|
||||
const refresh = report.uncollectedRefresh
|
||||
return { ...base, latestDate: refresh?.status === 'failed' ? refresh.date : report.uncollected.date,
|
||||
updatedAt: refresh?.status === 'failed' ? refresh.attemptedAt : report.uncollected.queriedAt,
|
||||
...(refresh?.status === 'failed' ? {} : { uncollected: report.uncollected }),
|
||||
...(refresh ? { uncollectedRefresh: { status: refresh.status, date: refresh.date, exceptions: refresh.exceptions.length,
|
||||
message: refresh.status === 'partial' ? `本次有 ${refresh.exceptions.length} 条订单核对异常,列表展示本次已核对成功的数据,异常另行通知。` : '本次未揽收数据更新未完成,暂无本次已核对数据,异常另行通知。' } } : {}) }
|
||||
}
|
||||
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) } }
|
||||
@ -30,6 +37,7 @@ export class DailyExpressVolumeService {
|
||||
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()
|
||||
if (query.view === 'uncollected' && !data.uncollected) throw new AppError(ErrorCode.VALIDATION_FAILED, '本次未揽收数据更新未完成,暂不能导出')
|
||||
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[])
|
||||
|
||||
@ -11,6 +11,7 @@ import {
|
||||
DEFAULT_REISSUE_TEMPLATE,
|
||||
REISSUE_QUALIFYING_OVERTIME_TYPES,
|
||||
REISSUE_QUALIFYING_RELABEL,
|
||||
reissueOwnerForSupplier,
|
||||
reissueSyncDateRange,
|
||||
type FollowupRecord,
|
||||
type FollowupStore,
|
||||
@ -94,14 +95,7 @@ class PurchaseLegacyModulesService {
|
||||
|
||||
async syncReissueFromOrderNotDispatched() {
|
||||
const current = await this.getReissueStore()
|
||||
const supplierOwners = current.supplierOwners || {}
|
||||
const mappedSuppliers = new Set(Object.keys(supplierOwners))
|
||||
if (!mappedSuppliers.size) {
|
||||
throw new AppError(
|
||||
ErrorCode.VALIDATION_REQUIRED_FIELD,
|
||||
'请先配置供应商与跟单员映射,再识别聚水潭订单',
|
||||
)
|
||||
}
|
||||
const supplierOwners = { ...(current.supplierOwners || {}) }
|
||||
|
||||
const syncDays = Math.max(1, Number(current.config.syncDays) || 7)
|
||||
const dateRange = reissueSyncDateRange(syncDays)
|
||||
@ -125,17 +119,18 @@ class PurchaseLegacyModulesService {
|
||||
let matched = 0
|
||||
let added = 0
|
||||
let updated = 0
|
||||
let ignoredUnmapped = 0
|
||||
let fallbackAssigned = 0
|
||||
let outsideWindow = 0
|
||||
let outsideCriteria = 0
|
||||
const qualifyingSourceIds = new Set<string>()
|
||||
|
||||
sourceRows.forEach((row) => {
|
||||
const supplier = String(row.supplierName || '').trim()
|
||||
const owner = supplierOwners[supplier]
|
||||
let owner = supplierOwners[supplier]
|
||||
if (!owner) {
|
||||
ignoredUnmapped += 1
|
||||
return
|
||||
owner = reissueOwnerForSupplier(supplier, supplierOwners)
|
||||
supplierOwners[supplier] = owner
|
||||
fallbackAssigned += 1
|
||||
}
|
||||
const sourceDateText = row.localCreated || row.created || row.orderDate
|
||||
const sourceDate = sourceDateText ? new Date(sourceDateText.replace(' ', 'T')).getTime() : NaN
|
||||
@ -227,9 +222,19 @@ class PurchaseLegacyModulesService {
|
||||
}
|
||||
})
|
||||
|
||||
const retainedRecords = records.filter((record) =>
|
||||
!record.sourceId || qualifyingSourceIds.has(String(record.sourceId)),
|
||||
)
|
||||
const retainedRecords = records
|
||||
.filter((record) =>
|
||||
!record.sourceId || qualifyingSourceIds.has(String(record.sourceId)),
|
||||
)
|
||||
.map((record) => {
|
||||
const supplier = String(record.supplier || '').trim()
|
||||
if (!supplier) return record
|
||||
const owner = reissueOwnerForSupplier(supplier, supplierOwners)
|
||||
supplierOwners[supplier] = owner
|
||||
return record.followupOwner === owner
|
||||
? record
|
||||
: { ...record, followupOwner: owner }
|
||||
})
|
||||
const removed = records.length - retainedRecords.length
|
||||
const syncedAt = new Date().toISOString()
|
||||
const next = await this.saveReissueStore({
|
||||
@ -259,7 +264,8 @@ class PurchaseLegacyModulesService {
|
||||
matched,
|
||||
added,
|
||||
updated,
|
||||
ignoredUnmapped,
|
||||
ignoredUnmapped: 0,
|
||||
fallbackAssigned,
|
||||
outsideWindow,
|
||||
outsideCriteria,
|
||||
removed,
|
||||
|
||||
@ -91,7 +91,13 @@ describe('supplier reissue response service', () => {
|
||||
const { supplierReissueResponseService } = await import('./supplier-reissue-response.service')
|
||||
const link = await supplierReissueResponseService.createSupplierLink('兰考华兰家具', '昭君')
|
||||
const token = link.path.split('/').at(-1)!
|
||||
const shortCode = link.shortPath.split('/').at(-1)!
|
||||
expect(JSON.stringify([...mockSystemConfig.entries()])).not.toContain(token)
|
||||
expect(shortCode).toMatch(/^[A-Za-z0-9_-]{10}$/)
|
||||
await expect(supplierReissueResponseService.resolveShortPath(shortCode)).resolves.toMatchObject({
|
||||
supplier: '兰考华兰家具',
|
||||
path: link.path,
|
||||
})
|
||||
mockFindMany.mockResolvedValue([...mockSystemConfig.entries()].map(([key, value]) => ({ key, value })))
|
||||
await expect(supplierReissueResponseService.ensureSupplierLink('兰考华兰家具')).resolves.toMatchObject({
|
||||
path: link.path,
|
||||
|
||||
@ -24,8 +24,11 @@ import { reissueHistoryService } from '@/server/services/reissue-history.service
|
||||
import { systemConfigService } from '@/server/services/system-config.service'
|
||||
|
||||
const LINK_KEY_PREFIX = 'supplierReissueLinkV1:'
|
||||
const SHORT_LINK_KEY_PREFIX = 'supplierReissueShortLinkV1:'
|
||||
const RESPONSE_KEY_PREFIX = 'supplierReissueResponseV1:'
|
||||
const LINK_TTL_DAYS = 30
|
||||
const SHORT_CODE_LENGTH = 10
|
||||
const SHORT_CODE_ALPHABET = '23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
|
||||
|
||||
type StoredSupplierLink = {
|
||||
supplier: string
|
||||
@ -33,6 +36,7 @@ type StoredSupplierLink = {
|
||||
createdAt: string
|
||||
expiresAt: string
|
||||
tokenCiphertext?: string
|
||||
shortCode?: string
|
||||
revokedAt?: string
|
||||
viewCount?: number
|
||||
lastViewedAt?: string
|
||||
@ -51,6 +55,13 @@ type StoredSupplierResponse = {
|
||||
respondedAt: string
|
||||
}
|
||||
|
||||
type StoredShortLink = {
|
||||
code: string
|
||||
tokenHash: string
|
||||
supplier: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
function sha256(value: string) {
|
||||
return createHash('sha256').update(value).digest('hex')
|
||||
}
|
||||
@ -122,6 +133,17 @@ function responseKey(recordId: string) {
|
||||
return `${RESPONSE_KEY_PREFIX}${recordId}`
|
||||
}
|
||||
|
||||
function shortLinkKey(code: string) {
|
||||
return `${SHORT_LINK_KEY_PREFIX}${code}`
|
||||
}
|
||||
|
||||
function createShortCode() {
|
||||
const bytes = randomBytes(SHORT_CODE_LENGTH)
|
||||
return [...bytes]
|
||||
.map((value) => SHORT_CODE_ALPHABET[value % SHORT_CODE_ALPHABET.length])
|
||||
.join('')
|
||||
}
|
||||
|
||||
function publicOrder(record: ReissueRecord): SupplierReissueOrder {
|
||||
const category = record.supplierReasonCategory || ''
|
||||
const inferredRoot = supplierReasonRootForCategory(category)
|
||||
@ -148,6 +170,25 @@ function publicOrder(record: ReissueRecord): SupplierReissueOrder {
|
||||
}
|
||||
|
||||
class SupplierReissueResponseService {
|
||||
private async createUniqueShortCode(
|
||||
tokenHash: string,
|
||||
supplier: string,
|
||||
) {
|
||||
for (let attempt = 0; attempt < 12; attempt += 1) {
|
||||
const code = createShortCode()
|
||||
const existing = await systemConfigService.get<StoredShortLink>(shortLinkKey(code))
|
||||
if (existing) continue
|
||||
await systemConfigService.set(shortLinkKey(code), {
|
||||
code,
|
||||
tokenHash,
|
||||
supplier,
|
||||
createdAt: new Date().toISOString(),
|
||||
} satisfies StoredShortLink, `供应商应发未发短链接(${supplier})`)
|
||||
return code
|
||||
}
|
||||
throw new AppError(ErrorCode.SYSTEM_INTERNAL, '供应商短链接生成失败,请稍后重试')
|
||||
}
|
||||
|
||||
async createSupplierLink(supplier: string, createdBy: string) {
|
||||
const normalizedSupplier = trim(supplier)
|
||||
if (!normalizedSupplier) {
|
||||
@ -181,6 +222,8 @@ class SupplierReissueResponseService {
|
||||
tokenCiphertext: encryptSupplierToken(token),
|
||||
viewCount: 0,
|
||||
}
|
||||
const shortCode = await this.createUniqueShortCode(tokenHash, normalizedSupplier)
|
||||
stored.shortCode = shortCode
|
||||
await systemConfigService.set(
|
||||
linkKey(tokenHash),
|
||||
stored,
|
||||
@ -189,6 +232,7 @@ class SupplierReissueResponseService {
|
||||
return {
|
||||
supplier: normalizedSupplier,
|
||||
path: `/supplier-response/${token}`,
|
||||
shortPath: `/s/${shortCode}`,
|
||||
expiresAt: expiresAt.toISOString(),
|
||||
}
|
||||
}
|
||||
@ -216,9 +260,22 @@ class SupplierReissueResponseService {
|
||||
)
|
||||
if (active) {
|
||||
const token = decryptSupplierToken(trim(active.value.tokenCiphertext))
|
||||
const tokenHash = active.key.slice(LINK_KEY_PREFIX.length)
|
||||
let shortCode = trim(active.value.shortCode)
|
||||
const existingShort = shortCode
|
||||
? await systemConfigService.get<StoredShortLink>(shortLinkKey(shortCode))
|
||||
: null
|
||||
if (!shortCode || existingShort?.tokenHash !== tokenHash) {
|
||||
shortCode = await this.createUniqueShortCode(tokenHash, normalizedSupplier)
|
||||
await systemConfigService.set(active.key, {
|
||||
...active.value,
|
||||
shortCode,
|
||||
}, '供应商应发未发专属填报链接')
|
||||
}
|
||||
return {
|
||||
supplier: normalizedSupplier,
|
||||
path: `/supplier-response/${token}`,
|
||||
shortPath: `/s/${shortCode}`,
|
||||
expiresAt: active.value.expiresAt,
|
||||
}
|
||||
}
|
||||
@ -283,6 +340,37 @@ class SupplierReissueResponseService {
|
||||
return (await this.resolveLink(token)).supplier
|
||||
}
|
||||
|
||||
async resolveShortPath(code: string) {
|
||||
const normalizedCode = trim(code)
|
||||
if (!new RegExp(`^[A-Za-z0-9_-]{${SHORT_CODE_LENGTH}}$`).test(normalizedCode)) {
|
||||
throw new AppError(ErrorCode.SHARE_LINK_NOT_FOUND, '供应商短链接无效')
|
||||
}
|
||||
const mapping = await systemConfigService.get<StoredShortLink>(shortLinkKey(normalizedCode))
|
||||
if (!mapping?.tokenHash || !trim(mapping.supplier)) {
|
||||
throw new AppError(ErrorCode.SHARE_LINK_NOT_FOUND, '供应商短链接不存在')
|
||||
}
|
||||
const stored = await systemConfigService.get<StoredSupplierLink>(linkKey(mapping.tokenHash))
|
||||
if (
|
||||
!stored
|
||||
|| !trim(stored.tokenCiphertext)
|
||||
|| trim(stored.supplier) !== trim(mapping.supplier)
|
||||
) {
|
||||
throw new AppError(ErrorCode.SHARE_LINK_NOT_FOUND, '供应商短链接不存在')
|
||||
}
|
||||
if (!stored.active) {
|
||||
throw new AppError(ErrorCode.SHARE_LINK_DISABLED, '供应商填报链接已停用')
|
||||
}
|
||||
if (!stored.expiresAt || new Date(stored.expiresAt).getTime() <= Date.now()) {
|
||||
throw new AppError(ErrorCode.SHARE_LINK_EXPIRED, '供应商填报链接已过期')
|
||||
}
|
||||
const token = decryptSupplierToken(trim(stored.tokenCiphertext))
|
||||
return {
|
||||
supplier: trim(stored.supplier),
|
||||
path: `/supplier-response/${token}`,
|
||||
expiresAt: stored.expiresAt,
|
||||
}
|
||||
}
|
||||
|
||||
async submitResponses(
|
||||
token: string,
|
||||
items: SupplierReissueResponseInput[],
|
||||
|
||||
@ -44,6 +44,22 @@ function itemKey(
|
||||
].join('\u0000')
|
||||
}
|
||||
|
||||
function taskIdentityKey(
|
||||
periodKey: string,
|
||||
barcode: string,
|
||||
profitCenter: string,
|
||||
submittedById: string,
|
||||
ownerName: string,
|
||||
) {
|
||||
return [
|
||||
periodKey,
|
||||
barcode.trim().toUpperCase(),
|
||||
profitCenter.trim(),
|
||||
submittedById.trim(),
|
||||
ownerName.trim(),
|
||||
].join('\u0000')
|
||||
}
|
||||
|
||||
function normalizedPeriod(value: string) {
|
||||
const periodKey = value.trim()
|
||||
if (!PERIOD_PATTERN.test(periodKey)) {
|
||||
@ -362,10 +378,15 @@ export class SupplyChainClearanceTaskImportService {
|
||||
`组合编码展开后存在重复组件,请勿同时导入组合编码和组件编码:${barcodeList(duplicates)}`,
|
||||
)
|
||||
}
|
||||
|
||||
const candidatesByKey = new Map<string, typeof existingTasks>()
|
||||
for (const task of existingTasks) {
|
||||
const key = itemKey(periodKey, task.barcode, task.profitCenter, task.ownerName)
|
||||
const key = taskIdentityKey(
|
||||
periodKey,
|
||||
task.barcode,
|
||||
task.profitCenter,
|
||||
task.submittedById,
|
||||
task.ownerName,
|
||||
)
|
||||
const candidates = candidatesByKey.get(key) ?? []
|
||||
candidates.push(task)
|
||||
candidatesByKey.set(key, candidates)
|
||||
@ -383,10 +404,11 @@ export class SupplyChainClearanceTaskImportService {
|
||||
}
|
||||
const fixedTaskDiscountErrors = preparedRows.flatMap((row) => {
|
||||
if (row.discount >= 1) return []
|
||||
const existing = existingByKey.get(itemKey(
|
||||
const existing = existingByKey.get(taskIdentityKey(
|
||||
periodKey,
|
||||
row.barcode,
|
||||
row.profitCenter,
|
||||
input.user.id,
|
||||
row.clearanceOwner,
|
||||
))
|
||||
if (!isClearanceDiscountBlockedPriority(row.priority, existing?.priorityOverride)) return []
|
||||
@ -400,10 +422,11 @@ export class SupplyChainClearanceTaskImportService {
|
||||
}
|
||||
|
||||
const writes: Parameters<TaskImportRepository['writeTasksWithEvents']>[0] = preparedRows.map((row) => {
|
||||
const existing = existingByKey.get(itemKey(
|
||||
const existing = existingByKey.get(taskIdentityKey(
|
||||
periodKey,
|
||||
row.barcode,
|
||||
row.profitCenter,
|
||||
input.user.id,
|
||||
row.clearanceOwner,
|
||||
))
|
||||
const common = {
|
||||
@ -488,7 +511,17 @@ export class SupplyChainClearanceTaskImportService {
|
||||
}
|
||||
})
|
||||
|
||||
await this.repository.writeTasksWithEvents(writes)
|
||||
try {
|
||||
await this.repository.writeTasksWithEvents(writes)
|
||||
} catch (error) {
|
||||
if ((error as { code?: unknown } | null)?.code === 'P2002') {
|
||||
throw new AppError(
|
||||
ErrorCode.VALIDATION_INVALID_FORMAT,
|
||||
'清货任务在导入过程中已被其他操作更新,请刷新后重新导入',
|
||||
)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
return {
|
||||
periodKey,
|
||||
importedCount: preparedRows.length,
|
||||
|
||||
@ -2428,6 +2428,101 @@ class SupplyChainClearanceService {
|
||||
}
|
||||
}
|
||||
|
||||
async refreshClearanceTaskDailyMetrics(
|
||||
periodKeyInput?: string | null,
|
||||
metricsAt = new Date(),
|
||||
) {
|
||||
const periodKey = normalizePeriodKey(periodKeyInput)
|
||||
const frozenArchive = await this.frozenPeriodArchive(periodKey)
|
||||
if (frozenArchive) {
|
||||
return {
|
||||
periodKey,
|
||||
tasks: 0,
|
||||
updated: 0,
|
||||
metricsDate: shanghaiDateKey(metricsAt),
|
||||
frozen: true,
|
||||
frozenAt: frozenArchive.generatedAt.toISOString(),
|
||||
}
|
||||
}
|
||||
const tasks = await supplyChainClearanceRepository.listTasks({ periodKey })
|
||||
const barcodes = Array.from(new Set(
|
||||
tasks.map((task) => task.barcode.trim().toUpperCase()).filter(Boolean),
|
||||
))
|
||||
if (!barcodes.length) {
|
||||
return {
|
||||
periodKey,
|
||||
tasks: 0,
|
||||
updated: 0,
|
||||
metricsDate: shanghaiDateKey(metricsAt),
|
||||
frozen: false,
|
||||
frozenAt: null,
|
||||
}
|
||||
}
|
||||
const [archiveValues, warehouseProfiles, supplierProfiles] = await Promise.all([
|
||||
supplyChainClearanceRepository.listProductArchiveTaskValuesByBarcodes(barcodes),
|
||||
supplyChainDiscontinuationSourceRepository.listClearanceWarehouseInventoryByBarcodes(
|
||||
barcodes,
|
||||
),
|
||||
supplyChainDiscontinuationSourceRepository.listSupplierClearanceByBarcodes(barcodes),
|
||||
])
|
||||
const archiveByBarcode = new Map(
|
||||
archiveValues.map((row) => [row.barcode.trim().toUpperCase(), row]),
|
||||
)
|
||||
const warehouseByBarcode = new Map(
|
||||
warehouseProfiles.map((row) => [row.barcode.trim().toUpperCase(), row]),
|
||||
)
|
||||
const supplierByBarcode = new Map(
|
||||
supplierProfiles.map((row) => [row.barcode.trim().toUpperCase(), row]),
|
||||
)
|
||||
const updates = barcodes.map((barcode) => {
|
||||
const warehouse = warehouseByBarcode.get(barcode)
|
||||
const supplier = supplierByBarcode.get(barcode)
|
||||
const archive = archiveByBarcode.get(barcode)
|
||||
const bigWarehouseStock = integer(warehouse?.bigWarehouseStock)
|
||||
const frontWarehouseStock = integer(warehouse?.frontWarehouseStock)
|
||||
const dedicatedWarehouseStock = integer(warehouse?.dedicatedWarehouseStock)
|
||||
const dropshipStock = integer(warehouse?.dropshipStock)
|
||||
const supplierRemainingStock = integer(supplier?.supplierRemainingStock)
|
||||
const stockJianshang = clearancePriorityJianshangStock(
|
||||
bigWarehouseStock,
|
||||
frontWarehouseStock,
|
||||
dedicatedWarehouseStock,
|
||||
)
|
||||
const stockFactory = Math.max(0, supplierRemainingStock + dropshipStock)
|
||||
const totalStock = stockJianshang + stockFactory
|
||||
const dailySales = archive ? calculateClearanceDailySales(archive) : null
|
||||
return {
|
||||
barcode,
|
||||
stockJianshang,
|
||||
stockFactory,
|
||||
totalStock,
|
||||
dailySales: dailySales?.toFixed(2) ?? null,
|
||||
availableDays: availableDaysText(totalStock, dailySales),
|
||||
breakdown: {
|
||||
bigWarehouseStock,
|
||||
frontWarehouseStock,
|
||||
dedicatedWarehouseStock,
|
||||
dropshipStock,
|
||||
supplierRemainingStock,
|
||||
factoryTotalStock: stockFactory,
|
||||
},
|
||||
updatedAt: metricsAt,
|
||||
}
|
||||
})
|
||||
const updated = await supplyChainClearanceRepository.updateTaskDailyMetrics({
|
||||
periodKey,
|
||||
updates,
|
||||
})
|
||||
return {
|
||||
periodKey,
|
||||
tasks: tasks.length,
|
||||
updated,
|
||||
metricsDate: shanghaiDateKey(metricsAt),
|
||||
frozen: false,
|
||||
frozenAt: null,
|
||||
}
|
||||
}
|
||||
|
||||
async getPool(input: ClearancePoolQueryInput) {
|
||||
const generations = await supplyChainClearanceRepository.listPoolGenerations()
|
||||
const requestedPeriod = isPeriodKey(input.periodKey) ? normalizePeriodKey(input.periodKey) : null
|
||||
@ -3611,9 +3706,16 @@ class SupplyChainClearanceService {
|
||||
?? (componentCost == null
|
||||
? null
|
||||
: round(componentCost * (hasDiscount ? discount : 1), 3))
|
||||
const stockJianshang = poolItem?.stockJianshang ?? 0
|
||||
const stockFactory = poolItem?.stockFactory ?? 0
|
||||
const totalStock = Math.trunc(stockJianshang + stockFactory)
|
||||
const hasTaskInventory = Boolean(task.inventoryUpdatedAt)
|
||||
const stockJianshang = hasTaskInventory
|
||||
? Math.max(0, task.inventoryStockJianshang ?? 0)
|
||||
: poolItem?.stockJianshang ?? 0
|
||||
const stockFactory = hasTaskInventory
|
||||
? Math.max(0, task.inventoryStockFactory ?? 0)
|
||||
: poolItem?.stockFactory ?? 0
|
||||
const totalStock = hasTaskInventory
|
||||
? Math.max(0, task.inventoryTotalStock ?? stockJianshang + stockFactory)
|
||||
: Math.trunc(stockJianshang + stockFactory)
|
||||
const profitCenter =
|
||||
String(task.profitCenter ?? '').trim()
|
||||
|| String(extra.profitCenter ?? '').trim()
|
||||
@ -3629,9 +3731,14 @@ class SupplyChainClearanceService {
|
||||
}),
|
||||
})
|
||||
const { realTaskQty, shipQty, clearanceProgress } = execution
|
||||
const dailySales = (
|
||||
archiveItem ? calculateClearanceDailySales(archiveItem) : null
|
||||
) ?? number(poolItem?.dailySales)
|
||||
const dailySales = hasTaskInventory
|
||||
? number(task.inventoryDailySales)
|
||||
: (
|
||||
archiveItem ? calculateClearanceDailySales(archiveItem) : null
|
||||
) ?? number(poolItem?.dailySales)
|
||||
const taskAvailableDays = hasTaskInventory
|
||||
? task.inventoryAvailableDays.trim()
|
||||
: ''
|
||||
const taskMetadata = taskMetadataByBarcode.get(barcode)
|
||||
return {
|
||||
...taskWithProgress,
|
||||
@ -3663,7 +3770,7 @@ class SupplyChainClearanceService {
|
||||
stockFactory,
|
||||
totalStock,
|
||||
dailySales,
|
||||
availableDays: availableDaysText(totalStock, dailySales),
|
||||
availableDays: taskAvailableDays || availableDaysText(totalStock, dailySales),
|
||||
nationwideFreight: number(freightByBarcode.get(barcode)?.freightNationwide),
|
||||
clearanceBatch: String(extra.clearanceBatch ?? '').trim()
|
||||
|| taskMetadata?.clearanceBatch
|
||||
@ -4197,7 +4304,19 @@ class SupplyChainClearanceService {
|
||||
filteredTasks = directFilteredTasks.filter((task) => {
|
||||
const poolItem = poolByBarcode.get(task.barcode.trim().toUpperCase())
|
||||
const extra = poolItem ? poolExtra(poolItem) : {}
|
||||
const dailySales = number(poolItem?.dailySales)
|
||||
const hasTaskInventory = Boolean(task.inventoryUpdatedAt)
|
||||
const stockJianshang = hasTaskInventory
|
||||
? Math.max(0, task.inventoryStockJianshang ?? 0)
|
||||
: Math.max(0, poolItem?.stockJianshang ?? 0)
|
||||
const stockFactory = hasTaskInventory
|
||||
? Math.max(0, task.inventoryStockFactory ?? 0)
|
||||
: Math.max(0, poolItem?.stockFactory ?? 0)
|
||||
const totalStock = hasTaskInventory
|
||||
? Math.max(0, task.inventoryTotalStock ?? stockJianshang + stockFactory)
|
||||
: Math.max(0, poolItem?.totalStock ?? 0)
|
||||
const dailySales = hasTaskInventory
|
||||
? number(task.inventoryDailySales)
|
||||
: number(poolItem?.dailySales)
|
||||
const discount = number(task.discount) ?? 0
|
||||
return matchesClearanceFilters({
|
||||
taskId: task.id,
|
||||
@ -4221,13 +4340,15 @@ class SupplyChainClearanceService {
|
||||
|| String(extra.profitCenter ?? '').trim(),
|
||||
priority: String(extra.priority ?? '').trim(),
|
||||
clearanceBatch: String(extra.clearanceBatch ?? '').trim(),
|
||||
stockJianshang: Math.max(0, poolItem?.stockJianshang ?? 0),
|
||||
stockFactory: Math.max(0, poolItem?.stockFactory ?? 0),
|
||||
totalStock: Math.max(0, poolItem?.totalStock ?? 0),
|
||||
stockJianshang,
|
||||
stockFactory,
|
||||
totalStock,
|
||||
clearanceTotal: poolItem ? poolClearanceTotal(poolItem) : null,
|
||||
dailySales,
|
||||
thirtyDayClearableQty: dailySales == null ? null : Math.round(dailySales * 30),
|
||||
availableDays: poolItem?.availableDays ?? '',
|
||||
availableDays: hasTaskInventory
|
||||
? task.inventoryAvailableDays.trim()
|
||||
: poolItem?.availableDays ?? '',
|
||||
taskQty: task.taskQty,
|
||||
discount,
|
||||
discountLabel: discountLabel(discount),
|
||||
@ -4309,6 +4430,19 @@ class SupplyChainClearanceService {
|
||||
const extra = poolItem ? poolExtra(poolItem) : {}
|
||||
const discount = number(task.discount) ?? 0
|
||||
const auditSnapshot = auditSnapshotByTaskId.get(task.id)
|
||||
const hasTaskInventory = Boolean(task.inventoryUpdatedAt)
|
||||
const stockJianshang = hasTaskInventory
|
||||
? Math.max(0, task.inventoryStockJianshang ?? 0)
|
||||
: Math.max(0, poolItem?.stockJianshang ?? 0)
|
||||
const stockFactory = hasTaskInventory
|
||||
? Math.max(0, task.inventoryStockFactory ?? 0)
|
||||
: Math.max(0, poolItem?.stockFactory ?? 0)
|
||||
const totalStock = hasTaskInventory
|
||||
? Math.max(0, task.inventoryTotalStock ?? stockJianshang + stockFactory)
|
||||
: Math.max(0, poolItem?.totalStock ?? 0)
|
||||
const dailySales = hasTaskInventory
|
||||
? number(task.inventoryDailySales)
|
||||
: number(poolItem?.dailySales)
|
||||
return {
|
||||
taskId: task.id,
|
||||
barcode: task.barcode,
|
||||
@ -4332,15 +4466,17 @@ class SupplyChainClearanceService {
|
||||
|| String(extra.profitCenter ?? '').trim(),
|
||||
priority: String(extra.priority ?? '').trim(),
|
||||
clearanceBatch: String(extra.clearanceBatch ?? '').trim(),
|
||||
stockJianshang: Math.max(0, poolItem?.stockJianshang ?? 0),
|
||||
stockFactory: Math.max(0, poolItem?.stockFactory ?? 0),
|
||||
totalStock: Math.max(0, poolItem?.totalStock ?? 0),
|
||||
stockJianshang,
|
||||
stockFactory,
|
||||
totalStock,
|
||||
clearanceTotal: poolItem ? poolClearanceTotal(poolItem) : null,
|
||||
dailySales: number(poolItem?.dailySales),
|
||||
thirtyDayClearableQty: number(poolItem?.dailySales) == null
|
||||
dailySales,
|
||||
thirtyDayClearableQty: dailySales == null
|
||||
? null
|
||||
: Math.round(number(poolItem?.dailySales)! * 30),
|
||||
availableDays: poolItem?.availableDays ?? '',
|
||||
: Math.round(dailySales * 30),
|
||||
availableDays: hasTaskInventory
|
||||
? task.inventoryAvailableDays.trim()
|
||||
: poolItem?.availableDays ?? '',
|
||||
taskQty: task.taskQty,
|
||||
discount,
|
||||
discountLabel: discountLabel(discount),
|
||||
|
||||
@ -45,6 +45,7 @@ describe('wecom reissue service', () => {
|
||||
mockEnsureSupplierLink.mockResolvedValue({
|
||||
supplier: '兰考华兰家具',
|
||||
path: '/supplier-response/test-link',
|
||||
shortPath: '/s/test-link',
|
||||
expiresAt: '2099-12-31T00:00:00.000Z',
|
||||
})
|
||||
})
|
||||
@ -140,7 +141,7 @@ describe('wecom reissue service', () => {
|
||||
expect(taskBody.sender).toBe('owner-1')
|
||||
expect(taskBody.text.content).toContain('兰考华兰家具')
|
||||
expect(taskBody.text.content).not.toContain('曹县天山')
|
||||
expect(taskBody.text.content).toContain('/supplier-response/test-link')
|
||||
expect(taskBody.text.content).toContain('/s/test-link')
|
||||
})
|
||||
|
||||
it('pushes internal-group messages through the webhook without an external chat id', async () => {
|
||||
@ -353,6 +354,13 @@ describe('wecom reissue service', () => {
|
||||
reportedAt: '2026-11-16T07:00',
|
||||
supplierRespondedAt: '2026-11-16T12:00:00.000Z',
|
||||
},
|
||||
{
|
||||
id: 'jst-legacy-filled-1',
|
||||
supplier: '兰考华兰家具',
|
||||
orderNo: 'SO-LEGACY-FILLED-1',
|
||||
reportedAt: '2026-11-16T07:00',
|
||||
supplierReasonCategory: '工厂原因-原材料供应异常(质量/交期)',
|
||||
},
|
||||
]
|
||||
mockGetReissueStore.mockResolvedValue(store)
|
||||
mockSaveReissueStore.mockImplementation(async (input: {
|
||||
@ -384,14 +392,17 @@ describe('wecom reissue service', () => {
|
||||
const body = JSON.parse(String(jest.mocked(global.fetch).mock.calls[0][1]?.body)) as {
|
||||
text: { content: string; mentioned_list?: string[] }
|
||||
}
|
||||
expect(body.text.content).toContain('订单号:SO-FOLLOWUP-1')
|
||||
expect(body.text.content).toContain('超时类型:超平台时效')
|
||||
expect(body.text.content).toContain('【14:00|未填写催办')
|
||||
expect(body.text.content).toContain('待催供应商:1 家|未填写:1 条|已填写剔除:2 条')
|
||||
expect(body.text.content).toContain('兰考华兰家具|未填 1 条')
|
||||
expect(body.text.content).not.toContain('SO-FOLLOWUP-1')
|
||||
expect(body.text.content).not.toContain('BARCODE-SHOULD-NOT-APPEAR')
|
||||
expect(body.text.content).not.toContain('DETAIL-SHOULD-NOT-APPEAR')
|
||||
expect(body.text.content).not.toContain('条码:')
|
||||
expect(body.text.content).not.toContain('明细:')
|
||||
expect(body.text.content).toContain('/supplier-response/test-link')
|
||||
expect(body.text.content).toContain('/s/test-link')
|
||||
expect(body.text.content).not.toContain('SO-RESPONDED-1')
|
||||
expect(body.text.content).not.toContain('SO-LEGACY-FILLED-1')
|
||||
expect(body.text.mentioned_list).toEqual(['@all'])
|
||||
const savedRecords = mockSaveReissueStore.mock.calls[0][0].records as Array<Record<string, unknown>>
|
||||
expect(savedRecords.find((record) => record.id === 'jst-followup-1')?.followupRemindedAt).toBeTruthy()
|
||||
@ -446,6 +457,7 @@ describe('wecom reissue service', () => {
|
||||
mockEnsureSupplierLink.mockImplementation(async (supplier: unknown) => ({
|
||||
supplier,
|
||||
path: `/supplier-response/${supplier === '双爱家私' ? 'shuang-link' : 'linyi-link'}`,
|
||||
shortPath: `/s/${supplier === '双爱家私' ? 'shuang-short' : 'linyi-short'}`,
|
||||
expiresAt: '2099-12-31T00:00:00.000Z',
|
||||
}))
|
||||
global.fetch = jest.fn().mockResolvedValueOnce({
|
||||
@ -465,8 +477,10 @@ describe('wecom reissue service', () => {
|
||||
.join('\n')
|
||||
expect(sentText).toContain('双爱家私')
|
||||
expect(sentText).toContain('临沂恒思')
|
||||
expect(sentText).toContain('/supplier-response/shuang-link')
|
||||
expect(sentText).toContain('/supplier-response/linyi-link')
|
||||
expect(sentText).toContain('【10:00|供应商填报')
|
||||
expect(sentText).toContain('供应商:2 家|待填明细:2 条')
|
||||
expect(sentText).toContain('/s/shuang-short')
|
||||
expect(sentText).toContain('/s/linyi-short')
|
||||
})
|
||||
|
||||
it('skips the 14:00 reminder on weekends', async () => {
|
||||
|
||||
@ -1,13 +1,19 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import {
|
||||
DEFAULT_REISSUE_FALLBACK_OWNER,
|
||||
REISSUE_SUPPLIER_OWNER_GROUPS,
|
||||
reissueHasCallback,
|
||||
reissueHasSupplierFeedback,
|
||||
reissueScript,
|
||||
reissueSupplier,
|
||||
reissueSupplierNames,
|
||||
type ReissueRecord,
|
||||
} from '@/lib/purchase-legacy-modules'
|
||||
import {
|
||||
buildFollowupSupplierMessages,
|
||||
buildInitialSupplierDigestMessages,
|
||||
} from '@/lib/wecom-reissue-message'
|
||||
import { AppError, ErrorCode } from '@/server/core/errors'
|
||||
import { deliveryControlService } from '@/server/services/delivery-control.service'
|
||||
import { purchaseLegacyModulesService } from '@/server/services/purchase-legacy-modules.service'
|
||||
import { supplierReissueResponseService } from '@/server/services/supplier-reissue-response.service'
|
||||
import { systemConfigService } from '@/server/services/system-config.service'
|
||||
@ -315,7 +321,10 @@ class WecomReissueService {
|
||||
department_id: '1',
|
||||
fetch_child: '1',
|
||||
})
|
||||
const wantedNames = new Set(['雁兰', '东皇太一', '貂蝉'])
|
||||
const wantedNames = new Set([
|
||||
...REISSUE_SUPPLIER_OWNER_GROUPS.map(([owner]) => owner),
|
||||
DEFAULT_REISSUE_FALLBACK_OWNER,
|
||||
])
|
||||
const matches = (payload.userlist || []).filter((user) =>
|
||||
wantedNames.has(trim(user.name)),
|
||||
)
|
||||
@ -529,35 +538,22 @@ class WecomReissueService {
|
||||
return this.createGroupMessageTask(supplier, renderedText, contact)
|
||||
}
|
||||
|
||||
private async sendInternalSupplierBatch(
|
||||
header: string,
|
||||
owner: string,
|
||||
entries: Array<{ supplier: string; text: string }>,
|
||||
) {
|
||||
const renderedEntries: string[] = []
|
||||
for (const entry of entries) {
|
||||
renderedEntries.push(await this.renderSupplierLink(entry.supplier, entry.text))
|
||||
}
|
||||
return this.sendInternalWebhook(
|
||||
[
|
||||
header,
|
||||
`跟单员:${owner || '未分配'}`,
|
||||
'',
|
||||
renderedEntries.join('\n\n————————\n\n'),
|
||||
].join('\n'),
|
||||
await this.resolveOwnerMention(owner),
|
||||
)
|
||||
}
|
||||
|
||||
private async renderSupplierLink(supplier: string, text: string) {
|
||||
if (!text.includes('{填写链接}')) return text
|
||||
const link = await supplierReissueResponseService.ensureSupplierLink(supplier)
|
||||
const baseUrl = (
|
||||
private resolvePublicBaseUrl() {
|
||||
return (
|
||||
process.env.SUPPLIER_RESPONSE_PUBLIC_BASE_URL?.trim()
|
||||
|| process.env.NEXT_PUBLIC_APP_URL?.trim()
|
||||
|| 'http://localhost:3000'
|
||||
).replace(/\/$/, '')
|
||||
return text.replaceAll('{填写链接}', `${baseUrl}${link.path}`)
|
||||
}
|
||||
|
||||
private async supplierPublicLink(supplier: string) {
|
||||
const link = await supplierReissueResponseService.ensureSupplierLink(supplier)
|
||||
return `${this.resolvePublicBaseUrl()}${link.shortPath || link.path}`
|
||||
}
|
||||
|
||||
private async renderSupplierLink(supplier: string, text: string) {
|
||||
if (!text.includes('{填写链接}')) return text
|
||||
return text.replaceAll('{填写链接}', await this.supplierPublicLink(supplier))
|
||||
}
|
||||
|
||||
async sendSupplierReminder(supplier: string, text: string) {
|
||||
@ -679,52 +675,55 @@ class WecomReissueService {
|
||||
const now = localDateTime(nowDate)
|
||||
const failures: Array<{ supplier: string; message: string }> = []
|
||||
const successIds = new Set<string>()
|
||||
const prepared: Array<{
|
||||
const prepared = new Map<string, Array<{
|
||||
supplier: string
|
||||
owner: string
|
||||
missing: ReissueRecord[]
|
||||
text: string
|
||||
}> = []
|
||||
}>>()
|
||||
const excludedByOwner = new Map<string, number>()
|
||||
|
||||
for (const supplier of supplierNames) {
|
||||
const owner = trim(store.supplierOwners[supplier])
|
||||
const supplierRecords = store.records.filter((record) =>
|
||||
reissueSupplier(record) === supplier
|
||||
&& !reissueHasCallback(record),
|
||||
)
|
||||
excludedByOwner.set(
|
||||
owner,
|
||||
(excludedByOwner.get(owner) || 0)
|
||||
+ supplierRecords.filter(reissueHasSupplierFeedback).length,
|
||||
)
|
||||
const missing = store.records.filter((record) =>
|
||||
reissueSupplier(record) === supplier
|
||||
&& !reissueHasCallback(record)
|
||||
&& !trim(record.supplierRespondedAt)
|
||||
&& !reissueHasSupplierFeedback(record)
|
||||
&& localDateKey(record.followupRemindedAt) !== today,
|
||||
)
|
||||
if (!missing.length) continue
|
||||
const owner = trim(store.supplierOwners[supplier])
|
||||
const lines = missing.map((record, index) =>
|
||||
`${index + 1}. 订单号:${record.orderNo || '未填'} | 超时类型:${record.sourceDetails?.overtimeType || record.reason || '未填'}`,
|
||||
)
|
||||
const text = [
|
||||
`供应商:${supplier}`,
|
||||
`尚未反馈:${missing.length} 条`,
|
||||
nowDate.getDay() === 1 ? '说明:本清单已补入周六、周日异常订单。' : '',
|
||||
'',
|
||||
...lines,
|
||||
'',
|
||||
'填写链接:{填写链接}',
|
||||
'',
|
||||
'请跟单人员确认供应商反馈情况并继续跟进。',
|
||||
].filter((line, index, all) => line || all[index - 1] !== '').join('\n')
|
||||
prepared.push({ supplier, owner, missing, text })
|
||||
prepared.set(owner, [...(prepared.get(owner) || []), { supplier, missing }])
|
||||
}
|
||||
|
||||
const attempted = prepared.length
|
||||
const attempted = [...prepared.values()].reduce((sum, entries) => sum + entries.length, 0)
|
||||
let created = 0
|
||||
const ownerGroups = new Map<string, typeof prepared>()
|
||||
prepared.forEach((entry) => {
|
||||
ownerGroups.set(entry.owner, [...(ownerGroups.get(entry.owner) || []), entry])
|
||||
})
|
||||
for (const [owner, entries] of ownerGroups) {
|
||||
for (const [owner, entries] of prepared) {
|
||||
try {
|
||||
await this.sendInternalSupplierBatch(
|
||||
`【14:00 未反馈催办 · ${entries.length} 家供应商】`,
|
||||
const suppliersWithLinks = await Promise.all(entries.map(async (entry) => ({
|
||||
supplier: entry.supplier,
|
||||
link: await this.supplierPublicLink(entry.supplier),
|
||||
orders: entry.missing.map((record) => ({
|
||||
orderNo: record.orderNo || '未填订单号',
|
||||
overtimeType: record.sourceDetails?.overtimeType || record.reason || '未填超时类型',
|
||||
})),
|
||||
})))
|
||||
const messages = buildFollowupSupplierMessages({
|
||||
owner,
|
||||
entries.map((entry) => ({ supplier: entry.supplier, text: entry.text })),
|
||||
)
|
||||
suppliers: suppliersWithLinks,
|
||||
excludedCount: excludedByOwner.get(owner) || 0,
|
||||
includeWeekend: nowDate.getDay() === 1,
|
||||
})
|
||||
const mention = await this.resolveOwnerMention(owner)
|
||||
for (const [index, message] of messages.entries()) {
|
||||
await this.sendInternalWebhook(message, index === 0 ? mention : {})
|
||||
}
|
||||
entries.forEach((entry) => {
|
||||
entry.missing.forEach((record) => successIds.add(record.id))
|
||||
created += 1
|
||||
@ -759,81 +758,11 @@ class WecomReissueService {
|
||||
created,
|
||||
failures,
|
||||
deliveryMode: 'internal' as const,
|
||||
skipped: '',
|
||||
skipped: attempted ? '' : 'no-unfilled',
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async dispatchDeliveryNodeAlerts(input: { includeQa?: boolean } = {}) {
|
||||
const dashboard = await deliveryControlService.getDashboard()
|
||||
const actionable = dashboard.nodeTasks.filter((task) =>
|
||||
task.state === 'overdue' || task.state === 'due-today',
|
||||
)
|
||||
const groups = new Map<string, typeof actionable>()
|
||||
actionable.forEach((task) => {
|
||||
const key = `${task.owner}::${task.supplier}`
|
||||
groups.set(key, [...(groups.get(key) || []), task])
|
||||
})
|
||||
let attempted = 0
|
||||
let created = 0
|
||||
const failures: Array<{ supplier: string; message: string }> = []
|
||||
for (const tasks of groups.values()) {
|
||||
attempted += 1
|
||||
const first = tasks[0]
|
||||
try {
|
||||
let fillLink = ''
|
||||
if (first.supplier) {
|
||||
try {
|
||||
const link = await supplierReissueResponseService.ensureSupplierLink(first.supplier)
|
||||
const baseUrl = (
|
||||
process.env.SUPPLIER_RESPONSE_PUBLIC_BASE_URL?.trim()
|
||||
|| process.env.NEXT_PUBLIC_APP_URL?.trim()
|
||||
|| 'http://localhost:3000'
|
||||
).replace(/\/$/, '')
|
||||
fillLink = `${baseUrl}${link.path}`
|
||||
} catch {
|
||||
fillLink = ''
|
||||
}
|
||||
}
|
||||
const lines = tasks.map((task, index) => [
|
||||
`${index + 1}. ${task.orderNo || task.contractNo || '未填订单'}|${task.product || '未填产品'}`,
|
||||
` 节点:${task.nodeName}|计划:${task.plannedDate}|交期:${task.dueDate}`,
|
||||
` 状态:${task.state === 'overdue' ? '已超期' : '今日应反馈'}`,
|
||||
].join('\n'))
|
||||
const qaLines = input.includeQa
|
||||
? dashboard.qaPlans
|
||||
.filter((plan) => plan.owner === first.owner)
|
||||
.map((plan) => `${plan.inspectionDate} 质检|${plan.supplier}|${plan.orderNo || plan.contractNo}|${plan.product}`)
|
||||
: []
|
||||
const text = [
|
||||
'【交期节点提醒】',
|
||||
`跟单员:${first.owner || '未分配'}`,
|
||||
`供应商:${first.supplier}`,
|
||||
'',
|
||||
...lines,
|
||||
qaLines.length ? '\n质检准备:' : '',
|
||||
...qaLines,
|
||||
fillLink ? `\n供应商节点反馈链接:${fillLink}` : '',
|
||||
'\n请跟单员确认未反馈节点,并督促供应商通过链接提交进度说明和现场照片。',
|
||||
].filter(Boolean).join('\n')
|
||||
await this.sendInternalWebhook(text, await this.resolveOwnerMention(first.owner))
|
||||
created += 1
|
||||
} catch (error) {
|
||||
failures.push({
|
||||
supplier: first.supplier,
|
||||
message: error instanceof Error ? error.message : '交期节点提醒失败',
|
||||
})
|
||||
}
|
||||
}
|
||||
return {
|
||||
attempted,
|
||||
created,
|
||||
failures,
|
||||
taskCount: actionable.length,
|
||||
qaCount: dashboard.qaPlans.length,
|
||||
}
|
||||
}
|
||||
|
||||
private async dispatchSuppliersInternal(
|
||||
requireAutoSend: boolean,
|
||||
supplierScope?: readonly string[],
|
||||
@ -889,11 +818,19 @@ class WecomReissueService {
|
||||
})
|
||||
for (const [owner, entries] of ownerGroups) {
|
||||
try {
|
||||
await this.sendInternalSupplierBatch(
|
||||
`【应发未发提醒 · ${entries.length} 家供应商】`,
|
||||
const suppliersWithLinks = await Promise.all(entries.map(async (entry) => ({
|
||||
supplier: entry.supplier,
|
||||
count: entry.pending.length,
|
||||
link: await this.supplierPublicLink(entry.supplier),
|
||||
})))
|
||||
const messages = buildInitialSupplierDigestMessages({
|
||||
owner,
|
||||
entries.map((entry) => ({ supplier: entry.supplier, text: entry.text })),
|
||||
)
|
||||
suppliers: suppliersWithLinks,
|
||||
})
|
||||
const mention = await this.resolveOwnerMention(owner)
|
||||
for (const [index, message] of messages.entries()) {
|
||||
await this.sendInternalWebhook(message, index === 0 ? mention : {})
|
||||
}
|
||||
entries.forEach((entry) => {
|
||||
entry.pending.forEach((record) => successIds.add(record.id))
|
||||
created += 1
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user