增加库存流水分页筛选与每日自动快照
This commit is contained in:
1 parent
b3b67c8003
commit
aa7f7cad27
12 files changed
+659
-55
No files matched your search
+50
-12
@@ -37,8 +37,10 @@ const CARD_FEE_NOTE=CreditCardFees.note();
|
||||
const isCardFee=item=>item?.system==='credit_card'||String(item?.key||'').startsWith('card_fee:');
|
||||
const cardFeeAmount=CreditCardFees.amount;
|
||||
const paymentAccount=value=>pick(CreditCardFees.normalizeAccount(value),ACCOUNTS,'收付款账户');
|
||||
const today = () => new Intl.DateTimeFormat('sv-SE',{timeZone:'Asia/Shanghai'}).format(new Date());
|
||||
const today = (date=new Date()) => new Intl.DateTimeFormat('sv-SE',{timeZone:'Asia/Shanghai'}).format(date);
|
||||
const now = () => new Date().toISOString();
|
||||
const AUTOMATIC_SNAPSHOT_LAST_SUCCESS='inventory-auto-snapshot:last-success';
|
||||
const automaticSnapshotKey=date=>'inventory-auto-snapshot:'+date;
|
||||
const sum = (rows, key) => rows.reduce((s,r)=>s+(typeof key==='function'?key(r):r[key]),0);
|
||||
function fail(message, status=400) { const e=new Error(message); e.status=status; throw e; }
|
||||
function text(value, name, max=100, optional=false) { const s=String(value??'').trim(); if ((!s&&!optional)||s.length>max) fail(`${name}请填写${optional?'不超过':'1~'}${max}字`); return s; }
|
||||
@@ -119,7 +121,7 @@ class Ledger {
|
||||
CREATE TABLE IF NOT EXISTS corrections(target TEXT PRIMARY KEY,type TEXT NOT NULL,reason TEXT NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS sync(entity TEXT PRIMARY KEY,revision INTEGER NOT NULL,done_revision INTEGER NOT NULL DEFAULT 0,record_id TEXT,attempts INTEGER NOT NULL DEFAULT 0,error TEXT,updated TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS closes(date TEXT PRIMARY KEY,report TEXT NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL,stale INTEGER NOT NULL DEFAULT 0);
|
||||
CREATE TABLE IF NOT EXISTS inventory_snapshots(date TEXT PRIMARY KEY,inventory TEXT NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL,updated TEXT NOT NULL,stale INTEGER NOT NULL DEFAULT 0,revision TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS inventory_snapshots(date TEXT PRIMARY KEY,inventory TEXT NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL,updated TEXT NOT NULL,stale INTEGER NOT NULL DEFAULT 0,revision TEXT NOT NULL,source TEXT NOT NULL DEFAULT 'manual' CHECK(source IN ('manual','automatic')),scheduled_for TEXT);
|
||||
CREATE INDEX IF NOT EXISTS ix_movements_date ON movements(date,pocket);
|
||||
CREATE INDEX IF NOT EXISTS ix_payment_order ON payments(order_id);
|
||||
CREATE INDEX IF NOT EXISTS ix_journal_date ON journal(date);
|
||||
@@ -134,6 +136,10 @@ class Ledger {
|
||||
const peopleColumns=this.rows('PRAGMA table_info(daily_people_counts)').map(row=>row.name);
|
||||
for(const name of ['assistant1_count','assistant2_count'])if(!peopleColumns.includes(name))
|
||||
this.db.exec(`ALTER TABLE daily_people_counts ADD COLUMN ${name} INTEGER CHECK(${name} IS NULL OR (typeof(${name})='integer' AND ${name}>=0 AND ${name}<=1000000))`);
|
||||
// 旧快照均来自人工保存,只增加来源字段,不重算或补造历史库存。
|
||||
const snapshotColumns=this.rows('PRAGMA table_info(inventory_snapshots)').map(row=>row.name);
|
||||
if(!snapshotColumns.includes('source'))this.db.exec("ALTER TABLE inventory_snapshots ADD COLUMN source TEXT NOT NULL DEFAULT 'manual' CHECK(source IN ('manual','automatic'))");
|
||||
if(!snapshotColumns.includes('scheduled_for'))this.db.exec('ALTER TABLE inventory_snapshots ADD COLUMN scheduled_for TEXT');
|
||||
PriceLocks.initialize(this);
|
||||
MaterialPools.initialize(this);
|
||||
OrderTemplates.initialize(this);
|
||||
@@ -465,16 +471,22 @@ class Ledger {
|
||||
return {date,yesterdayDate,pockets:ACTIVE_POCKETS,current:inventory.filter(r=>ACTIVE_POCKETS.includes(r.pocket)),yesterday:this.inventorySnapshot(yesterdayDate),todaySnapshot:this.inventorySnapshot(date),revision:this.inventoryRevision(date),legacyInventory:inventory.filter(r=>!ACTIVE_POCKETS.includes(r.pocket)&&(r.mg!==0||r.reserved!==0)),canReview:actor?.role==='owner'};
|
||||
}
|
||||
inventoryMovements(query={},actor=this.actor){
|
||||
const historical=new Set(this.rows('SELECT DISTINCT pocket FROM movements').map(r=>r.pocket));
|
||||
if(!query||typeof query!=='object'||Array.isArray(query))fail('库存流水筛选无效');
|
||||
const kind=query.kind===undefined?'all':query.kind,pageValue=query.page===undefined?'1':query.page;
|
||||
if(typeof kind!=='string'||!['all','increase','decrease','transfer','manual'].includes(kind))fail('筛选流水类型无效');
|
||||
if(!['string','number'].includes(typeof pageValue)||!Number.isSafeInteger(Number(pageValue))||Number(pageValue)<1||String(Number(pageValue))!==String(pageValue))fail('流水页码须为正整数');
|
||||
const allRows=this.rows('SELECT * FROM movements ORDER BY created DESC,rowid DESC');
|
||||
const visible=allRows.filter(row=>this.canAccess('movement',row.id,actor));
|
||||
const historical=new Set(visible.map(r=>r.pocket));
|
||||
const pockets=POCKETS.filter(pocket=>ACTIVE_POCKETS.includes(pocket)||historical.has(pocket)).map(pocket=>({pocket,active:ACTIVE_POCKETS.includes(pocket)}));
|
||||
const pocket=query.pocket??'';
|
||||
const pocket=query.pocket===undefined?'':query.pocket;
|
||||
if(typeof pocket!=='string'||pocket&&!pockets.some(p=>p.pocket===pocket))fail('筛选货盘无效');
|
||||
const where=pocket?' WHERE pocket=?':'',args=pocket?[pocket]:[];
|
||||
const all=this.rows('SELECT * FROM movements'+where+' ORDER BY created DESC,rowid DESC',...args).filter(row=>this.canAccess('movement',row.id,actor));
|
||||
const total=all.length;
|
||||
// 先筛选再限条数;同一毫秒的流水按实际录入顺序稳定排列。
|
||||
const movements=InventoryChanges.decorate(this,all.slice(0,100),actor,priceLockEnv);
|
||||
return {pocket,pockets,total,shown:movements.length,limit:100,movements};
|
||||
const manualKinds=kind==='all'?null:InventoryChanges.manualMovementKinds(this,allRows,visible);
|
||||
const filtered=visible.filter(row=>(!pocket||row.pocket===pocket)&&(kind==='all'||(kind==='manual'?manualKinds.has(row.id):manualKinds.get(row.id)===kind)));
|
||||
const total=filtered.length,limit=100,totalPages=Math.max(1,Math.ceil(total/limit)),page=Math.min(Number(pageValue),totalPages);
|
||||
// 权限与所有筛选之后再分页;同一毫秒的流水按实际录入顺序稳定排列。
|
||||
const movements=InventoryChanges.decorate(this,filtered.slice((page-1)*limit,page*limit),actor,priceLockEnv);
|
||||
return {pocket,pockets,kind,total,shown:movements.length,limit,pageSize:limit,page,totalPages,hasPrev:page>1,hasNext:page<totalPages,movements};
|
||||
}
|
||||
inventorySnapshots(query={}){
|
||||
const date=day(query.date||today()),from=day(query.from||'2000-01-01');
|
||||
@@ -485,10 +497,36 @@ class Ledger {
|
||||
saveInventorySnapshot(date,actor){
|
||||
owner(actor);day(date);
|
||||
const inventory=this.inventory(date),revision=this.inventoryRevision(date),timestamp=now();
|
||||
this.run('INSERT INTO inventory_snapshots(date,inventory,actor,created,updated,stale,revision) VALUES (?,?,?,?,?,0,?) ON CONFLICT(date) DO UPDATE SET inventory=excluded.inventory,actor=excluded.actor,updated=excluded.updated,stale=0,revision=excluded.revision',date,JSON.stringify(inventory),actor.name,timestamp,timestamp,revision);
|
||||
this.writeInventorySnapshot(date,inventory,revision,actor.name,timestamp,'manual',null);
|
||||
this.audit('inventory:'+date,'复核并保存库存快照',actor,{date,revision,inventory});
|
||||
return this.inventorySnapshot(date);
|
||||
}
|
||||
writeInventorySnapshot(date,inventory,revision,actor,timestamp,source,scheduledFor){
|
||||
this.run('INSERT INTO inventory_snapshots(date,inventory,actor,created,updated,stale,revision,source,scheduled_for) VALUES (?,?,?,?,?,0,?,?,?) ON CONFLICT(date) DO UPDATE SET inventory=excluded.inventory,actor=excluded.actor,updated=excluded.updated,stale=0,revision=excluded.revision,source=excluded.source,scheduled_for=excluded.scheduled_for',date,JSON.stringify(inventory),actor,timestamp,timestamp,revision,source,scheduledFor);
|
||||
}
|
||||
saveAutomaticInventorySnapshot(date,clock=()=>new Date()){
|
||||
day(date);const scheduledFor=date+'T23:50:00+08:00',actor={id:'system-inventory-snapshot',name:'系统自动',role:'system'};
|
||||
// 不复用 transact:库存定时保存不能触发订单、资金或购料的同步与重算。
|
||||
this.db.exec('BEGIN IMMEDIATE');
|
||||
try{
|
||||
// BEGIN 可能等待其他写事务;取得锁后重新读实际时钟,不用等锁前的日期或时间冒充保存时刻。
|
||||
let actual=new Date(clock());
|
||||
if(!Number.isFinite(actual.getTime()))fail('自动库存快照时钟无效');
|
||||
if(today(actual)!==date||actual.getTime()<Date.parse(scheduledFor)){this.db.exec('ROLLBACK');return {saved:false,reason:today(actual)!==date?'date-changed':'not-due'};}
|
||||
const previous=this.meta(automaticSnapshotKey(date));
|
||||
if(previous){this.db.exec('COMMIT');return {saved:false,record:previous};}
|
||||
const inventory=this.inventory(date),revision=this.inventoryRevision(date);
|
||||
// 查询较慢时也在真正写入前再检查一次,跨午夜就跳过旧日期。
|
||||
actual=new Date(clock());
|
||||
if(!Number.isFinite(actual.getTime()))fail('自动库存快照时钟无效');
|
||||
if(today(actual)!==date||actual.getTime()<Date.parse(scheduledFor)){this.db.exec('ROLLBACK');return {saved:false,reason:today(actual)!==date?'date-changed':'not-due'};}
|
||||
const timestamp=actual.toISOString(),record={date,scheduledFor,savedAt:timestamp};
|
||||
this.writeInventorySnapshot(date,inventory,revision,actor.name,timestamp,'automatic',scheduledFor);
|
||||
this.audit('inventory:'+date,'自动保存库存快照',actor,{date,revision,inventory,source:'automatic',scheduledFor,savedAt:timestamp,notice:'仅保存账面库存,不代表麦麦已核对实物'});
|
||||
this.setMeta(automaticSnapshotKey(date),record);this.setMeta(AUTOMATIC_SNAPSHOT_LAST_SUCCESS,record);
|
||||
this.db.exec('COMMIT');return {saved:true,record};
|
||||
}catch(error){if(this.db.isTransaction)this.db.exec('ROLLBACK');throw error;}
|
||||
}
|
||||
reviewInventory(input,actor){
|
||||
owner(actor);const date=day(input.date||today());
|
||||
if(input.verified!==true)fail('请先核对各货盘克重,再确认保存快照');
|
||||
@@ -837,4 +875,4 @@ class Ledger {
|
||||
async backupTo(filename){fs.mkdirSync(path.dirname(filename),{recursive:true,mode:0o700});await backup(this.db,filename);fs.chmodSync(filename,0o600);return filename;}
|
||||
close(){this.db.close();}
|
||||
}
|
||||
module.exports={Ledger,POCKETS,ACTIVE_POCKETS,ACCOUNTS,today,day,money,weight,fail,text,owner,now};
|
||||
module.exports={Ledger,POCKETS,ACTIVE_POCKETS,ACCOUNTS,today,day,money,weight,fail,text,owner,now,AUTOMATIC_SNAPSHOT_LAST_SUCCESS,automaticSnapshotKey};
|
||||
Reference in new issue
Block a user