Files
order-notification-automation/web/modules/field-mappings/sample-picker.js
T

23 lines
9.4 KiB
JavaScript

(() => {
'use strict';let sequence=0;
function mount(host,{api,esc,formatDate=v=>v||'—',user={},isActive=()=>true,processNames=[],connections=[],guardSelection=apply=>apply(),onSelect,feedback=()=>{}}){
const prefix='sample-picker-'+(++sequence),admin=user.role==='admin';let disposed=false,revision=0,selectionRevision=0,timer=null,items=[],nextCursor=null,cursors=[null],page=0,selected=null,listing=null,capturing=false,listBusy=false,keys=new Map();
const live=()=>!disposed&&isActive(),get=name=>host.querySelector('[data-picker="'+name+'"]'),key=body=>{const sig=JSON.stringify(body);if(!keys.has(sig))keys.set(sig,window.PageLifecycle?.requestKey?.()||crypto.randomUUID());return keys.get(sig);};
host.dataset.readonlySelection='true';
host.innerHTML=`<div class="field-sample-picker"><div class="fm-picker-filters"><div><label class="form-label" for="${prefix}-q">搜索订单号、流水号或标题</label><input id="${prefix}-q" data-picker="q" class="form-control" type="search" maxlength="200" placeholder="搜索已采集订单"></div><div><label class="form-label" for="${prefix}-process">流程范围</label><select id="${prefix}-process" data-picker="process" class="form-select"></select></div><div><label class="form-label" for="${prefix}-source">证据来源</label><select id="${prefix}-source" data-picker="source" class="form-select"><option value="todo">已采集待办</option><option value="history">已采集历史(仅核字段)</option><option value="all">全部已采集</option></select></div></div><div class="btn-list mt-2"><button type="button" class="btn btn-sm" data-picker="clear">清空搜索</button><button type="button" class="btn btn-sm" data-picker="retry">重新读取</button><button type="button" class="btn btn-sm" data-picker="cancel">取消选择</button></div><div data-picker="status" class="small text-secondary mt-2" role="status" aria-live="polite"></div><div data-picker="selected" class="fm-selected-order"></div><div data-picker="items"></div><div class="btn-list mt-2"><button type="button" class="btn btn-sm" data-picker="prev">上一页</button><button type="button" class="btn btn-sm" data-picker="next">下一页</button><span data-picker="page" class="small text-secondary"></span></div>${admin?`<details class="mt-3"><summary>从 BPM 选择</summary><p class="small text-secondary mt-2">只读采集字段。实时列表可搜索已有标题/流水号;已开始的采集可能完成并留下证据。</p><label class="form-label" for="${prefix}-connection">BPM 连接</label><select class="form-select" id="${prefix}-connection" data-picker="connection"><option value="">请选择已授权连接</option>${connections.filter(c=>c.status!=='disabled').map(c=>`<option value="${esc(c.id)}">${esc(c.name||c.id)}</option>`).join('')}</select><label class="form-label mt-2" for="${prefix}-scope">读取范围</label><select class="form-select" id="${prefix}-scope" data-picker="scope"><option value="configuration">全部待办(仅配置采样)</option><option value="window">当前窗口待办</option><option value="history">已办/历史(仅核字段)</option></select><button class="btn btn-sm mt-2" type="button" data-picker="list">读取待办列表</button><input aria-label="搜索实时列表标题或流水号" class="form-control mt-2" type="search" data-picker="live-q"><div data-picker="live-items"></div></details>`:''}</div>`;
function processes(){get('process').innerHTML=[...new Set(processNames)].map(p=>`<option value="${esc(p)}">${esc(p)}</option>`).join('')+'<option value="">查看其他流程(全部)</option>';}
function controls(){get('prev').disabled=page===0;get('next').disabled=!nextCursor;get('page').textContent='第 '+(page+1)+' 页';if(admin){for(const name of ['connection','scope','list'])get(name).disabled=capturing||listBusy;host.querySelectorAll('[data-picker-capture]').forEach(b=>b.disabled=capturing||listBusy);}}
function draw(){get('items').innerHTML=items.map((s,i)=>`<article class="fm-sample-row"><strong>${esc(s.serialNum||s.id)}</strong><div>${esc(s.processName||'')} · ${esc(s.processVersion||'版本未提供')} · ${esc(s.source==='history'?'历史 · 节点未提供':s.nodeName||'节点未提供')}</div><div class="small text-secondary">${esc(s.title||'无标题')}</div><div class="small text-secondary">${s.source==='history'?'发起时间':'接收时间'} ${esc(formatDate(s.receivedAt))} · 采集 ${esc(formatDate(s.capturedAt))}</div><button type="button" class="btn btn-sm mt-2" data-picker-select="${i}">选择订单 ${esc(s.serialNum||s.id)}</button></article>`).join('')||'<p class="small text-secondary mt-3">没有符合条件的已采集订单。可调整搜索或从 BPM 选择。</p>';host.querySelectorAll('[data-picker-select]').forEach(b=>b.onclick=()=>select(items[Number(b.dataset.pickerSelect)]));controls();}
async function select(item){return guardSelection(async()=>{if(!live())return;const request=++selectionRevision;selected=item;get('selected').textContent=item?'当前选择:'+(item.serialNum||item.id):'';try{await onSelect({sampleId:item?.id||null});}catch(error){if(live()&&request===selectionRevision)feedback(error.message,'danger');}});}
async function read(target=0){const request=++revision,params=new URLSearchParams({source:get('source').value,limit:'20'}),q=get('q').value.trim(),process=get('process').value;if(q)params.set('q',q);if(process)params.set('processName',process);if(cursors[target])params.set('cursor',cursors[target]);get('status').textContent='正在读取已采集证据…';try{const result=await api('/order-rules/field-samples/catalog?'+params);if(!live()||request!==revision)return;items=result.items||[];nextCursor=result.nextCursor||null;page=target;cursors[page+1]=nextCursor;get('status').textContent='已采集证据反映采集时状态;选择仅查看,不保存配置。';draw();}catch(error){if(!live()||request!==revision)return;get('status').textContent='订单读取失败:'+error.message;controls();}}
function reset(){++revision;clearTimeout(timer);cursors=[null];return read(0);}
host.onkeydown=event=>{if(event.key==='Enter'&&event.target.matches('input[type=search]')){event.preventDefault();if(event.target===get('q'))reset();}};get('q').oninput=()=>{++revision;clearTimeout(timer);timer=setTimeout(reset,250);};get('source').onchange=get('process').onchange=reset;get('clear').onclick=()=>{get('q').value='';reset();};get('retry').onclick=()=>read(page);get('prev').onclick=()=>read(page-1);get('next').onclick=()=>read(page+1);get('cancel').onclick=()=>{++selectionRevision;select(null);};
async function post(route,body){const sig=JSON.stringify(body);try{const result=await api(route,{...body,idempotencyKey:key(body)});keys.delete(sig);return result;}catch(error){if(Number.isInteger(error.status)||error.outcome==='rejected')keys.delete(sig);throw error;}}
function drawLive(){const q=get('live-q').value.toLocaleLowerCase();get('live-items').innerHTML=(listing?.rows||[]).map((s,i)=>({s,i})).filter(({s})=>[s.title,s.serialNum].some(v=>String(v||'').toLocaleLowerCase().includes(q))).map(({s,i})=>`<article class="fm-sample-row"><strong>${esc(s.serialNum||s.taskId)}</strong><div>${esc(s.processName)} · ${esc(s.processVersion||'版本未提供')} · ${esc(s.source==='history'?'历史 · 节点未提供':s.nodeName)}</div><div class="small">${esc(s.title||'无标题')}</div><button class="btn btn-sm mt-2" type="button" data-picker-capture="${i}">读取并选择 ${esc(s.serialNum||s.taskId)}</button></article>`).join('')||'<p class="small mt-2">没有符合条件的待办</p>';host.querySelectorAll('[data-picker-capture]').forEach(b=>b.onclick=()=>guardSelection(()=>capture(listing.rows[Number(b.dataset.pickerCapture)])));controls();}
async function capture(row){if(capturing||!listing||!live())return;capturing=true;controls();const owner=listing,request=++selectionRevision;get('status').textContent='正在只读采集字段…';try{const result=await post('/order-rules/field-samples/capture',{connectionId:owner.connectionId,listId:owner.id,rowId:row.id});if(!live()||request!==selectionRevision)return;get('status').textContent='样本已读取;未执行订单。';selected={...row,id:result.id};get('selected').textContent='当前选择:'+(row.serialNum||row.taskId);await onSelect({sampleId:result.id});if(live()&&request===selectionRevision)await reset();}catch(error){if(live()&&request===selectionRevision)feedback(error.message,'danger');}finally{capturing=false;if(live())controls();}}
if(admin){get('live-q').oninput=drawLive;get('connection').onchange=get('scope').onchange=()=>{++selectionRevision;listing=null;get('live-items').replaceChildren();};get('list').onclick=async()=>{if(listBusy||capturing)return;const connectionId=get('connection').value;if(!connectionId){feedback('请先选择 BPM 连接。','warning');return;}listBusy=true;controls();const owner=++selectionRevision;try{const result=await post('/order-rules/field-samples/list',{connectionId,scope:get('scope').value});if(!live()||owner!==selectionRevision)return;listing={...result,connectionId};drawLive();}catch(error){if(live()&&owner===selectionRevision)feedback(error.message,'warning');}finally{listBusy=false;if(live())controls();}};}
processes();controls();read();return {setContext(context){processNames=context.processNames||[];++selectionRevision;selected=null;get('selected').textContent='';processes();reset();},dispose(){disposed=true;++revision;++selectionRevision;clearTimeout(timer);}};
}
window.FieldSamplePicker={mount};
})();