Files
order-notification-automation/src/modules/order-rules/collecting-batches.cjs
T

58 lines
7.2 KiB
JavaScript

'use strict';
const crypto=require('node:crypto');
const {fail}=require('./validation.cjs'),{upcomingWindow}=require('./window.cjs'),{delivery}=require('./delivery.cjs');
const digest=value=>crypto.createHash('sha256').update(JSON.stringify(value)).digest('hex');
const idFor=(rule,cutoff,mode='normal')=>'collecting-'+digest([rule.id,rule.version,rule.categoryId,mode,new Date(cutoff).toISOString(),mode==='huizhou'?rule.huizhouTemplateId:rule.bodyTemplateId]).slice(0,32);
function definition(store,rule,cutoff,mode,template){
const signature=store.settings().channelId?store.signatureResolver?.(store.settings().channelId):null;
const subject=template?.subject||rule.subjectPrefix||rule.name,format=template?.html?'html':'text',body=template?.html||template?.text||[rule.intro,'{{订单明细}}',mode==='normal'?'存放地址:{{存放地址}}':''].filter(Boolean).join('\n\n');
return {context:digest([rule,new Date(cutoff).toISOString(),mode,template?[template.id,template.version,template.bindingVersion]:null,signature?[signature.channelId,signature.version]:null]),subject,format,body};
}
function contentFor(store,rule,cutoff,mode,template){
const id=idFor(rule,cutoff,mode),saved=store.get('batch-content-drafts',id);if(!saved)return null;
const base=definition(store,rule,cutoff,mode,template);if(saved.context!==base.context)fail('本批次模板、规则或发件账户已变化,请重新核对并保存批次内容。',409);
if(template?.attachments?.length)fail('业务通知模板禁止附件,批次编辑不能覆盖此限制。',409);
return {template:{...(template||{}),id:template?.id||rule.bodyTemplateId||id,version:template?.version||rule.version,notificationMode:mode,status:'active',attachments:[],subject:saved.subject,text:saved.text,html:saved.html},edit:{id,version:saved.version,updatedAt:saved.updatedAt,updatedBy:saved.updatedBy}};
}
function list(store,{cutoff}={}){
if(typeof store.clock!=='function'||typeof store.schedule!=='function'||typeof store.calendar!=='function')return [];
const window=cutoff?require('./window.cjs').windowForCutoff(cutoff,store.schedule(),store.calendar()):upcomingWindow(store.clock(),store.schedule(),store.calendar());if(!window)return [];
const groups=new Map(),frozen=store.all('batches');
for(const order of store.all('orders')){
const rule=order.ruleSnapshot;if(order.removedAt||!rule?.id||!rule.categoryId||!require('./scopes.cjs').matchesScope(rule,order.event||{}))continue;
if(order.blockedByBatchId||order.status==='ignored')continue;
for(const mode of ['normal','huizhou']){
const carried=require('./carry-forward.cjs').windowForOrder(store,order,mode);if(order.missedWindow&&!carried||!require('./restricted-test.cjs').orderInWindow(store,order,window,mode))continue;
const notice=delivery(order,mode);if(!notice||notice.batchId||!['identified','preparing','archived','pending','blocked','failed'].includes(notice.status))continue;
if(mode==='huizhou'&&rule.huizhouEnabled!==true)continue;
if(frozen.some(b=>b.categoryId===rule.categoryId&&(b.notificationMode||'normal')===mode&&b.cutoff===window.end))continue;
const id=idFor(rule,window.end,mode);if(!groups.has(id))groups.set(id,{id,status:'collecting',categoryId:rule.categoryId,notificationMode:mode,cutoff:window.end,window,windowStart:window.start,windowEnd:window.end,rule,orders:[],orderIds:[],attachments:[],createdAt:order.ingestedAt||order.createdAt,...(rule.testRunId?{testRunId:rule.testRunId}:{})});const group=groups.get(id);group.orders.push(order);group.orderIds.push(order.id);
}
}
return [...groups.values()].map(group=>{
const {rule,orders,...value}=group,saved=store.get('batch-content-drafts',group.id);let template,sourceError;try{template=store.templateResolver?.(rule.categoryId,rule,group.notificationMode);}catch(error){sourceError=error.message;}let base;try{base=definition(store,rule,window.end,group.notificationMode,template);}catch(error){sourceError=error.message;base={context:digest([rule,window.end,group.notificationMode]),subject:rule.subjectPrefix||rule.name,format:'text',body:'{{订单明细}}\n{{存放地址}}'};}
const row={...value,carriedOrderIds:orders.filter(o=>require('./carry-forward.cjs').windowForOrder(store,o,group.notificationMode)?.end===window.end).map(o=>o.id),version:saved?.version||0,context:base.context,editor:saved?{subject:saved.subject,format:saved.format,body:saved.body}:base,edited:!!saved,editable:!sourceError&&+store.clock()<Date.parse(window.end),subject:saved?.subject||base.subject,to:rule.to,cc:rule.cc||[],orderNos:orders.map(o=>o.event?.orderNo).filter(Boolean),ruleSnapshot:rule};
try{if(sourceError)fail(sourceError,409);const snapshot=require('./template.cjs').composeBatch(rule,require('./huizhou.cjs').ordersForMode(orders,group.notificationMode),window.end,store,{window,notificationMode:group.notificationMode});Object.assign(row,{subject:snapshot.subject,text:snapshot.text,html:snapshot.html,template:snapshot.template,signature:snapshot.signature});}
catch(error){row.error=error.message;row.text='';row.html='';}
return row;
});
}
function get(store,id){const group=list(store).find(b=>b.id===id);if(!group)fail('收集批次已结束、冻结或不存在,请刷新。',409);return group;}
function save(store,id,input,actor){
if(actor?.role!=='admin')fail('仅管理员可以编辑批次邮件内容。',403);
return store.transaction(()=>{
const group=get(store,id);if(!group.editable)fail('本批次已到发送截止时间,不能再编辑。',409);
if(!input||Object.keys(input).some(k=>!['version','context','subject','format','body'].includes(k))||input.version!==group.version||input.context!==group.context)fail('批次版本或来源配置已变化,请刷新后重新编辑。',409);
if(typeof input.subject!=='string'||!input.subject.trim()||input.subject.length>300||/[\x00-\x1f]/.test(input.subject))fail('邮件标题无效。');
const content=require('../mail/content.cjs').normalizeBody(input);require('../mail/parser.cjs').validateVariables(input.subject,content.text,content.html);
if(!/{{\s*(订单明细|订单列表)\s*}}/.test(input.body))fail('请保留 {{订单明细}} 或 {{订单列表}},以便新增订单自动加入邮件。');
if(group.notificationMode==='normal'&&!/{{\s*存放地址\s*}}/.test(input.body))fail('普通通知请保留 {{存放地址}}。');
const value={id,version:group.version+1,context:group.context,subject:input.subject.trim(),...content,updatedAt:store.now(),updatedBy:actor.username};store.put('batch-content-drafts',value);
const template=store.templateResolver?.(group.ruleSnapshot.categoryId,group.ruleSnapshot,group.notificationMode);contentFor(store,group.ruleSnapshot,group.cutoff,group.notificationMode,template);
const signature=store.settings().channelId?store.signatureResolver?.(store.settings().channelId):null;require('../mail/content.cjs').appendSignature({subject:value.subject,text:value.text,html:value.html},signature,store.settings().maxMessageBytes);
if(16384+Buffer.byteLength(value.subject+value.text+value.html)*2>store.settings().maxMessageBytes)fail('编辑后的批次内容超过邮件容量限制。',409);
const rendered=get(store,id);store.audit(actor.username,'编辑收集中批次',id+' v'+value.version);return rendered;
});
}
module.exports={idFor,list,get,save,contentFor};