fix: separate pending and sent mail batches
This commit is contained in:
1 parent
fd2dd557c7
commit
5fe461c77d
7 files changed
+50
-8
No files matched your search
@@ -1,5 +1,12 @@
|
||||
# 开发交接(2026-10-23)
|
||||
|
||||
## 2026-10-26 邮件批次待发送/已发送分离
|
||||
|
||||
- 邮件批次以 Tabler 页签提供待发送、已发送、全部;替代原范围下拉。待发送含收集中、已冻结、发送中、失败及结果待核实;已发送仅显示 sent,取消记录在全部中保留。
|
||||
- 修复默认 active 与 status=sent 相交导致历史不可见;服务端和地址状态均将该旧查询规范到 sent 范围。范围在权限筛选后分页,不改冻结正文、收件人、发送回执或发送行为。切换清除状态并回第一页,刷新/前后退恢复地址;点击当前页签不重复加载。
|
||||
- 批次列表和详情显示发送时间(缺失不造时间);已发送正文和订单详情继续可查,只读且不提供编辑/补发。实机核对当前业务批次表为空,邮箱存在两条独立 sends 回执,不伪造为业务批次历史。
|
||||
- 验证使用隔离批次与账号,未发送邮件、未办理 BPM、未调整自动处理或发信设置;相关查询/分页/导航/弹窗30项通过。用户三份本地业务设计草稿保持不动。
|
||||
|
||||
## 2026-10-26 订单采集失败修复与剩余边界
|
||||
|
||||
- 修复动态明细 datamap 包含合法隐藏列时被误判的问题:额外列必须有同表隐藏控件,且每条后端记录都确有对应列;仍拒绝跨表映射、不明确行关系及缺少可见字段。
|
||||
|
||||
@@ -21,7 +21,8 @@ function filters(input={},kind){
|
||||
for(const name of ['page','pageSize']){result[name]=Number(result[name]);if(!Number.isSafeInteger(result[name])||result[name]<1)fail('页码或分页大小无效。');}
|
||||
if(![25,50,100].includes(result.pageSize))fail('每页仅支持25、50或100条。');
|
||||
if(result.status&&!(kind==='batches'?batchStates:orderStates).includes(result.status))fail('状态筛选无效。');
|
||||
if(kind==='batches'&&!['active','all'].includes(result.scope))fail('批次范围无效。');
|
||||
if(kind==='batches'&&!['active','sent','all'].includes(result.scope))fail('批次范围无效。');
|
||||
if(kind==='batches'&&result.status==='sent'&&result.scope==='active')result.scope='sent';
|
||||
for(const key of ['q','categoryId','connectionId'])if(result[key]!==undefined&&(typeof result[key]!=='string'||result[key].length>200))fail('查询内容过长或无效。');
|
||||
for(const key of ['from','to'])if(result[key]&&(!/^\d{4}-\d{2}-\d{2}$/.test(result[key])||!Number.isFinite(Date.parse(result[key]))||new Date(result[key]).toISOString().slice(0,10)!==result[key]))fail('日期筛选无效。');
|
||||
if(result.from&&result.to&&result.from>result.to)fail('开始日期不能晚于结束日期。');
|
||||
@@ -90,11 +91,11 @@ function publicRevision(context,user){
|
||||
}
|
||||
function queryOrders(context,input,user){const rows=visibleOrders(context,user),revision=crypto.createHash('sha256').update(publicRevision(context,user)+JSON.stringify(rows.map(r=>[r.id,r.collectingBatches]))).digest('hex').slice(0,24);return page(rows,filters(input,'orders'),revision);}
|
||||
function batchRow(context,batch){
|
||||
return {...pick(batch,['id','version','categoryId','subject','status','error','createdAt','windowStart','windowEnd','cutoff','orderNos','testRunId']),categoryName:batch.ruleSnapshot?.name||context.orderRules.get('rules',batch.categoryId)?.draft?.name||batch.categoryId,notificationMode:modeOf(batch),windowStart:batch.windowStart||batch.window?.start,windowEnd:batch.windowEnd||batch.window?.end||batch.cutoff,orderCount:batch.orderIds?.length||0,connectionIds:[...new Set((batch.orderIds||[]).map(id=>{const o=context.orderRules.get('orders',id);return o?.sample?.connectionId||o?.event?.connectionId||o?.connectionId;}).filter(Boolean))]};
|
||||
return {...pick(batch,['id','version','categoryId','subject','status','error','createdAt','sentAt','resolvedAt','windowStart','windowEnd','cutoff','orderNos','testRunId']),categoryName:batch.ruleSnapshot?.name||context.orderRules.get('rules',batch.categoryId)?.draft?.name||batch.categoryId,notificationMode:modeOf(batch),windowStart:batch.windowStart||batch.window?.start,windowEnd:batch.windowEnd||batch.window?.end||batch.cutoff,orderCount:batch.orderIds?.length||0,connectionIds:[...new Set((batch.orderIds||[]).map(id=>{const o=context.orderRules.get('orders',id);return o?.sample?.connectionId||o?.event?.connectionId||o?.connectionId;}).filter(Boolean))]};
|
||||
}
|
||||
function queryBatches(context,input,user){
|
||||
const f=filters(input,'batches'),data=records(context.orderRules);
|
||||
const rows=[...data.batches,...require('./collecting-batches.cjs').list(context.orderRules)].filter(b=>canReadBatch(context.workspace,user,b,context.orderRules)&&(f.scope==='all'||!['sent','cancelled'].includes(b.status))).map(b=>batchRow(context,b));
|
||||
const rows=[...data.batches,...require('./collecting-batches.cjs').list(context.orderRules)].filter(b=>canReadBatch(context.workspace,user,b,context.orderRules)&&(f.scope==='all'||(f.scope==='sent'?b.status==='sent':!['sent','cancelled'].includes(b.status)))).map(b=>batchRow(context,b));
|
||||
return page(rows,f,crypto.createHash('sha256').update(publicRevision(context,user)+JSON.stringify(rows)).digest('hex').slice(0,24));
|
||||
}
|
||||
function orderDetail(context,id,user){
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict');
|
||||
const {orderDrivenUI}=require('../fixtures/order-driven-ui.cjs');
|
||||
test('batch tabs separate sent history, survive reload/back and keep sent content read-only',{timeout:60000},async t=>{
|
||||
const {page,runtime,base,sample}=await orderDrivenUI(t,'#notification-batches'),s=runtime.orderRules;
|
||||
s.put('orders',{id:'history-order',categoryId:'bs-change',orderNo:'HISTORY-1',status:'sent',sample:{connectionId:sample.connectionId},event:{connectionId:sample.connectionId}});
|
||||
for(const [id,status]of [['pending-batch','prepared'],['sent-batch','sent'],['cancelled-batch','cancelled']])s.put('batches',{id,status,version:1,orderIds:['history-order'],orderNos:['HISTORY-1'],categoryId:'bs-change',subject:id,createdAt:'2026-10-26T02:00:00Z',sentAt:status==='sent'?'2026-10-26T03:00:00Z':undefined,text:'Frozen body',to:['2639266652@qq.com'],cc:[],attachments:[]});
|
||||
await page.getByRole('button',{name:'刷新数据',exact:true}).click();
|
||||
const pending=page.getByRole('tab',{name:'待发送',exact:true}),sent=page.getByRole('tab',{name:'已发送',exact:true});await pending.waitFor();await page.getByText('pending-batch',{exact:true}).waitFor();assert.equal(await page.getByText('sent-batch',{exact:true}).count(),0);
|
||||
await sent.click();await page.getByText('sent-batch',{exact:true}).waitFor();assert.match(page.url(),/scope=sent/);assert.equal(await sent.getAttribute('aria-selected'),'true');assert.equal(await page.getByText('pending-batch',{exact:true}).count(),0);
|
||||
await page.getByRole('button',{name:'查看详情',exact:true}).click();const dialog=page.getByRole('dialog',{name:'业务详情',exact:true});await dialog.getByText('Frozen body',{exact:true}).waitFor();await dialog.getByText('发送时间',{exact:true}).waitFor();assert.equal(await dialog.getByRole('button',{name:'保存批次内容',exact:true}).count(),0);assert.equal(await dialog.getByRole('button',{name:'人工补发原冻结批次',exact:true}).count(),0);await dialog.getByRole('button',{name:'关闭详情',exact:true}).click();
|
||||
await page.reload();await page.getByText('sent-batch',{exact:true}).waitFor();await page.getByRole('tab',{name:'待发送',exact:true}).click();await page.getByText('pending-batch',{exact:true}).waitFor();await page.goBack();await page.getByText('sent-batch',{exact:true}).waitFor();
|
||||
await page.goto(base+'/#notification-batches?status=sent');await page.getByText('sent-batch',{exact:true}).waitFor();assert.equal(await page.getByRole('tab',{name:'已发送',exact:true}).getAttribute('aria-selected'),'true');
|
||||
await page.getByRole('tab',{name:'全部',exact:true}).click();await page.getByText('cancelled-batch',{exact:true}).waitFor();
|
||||
});
|
||||
@@ -60,6 +60,16 @@ test('batch pagination covers more than three pages and scope all retains comple
|
||||
const c=fixture();for(let i=0;i<85;i++)c.orderRules.all('batches').push({id:'b'+i,orderIds:['o0'],status:i===0?'sent':'prepared',subject:'Batch '+i});
|
||||
const active=queryBatches(c,{page:999,pageSize:25},user);assert.equal(active.page,4);assert.equal(active.total,85);assert.equal(active.items.length,10);assert.equal(queryBatches(c,{scope:'all'},user).total,86);
|
||||
});
|
||||
|
||||
test('sent batches have a dedicated history scope and status-only links never hide sent records',()=>{
|
||||
const c=fixture(),batches=c.orderRules.all('batches');
|
||||
batches.push({id:'delivered',orderIds:['o0'],status:'sent',subject:'Sent notice',sentAt:'2026-10-26T03:00:00Z'},{id:'cancelled',orderIds:['o0'],status:'cancelled'},{id:'private-sent',orderIds:['foreign'],status:'sent'});
|
||||
const history=queryBatches(c,{scope:'sent'},user);assert.deepEqual(history.items.map(b=>b.id),['delivered']);assert.equal(history.items[0].sentAt,'2026-10-26T03:00:00Z');
|
||||
assert.deepEqual(queryBatches(c,{status:'sent'},user).items.map(b=>b.id),['delivered']);
|
||||
assert.deepEqual(queryBatches(c,{},user).items.map(b=>b.id),['old']);
|
||||
assert.equal(queryBatches(c,{scope:'all'},user).total,3);
|
||||
assert.equal(queryBatches(c,{scope:'sent',status:'unknown'},user).total,0);
|
||||
});
|
||||
test('HTTP query routing rejects missing services, invalid parameters and malformed encoding',async()=>{
|
||||
const {orderRuleQueryApi}=require('../../src/modules/order-rules/query-api.cjs');const c=fixture(),invoke=(route,extra={})=>orderRuleQueryApi({...c,user,route,method:'GET',url:new URL(route,'http://localhost'),reply(){},...extra});
|
||||
await assert.rejects(()=>invoke('/api/order-rules/orders?unused=1',{route:'/api/order-rules/orders'}),e=>e.status===400||e.statusCode===400);
|
||||
|
||||
@@ -23,7 +23,7 @@ window.BusinessRecordDetail=(()=>{
|
||||
if(d.status==='candidate')return '<h3 class="h4">未匹配通知规则</h3><p>当前流程或节点未命中 Excel 通知规则,不会归档或发送邮件。</p><dl>'+field('原因',d.reason)+field('流程',e.processName)+field('当前节点',e.nodeName)+field('BPM任务',e.taskId)+field('接收时间',formatDate(e.receivedAt))+'</dl>';
|
||||
return `<h3 class="h4">处理进度</h3><dl>${field('订单',d.orderNo)}${field('状态',statuses[d.status]||d.status)}${field('原因',t?.error||d.error||d.reason)}${field('执行步骤',t?.step)}${field('执行任务',t?.id)}${field('规则版本',d.ruleVersion)}</dl>${captureBody(d)}${notificationBody('normal',d.notifications?.normal)}${notificationBody('huizhou',d.notifications?.huizhou)}<h3 class="h4">来源</h3><dl>${field('连接',d.connectionId)}${field('流程',e.processName)}${field('节点',e.nodeName)}${field('流程实例',e.instanceId)}${field('BPM任务',e.taskId)}${field('来源版本',e.revision)}${field('接收时间',formatDate(e.receivedAt))}</dl><h3 class="h4">订单摘要</h3><pre class="notification-brief">${esc(e.brief||e.title||'未取得摘要')}</pre><h3 class="h4">PDF / 归档</h3><p>归档代次 ${esc(d.archiveGeneration)} · ${esc(formatDate(d.archivedAt))}</p>${d.files.map(f=>`<p><a href="${esc(f.url)}">${esc(f.name||'下载归档 PDF')}</a> · ${esc(f.size)} 字节</p>`).join('')||'<p class="text-secondary">尚无可验证归档文件</p>'}<h3 class="h4">邮件批次</h3>${d.batches.map(b=>`<p><button type="button" class="btn btn-link p-0" data-related-batch="${esc(b.id)}">${esc(b.subject||b.id)}</button> · ${b.notificationMode==='huizhou'?'惠州通知':'普通通知'} · ${esc(statuses[b.status]||b.status)}</p>`).join('')||'<p class="text-secondary">尚未编入批次</p>'}${t?.exceptionId?`<a href="#exceptions?id=${encodeURIComponent(t.exceptionId)}">处理关联异常</a>`:''}${t?.revisionEvidence?`<h3 class="h4 mt-3">修订核对</h3><div class="table-responsive"><table class="table"><thead><tr><th>信息</th><th>原修订</th><th>新修订</th></tr></thead><tbody>${['revision','orderNo','title','receivedAt','processName','nodeName','quantity','brief'].map(key=>`<tr><td>${esc(key)}</td><td>${esc(t.revisionEvidence.previous[key]||'—')}</td><td>${esc(t.revisionEvidence.incoming[key]||'—')}</td></tr>`).join('')}</tbody></table></div>`:''}${user.role==='admin'&&t?.conflict&&!t.missedWindow&&!['unknown','sent','sending','batched'].includes(d.status)?form('revision','保存修订核对','<select name="resolution" class="form-select"><option value="adopt">采用新修订</option><option value="ignore">忽略该变更</option></select>'):''}${user.role!=='viewer'&&t&&!t.conflict&&!t.missedWindow&&['failed','blocked'].includes(t.status)?form('retry',taskLeftNode(t)?'核验当前任务并重试':t.retryPolicy==='manual'?'核验后重试采集':'重试失败任务',taskLeftNode(t)?'<label class="form-check mb-2"><input class="form-check-input" type="checkbox" required><span class="form-check-label">确认仅核验原通知任务;不使用历史实例替代</span></label>':t.retryPolicy==='manual'?'<label class="form-check mb-2"><input class="form-check-input" type="checkbox" required><span class="form-check-label">已核对原任务证据并完成适配修复</span></label>':''):''}`;
|
||||
}
|
||||
function batchBody(d){return `<dl>${field('主题',d.subject)}${field('通知模式',d.notificationMode==='huizhou'?'惠州通知':'普通通知')}${field('类别',d.categoryName||d.categoryId)}${field('状态',statuses[d.status]||d.status)}${field('原因 / 超时说明',d.error)}${field('时段开始',formatDate(d.windowStart||d.window?.start))}${field('截止时间',formatDate(d.windowEnd||d.cutoff||d.window?.end))}${field('收件人',(d.to||[]).join('、'))}${field('抄送',(d.cc||[]).join('、'))}</dl><h3 class="h4">${d.status==='collecting'?'当前汇总正文':'冻结正文'}</h3><pre class="notification-brief">${esc(d.text||'无正文')}</pre><details class="mb-3"><summary>查看实际HTML邮件预览</summary><iframe class="mail-preview mt-2" title="批次邮件预览" sandbox src="/api/order-rules/batches/${encodeURIComponent(d.id)}/preview"></iframe></details>${window.BatchContentEditor.render(d,{esc,user})}<h3 class="h4">附件</h3>${d.attachments.map(a=>`<p>${esc(a.name||a.filename)} · ${esc(a.size||'—')} 字节</p>`).join('')||'无附件'}<h3 class="h4 mt-3">关联订单</h3>${d.orders.map(o=>`<p><button type="button" class="btn btn-link p-0" data-related-order="${esc(o.id)}">${esc(o.orderNo||o.id)}</button></p>`).join('')}<p class="small text-secondary">SMTP 接受不代表最终送达。结果不明时必须先核验,不会自动补发。</p>${user.role==='admin'&&d.status==='unknown'?form('resolve','保存核验结论','<select name="resolution" class="form-select"><option value="sent">已核实邮件服务器接受</option><option value="retry">已核实未发送,允许重试</option></select>'):''}${user.role==='admin'&&d.status==='failed'?form('resend','人工补发原冻结批次'):''}`;}
|
||||
function batchBody(d){return `<dl>${field('主题',d.subject)}${field('通知模式',d.notificationMode==='huizhou'?'惠州通知':'普通通知')}${field('类别',d.categoryName||d.categoryId)}${field('状态',statuses[d.status]||d.status)}${d.status==='sent'?field('发送时间',formatDate(d.sentAt||d.resolvedAt)):''}${field('原因 / 超时说明',d.error)}${field('时段开始',formatDate(d.windowStart||d.window?.start))}${field('截止时间',formatDate(d.windowEnd||d.cutoff||d.window?.end))}${field('收件人',(d.to||[]).join('、'))}${field('抄送',(d.cc||[]).join('、'))}</dl><h3 class="h4">${d.status==='collecting'?'当前汇总正文':'冻结正文'}</h3><pre class="notification-brief">${esc(d.text||'无正文')}</pre><details class="mb-3"><summary>查看实际HTML邮件预览</summary><iframe class="mail-preview mt-2" title="批次邮件预览" sandbox src="/api/order-rules/batches/${encodeURIComponent(d.id)}/preview"></iframe></details>${window.BatchContentEditor.render(d,{esc,user})}<h3 class="h4">附件</h3>${d.attachments.map(a=>`<p>${esc(a.name||a.filename)} · ${esc(a.size||'—')} 字节</p>`).join('')||'无附件'}<h3 class="h4 mt-3">关联订单</h3>${d.orders.map(o=>`<p><button type="button" class="btn btn-link p-0" data-related-order="${esc(o.id)}">${esc(o.orderNo||o.id)}</button></p>`).join('')}<p class="small text-secondary">SMTP 接受不代表最终送达。结果不明时必须先核验,不会自动补发。</p>${user.role==='admin'&&d.status==='unknown'?form('resolve','保存核验结论','<select name="resolution" class="form-select"><option value="sent">已核实邮件服务器接受</option><option value="retry">已核实未发送,允许重试</option></select>'):''}${user.role==='admin'&&d.status==='failed'?form('resend','人工补发原冻结批次'):''}`;}
|
||||
async function load(kind,id,trigger,back=null){
|
||||
const request=++revision;editor?.dispose();controller?.abort();controller=new AbortController();panel.show('<p>正在加载详情…</p>',trigger);
|
||||
try{const d=await api('/order-rules/'+kind+'/'+encodeURIComponent(id),undefined,{signal:controller.signal});if(!isActive()||request!==revision)return;
|
||||
|
||||
@@ -7,11 +7,20 @@ window.BusinessRecordViews=(()=>{
|
||||
const catalogs={categories:new Map(),connections:new Map()};
|
||||
const select=(name,label)=>`<label class="small" for="business-${name}">${label}</label><select class="form-select" id="business-${name}" name="${name}"><option value="">全部</option>${filters[name]?`<option selected value="${esc(filters[name])}">${esc(filters[name])}</option>`:''}</select>`;
|
||||
const input=(name,label,type='text')=>`<label class="small">${label}<input class="form-control" type="${type}" name="${name}" maxlength="200" value="${esc(filters[name]||'')}"></label>`;
|
||||
container.innerHTML=`<div class="alert alert-warning" data-record-error hidden role="alert"></div><section class="card"><div class="card-header flex-wrap gap-2"><h2 class="card-title">${kind==='orders'?'订单中心':'邮件批次'}</h2><div class="btn-list ms-auto"></div></div><div class="card-body record-filters"><div class="row g-2"><div class="col-12 col-md-4">${input('q','搜索订单 / 标识 / 主题')}</div><div class="col-6 col-md-2">${select('categoryId','类别')}</div><div class="col-6 col-md-2">${select('connectionId','来源连接')}</div><div class="col-6 col-md-2"><label class="small">状态<select class="form-select" name="status"><option value="">全部状态</option>${states.map(s=>`<option value="${s}" ${filters.status===s?'selected':''}>${labels[s]}</option>`).join('')}</select></label></div>${kind==='batches'?`<div class="col-6 col-md-2"><label class="small">范围<select class="form-select" name="scope"><option value="active" ${filters.scope==='active'?'selected':''}>未终结批次</option><option value="all" ${filters.scope==='all'?'selected':''}>全部批次</option></select></label></div>`:''}<div class="col-6 col-md-3">${input('from',kind==='batches'?'窗口截止日期从(北京时间)':'接收日期从(北京时间)','date')}</div><div class="col-6 col-md-3">${input('to',kind==='batches'?'窗口截止日期至':'接收日期至','date')}</div><div class="col-12 col-md-2 align-self-end"><button class="btn" data-record-query type="button">查询</button></div></div></div><div data-arrival-list></div>${window.RecordUi.footer}</section>${kind==='orders'&&user.role!=='viewer'?'<section class="card mt-3"><div class="card-body"><h3 class="h4">扫描并处理订单</h3><p class="text-secondary">读取授权待办、采集真实字段、生成 PDF 并归档;BPM 节点由人工办理。邮件按独立开关和批次调度发送。</p><form data-business-scan><label class="form-label" for="business-scan-connection">扫描连接</label><select id="business-scan-connection" class="form-select" name="scanConnectionId" required><option value="">正在读取授权连接</option></select><button class="btn" type="submit">扫描并处理订单</button><div role="alert"></div></form></div></section>':''}`;
|
||||
container.innerHTML=`<div class="alert alert-warning" data-record-error hidden role="alert"></div><section class="card"><div class="card-header flex-wrap gap-2"><h2 class="card-title">${kind==='orders'?'订单中心':'邮件批次'}</h2><div class="btn-list ms-auto"></div></div>${kind==='batches'?'<div class="card-header border-bottom"><nav class="nav nav-tabs card-header-tabs" role="tablist" aria-label="邮件批次范围">'+[['active','待发送'],['sent','已发送'],['all','全部']].map(([scope,label])=>'<a class="nav-link" role="tab" data-batch-scope="'+scope+'">'+label+'</a>').join('')+'</nav></div>':''}<div class="card-body record-filters"><div class="row g-2"><div class="col-12 col-md-4">${input('q','搜索订单 / 标识 / 主题')}</div><div class="col-6 col-md-2">${select('categoryId','类别')}</div><div class="col-6 col-md-2">${select('connectionId','来源连接')}</div><div class="col-6 col-md-2"><label class="small">状态<select class="form-select" name="status"><option value="">全部状态</option>${states.map(s=>`<option value="${s}" ${filters.status===s?'selected':''}>${labels[s]}</option>`).join('')}</select></label></div>${kind==='batches'?'<input type="hidden" name="scope" value="'+esc(filters.scope)+'">':''}<div class="col-6 col-md-3">${input('from',kind==='batches'?'窗口截止日期从(北京时间)':'接收日期从(北京时间)','date')}</div><div class="col-6 col-md-3">${input('to',kind==='batches'?'窗口截止日期至':'接收日期至','date')}</div><div class="col-12 col-md-2 align-self-end"><button class="btn" data-record-query type="button">查询</button></div></div></div><div data-arrival-list></div>${window.RecordUi.footer}</section>${kind==='orders'&&user.role!=='viewer'?'<section class="card mt-3"><div class="card-body"><h3 class="h4">扫描并处理订单</h3><p class="text-secondary">读取授权待办、采集真实字段、生成 PDF 并归档;BPM 节点由人工办理。邮件按独立开关和批次调度发送。</p><form data-business-scan><label class="form-label" for="business-scan-connection">扫描连接</label><select id="business-scan-connection" class="form-select" name="scanConnectionId" required><option value="">正在读取授权连接</option></select><button class="btn" type="submit">扫描并处理订单</button><div role="alert"></div></form></div></section>':''}`;
|
||||
let table;const detail=window.BusinessRecordDetail.mount(container,{...options,onChanged:()=>{const error=container.querySelector('[data-record-error]');error.hidden=false;error.textContent='业务状态已变化,请刷新记录核对。';}});
|
||||
function draw(data){const host=container.querySelector('[data-arrival-list]');host.innerHTML=`<div class="table-responsive"><table class="table table-vcenter card-table"><thead><tr><th>${kind==='orders'?'订单 / 类别':'主题 / 类别'}</th><th>状态与原因</th><th>接收 / 创建时间</th><th>详情</th></tr></thead><tbody>${data.items.map((row,index)=>`<tr><td class="text-break"><strong>${esc(row.orderNo||row.subject||row.id)}</strong><div class="small text-secondary">${esc(catalogs.categories.get(row.categoryId)||row.categoryName||row.categoryId||'未分类')}</div>${row.testRunId?'<span class="badge bg-yellow-lt mt-1">受限测试</span>':''}${kind==='batches'?'<div class="small text-secondary">'+Number(row.orderCount||0)+' 个订单 · '+esc(formatDate(row.windowEnd||row.cutoff))+' 截止</div>':(row.collectingBatches||[]).map(b=>'<button type="button" class="btn btn-link btn-sm p-0 mt-1" data-collecting-detail="'+esc(b.id)+'">查看收集中批次</button>').join('')}${kind==='batches'?'<span class="badge bg-blue-lt mt-1">'+(row.notificationMode==='huizhou'?'惠州通知':'普通通知')+'</span>':''}</td><td>${esc(labels[row.status]||row.status)}${kind==='orders'&&row.notifications?['normal','huizhou'].map(mode=>{const notice=row.notifications[mode];return notice?'<div class="small mt-1"><strong>'+(mode==='huizhou'?'惠州通知':'普通通知')+'</strong>:'+esc(labels[notice.status]||notice.status)+'<div class="text-danger text-break">'+esc(notice.error||'')+'</div>'+(notice.issues?.length?'<div class="text-warning text-break">'+notice.issues.map(esc).join(';')+'</div>':'')+'</div>':'';}).join(''):''}<div class="small text-danger text-break">${esc(row.error||row.reason||'')}</div></td><td class="small">${esc(formatDate(row.receivedAt||row.createdAt))}</td><td><button class="btn btn-sm" type="button" data-business-detail="${index}">查看详情</button></td></tr>`).join('')||'<tr><td colspan="4" class="text-secondary">暂无匹配记录</td></tr>'}</tbody></table></div>`;host.querySelectorAll('[data-collecting-detail]').forEach(button=>button.onclick=()=>detail.open('batches',button.dataset.collectingDetail,button));host.querySelectorAll('[data-business-detail]').forEach(button=>button.onclick=()=>detail.open(kind,data.items[Number(button.dataset.businessDetail)].id,button));}
|
||||
function draw(data){const host=container.querySelector('[data-arrival-list]');host.innerHTML=`<div class="table-responsive"><table class="table table-vcenter card-table"><thead><tr><th>${kind==='orders'?'订单 / 类别':'主题 / 类别'}</th><th>状态与原因</th><th>${kind==='batches'?'创建 / 发送时间':'接收 / 创建时间'}</th><th>详情</th></tr></thead><tbody>${data.items.map((row,index)=>`<tr><td class="text-break"><strong>${esc(row.orderNo||row.subject||row.id)}</strong><div class="small text-secondary">${esc(catalogs.categories.get(row.categoryId)||row.categoryName||row.categoryId||'未分类')}</div>${row.testRunId?'<span class="badge bg-yellow-lt mt-1">受限测试</span>':''}${kind==='batches'?'<div class="small text-secondary">'+Number(row.orderCount||0)+' 个订单 · '+esc(formatDate(row.windowEnd||row.cutoff))+' 截止</div>':(row.collectingBatches||[]).map(b=>'<button type="button" class="btn btn-link btn-sm p-0 mt-1" data-collecting-detail="'+esc(b.id)+'">查看收集中批次</button>').join('')}${kind==='batches'?'<span class="badge bg-blue-lt mt-1">'+(row.notificationMode==='huizhou'?'惠州通知':'普通通知')+'</span>':''}</td><td>${esc(labels[row.status]||row.status)}${kind==='orders'&&row.notifications?['normal','huizhou'].map(mode=>{const notice=row.notifications[mode];return notice?'<div class="small mt-1"><strong>'+(mode==='huizhou'?'惠州通知':'普通通知')+'</strong>:'+esc(labels[notice.status]||notice.status)+'<div class="text-danger text-break">'+esc(notice.error||'')+'</div>'+(notice.issues?.length?'<div class="text-warning text-break">'+notice.issues.map(esc).join(';')+'</div>':'')+'</div>':'';}).join(''):''}<div class="small text-danger text-break">${esc(row.error||row.reason||'')}</div></td><td class="small">${esc(formatDate(row.receivedAt||row.createdAt))}${kind==='batches'&&row.status==='sent'?'<div class="text-secondary">发送:'+esc(formatDate(row.sentAt||row.resolvedAt)||'未记录')+'</div>':''}</td><td><button class="btn btn-sm" type="button" data-business-detail="${index}">查看详情</button></td></tr>`).join('')||'<tr><td colspan="4" class="text-secondary">暂无匹配记录</td></tr>'}</tbody></table></div>`;host.querySelectorAll('[data-collecting-detail]').forEach(button=>button.onclick=()=>detail.open('batches',button.dataset.collectingDetail,button));host.querySelectorAll('[data-business-detail]').forEach(button=>button.onclick=()=>detail.open(kind,data.items[Number(button.dataset.businessDetail)].id,button));}
|
||||
function tabs(next){
|
||||
container.querySelectorAll('[data-batch-scope]').forEach(link=>{
|
||||
const selected=link.dataset.batchScope===next.scope;
|
||||
link.classList.toggle('active',selected);link.setAttribute('aria-selected',String(selected));
|
||||
link.href=window.RecordState.serialize(view,{...next,scope:link.dataset.batchScope,status:'',page:1});
|
||||
link.onclick=event=>{if(table?.busy||selected)event.preventDefault();};
|
||||
});
|
||||
}
|
||||
if(kind==='batches')tabs(filters);
|
||||
const names=Object.keys(filters).filter(k=>!['page','pageSize'].includes(k));
|
||||
table=window.RecordTable.mount({view,container,isActive,api,endpoint:'/order-rules/'+kind,render:draw,readDraft:()=>Object.fromEntries(names.map(k=>[k,container.querySelector('[name="'+k+'"]').value.trim()])),writeDraft(next){for(const k of names)container.querySelector('[name="'+k+'"]').value=next[k];}});
|
||||
table=window.RecordTable.mount({view,container,isActive,api,endpoint:'/order-rules/'+kind,onCommit:next=>{if(kind==='batches'){tabs(next);container.querySelector('[name="scope"]').value=next.scope;}},render:draw,readDraft:()=>Object.fromEntries(names.map(k=>[k,container.querySelector('[name="'+k+'"]').value.trim()])),writeDraft(next){for(const k of names)container.querySelector('[name="'+k+'"]').value=next[k];}});
|
||||
const workspaceRead=api('/workspace');
|
||||
const summaryRead=api('/order-rules?view=summary');
|
||||
function fillOptions(name,entries){
|
||||
|
||||
@@ -4,7 +4,7 @@ window.RecordState=(()=>{
|
||||
const route=hash=>String(hash||'').replace(/^#/,'').split('?')[0];
|
||||
const isRecord=hash=>routes.includes(route(hash));
|
||||
const defaults=view=>view.startsWith('notification-')?{q:'',categoryId:'',connectionId:'',status:'',from:'',to:'',page:1,pageSize:25,...(view==='notification-batches'?{scope:'active'}:{})}:view==='records'?{scope:'current',business:'orders',kind:'all',q:'',connectionId:'',from:'',to:'',page:1,pageSize:25}:{q:'',status:'',page:1,pageSize:25};
|
||||
function normalize(view,input={}){const result=defaults(view);for(const field of Object.keys(result)){const value=input[field];if(value===undefined)continue;if(field==='page'){const n=Number(value);if(Number.isSafeInteger(n)&&n>0&&n<=1000000)result.page=n;}else if(field==='pageSize'){if([25,50,100].includes(Number(value)))result.pageSize=Number(value);}else if(field==='q'||field==='connectionId'||field==='categoryId'){if(typeof value==='string')result[field]=value.slice(0,200);}else if(field==='from'||field==='to'){if(typeof value==='string'&&/^\d{4}-\d{2}-\d{2}$/.test(value)&&Number.isFinite(Date.parse(value+'T00:00:00Z'))&&new Date(value+'T00:00:00Z').toISOString().slice(0,10)===value)result[field]=value;}else if(({scope:view==='notification-batches'?['active','all']:['current','archived','all'],business:['orders','all'],kind:['all','todo','inform'],status:view.startsWith('notification-')?['','identified','preparing','archived','pending','batched','blocked','unknown','sent','failed','capturing','archiving','queued','ignored','collecting','prepared','sending','cancelled']:['','success','running','error','interrupted']})[field]?.includes(value))result[field]=value;}return result;}
|
||||
function normalize(view,input={}){const result=defaults(view);for(const field of Object.keys(result)){const value=input[field];if(value===undefined)continue;if(field==='page'){const n=Number(value);if(Number.isSafeInteger(n)&&n>0&&n<=1000000)result.page=n;}else if(field==='pageSize'){if([25,50,100].includes(Number(value)))result.pageSize=Number(value);}else if(field==='q'||field==='connectionId'||field==='categoryId'){if(typeof value==='string')result[field]=value.slice(0,200);}else if(field==='from'||field==='to'){if(typeof value==='string'&&/^\d{4}-\d{2}-\d{2}$/.test(value)&&Number.isFinite(Date.parse(value+'T00:00:00Z'))&&new Date(value+'T00:00:00Z').toISOString().slice(0,10)===value)result[field]=value;}else if(({scope:view==='notification-batches'?['active','sent','all']:['current','archived','all'],business:['orders','all'],kind:['all','todo','inform'],status:view.startsWith('notification-')?['','identified','preparing','archived','pending','batched','blocked','unknown','sent','failed','capturing','archiving','queued','ignored','collecting','prepared','sending','cancelled']:['','success','running','error','interrupted']})[field]?.includes(value))result[field]=value;}if(view==='notification-batches'&&result.status==='sent'&&result.scope==='active')result.scope='sent';return result;}
|
||||
function serialize(view,filters){const normal=normalize(view,filters),base=defaults(view),params=new URLSearchParams();for(const field of Object.keys(base))if(normal[field]!==base[field])params.set(field,normal[field]);return '#'+view+(params.size?'?'+params:'');}
|
||||
function write(){if(!key)return;try{sessionStorage.setItem(key,JSON.stringify(cache));}catch{}}
|
||||
function clear(){try{for(let i=sessionStorage.length-1;i>=0;i--){const name=sessionStorage.key(i);if(name?.startsWith(prefix))sessionStorage.removeItem(name);}}catch{}key=null;cache={};if(isRecord(location.hash))history.replaceState({appIndex:history.state?.appIndex},'','#'+route(location.hash));}
|
||||
|
||||
Reference in new issue
Block a user