Files
weiguang-jewelry-ledger/新账系统/rolling-material-pools.js
T

1070 lines
42 KiB
JavaScript
Raw Normal View History

'use strict';
// 滚动日料池:期初结转不造采购,日终冻结不回写历史订单。
const { randomUUID, createHash } = require('node:crypto');
const Calc = require('./public/calculations');
const KEY = 'rolling-material-pools-v1';
const Amounts = require('./material-member-amounts');
const TeamMembers = require('./team-members');
const LockPools = require('./price-lock-pools'),
Allocation = require('./material-pool-allocation');
const sum = (rows, key) => rows.reduce((n, row) => n + (row[key] ?? 0), 0);
const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
const legacy = () => require('./material-pools');
function initialize(l) {
l.db.exec(`
CREATE TABLE IF NOT EXISTS material_rolling_days(date TEXT PRIMARY KEY,opening TEXT NOT NULL,snapshot TEXT NOT NULL DEFAULT '',frozen INTEGER NOT NULL DEFAULT 0,revision INTEGER NOT NULL DEFAULT 1);
CREATE TABLE IF NOT EXISTS material_rolling_legacy(pool_id TEXT PRIMARY KEY,snapshot TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS material_rolling_source_order(sequence INTEGER PRIMARY KEY AUTOINCREMENT,kind TEXT NOT NULL,source_id TEXT NOT NULL,UNIQUE(kind,source_id));
CREATE TABLE IF NOT EXISTS material_rolling_returns(id TEXT PRIMARY KEY,order_id TEXT NOT NULL,line_index INTEGER NOT NULL,date TEXT NOT NULL,mg INTEGER NOT NULL,amount INTEGER,allocations TEXT NOT NULL,origin_pool_id TEXT NOT NULL,same_day INTEGER NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL,UNIQUE(order_id,line_index));
`);
// 撤销原回收后,历史退货回料也可能暂缺成本;保留原行及顺序,只放宽该金额字段。
if (l.rows('PRAGMA table_info(material_rolling_returns)').find(r => r.name === 'amount')?.notnull) {
l.db.exec('SAVEPOINT rolling_return_pending_upgrade');
try {
const sql = l.one("SELECT sql FROM sqlite_master WHERE type='table' AND name='material_rolling_returns'").sql;
const indexes = l.rows(
"SELECT sql FROM sqlite_master WHERE tbl_name='material_rolling_returns' AND type IN ('index','trigger') AND sql IS NOT NULL",
);
l.db.exec(
sql
.replace(
/CREATE TABLE\s+(?:"material_rolling_returns"|material_rolling_returns)/i,
'CREATE TABLE material_rolling_returns_pending_upgrade',
)
.replace(/amount\s+INTEGER\s+NOT NULL/i, 'amount INTEGER'),
);
l.db.exec(
'INSERT INTO material_rolling_returns_pending_upgrade(rowid,id,order_id,line_index,date,mg,amount,allocations,origin_pool_id,same_day,actor,created) SELECT rowid,* FROM material_rolling_returns',
);
l.db.exec(
'DROP TABLE material_rolling_returns;ALTER TABLE material_rolling_returns_pending_upgrade RENAME TO material_rolling_returns',
);
for (const r of indexes) l.db.exec(r.sql);
l.db.exec('RELEASE rolling_return_pending_upgrade');
} catch (e) {
l.db.exec('ROLLBACK TO rolling_return_pending_upgrade');
l.db.exec('RELEASE rolling_return_pending_upgrade');
throw e;
}
}
}
function config(l) {
return l.meta(KEY);
}
function enabled(l) {
return !!config(l)?.enabled;
}
function isDay(l, date) {
const c = config(l);
return !!c?.enabled && date >= c.cutover;
}
function withHistorical(l, fn) {
const previous = l.rollingHistorical;
l.rollingHistorical = true;
try {
return fn();
} finally {
l.rollingHistorical = previous;
}
}
function assertDate(l, date, env) {
if (enabled(l) && !l.rollingHistorical && date !== env.today())
env.fail('已结转日期的料池已冻结,历史更正须提交麦麦复核', 409);
}
function dependency(l) {
const tables = [
'material_purchases',
'material_purchase_shares',
'material_purchase_payment_origins',
'recovery_purchase_sources',
'material_pool_usages',
'material_usage_parties',
'material_rolling_days',
'material_rolling_returns',
'material_rolling_legacy',
'material_rolling_source_order',
];
if (
l.one("SELECT name FROM sqlite_master WHERE type='table' AND name='recovery_material_batches'") &&
l.one('SELECT purchase_id FROM recovery_material_batches LIMIT 1')
)
tables.push('recovery_material_batches', 'material_usage_sources', 'material_return_sources');
if (l.one('SELECT id FROM price_lock_pool_reservations LIMIT 1'))
tables.push('price_lock_pool_reservations', 'price_lock_pool_returns', 'price_locks', 'material_usage_order');
if (l.one('SELECT source_id FROM material_public_substitutions LIMIT 1'))
tables.push('material_public_substitutions');
return hash({
config: config(l),
tables: tables.map(table => [table, l.rows('SELECT * FROM ' + table + ' ORDER BY rowid')]),
orders: l.rows('SELECT id,revision,status,lines FROM orders ORDER BY rowid'),
});
}
function parts(p) {
return (p.allocations ?? [{ payer: p.payer, amount: p.amount }]).filter(a => a.amount > 0);
}
function registerSource(l, kind, id) {
l.run('INSERT OR IGNORE INTO material_rolling_source_order(kind,source_id) VALUES (?,?)', kind, id);
return l.one('SELECT sequence FROM material_rolling_source_order WHERE kind=? AND source_id=?', kind, id).sequence;
}
function remainingParts(purchases, consumed) {
let skip = consumed;
const result = [];
for (const p of purchases)
for (const part of parts(p)) {
const taken = Math.min(skip, part.amount);
skip -= taken;
if (part.amount > taken)
result.push({
...part,
amount: part.amount - taken,
source_id: part.source_id ?? p.id,
created: part.created ?? p.created,
});
}
if (skip) throw new Error('料池结转资金不守恒');
return result;
}
function legacyOpening(l, cutover, env) {
const ids = l
.rows(
"SELECT DISTINCT pool_id FROM material_purchases WHERE pool_id<? AND deleted_at='' UNION SELECT DISTINCT pool_id FROM material_pool_usages WHERE pool_id<? UNION SELECT date AS pool_id FROM material_rolling_returns WHERE date<? AND order_id IN (SELECT order_id FROM order_after_sales) ORDER BY pool_id",
cutover,
cutover,
cutover,
)
.map(r => r.pool_id);
const pools = ids.map(id => legacy().readPool(l, id, env, { internal: true }));
const returned = l.rows(
'SELECT * FROM material_rolling_returns WHERE origin_pool_id<>? AND origin_pool_id<? AND same_day=0 AND order_id NOT IN (SELECT order_id FROM order_after_sales)',
'',
cutover,
);
if (pools.some(pool => pool.materialGroups)) {
const balances = pools.flatMap(pool =>
Allocation.balances(
{ ...pool, materialGroups: pool.materialGroups ?? Allocation.groups(pool.purchases) },
pool.usages.filter(u => u.active && l.one('SELECT date FROM orders WHERE id=?', u.order_id)?.date < cutover),
),
);
const common = balances.filter(g => g.kind === 'public'),
personal = balances.filter(g => g.kind === 'personal_recovery'),
pending = balances.some(g => g.status === 'pending');
const mg = sum(common, 'remainingMg') - sum(returned, 'mg'),
amount = pending ? null : sum(common, 'remainingCost') - sum(returned, 'amount'),
remaining = common.flatMap(g => g.remainingAllocations),
reversed = Object.fromEntries(TeamMembers.keys(l).map(p => [p, 0]));
for (const r of returned) for (const a of JSON.parse(r.allocations)) reversed[a.payer] += a.amount;
const allocations = remaining.flatMap(a => {
const n = Math.min(a.amount, reversed[a.payer]);
reversed[a.payer] -= n;
return a.amount === n ? [] : [{ ...a, amount: a.amount - n }];
});
const materialGroups = [
{ kind: 'public', member: null, mg, amount, allocations, batches: common.flatMap(g => g.remainingBatches) },
...TeamMembers.keys(l).flatMap(member => {
const own = personal.filter(g => g.member === member);
return own.length
? [
{
kind: 'personal_recovery',
member,
mg: sum(own, 'remainingMg'),
amount: own.some(g => g.remainingCost === null) ? null : sum(own, 'remainingCost'),
allocations: own.flatMap(g => g.remainingAllocations),
batches: own.flatMap(g => g.remainingBatches),
},
]
: [];
}),
];
return {
mg,
amount,
allocations,
materialGroups,
pending: pending || mg < 0 || (amount !== null && amount < 0),
pools,
};
}
// 今日旧耗用会迁入新池;期初只扣冻结的历史耗用,不能先扣今日用量再迁入扣第二次。
const frozen = pools.map(p => ({
pool: p,
usages: p.usages.filter(u => u.active && l.one('SELECT date FROM orders WHERE id=?', u.order_id).date < cutover),
}));
const grossMg = sum(
frozen.map(v => ({ mg: v.pool.totalMg - sum(v.usages, 'mg') })),
'mg',
),
pending = frozen.some(v => v.usages.some(u => u.amount === null));
const grossAmount = pending
? null
: sum(
frozen.map(v => ({ amount: v.pool.totalAmount - sum(v.usages, 'amount') })),
'amount',
);
const allocations = frozen
.flatMap(({ pool, usages }) => {
const consumed = Object.fromEntries(TeamMembers.keys(l).map(payer => [payer, sum(usages, payer + '_amount')]));
return pool.purchases.flatMap(p =>
parts(p).flatMap(a => {
const take = Math.min(consumed[a.payer], a.amount);
consumed[a.payer] -= take;
return take === a.amount
? []
: [
{
...a,
amount: a.amount - take,
source_id: p.id,
created: p.created,
source_sequence:
l.one('SELECT rowid AS n FROM material_purchases WHERE id=?', p.id)?.n ?? p.source_sequence ?? 0,
},
];
}),
);
})
.sort((a, b) => String(a.created).localeCompare(String(b.created)) || a.source_sequence - b.source_sequence);
// 切换后退回的旧耗用已由当日回料承接,不能再次抬高切换日结转。
const reversed = Object.fromEntries(TeamMembers.keys(l).map(p => [p, 0]));
for (const r of returned) for (const a of JSON.parse(r.allocations)) reversed[a.payer] += a.amount;
const adjusted = allocations.flatMap(a => {
const take = Math.min(reversed[a.payer], a.amount);
reversed[a.payer] -= take;
return take === a.amount ? [] : [{ ...a, amount: a.amount - take }];
});
const mg = grossMg - sum(returned, 'mg'),
amount = grossAmount === null ? null : grossAmount - sum(returned, 'amount');
return { mg, amount, allocations: adjusted, pending: pending || mg < 0 || (amount !== null && amount < 0), pools };
}
function baseEnablePreview(l, query, actor, env) {
const date = env.day(query.date ?? env.today()),
c = config(l),
opening = legacyOpening(l, date, env);
const affected = l.rows(
'SELECT DISTINCT u.order_id FROM material_pool_usages u JOIN orders o ON o.id=u.order_id WHERE o.date>=? AND u.active=1',
date,
);
const reason = c?.enabled
? '滚动料池已经启用'
: date !== env.today()
? '请从当前营业日启用'
: opening.pending || opening.amount === null
? '历史料池存在待补成本或负余料,请先核实后切换'
: '';
return {
date,
revision: dependency(l),
canEnable: !reason,
reason,
opening: {
mg: opening.mg,
amount: opening.amount,
allocations: opening.allocations,
...(opening.materialGroups ? { materialGroups: opening.materialGroups } : {}),
},
affectedOrderCount: affected.length,
};
}
function finance(l) {
return new Map(
l.rows('SELECT id FROM orders ORDER BY rowid').map(({ id }) => {
const o = l.detail(id);
return [
id,
{
id,
number: o.paper_number || o.number,
date: o.date,
member: o.member,
goodsCost: o.goodsCost,
profit: o.profit,
settlementDue: o.settlementDue,
ownerCost: o.ownerCost,
total: o.total,
netReceived: o.netReceived,
},
];
}),
);
}
function previewEnable(l, query, actor, env) {
const result = baseEnablePreview(l, query, actor, env);
if (!result.canEnable) return result;
const before = l.scope(null, () => finance(l), null);
l.db.exec('SAVEPOINT rolling_enable_preview');
try {
enableInternal(l, result, actor ?? { id: 'system-preview', name: '切换预览', role: 'owner' }, env);
const after = l.scope(null, () => finance(l), null),
keys = ['goodsCost', 'profit', 'settlementDue', 'ownerCost', 'total', 'netReceived'],
relatedOrders = [];
for (const [id, b] of before) {
const a = after.get(id);
if (keys.some(k => a[k] !== b[k]))
relatedOrders.push({
id,
number: b.number,
date: b.date,
member: b.member,
before: Object.fromEntries(keys.map(k => [k, b[k]])),
after: Object.fromEntries(keys.map(k => [k, a[k]])),
});
}
return {
...result,
relatedOrders,
affectedDates: [...new Set(relatedOrders.map(o => o.date))].sort(),
summary: {
affectedOrderCount: relatedOrders.length,
goodsDelta: relatedOrders.reduce((n, r) => n + (r.after.goodsCost ?? 0) - (r.before.goodsCost ?? 0), 0),
profitDelta: relatedOrders.reduce((n, r) => n + (r.after.profit ?? 0) - (r.before.profit ?? 0), 0),
},
};
} finally {
l.db.exec('ROLLBACK TO rolling_enable_preview');
l.db.exec('RELEASE rolling_enable_preview');
}
}
function enable(l, input, actor, env) {
l.db.exec('SAVEPOINT rolling_material_enable');
try {
const result = enableAction(l, input, actor, env);
l.db.exec('RELEASE rolling_material_enable');
return result;
} catch (error) {
l.db.exec('ROLLBACK TO rolling_material_enable');
l.db.exec('RELEASE rolling_material_enable');
throw error;
}
}
function enableAction(l, input, actor, env) {
if (actor?.role !== 'owner') env.fail('滚动料池须由麦麦核实后启用', 403);
const preview = baseEnablePreview(l, input, actor, env);
if (!preview.canEnable) env.fail(preview.reason, 409);
if (input.verified !== true || input.revision !== preview.revision) env.fail('切换依据有变动,请重新预览并确认', 409);
return enableInternal(l, preview, actor, env);
}
function enableInternal(l, preview, actor, env) {
for (const p of l.rows('SELECT id FROM material_purchases ORDER BY created,rowid'))
registerSource(l, 'purchase', p.id);
const opening = legacyOpening(l, preview.date, env);
for (const pool of opening.pools)
l.run('INSERT INTO material_rolling_legacy VALUES (?,?)', pool.id, JSON.stringify(pool));
l.setMeta(KEY, { enabled: true, cutover: preview.date, created: env.now(), actor: actor.name });
l.run('INSERT INTO material_rolling_days(date,opening) VALUES (?,?)', preview.date, JSON.stringify(preview.opening));
const migrated = new Set();
for (const u of l.rows(
'SELECT u.* FROM material_pool_usages u JOIN orders o ON o.id=u.order_id WHERE o.date>=? AND u.active=1 ORDER BY u.rowid',
preview.date,
)) {
const order = l.rawOrder(u.order_id),
line = order.lines[u.line_index],
origin = u.pool_id;
line.costMaterial = { ...line.costMaterial, poolId: preview.date };
l.run(
'UPDATE material_pool_usages SET pool_id=?,revision=revision+1,updated=? WHERE id=?',
preview.date,
env.now(),
u.id,
);
l.run('UPDATE orders SET lines=? WHERE id=?', JSON.stringify(order.lines), order.id);
l.run(
'INSERT INTO material_pool_events VALUES (?,?,?,?,?,?,?,?,?,?)',
randomUUID(),
preview.date,
u.id,
u.order_id,
preview.date,
'切换今日统一料池',
JSON.stringify(u),
JSON.stringify({ ...u, pool_id: preview.date, origin_pool_id: origin }),
actor.name,
env.now(),
);
migrated.add(order.id);
}
for (const id of migrated) l.touch(id);
const current = reconcile(l, preview.date, actor, env);
l.audit('system:rolling-material', '启用滚动日料池', actor, {
...preview,
notice: '结转不重复登记采购、现金、实物或历史订单成本',
});
return { rolling: status(l, env), current };
}
function legacySnapshot(l, id) {
const r = l.one('SELECT snapshot FROM material_rolling_legacy WHERE pool_id=?', id);
return r ? JSON.parse(r.snapshot) : null;
}
function status(l, env) {
const c = config(l),
preview = c?.enabled ? null : baseEnablePreview(l, {}, null, env);
return {
enabled: !!c?.enabled,
cutover: c?.cutover ?? null,
canEnable: preview?.canEnable ?? false,
reason: preview?.reason ?? '',
};
}
function nextOpening(l, date, env) {
const previous = l.one('SELECT date FROM material_rolling_days WHERE date<? ORDER BY date DESC LIMIT 1', date);
if (!previous) return legacyOpening(l, config(l).cutover, env);
const pool = readPool(l, previous.date, env, { internal: true });
return {
mg: pool.remainingMg,
amount: pool.remainingCost,
allocations: pool.remainingAllocations,
pending: pool.status === 'pending',
...(pool.remainingMaterialGroups ? { materialGroups: pool.remainingMaterialGroups } : {}),
};
}
function ensureDay(l, date, env) {
const current = l.one('SELECT * FROM material_rolling_days WHERE date=?', date);
if (current) return current;
const previous = l.one('SELECT date FROM material_rolling_days WHERE date<? ORDER BY date DESC LIMIT 1', date),
opening = nextOpening(l, date, env);
if (opening.amount === null && !l.rollingHistorical) env.fail('上日金料成本尚未补齐,请先由麦麦核实历史料池', 409);
if (previous) {
const pool = readPool(l, previous.date, env, { internal: true });
l.run('UPDATE material_rolling_days SET snapshot=?,frozen=1 WHERE date=?', JSON.stringify(pool), previous.date);
}
l.run('INSERT INTO material_rolling_days(date,opening) VALUES (?,?)', date, JSON.stringify(opening));
return l.one('SELECT * FROM material_rolling_days WHERE date=?', date);
}
function returnsFor(l, date) {
return l
.rows(
"SELECT r.*,s.sequence AS source_sequence,o.number,o.paper_number,o.date AS order_date FROM material_rolling_returns r JOIN orders o ON o.id=r.order_id LEFT JOIN material_rolling_source_order s ON s.kind='return' AND s.source_id=r.id WHERE r.date=? ORDER BY r.created,r.rowid",
date,
)
.map(r => ({
...r,
number: r.paper_number || r.number,
allocations: JSON.parse(r.allocations),
...(Allocation.returnSources(l, 'order', r.id)
? { materialSources: Allocation.returnSources(l, 'order', r.id) }
: {}),
sameDay: !!r.same_day,
cashAmount: 0,
}));
}
function consumed(l, u, date) {
return (
!!u.active ||
(!!l.rollingRebuilding &&
!!l.one(
'SELECT id FROM material_rolling_returns WHERE order_id=? AND line_index=? AND origin_pool_id=? AND date>? AND same_day=0',
u.order_id,
u.line_index,
date,
date,
))
);
}
// 重算只读取采购、结转、回料及用量事实,不能先用旧耗用金额扣除已经更正的新资金。
// 最终余额与归属仍由 readPool 严格核对;普通读取不重算、不写入。
function readSources(l, date, env, saved = l.one('SELECT * FROM material_rolling_days WHERE date=?', date)) {
const opening = saved ? JSON.parse(saved.opening) : nextOpening(l, date, env);
const actual = l
.rows(
"SELECT p.*,s.sequence AS source_sequence FROM material_purchases p LEFT JOIN material_rolling_source_order s ON s.kind='purchase' AND s.source_id=p.id WHERE p.date=? AND p.deleted_at='' ORDER BY p.created,p.rowid",
date,
)
.map(r => ({ ...legacy().actualPurchase(l, r), sourceKind: 'purchase' }));
const returns = [...returnsFor(l, date), ...LockPools.returns(l, date)],
netReturns = returns.filter(r => !r.sameDay);
const carry =
Allocation.carrySources(opening, date) ??
(opening.mg
? [
{
id: 'carry:' + date,
date,
mg: opening.mg,
amount: opening.amount,
payer: opening.allocations?.[0]?.payer ?? 'owner',
allocations: opening.allocations ?? [],
created: date + 'T00:00:00.000Z',
note: '以前结转',
sourceKind: 'carry',
cashAmount: 0,
canEdit: false,
},
]
: []);
const returned = netReturns
.flatMap(r => Allocation.expandSource(r))
.map(r => ({
...r,
id: 'return:' + r.id,
payer: r.allocations[0]?.payer ?? 'owner',
sourceKind: 'return',
note: r.note ?? '退货回料',
canEdit: false,
}));
const purchases = [
...carry,
...[...actual, ...returned].sort((a, b) =>
a.created < b.created ? -1 : a.created > b.created ? 1 : a.source_sequence - b.source_sequence,
),
];
const usages = LockPools.combined(
l,
date,
l
.rows(
'SELECT u.*,u.rowid AS fifo_sequence,o.number,o.customer,o.status AS order_status,o.lines FROM material_pool_usages u JOIN orders o ON o.id=u.order_id WHERE u.pool_id=? ORDER BY u.created,u.rowid',
date,
)
.map(({ lines, ...r }) => ({
...r,
...l.one('SELECT assistant2_amount FROM material_usage_parties WHERE usage_id=?', r.id),
...Amounts.read(l, r.id),
member: l.entityMember('order', r.order_id),
...(Allocation.usageSources(l, r.id) ? { materialSources: Allocation.usageSources(l, r.id) } : {}),
product: JSON.parse(lines)[r.line_index]?.name ?? '',
})),
);
const totalMg = opening.mg + sum(actual, 'mg') + sum(netReturns, 'mg'),
totalAmount =
opening.amount === null || netReturns.some(r => r.amount === null)
? null
: opening.amount + sum(actual, 'amount') + sum(netReturns, 'amount'),
active = usages.filter(r => consumed(l, r, date)),
usedMg = sum(active, 'mg');
const materialGroups = Allocation.groups(purchases),
segmented = materialGroups.some(g => g.kind === 'personal_recovery'),
publicGroup = materialGroups.find(g => g.kind === 'public');
return {
id: date,
date,
rolling: true,
opening,
actual: segmented ? actual.filter(p => !p.materialOwner) : actual,
returns,
netReturns,
purchases: segmented ? publicGroup.purchases : purchases,
usages,
totalMg: segmented ? publicGroup.totalMg : totalMg,
totalAmount: segmented ? publicGroup.totalAmount : totalAmount,
usedMg,
averageRate: segmented
? publicGroup.averageRate
: totalAmount !== null && totalMg
? Calc.poolMaterialAmount(totalAmount, totalMg, 1000)
: null,
...(segmented ? { materialGroups } : {}),
revision: hash({ opening, actual, returns, usages: usages.map(({ lines, ...r }) => r) }),
};
}
function readPool(l, date, env, { internal = false, live = false, member = null } = {}) {
const saved = l.one('SELECT * FROM material_rolling_days WHERE date=?', date);
if (saved?.frozen && saved.snapshot && !live) {
let pool = { ...JSON.parse(saved.snapshot), frozen: true };
if (member) pool = Allocation.eligible(pool, member);
return internal ? pool : legacy().visiblePool(l, pool);
}
const source = readSources(l, date, env, saved),
{ opening, actual, returns, netReturns, purchases, usages, totalMg, totalAmount, usedMg, averageRate, revision } =
source,
active = usages.filter(r => consumed(l, r, date));
const pending = totalAmount === null || totalMg < usedMg || active.some(r => r.amount === null),
consumedCost = pending ? null : sum(active, 'amount'),
remainingCost = pending ? null : totalAmount - consumedCost;
const funding = purchases.filter(p => p.amount > 0),
remainingAllocations = Allocation.enabled(source) || pending ? [] : remainingParts(funding, consumedCost);
const byPayer = Object.fromEntries(
Amounts.keys(funding, active).map(payer => {
const purchased = sum(
funding.flatMap(parts).filter(a => a.payer === payer),
'amount',
),
consumed = pending ? null : sum(active, payer + '_amount');
return [payer, { purchased, consumed, remaining: pending ? null : purchased - consumed }];
}),
);
const pool = {
id: date,
date,
rolling: true,
frozen: !!saved?.frozen,
totalMg,
totalAmount,
usedMg,
remainingMg: Math.max(0, totalMg - usedMg),
shortageMg: Math.max(0, usedMg - totalMg),
consumedCost,
remainingCost,
remainingAllocations,
byPayer,
averageRate,
status: pending ? 'pending' : !usedMg ? 'unused' : usedMg === totalMg ? 'exhausted' : 'using',
revision,
opening,
todayPurchases: { mg: sum(actual, 'mg'), amount: sum(actual, 'amount'), count: actual.length, items: actual },
todayReturns: {
mg: sum(netReturns, 'mg'),
amount: sum(netReturns, 'amount'),
count: netReturns.length,
grossMg: sum(returns, 'mg'),
grossAmount: sum(returns, 'amount'),
grossCount: returns.length,
},
returns,
purchases,
usages,
settlements: [],
settlement: { legacyReadOnly: true, settlementDue: 0, assistantInventoryCredit: 0, transferred: 0, pending },
};
if (Allocation.enabled(source)) {
const groups = Allocation.balances(source, active),
common = groups.find(g => g.kind === 'public');
Object.assign(pool, {
usedMg: common.usedMg,
remainingMg: common.remainingMg,
shortageMg: common.shortageMg,
consumedCost: common.consumedCost,
remainingCost: common.remainingCost,
remainingAllocations: common.remainingAllocations,
byPayer: common.byPayer,
status: common.status,
materialGroups: source.materialGroups,
personalPools: Object.fromEntries(
groups.filter(g => g.kind === 'personal_recovery').map(g => [g.member, { ...g, date, id: date }]),
),
remainingMaterialGroups: Allocation.remainingGroups(source, active),
});
pool.settlement.pending = common.status === 'pending';
}
const result = member ? Allocation.eligible(pool, member) : pool;
return internal ? result : legacy().visiblePool(l, result);
}
function allocations(pool, usages, l = null) {
const base = (value, rows) => LockPools.allocate(value, rows, legacy().allocatePayers);
return l ? require('./order-after-sales').allocateFrozen(l, pool, usages, base) : base(pool, usages);
}
function applyLine(line, row, pool) {
const a = Amounts.parts(row);
if (row.amount === 0 && !a.length) a.push({ payer: row.zero_payer ?? 'owner', amount: 0 });
line.costParts = { ...line.costParts, material: row.amount };
line.cost = Object.values(line.costParts).some(v => v === null)
? null
: sum(
Object.values(line.costParts).map(amount => ({ amount })),
'amount',
);
line.materialPool = {
...(row.materialSources ? { materialSources: row.materialSources } : {}),
poolId: pool.id,
date: pool.date,
status: row.amount === null ? 'pending' : 'allocated',
amount: row.amount,
quantity: row.mg,
averageRate: row.materialSources
? row.amount === null
? null
: Calc.poolMaterialAmount(row.amount, row.mg, 1000)
: pool.averageRate,
allocations: a,
revision: pool.revision,
rolling: true,
};
}
function prepareLines(l, lines, businessDate, env, { orderId = null, member = null } = {}) {
const selected = lines.flatMap((line, index) => (line.costMaterial?.mode === 'pool' ? [{ line, index }] : []));
if (!selected.length) return lines;
assertDate(l, businessDate, env);
for (const { line } of selected) {
if (line.costMaterial.poolId !== businessDate) env.fail('滚动日料池须使用订单当天日期');
if (line.unit !== 'g' || Calc.isSilver(line.name)) env.fail('日购料成本只支持按克黄金商品');
}
const pool = readPool(l, businessDate, env, { internal: true }),
original = LockPools.decorate(
l,
l.rows('SELECT rowid AS fifo_sequence,* FROM material_pool_usages WHERE order_id=?', orderId ?? ''),
),
last = l.one('SELECT COALESCE(MAX(sequence),0) AS n FROM material_usage_order').n;
const usages = pool.usages.filter(u => u.active && (!orderId || u.order_id !== orderId));
for (const { line, index } of selected) {
const before = original.find(u => u.line_index === index);
usages.push({
...before,
member: member ?? (orderId ? l.entityMember('order', orderId) : null) ?? l.memberFor(l.actor),
mg: line.costMaterial?.consumptionMg ?? line.quantity,
preview_index: index,
created: before?.created ?? env.now(),
fifo_sequence: before?.fifo_sequence ?? last + index + 1,
});
}
usages.sort((a, b) => (a.created < b.created ? -1 : a.created > b.created ? 1 : a.fifo_sequence - b.fifo_sequence));
for (const u of allocations(pool, usages, l))
if (u.preview_index !== undefined) applyLine(lines[u.preview_index], u, pool);
return lines;
}
function reconcile(l, ...args) {
return l.scope(null, () => reconcileInternal(l, ...args), null);
}
function reconcileInternal(
l,
date,
actor,
env,
{ skipJournalOrder = null, preservePriceLockIds = [], repriceExtraPriceLockIds = [] } = {},
) {
assertDate(l, date, env);
ensureDay(l, date, env);
const pool = readSources(l, date, env),
updates = new Map();
const preserved = new Set(preservePriceLockIds);
for (const u of allocations(
pool,
pool.usages.filter(u => consumed(l, u, date) || (u.kind === 'priceLock' && u.reservedPublicSubstitutionMg > 0)),
l,
)) {
if (u.kind === 'priceLock') {
if (!preserved.has(u.price_lock_id) || (u.line_index < 0 && repriceExtraPriceLockIds.includes(u.price_lock_id)))
LockPools.update(l, u, pool, actor, env, { skipJournalOrder });
continue;
}
if (require('./order-after-sales').read(l, u.order_id)) continue;
if (!updates.has(u.order_id)) updates.set(u.order_id, { order: l.rawOrder(u.order_id), delta: 0, changed: false });
const v = updates.get(u.order_id),
line = v.order.lines[u.line_index];
if (!line || line.costMaterial?.poolId !== date) env.fail('滚动料池与商品来源不一致', 409);
const before = line.costParts?.material,
oldAlloc = line.materialPool?.allocations,
oldRate = line.materialPool?.averageRate,
oldSources = line.materialPool?.materialSources;
applyLine(line, u, pool);
Allocation.saveUsage(l, u.id, u.materialSources);
v.delta += (u.amount ?? 0) - (before ?? 0);
v.changed =
v.changed ||
before !== u.amount ||
oldRate !== pool.averageRate ||
JSON.stringify(oldAlloc) !== JSON.stringify(line.materialPool.allocations) ||
JSON.stringify(oldSources) !== JSON.stringify(line.materialPool.materialSources);
l.run(
'UPDATE material_pool_usages SET amount=?,owner_amount=?,assistant_amount=?,revision=revision+?,updated=? WHERE id=?',
u.amount,
u.owner_amount,
u.assistant_amount,
v.changed ? 1 : 0,
env.now(),
u.id,
);
Amounts.save(l, u.id, u);
if (u.assistant2_amount !== undefined)
l.run(
'INSERT INTO material_usage_parties VALUES (?,?) ON CONFLICT(usage_id) DO UPDATE SET assistant2_amount=excluded.assistant2_amount',
u.id,
u.assistant2_amount,
);
else l.run('DELETE FROM material_usage_parties WHERE usage_id=?', u.id);
}
for (const [id, v] of updates) {
l.run('UPDATE orders SET lines=? WHERE id=?', JSON.stringify(v.order.lines), id);
if (v.changed && id !== skipJournalOrder) {
if (v.delta && v.order.status === 'delivered')
l.journal(id, v.order.delivered_date || date, '滚动日料池成本调整', 0, v.delta, 0);
if (v.delta && v.order.status === 'returned' && l.rollingRebuilding) {
l.journal(id, v.order.delivered_date || date, '复核更正原耗用成本', 0, v.delta, 0);
l.journal(id, v.order.returned_date, '复核更正退货成本冲回', 0, -v.delta, 0);
}
l.touch(id);
l.dirty(v.order.date);
l.audit(id, '滚动日料池自动重算', actor, { date, goodsDelta: v.delta });
}
}
const final = readPool(l, date, env, { internal: true, live: true });
l.run('UPDATE material_rolling_days SET snapshot=?,revision=revision+1 WHERE date=?', JSON.stringify(final), date);
l.dirty(date);
return final;
}
function recordReturns(l, order, date, input, actor, env) {
if (!enabled(l) || date < config(l).cutover) return;
assertDate(l, date, env);
ensureDay(l, date, env);
const lockedReturns = LockPools.recordReturn(l, order, date, input, actor, env);
for (const [index, line] of order.lines.entries()) {
if (lockedReturns && lockedReturns.includes(index)) continue;
const destination = input.returnPockets?.[index] ?? line.pocket;
if (!env.selfPockets?.includes(destination) || line.unit !== 'g' || Calc.isSilver(line.name)) continue;
const amount = line.costParts?.material;
if (!Number.isSafeInteger(amount) || amount < 0)
env.fail('原商品金料成本尚未核实,不能将未知金额记为退货回料', 409);
const usage = l.one('SELECT * FROM material_pool_usages WHERE order_id=? AND line_index=?', order.id, index),
old =
line.materialPool?.allocations ??
(line.materialAllocations
? Amounts.keys(line.materialAllocations)
.map(payer => ({
payer,
amount: sum(
line.materialAllocations.filter(part => part.payer === payer),
'amount',
),
}))
.filter(part => part.amount > 0)
: null);
const allocations = old?.length ? old : [{ payer: line.costPayers?.material ?? line.payer, amount }];
if (sum(allocations, 'amount') !== amount) env.fail('退货回料金料成本归属不守恒');
const id = randomUUID();
l.run(
'INSERT INTO material_rolling_returns VALUES (?,?,?,?,?,?,?,?,?,?,?)',
id,
order.id,
index,
date,
line.quantity,
amount,
JSON.stringify(allocations),
usage?.pool_id ?? '',
usage?.pool_id === date ? 1 : 0,
actor.name,
env.now(),
);
registerSource(l, 'return', id);
Allocation.saveReturn(l, 'order', id, line.materialPool?.materialSources);
}
}
function release(l, order, date, actor, env, { kind = '实物退回释放' } = {}) {
assertDate(l, date, env);
ensureDay(l, date, env);
for (const u of l.rows('SELECT * FROM material_pool_usages WHERE order_id=? AND active=1', order.id)) {
l.run('UPDATE material_pool_usages SET active=0,revision=revision+1,updated=? WHERE id=?', env.now(), u.id);
l.run(
'INSERT INTO material_pool_events VALUES (?,?,?,?,?,?,?,?,?,?)',
randomUUID(),
u.pool_id,
u.id,
order.id,
date,
kind,
JSON.stringify(u),
JSON.stringify({ ...u, active: 0 }),
actor.name,
env.now(),
);
}
if (kind === '订单录错作废释放' && l.rollingHistorical) {
rebuild(l, actor, env);
return readPool(l, env.today(), env, { internal: true });
}
return reconcile(l, date, actor, env);
}
function list(l, query, env) {
const date = env.day(query.date ?? query.to ?? env.today()),
from = env.day(query.from ?? (query.date || query.to ? date : '2000-01-01'));
if (from > date) env.fail('开始日期不能晚于结束日期');
const c = config(l),
current = readPool(l, env.today(), env);
const legacyRows = l
.rows(
'SELECT pool_id,snapshot FROM material_rolling_legacy WHERE pool_id>=? AND pool_id<=? ORDER BY pool_id DESC',
from,
date,
)
.map(r => legacy().visiblePool(l, JSON.parse(r.snapshot)));
const days = l
.rows('SELECT date FROM material_rolling_days WHERE date>=? AND date<=? ORDER BY date DESC', from, date)
.map(r => readPool(l, r.date, env));
const rows = [...days, ...legacyRows];
return {
from,
date,
rows,
current,
rolling: status(l, env),
summary: {
totalMg: current.totalMg,
totalAmount: current.totalAmount,
usedMg: current.usedMg,
remainingMg: current.remainingMg,
remainingCost: current.remainingCost,
shortageMg: current.shortageMg,
pendingCount: current.status === 'pending' ? 1 : 0,
purchaseCount: current.todayPurchases.count,
},
settlement: {
legacyReadOnly: true,
settlementDue: 0,
knownSettlementDue: 0,
pendingCount: current.status === 'pending' ? 1 : 0,
pools: [],
},
};
}
function syncReturnSources(l, origin) {
for (const r of l.rows('SELECT * FROM material_rolling_returns WHERE origin_pool_id=?', origin)) {
if (require('./order-after-sales').read(l, r.order_id)) continue;
const o = l.rawOrder(r.order_id),
line = o.lines[r.line_index],
amount = line.costParts?.material,
allocations = line.materialPool?.allocations;
const pending =
amount === null &&
line.materialPool?.status === 'pending' &&
line.materialPool?.materialSources?.some(s => s.kind === 'public' && s.amount === null);
if (!pending && (!Number.isSafeInteger(amount) || !allocations || sum(allocations, 'amount') !== amount))
throw new Error('复核后的退货回料来源无法核对');
l.run(
'UPDATE material_rolling_returns SET amount=?,allocations=? WHERE id=?',
amount,
JSON.stringify(allocations),
r.id,
);
Allocation.saveReturn(l, 'order', r.id, line.materialPool?.materialSources);
}
}
function repriceLegacyReturns(l, actor, env) {
const c = config(l),
origins = l
.rows(
"SELECT DISTINCT origin_pool_id FROM material_rolling_returns WHERE origin_pool_id<>'' AND origin_pool_id<?",
c.cutover,
)
.map(r => r.origin_pool_id);
for (const origin of origins) {
const pool = legacy().readPool(l, origin, env, { internal: true });
const candidates = pool.usages.filter(
u =>
u.active ||
l.one(
'SELECT id FROM material_rolling_returns WHERE order_id=? AND line_index=? AND origin_pool_id=?',
u.order_id,
u.line_index,
origin,
),
);
for (const u of allocations(pool, candidates, l)) {
if (require('./order-after-sales').read(l, u.order_id)) continue;
const order = l.rawOrder(u.order_id),
line = order.lines[u.line_index],
old = line.costParts?.material,
oldAlloc = line.materialPool?.allocations;
applyLine(line, u, pool);
const delta = (u.amount ?? 0) - (old ?? 0);
l.run(
'UPDATE material_pool_usages SET amount=?,owner_amount=?,assistant_amount=?,revision=revision+1,updated=? WHERE id=?',
u.amount,
u.owner_amount,
u.assistant_amount,
env.now(),
u.id,
);
Amounts.save(l, u.id, u);
if (u.assistant2_amount !== undefined)
l.run(
'INSERT INTO material_usage_parties VALUES (?,?) ON CONFLICT(usage_id) DO UPDATE SET assistant2_amount=excluded.assistant2_amount',
u.id,
u.assistant2_amount,
);
else l.run('DELETE FROM material_usage_parties WHERE usage_id=?', u.id);
l.run('UPDATE orders SET lines=? WHERE id=?', JSON.stringify(order.lines), order.id);
Allocation.saveUsage(l, u.id, u.materialSources);
if (delta || JSON.stringify(oldAlloc) !== JSON.stringify(line.materialPool.allocations)) {
if (delta) {
l.journal(order.id, order.delivered_date || order.date, '历史复核金料成本调整', 0, delta, 0);
if (order.status === 'returned')
l.journal(order.id, order.returned_date, '历史复核退货成本冲回', 0, -delta, 0);
}
l.touch(order.id);
l.dirty(order.date);
l.audit(order.id, '历史复核退货来源重算', actor, { origin, goodsDelta: delta });
}
}
syncReturnSources(l, origin);
}
}
function rebuild(
l,
actor,
env,
{
fromDate = null,
skipJournalOrder = null,
preservePriceLockIds = [],
repriceExtraPriceLockIds = [],
ensureDates = [],
} = {},
) {
return withHistorical(l, () => {
const previous = l.rollingRebuilding;
l.rollingRebuilding = true;
try {
const c = config(l);
if (!c?.enabled) return;
if (!fromDate || fromDate <= c.cutover) {
repriceLegacyReturns(l, actor, env);
const opening = legacyOpening(l, c.cutover, env);
l.run('UPDATE material_rolling_days SET opening=? WHERE date=?', JSON.stringify(opening), c.cutover);
for (const p of opening.pools)
l.run(
'INSERT INTO material_rolling_legacy VALUES (?,?) ON CONFLICT(pool_id) DO UPDATE SET snapshot=excluded.snapshot',
p.id,
JSON.stringify(p),
);
}
for (const date of [...new Set(ensureDates)].sort())
if (date >= c.cutover) {
const existed = l.one('SELECT date FROM material_rolling_days WHERE date=?', date);
ensureDay(l, date, env);
if (!existed && date < env.today()) l.run('UPDATE material_rolling_days SET frozen=1 WHERE date=?', date);
}
const days = l.rows('SELECT date,frozen FROM material_rolling_days ORDER BY date');
for (let i = 0; i < days.length; i++) {
const d = days[i];
if (fromDate && d.date < fromDate) continue;
if (i) {
const prev = readPool(l, days[i - 1].date, env, {
internal: true,
live: !fromDate || days[i - 1].date >= fromDate,
});
l.run(
'UPDATE material_rolling_days SET opening=? WHERE date=?',
JSON.stringify({
mg: prev.remainingMg,
amount: prev.remainingCost,
allocations: prev.remainingAllocations,
pending: prev.status === 'pending',
...(prev.remainingMaterialGroups ? { materialGroups: prev.remainingMaterialGroups } : {}),
}),
d.date,
);
}
reconcile(l, d.date, actor, env, { skipJournalOrder, preservePriceLockIds, repriceExtraPriceLockIds });
syncReturnSources(l, d.date);
}
} finally {
l.rollingRebuilding = previous;
}
});
}
// 调用方必须先取得历史复核权限;局部重建本身不能绕过冻结检查。
function rebuildFrom(l, date, actor, env, options = {}) {
assertDate(l, date, env);
return rebuild(l, actor, env, { ...options, fromDate: date });
}
module.exports = {
initialize,
config,
enabled,
isDay,
withHistorical,
assertDate,
dependency,
previewEnable,
enable,
status,
legacySnapshot,
readPool,
prepareLines,
reconcile,
recordReturns,
release,
list,
rebuild,
rebuildFrom,
registerSource,
returnsFor,
};