'use strict'; const retryHistory=(store,id)=>store.db.prepare('SELECT id,payload FROM retry_audit WHERE item_id=? ORDER BY rowid').all(id).map(row=>store.decode(row.id,row.payload)); const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path'); const {NotificationStore}=require('../../src/modules/notifications/store.cjs');const {NotificationService}=require('../../src/modules/notifications/service.cjs');const {MailStore}=require('../../src/modules/mail/store.cjs');const {MailService}=require('../../src/modules/mail/service.cjs'); const fields={id:'flow.id',version:'flow.version',industry:'flow.industry',brief:'flow.brief',subject:'flow.subject',occurredAt:'flow.at'}; const event={flow:{id:'FLOW-001',version:'v1',industry:'宽带',brief:'第一行原文\n第二行 <原文> & 保留',subject:'业务提醒',at:'2026-10-17T08:00:00+08:00'}}; async function fixture(t,{uncertain=false}={}){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-notice-'));const store=new NotificationStore(path.join(dir,'notifications'));const mailStore=new MailStore(path.join(dir,'mail'));const channel=mailStore.saveChannel({name:'工作邮箱',email:'notice@company.test',smtp:{host:'smtp.company.test',port:465,security:'tls',user:'notice',password:'Fixture-only-password'},imap:{host:'imap.company.test',port:993,security:'tls',user:'notice',password:'Fixture-only-password'},senders:['author@company.test'],enabled:false});mailStore.setState(channel.id,1,{smtp:true});const sent=[];const mail=new MailService({store:mailStore,smtpFactory:()=>({verify:async()=>{},sendMail:async payload=>{sent.push(payload);if(uncertain)throw new Error('socket disconnected');return {accepted:['interface@company.test'],rejected:[]};},close(){}})});const service=new NotificationService({store,mail,settings:()=>({schedule:{times:['09:00','17:00'],timezone:'Asia/Shanghai',weekends:true,mode:'product_line',missed:'next_window'},groups:[{productLine:'宽带',to:['interface@company.test'],cc:[]}]}),calendar:()=>[],clock:()=>new Date('2026-10-17T08:59:00+08:00')});service.saveSettings({version:1,enabled:false,sourceName:'业务流程',channelId:channel.id,fieldMap:fields,maxAttempts:3});t.after(async()=>{await service.stop();await mail.stop();store.close();mailStore.close();await fs.rm(dir,{recursive:true,force:true});});return {dir,store,service,sent,channel};} test('mapped notifications copy brief text, deduplicate versions and send no attachments at a configured slot',async t=>{ const {store,service,sent}=await fixture(t);const preview=service.preview(event);assert.equal(preview.event.brief,event.flow.brief);assert.equal(store.items().length,0); const item=service.ingest(event);assert.equal(service.ingest(event).id,item.id);assert.equal(store.items().length,1); assert.throws(()=>service.ingest({flow:{...event.flow,brief:'changed without version'}}),e=>e.status===409); service.saveSettings({...store.settings(),sourceName:'来源改名'});assert.equal(service.ingest(event).id,item.id); await service.tick(new Date('2026-10-17T09:00:01+08:00'));assert.equal(sent.length,0); const settings=store.settings();service.saveSettings({...settings,enabled:true});await service.tick(new Date('2026-10-17T09:00:01+08:00'));assert.equal(sent.length,1); assert.equal(sent[0].text,'第一行原文\n第二行 <原文> & 保留');assert.deepEqual(sent[0].attachments,[]);assert.deepEqual(sent[0].to,['interface@company.test']);assert.equal(store.items()[0].status,'sent'); await service.tick(new Date('2026-10-17T09:00:20+08:00'));assert.equal(sent.length,1); }); test('unmapped industries cannot starve a later valid notification behind the queue read limit',async t=>{ const {store,service,sent}=await fixture(t);for(let i=0;i<201;i++)service.ingest({flow:{...event.flow,id:'unmapped-'+i,industry:'尚未配置'}}); service.ingest(event);service.saveSettings({...store.settings(),enabled:true});await service.tick(new Date('2026-10-17T09:00:00+08:00')); assert.equal(sent.length,1);assert.equal(sent[0].text,event.flow.brief); }); test('uncertain delivery remains blocked across restart and requires recorded human evidence to retry',async t=>{ const {store,service,sent}=await fixture(t,{uncertain:true});service.ingest(event);service.saveSettings({...store.settings(),enabled:true});await service.tick(new Date('2026-10-17T09:00:00+08:00'));assert.equal(store.items()[0].status,'unknown');assert.equal(store.batches()[0].status,'unknown'); await service.tick(new Date('2026-10-17T17:00:00+08:00'));assert.equal(sent.length,1); const unknownId=store.batches()[0].id;for(let index=0;index<101;index++){const item=service.ingest({flow:{...event.flow,id:'newer-'+index}}),batch=store.prepare([item],{industry:'宽带',to:['interface@company.test'],cc:[],text:'newer',subject:'newer'});store.mark(batch,'sent');} assert.equal(store.batches().some(batch=>batch.id===unknownId),true); assert.throws(()=>service.resolve(unknownId,{resolution:'retry',note:''},'admin'),e=>e.status===400); service.resolve(unknownId,{resolution:'sent',note:'已在 SMTP 服务端核实发送成功'},'admin');assert.equal(store.items()[0].status,'sent'); }); test('an IMAP operation occupying the due slot does not consume the notification window',async t=>{ const {store,service,sent}=await fixture(t);service.ingest(event);service.saveSettings({...store.settings(),enabled:true}); let release;const occupied=service.mail.exclusive(store.settings().channelId,()=>new Promise(resolve=>{release=resolve;}));await Promise.resolve(); await service.tick(new Date('2026-10-17T09:00:00+08:00'));assert.equal(sent.length,0);release();await occupied; await service.tick(new Date('2026-10-17T09:00:30+08:00'));assert.equal(sent.length,1); }); test('incomplete and unsafe field maps cannot enable delivery and unmapped industries stay visible',async t=>{ const {store,service}=await fixture(t);assert.equal(service.preview({flow:{...event.flow,industry:'未配置产业'}}).valid,false); assert.throws(()=>service.ingest({flow:{...event.flow,brief:''}}),e=>e.status===400); assert.throws(()=>service.saveSettings({...store.settings(),fieldMap:{...fields,brief:'__proto__.secret'}}),e=>e.status===400); service.ingest({flow:{...event.flow,industry:'未配置产业'}});service.saveSettings({...store.settings(),enabled:true});await service.tick(new Date('2026-10-17T09:00:00+08:00'));assert.equal(store.items()[0].status,'blocked'); }); test('field mapping supports Chinese object keys and rejects control characters in identity fields',async t=>{ const {store,service}=await fixture(t);service.saveSettings({...store.settings(),fieldMap:{id:'来源.编号',version:'',industry:'来源.产业',brief:'来源.简要说明',subject:'',occurredAt:''}}); const sample={来源:{编号:'FLOW-CN',产业:'宽带',简要说明:'中文字段原文'}};assert.equal(service.preview(sample).event.brief,'中文字段原文'); assert.throws(()=>service.ingest({来源:{...sample.来源,编号:'bad\u0000identity'}}),e=>e.status===400); }); test('opening another store never recovers the active owner reservation',async t=>{ const {dir,store,service}=await fixture(t);const item=service.ingest(event),batch=store.prepare([item],{to:[],sourceIds:[item.sourceId]}); const other=new NotificationStore(path.join(dir,'notifications'));try{ assert.equal(other.items()[0].status,'reserved');assert.equal(other.batches()[0].status,'prepared');assert.equal(store.items()[0].batch_id,batch); }finally{other.close();} }); test('cancelled or stolen reservations cannot cross the SMTP send boundary',async t=>{ const {store,service,sent}=await fixture(t);service.ingest(event);service.saveSettings({...store.settings(),enabled:true}); service.mail.smtpFactory=()=>({verify:async()=>{store.db.prepare("UPDATE batches SET status='cancelled' WHERE status='prepared'").run();},sendMail:async payload=>{sent.push(payload);return {accepted:['interface@company.test']};},close(){}}); await service.tick(new Date('2026-10-17T09:00:00+08:00'));assert.equal(sent.length,0);assert.equal(store.batches()[0].status,'cancelled'); const item=service.ingest({flow:{...event.flow,id:'stolen'}}),batch=store.prepare([item],{to:[]});store.db.prepare("UPDATE items SET batch_id='another-owner' WHERE id=?").run(item.id); assert.throws(()=>store.beginSending(batch),e=>e.status===409);assert.equal(store.batches().find(b=>b.id===batch).status,'prepared'); }); test('last SMTP verification failure exhausts one item until evidence-based CAS manual retry',async t=>{ const {store,service,sent}=await fixture(t);const item=service.ingest(event);service.saveSettings({...store.settings(),enabled:true,maxAttempts:1}); service.mail.smtpFactory=()=>({verify:async()=>{throw new Error('fixture verification failure');},close(){}}); await service.tick(new Date('2026-10-17T09:00:00+08:00'));assert.equal(store.items()[0].status,'exhausted');assert.doesNotMatch(store.items()[0].error,/等待下个时段/);assert.doesNotMatch(store.batches()[0].error,/等待下个时段/); await service.tick(new Date('2026-10-17T17:00:00+08:00'));assert.equal(store.items()[0].attempts,1);assert.equal(sent.length,0); const batchId=store.items()[0].batch_id;assert.throws(()=>service.retryItem(item.id,{batchId,note:''},'admin'),e=>e.status===400); service.retryItem(item.id,{batchId,note:'已修复 SMTP 并完成连接检查'},'admin');assert.equal(store.items()[0].status,'pending');assert.equal(store.items()[0].attempts,0); assert.throws(()=>service.retryItem(item.id,{batchId,note:'重复提交同一核验依据'},'admin'),e=>e.status===409); const audit=retryHistory(store,item.id);assert.equal(audit.length,1);assert.equal(audit[0].actor,'admin');assert.match(audit[0].note,/SMTP/); service.mail.smtpFactory=()=>({verify:async()=>{},sendMail:async payload=>{sent.push(payload);return {accepted:['interface@company.test'],rejected:[]};},close(){}});await service.tick(new Date('2026-10-18T09:00:00+08:00'));assert.equal(sent.length,1);assert.equal(store.items()[0].status,'sent'); }); test('explicit recovery and lowering attempts normalize eligible work but never revive unknown or exhausted',async t=>{ const {store,service}=await fixture(t);const item=service.ingest(event),batch=store.prepare([item],{to:[]}); store.saveSettings({...store.settings(),maxAttempts:1});store.recover();assert.equal(store.items()[0].status,'exhausted'); store.saveSettings({...store.settings(),maxAttempts:3});assert.equal(store.items()[0].status,'exhausted'); service.retryItem(item.id,{batchId:batch,note:'已核实未发送且完成连接修复'},'admin');const second=store.prepare(store.items(),{to:[]});store.beginSending(second);store.recover();assert.equal(store.items()[0].status,'unknown'); assert.throws(()=>service.retryItem(item.id,{batchId:second,note:'不能绕过未知发送结果核验'},'admin'),e=>e.status===409); store.recover();assert.equal(store.items()[0].status,'unknown'); const next=service.ingest({flow:{...event.flow,id:'lower-limit'}});store.db.prepare('UPDATE items SET attempts=2 WHERE id=?').run(next.id);store.saveSettings({...store.settings(),maxAttempts:2});assert.equal(store.items().find(i=>i.id===next.id).status,'exhausted'); }); test('manual retry resets only one exhausted item and stale evidence cannot reset its next failure',async t=>{ const {store,service}=await fixture(t);const first=service.ingest(event),second=service.ingest({flow:{...event.flow,id:'SECOND'}});store.saveSettings({...store.settings(),maxAttempts:1});const batchId=store.prepare([first,second],{to:[]});store.mark(batchId,'failed','fixture verify failure'); const input={batchId,note:'已修复 SMTP 并核实第一项未发送'};service.retryItem(first.id,input,'admin');assert.equal(store.items().find(i=>i.id===first.id).attempts,0);assert.equal(store.items().find(i=>i.id===second.id).status,'exhausted');assert.equal(store.items().find(i=>i.id===second.id).attempts,1); const nextBatch=store.prepare([store.items().find(i=>i.id===first.id)],{to:[]});store.mark(nextBatch,'failed','fixture verify failure again');assert.throws(()=>service.retryItem(first.id,input,'admin'),e=>e.status===409);assert.equal(store.items().find(i=>i.id===first.id).attempts,1);assert.equal(retryHistory(store,first.id).length,1); });