Files
weiguang-jewelry-ledger/新账系统/inventory-counts.js
T

130 lines
10 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 {randomUUID,createHash}=require('node:crypto');
const LIMIT=1000000000;
const empty=value=>value===undefined||value===null||value==='';
function fail(message,status=400){const error=new Error(message);error.status=status;throw error;}
function today(){return new Intl.DateTimeFormat('sv-SE',{timeZone:'Asia/Shanghai'}).format(new Date());}
function integer(value,{name='库存对数',signed=false,allowZero=false}={}){
if(!['string','number'].includes(typeof value)||!(signed?/^-?\d+$/:/^\d+$/).test(String(value).trim()))fail(name+'须为'+(signed?'可带负号的':'')+'整数');
const count=Number(value);if(!Number.isSafeInteger(count)||Math.abs(count)>LIMIT||(!allowZero&&count===0)||(!signed&&count<0))fail(name+'须为'+(allowZero?'非负':'正')+'整数,最多'+LIMIT+'对');
return count;
}
function initialize(ledger){ledger.db.exec(`
CREATE TABLE IF NOT EXISTS inventory_count_baselines(
pocket TEXT PRIMARY KEY,date TEXT NOT NULL,initial_count INTEGER NOT NULL CHECK(typeof(initial_count)='integer' AND initial_count>=0),
movement_id TEXT UNIQUE NOT NULL REFERENCES movements(id),created TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS movement_counts(
movement_id TEXT PRIMARY KEY REFERENCES movements(id),stock_count INTEGER NOT NULL CHECK(typeof(stock_count)='integer'),effective_date TEXT NOT NULL);
CREATE INDEX IF NOT EXISTS ix_movement_count_date ON movement_counts(effective_date,movement_id);
`);}
function baseline(ledger,pocket){return ledger.one('SELECT * FROM inventory_count_baselines WHERE pocket=?',pocket)||null;}
function validate(ledger,pocket,value,{original=null,allowLegacy=false,name='库存对数',signed=false,allowZero=false}={}){
if(ledger.pocket(pocket)?.countUnit!=='pair'){
if(!empty(value))fail(name+'只能填写在已启用按对计数的货盘');
return null;
}
if(empty(value)){
if(original!==null&&original!==undefined)return integer(original,{name,signed,allowZero});
if(allowLegacy)return null;
fail('请填写'+ledger.pocketLabel(pocket)+'的'+name+'(一对填1)');
}
return integer(value,{name,signed,allowZero});
}
function value(ledger,id){return ledger.one('SELECT stock_count FROM movement_counts WHERE movement_id=?',typeof id==='string'?id:id.id)?.stock_count??null;}
function decorate(ledger,rows){
const counts=new Map(ledger.rows('SELECT * FROM movement_counts').map(row=>[row.movement_id,row]));
const units=new Map(ledger.pocketCatalog().map(row=>[row.key,row.countUnit]));
return rows.map(row=>!row||units.get(row.pocket)!=='pair'?row:{...row,countUnit:'pair',stockCount:counts.get(row.id)?.stock_count??null,countEffectiveDate:counts.get(row.id)?.effective_date??null});
}
function attach(ledger,id,stockCount,{effectiveDate=null}={}){
if(stockCount===null||stockCount===undefined)return;
const row=ledger.one('SELECT * FROM movements WHERE id=?',id);if(!row)fail('库存流水不存在',404);
const count=integer(stockCount,{signed:true,allowZero:true}),start=baseline(ledger,row.pocket);
if(!start||ledger.pocket(row.pocket)?.countUnit!=='pair')fail('该货盘尚未建立对数盘点基准');
const date=effectiveDate??row.date;
if(!/^\d{4}-\d{2}-\d{2}$/.test(date)||date<start.date||date>today())fail(ledger.pocketLabel(row.pocket)+'的对数业务日期不能早于'+start.date+'盘点基准,也不能晚于今天');
ledger.run('INSERT INTO movement_counts VALUES (?,?,?)',id,count,date);
ledger.dirtyInventory(date);
}
function reverse(ledger,original,id){
const row=ledger.one('SELECT * FROM movement_counts WHERE movement_id=?',typeof original==='string'?original:original.id);
if(row)attach(ledger,id,-row.stock_count,{effectiveDate:row.effective_date});
}
function reserved(ledger){
const counts=new Map();
for(const order of ledger.rows("SELECT lines FROM orders WHERE status='confirmed'"))for(const line of JSON.parse(order.lines))if(line.pocket&&ledger.pocket(line.pocket)?.countUnit==='pair'){
const current=counts.get(line.pocket)||{count:0,unknown:0};
if(Number.isSafeInteger(line.stockCount)&&line.stockCount>0)current.count+=line.stockCount;else current.unknown++;
counts.set(line.pocket,current);
}
return counts;
}
function inventory(ledger,asOf=null){
const reservations=asOf?new Map():reserved(ledger),starts=new Map(ledger.rows('SELECT * FROM inventory_count_baselines').map(row=>[row.pocket,row]));
const totals=new Map(ledger.rows('SELECT m.pocket,SUM(c.stock_count) AS count FROM movement_counts c JOIN movements m ON m.id=c.movement_id'+(asOf?' WHERE c.effective_date<=?':'')+' GROUP BY m.pocket',...(asOf?[asOf]:[])).map(row=>[row.pocket,row.count]));
return new Map(ledger.pocketCatalog().map(pocket=>{
const start=starts.get(pocket.key),known=pocket.countUnit==='pair'&&start&&(!asOf||asOf>=start.date),reservation=reservations.get(pocket.key)||{count:0,unknown:0},count=known?(totals.get(pocket.key)??0):null;
return [pocket.key,{countUnit:pocket.countUnit,countSince:start?.date??null,count,knownReservedCount:known?reservation.count:null,
reservedCount:known&&!reservation.unknown?reservation.count:null,availableCount:known&&!reservation.unknown?count-reservation.count:null,unknownReservedCount:known?reservation.unknown:0}];
}));
}
function assertInventory(ledger,deltas=[]){
const dates=new Map(),changes=[];
for(const row of ledger.rows('SELECT m.pocket,c.effective_date AS date,SUM(c.stock_count) AS stockCount FROM movement_counts c JOIN movements m ON m.id=c.movement_id GROUP BY m.pocket,c.effective_date'))changes.push(row);
for(const row of deltas){
if(row.stockCount===null||row.stockCount===undefined)continue;
const stockCount=integer(row.stockCount,{signed:true,allowZero:true}),start=baseline(ledger,row.pocket),date=row.countEffectiveDate??row.effectiveDate??row.date;
if(!start||date<start.date)fail(ledger.pocketLabel(row.pocket)+'的对数变更不能早于盘点基准');
changes.push({pocket:row.pocket,date,stockCount});
}
for(const row of changes){const pocket=dates.get(row.pocket)||new Map();pocket.set(row.date,(pocket.get(row.date)||0)+row.stockCount);dates.set(row.pocket,pocket);}
const reservations=reserved(ledger);
for(const [key,days] of dates){
let count=0;for(const [date,change] of [...days].sort(([a],[b])=>a.localeCompare(b))){count+=change;if(!Number.isSafeInteger(count))fail('库存对数超出支持范围');if(count<0)fail(ledger.pocketLabel(key)+'在'+date+'库存对数不足,不能提交');}
if(count<(reservations.get(key)?.count??0))fail(ledger.pocketLabel(key)+'可用对数不足,已有订单占用'+reservations.get(key).count+'对');
}
for(const row of deltas)if((row.stockCount??0)<0&&reservations.get(row.pocket)?.unknown)fail(ledger.pocketLabel(row.pocket)+'存在未记录对数的待交付订单,请先补齐实际对数');
}
function requireAvailable(ledger,pocket,count){
const row=inventory(ledger).get(pocket);if(!row||row.countUnit!=='pair')return;
if(row.unknownReservedCount)fail(ledger.pocketLabel(pocket)+'存在未记录对数的待交付订单,请先补齐实际对数');
if(count>row.availableCount)fail(ledger.pocketLabel(pocket)+'可用对数不足,请先登记实物入库');
}
function enable(ledger,pocket,count,actor){
if(actor?.role!=='owner')fail('对数盘点由麦麦账号完成',403);
if(baseline(ledger,pocket))fail('该货盘已建立对数基准,差异请用当天数量调整纠正');
const initial=integer(count,{name:'盘点对数',allowZero:true}),date=today(),created=new Date().toISOString(),id=randomUUID(),group=randomUUID();
ledger.run('INSERT INTO movements VALUES (?,?,?,?,?,?,?,?,?,?,?)',id,group,null,date,pocket,0,'count_opening','启用按对计数:麦麦已核对实际库存',null,actor.name,created);
ledger.run('INSERT INTO inventory_count_baselines VALUES (?,?,?,?,?)',pocket,date,initial,id,created);
attach(ledger,id,initial);ledger.assignMember('movement',id,ledger.memberFor(actor));assertInventory(ledger);
return {date,initialCount:initial};
}
function snapshot(ledger,pockets){
const keys=[...new Set(pockets)].filter(key=>ledger.pocket(key)?.countUnit==='pair').sort();if(!keys.length)return null;
const set=new Set(keys),current=inventory(ledger);
return {baselines:ledger.rows('SELECT * FROM inventory_count_baselines ORDER BY pocket').filter(row=>set.has(row.pocket)),
movements:ledger.rows('SELECT m.id,m.pocket,c.stock_count,c.effective_date FROM movements m JOIN movement_counts c ON c.movement_id=m.id ORDER BY m.rowid').filter(row=>set.has(row.pocket)),
inventory:keys.map(pocket=>({pocket,...current.get(pocket)}))};
}
function snapshotHash(ledger,pockets){return createHash('sha256').update(JSON.stringify(snapshot(ledger,pockets))).digest('hex');}
function effect(ledger,pockets){
const saved=snapshot(ledger,pockets);if(!saved)return null;
const set=new Set(saved.baselines.map(row=>row.pocket));
return {baselines:saved.baselines,inventory:saved.inventory,
movements:ledger.rows('SELECT m.pocket,c.effective_date,SUM(c.stock_count) AS stock_count FROM movement_counts c JOIN movements m ON m.id=c.movement_id GROUP BY m.pocket,c.effective_date HAVING SUM(c.stock_count)<>0 ORDER BY m.pocket,c.effective_date').filter(row=>set.has(row.pocket))};
}
const legacyNotice='这笔记录在启用按对计数前没有记录对数。此次只更正历史克重,当前对数保留已核对的盘点基准。实物实际退回请登记退货并填写退回对数;盘点差异请登记当天数量调整。';
function legacyInfo(ledger,rows){
const orders=new Map();
const required=rows.some(row=>{
if(ledger.pocket(row.pocket)?.countUnit!=='pair'||value(ledger,row.id)!==null||row.mg===0)return false;
if(!row.order_id)return true;
if(!orders.has(row.order_id))orders.set(row.order_id,JSON.parse(ledger.one('SELECT lines FROM orders WHERE id=?',row.order_id)?.lines||'[]'));
return orders.get(row.order_id).some(line=>line.pocket===row.pocket&&!Number.isSafeInteger(line.stockCount));
});
return {requiresLegacyCountVerified:required,legacyCountNotice:required?legacyNotice:''};
}
function verifyLegacy(ledger,rows,input){const info=legacyInfo(ledger,rows);if(info.requiresLegacyCountVerified&&input?.legacyCountVerified!==true)fail('请核对并确认:'+legacyNotice);return info;}
module.exports={initialize,integer,baseline,validate,value,decorate,attach,reverse,inventory,assertInventory,requireAvailable,enable,snapshot,snapshotHash,effect,legacyInfo,verifyLegacy};