'use strict'; const {extractTitle}=require('./title.cjs'); const {sourcesFor,readSource}=require('./field-sources.cjs'); const {matchesScope,scopesFor}=require('./scopes.cjs'); const labels = { orderNo: '订单号', appDate: '申请日期', customer: '客户', productLine: '产品线', quantity: '数量', brief: '摘要', changeReason: '更改原因', changeContent: '更改内容', totalAmount: '总金额', }; const present = value => value !== undefined && value !== null && (typeof value !== 'string' || value.trim() !== ''); const scalar = value => typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value)); const nonblank = value => typeof value === 'string' && value.trim().length > 0; function validAppDate(value){ if(!nonblank(value)||!/^\d{4}-\d{2}-\d{2}(?:$|[ T])/.test(value))return false; const day=value.slice(0,10),date=new Date(day+'T00:00:00Z'); if(!Number.isFinite(+date)||date.toISOString().slice(0,10)!==day)return false; return value.length===10||Number.isFinite(Date.parse(value.replace(' ','T'))); } function previewMatch(rules, adapters, input, {mappingEvidence=false}={}) { const sample = input && typeof input === 'object' ? input : {}; const checks = [], issues = []; const check = (label, ok, detail) => { checks.push({ label, ok: !!ok, detail }); if (!ok) issues.push(detail); }; for (const key of ['connectionId', 'instanceId', 'taskId']) { check('事件身份', scalar(sample[key]) && present(sample[key]), `${key}:${present(sample[key]) ? String(sample[key]) : '缺失'}`); } check('事件来源', sample.source === 'todo'||mappingEvidence&&sample.source==='history'&&sample.configurationOnly===true, 'source 必须为 todo(待办);历史证据仅限字段配置检查'); check('事件修订', scalar(sample.revision) && present(sample.revision), `revision:${present(sample.revision) ? String(sample.revision) : '缺失'}`); check('接收时间', nonblank(sample.receivedAt) && /T.*(?:Z|[+-]\d{2}:\d{2})$/.test(sample.receivedAt) && Number.isFinite(Date.parse(sample.receivedAt)), 'receivedAt 必须是带时区的有效时间'); for (const key of ['processName', 'processVersion', 'nodeName']) { check('流程信息', nonblank(sample[key]), `${key}:${nonblank(sample[key]) ? sample[key] : '缺失'}`); } const matches = (Array.isArray(rules) ? rules : []).filter(rule => matchesScope(rule,sample)); check('分类命中', matches.length === 1, matches.length === 1 ? `唯一命中:${matches[0].name}` : matches.length ? `同时命中 ${matches.length} 条规则,须消除冲突` : '没有流程名称和节点名称均精确匹配的规则'); const rule = matches.length === 1 ? matches[0] : null; const available = rule ? (Array.isArray(adapters) ? adapters : []).filter(adapter => rule.adapterIds?.includes(adapter.id) && adapter.processName === sample.processName && adapter.processVersion === sample.processVersion && (adapter.reference ? sample.demo === true : adapter.verified === true)) : []; const adapter = available.length === 1 ? available[0] : null; check('字段适配', available.length === 1, adapter ? `字段适配 ${adapter.id}:仅表单结构已核对,不代表实时接口可用` : '没有唯一、已核对且流程版本一致的字段适配器'); const raw = sample.fields && typeof sample.fields === 'object' && !Array.isArray(sample.fields) ? sample.fields : {}; const event = {}; for (const key of ['connectionId', 'source', 'instanceId', 'taskId', 'revision', 'processName', 'processVersion', 'nodeName', 'receivedAt', 'serialNum', 'demo']) { if (Object.hasOwn(sample, key)) event[key] = sample[key]; } event.documentNum = sample.serialNum ?? ''; event.ruleId = rule?.id ?? null; event.ruleVersion = rule?.version ?? null; event.categoryId = rule?.categoryId ?? null; event.adapterId = adapter?.id ?? null; const fieldTrace = []; const mappings = adapter?.fields ?? {},sources=sourcesFor(adapter); const titleSource=Object.hasOwn(sample,'title')?'title':sources.brief?.type!=='title'&&typeof sample.brief==='string'&&/订单号\s*[::]/u.test(sample.brief)?'brief':null; const extracted=titleSource?extractTitle(sample[titleSource]):null; if(extracted){ event.rawTitle=extracted.rawTitle;event.titleOrders=extracted.orders;event.factoryHints=extracted.factoryHints; check('标题提取',extracted.issues.length===0,extracted.issues.join(';')||`从标题提取 ${extracted.orders.length} 个订单段落;惠州通知按每段业务模式与客户证据独立判断`); } for (const key of new Set(['orderNo', 'appDate', 'customer', 'productLine', 'quantity', ...Object.keys(mappings), ...Object.keys(sources), 'brief'])) { const selected=readSource(sources[key],sample); if(sources[key]?.type==='form'&&!(key==='brief'&&extracted))check('字段来源',Object.hasOwn(sample.fields||{},sources[key].path),'所选'+(labels[key]||key)+'来源字段不存在:'+sources[key].path); const path = key === 'brief' ? extracted?`${titleSource} → 订单段落`:selected.path||'brief' : selected.path; const value = key === 'brief' ? extracted?extracted.brief:sources.brief?.type==='title'?null:selected.value??sample.brief : selected.value; event[key] = value ?? null; fieldTrace.push({ key, label: labels[key] || key, path, value: value ?? null }); } for (const key of ['orderNo', 'brief']) { check(labels[key], nonblank(event[key]), `${key} ${nonblank(event[key]) ? '已取得' : '缺失或不是文本'}`); } if(extracted&&nonblank(event.orderNo))check('主订单号核对',extracted.orders.some(order=>order.orderNo===event.orderNo.trim()),'表单主订单号不在标题订单号中,请核对真实订单。'); check('流水编号',nonblank(sample.serialNum),'流水编号 serialNum 必须有值,用于文件命名和追溯'); if(rule?.filenameDate==='appDate')check('申请日期',validAppDate(event.appDate),'文件名使用申请日期,样本必须包含有效的申请日期'); if (present(event.quantity)) { const numeric = typeof event.quantity === 'number' ? event.quantity : typeof event.quantity === 'string' && event.quantity.trim() ? Number(event.quantity) : NaN; check('数量', Number.isFinite(numeric) && numeric >= 0, 'quantity 必须为非负数,零数量合法'); if (Number.isFinite(numeric)) event.quantity = numeric; } else check('数量', true, 'quantity 未提供;不猜测未核对的数量字段'); return { valid: issues.length === 0, ruleId: rule?.id ?? null, categoryId: rule?.categoryId ?? null, event, checks, issues, fieldTrace, candidates: matches.map(item => item.id), explanation: rule ? describeRule(rule) : '按照流程名称和通知节点精确分类;未命中或多条命中时阻塞。', }; } function describeRule(rule) { const date = { appDate: '申请日期', receivedAt: '接收日期', archiveDate: '归档日期' }[rule.filenameDate] || '待选择的日期'; return `${rule.name}:满足任一流程节点配对(${scopesFor(rule).map(row=>`“${row.processName}” → “${row.nodeName}”`).join(';')||'待选择'})时归入本类别。本时段内同类别订单合并一封,通知与更改分别汇总,更早历史不补发。每封从前一个有效发送时点连续积累;首封覆盖前一发送日晚间与休息日,第二封取两个时点之间。${rule.attachPdf ? '附电子流 PDF;' : ''}文件以订单号、${date}、流水编号命名。BPM 节点由人工办理。`; } module.exports = { previewMatch, describeRule };