Files
order-notification-automation/src/bpm-scan-store.cjs
T
abaishu0730 94fc985553 feat: add guarded BPM category and template workflow
Implement server-owned read-only sample checks, category publication, explicit
order-version identity and durable PDF/archive/notification steps. Freeze
category-bound templates and recipients for isolated scheduled delivery, and
require human verification for unknown SMTP outcomes. Add order/batch views
and local HTTP/browser/PDF/archive regression coverage.

Fix Unicode Windows startup links found by full regression using IShellLinkW.
Automatic processing and sending stay disabled; no service deployment.

Validation: npm ci; npm test -- --test-concurrency=1 (242 pass, 1 optional
ZCode skip, 0 fail); 31 syntax checks; scoped independent code review.
Live BPM V13/SMB/163 acceptance remains pending.
2026-10-22 16:52:59 +08:00

39 lines
5.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict';
const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');const {DatabaseSync}=require('node:sqlite');
const invalid=message=>Object.assign(new Error(message),{status:400});
class BpmScanStore{
constructor(dir){fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'scan.sqlite'));this.db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL;
CREATE TABLE IF NOT EXISTS config(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
INSERT OR IGNORE INTO config VALUES(1,'{"enabled":true,"intervalMinutes":5}');
CREATE TABLE IF NOT EXISTS arrivals(connection_id TEXT NOT NULL,source TEXT NOT NULL,task_id TEXT NOT NULL,day TEXT NOT NULL,value TEXT NOT NULL,first_seen TEXT NOT NULL,last_seen TEXT NOT NULL,PRIMARY KEY(connection_id,source,task_id));
CREATE INDEX IF NOT EXISTS arrivals_day ON arrivals(day DESC);
CREATE TABLE IF NOT EXISTS runs(id TEXT PRIMARY KEY,connection_id TEXT NOT NULL,actor TEXT NOT NULL,started_at TEXT NOT NULL,finished_at TEXT,status TEXT NOT NULL,seen INTEGER,added INTEGER,message TEXT);
UPDATE runs SET status='error',message='服务重启,扫描未完成。',finished_at=CURRENT_TIMESTAMP WHERE status='running';`);}
transaction(fn){this.db.exec('BEGIN IMMEDIATE');try{const r=fn();this.db.exec('COMMIT');return r;}catch(e){this.db.exec('ROLLBACK');throw e;}}
config(){return JSON.parse(this.db.prepare('SELECT value FROM config WHERE id=1').get().value);}
saveConfig(input){if(!input||Object.keys(input).some(k=>!['enabled','intervalMinutes'].includes(k))||typeof input.enabled!=='boolean'||!Number.isInteger(input.intervalMinutes)||input.intervalMinutes<1||input.intervalMinutes>1440)throw invalid('扫描间隔需为 1–1440 分钟。');this.db.prepare('UPDATE config SET value=? WHERE id=1').run(JSON.stringify(input));return this.config();}
begin(connectionId,actor){const id=crypto.randomUUID();this.db.prepare('INSERT INTO runs(id,connection_id,actor,started_at,status) VALUES(?,?,?,?,?)').run(id,connectionId,actor,new Date().toISOString(),'running');return id;}
complete(id,connectionId,rows){return this.transaction(()=>{
let added=0;const now=new Date().toISOString();
const insert=this.db.prepare('INSERT OR IGNORE INTO arrivals VALUES(?,?,?,?,?,?,?)');const update=this.db.prepare('UPDATE arrivals SET day=?,value=?,last_seen=? WHERE connection_id=? AND source=? AND task_id=?');
for(const row of rows){if(!row.arrivalDay||!row.taskId||!row.source)throw invalid('流程记录无效。');const value=JSON.stringify(row);added+=Number(insert.run(connectionId,row.source,row.taskId,row.arrivalDay,value,now,now).changes);update.run(row.arrivalDay,value,now,connectionId,row.source,row.taskId);}
this.db.prepare('UPDATE runs SET status=?,finished_at=?,seen=?,added=?,message=? WHERE id=? AND status=?').run('success',now,rows.length,added,'',id,'running');this.prune();return {seen:rows.length,added};
});}
fail(id,message){this.db.prepare('UPDATE runs SET status=?,finished_at=?,message=? WHERE id=?').run('error',new Date().toISOString(),message,id);this.prune();}
prune(){this.db.exec("DELETE FROM runs WHERE status!='running' AND id NOT IN(SELECT id FROM runs ORDER BY started_at DESC,rowid DESC LIMIT 200)");}
status(){return {config:this.config(),total:this.db.prepare('SELECT COUNT(*) n FROM arrivals').get().n,runs:this.db.prepare('SELECT id,connection_id AS connectionId,actor,started_at AS startedAt,finished_at AS finishedAt,status,seen,added,message FROM runs ORDER BY started_at DESC,rowid DESC LIMIT 30').all()};}
getArrival(connectionId,source,taskId){const row=this.db.prepare('SELECT connection_id AS connectionId,value,first_seen AS firstSeenAt FROM arrivals WHERE connection_id=? AND source=? AND task_id=?').get(connectionId,source,taskId);if(!row)return null;const {value,...metadata}=row;return {...JSON.parse(value),...metadata};}
recent({since='',limit=500}={}){return this.db.prepare('SELECT connection_id AS connectionId,value,first_seen AS firstSeenAt,last_seen AS lastSeenAt FROM arrivals WHERE first_seen>=? ORDER BY first_seen DESC,task_id LIMIT ?').all(since,limit).map(({value,...metadata})=>({...JSON.parse(value),...metadata}));}
list({connectionId='',q='',before='',days=7}={}){
if(typeof q!=='string'||q.length>200||typeof connectionId!=='string'||connectionId.length>200||typeof before!=='string'||(before&&!/^\d{4}-\d{2}-\d{2}$/.test(before))||!Number.isInteger(days)||days<1||days>31)throw invalid('查询条件无效。');
const conditions=[],args=[];if(connectionId){conditions.push('connection_id=?');args.push(connectionId);}if(q){conditions.push("value LIKE ? ESCAPE '\\'");args.push('%'+q.replace(/[\\%_]/g,'\\$&')+'%');}
const where=conditions.length?' WHERE '+conditions.join(' AND '):'';const total=this.db.prepare('SELECT COUNT(*) n FROM arrivals'+where).get(...args).n;
if(before){conditions.push('day<?');args.push(before);}const filtered=conditions.length?' WHERE '+conditions.join(' AND '):'';
const dates=this.db.prepare('SELECT DISTINCT day FROM arrivals'+filtered+' ORDER BY day DESC LIMIT ?').all(...args,days+1).map(r=>r.day);const shown=dates.slice(0,days);
const groups=shown.map(day=>({day,items:this.db.prepare('SELECT connection_id AS connectionId,value,first_seen AS firstSeenAt,last_seen AS lastSeenAt FROM arrivals'+(filtered?filtered+' AND ':' WHERE ')+'day=? ORDER BY json_extract(value,\'$.arrivedAt\') DESC,task_id').all(...args,day).map(({value,...rest})=>({...JSON.parse(value),...rest}))}));
return {total,groups,nextBefore:dates.length>days?shown.at(-1):null};
}
close(){this.db.close();}
}
module.exports={BpmScanStore};