目录重组:后端按core/domains分领域存放(仅移动与更新引用)

- 50个后端模块用git mv移入core/与domains/<领域>/,入口server.js、launch.js、restore.js及server/原位不动
- 所有require路径由脚本按新旧位置统一换算(后端、server/、测试)
- 新增test/app-paths.test.js,锁定默认数据目录、public目录与飞书配置文件的绝对位置
- 维护与部署.md补充目录说明并更新模块路径

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
黄健铭andClaude Opus 5.5 committed 2026-12-04 13:01:19 -08:00
1 parent 95c481c74a
commit 9ec37196d4
172 files changed
+458 -384

No files matched your search

@@ -0,0 +1,68 @@
'use strict';
// 旧三人列继续逐值保留;新增员工的分摊单独保存,避免借用其他员工的列。
const LEGACY = ['owner', 'assistant', 'assistant2'];
const isKey = value => LEGACY.includes(value) || (typeof value === 'string' && /^staff_[a-f0-9-]{36}$/.test(value));
function keys(...values) {
const result = new Set(LEGACY);
const visit = value => {
if (Array.isArray(value)) {
for (const row of value) visit(row);
return;
}
if (!value || typeof value !== 'object') return;
for (const [key, child] of Object.entries(value)) {
if (['payer', 'materialOwner', 'member'].includes(key) && isKey(child)) result.add(child);
if (key.endsWith('_amount') && isKey(key.slice(0, -7))) result.add(key.slice(0, -7));
if (child && typeof child === 'object') visit(child);
}
};
for (const value of values) visit(value);
return [...result];
}
function parts(row) {
return (
row.allocations ??
keys(row)
.map(payer => ({ payer, amount: row[payer + '_amount'] ?? 0 }))
.filter(part => part.amount > 0)
);
}
function fields(allocations, amount, { third = true } = {}) {
const members = keys(allocations),
result = Object.fromEntries(
members
.filter(payer => payer !== 'assistant2' || third)
.map(payer => [
payer + '_amount',
amount === null
? null
: allocations.filter(part => part.payer === payer).reduce((sum, part) => sum + part.amount, 0),
]),
);
if (members.some(payer => !LEGACY.includes(payer))) result.allocations = allocations;
return result;
}
function initialize(ledger) {
ledger.db.exec(
'CREATE TABLE IF NOT EXISTS material_usage_allocations(usage_id TEXT PRIMARY KEY REFERENCES material_pool_usages(id),allocations TEXT NOT NULL)',
);
}
function read(ledger, id) {
const row = ledger.one('SELECT allocations FROM material_usage_allocations WHERE usage_id=?', id);
if (!row) return {};
const allocations = JSON.parse(row.allocations);
return { allocations, ...fields(allocations, allocations.some(part => part.amount === null) ? null : 0) };
}
function save(ledger, id, row) {
const allocations = parts(row);
if (!allocations.some(part => !LEGACY.includes(part.payer))) {
ledger.run('DELETE FROM material_usage_allocations WHERE usage_id=?', id);
return;
}
ledger.run(
'INSERT INTO material_usage_allocations VALUES (?,?) ON CONFLICT(usage_id) DO UPDATE SET allocations=excluded.allocations',
id,
JSON.stringify(allocations),
);
}
module.exports = { LEGACY, isKey, keys, parts, fields, initialize, read, save };
@@ -0,0 +1,505 @@
'use strict';
// 个人回收料与公共料分别加权;实际克重批次和付款金额区间分别追溯。
const Calc = require('../../public/calculations');
const Amounts = require('./material-member-amounts');
const sum = (rows, key) => rows.reduce((n, row) => n + (row[key] ?? 0), 0);
const keyOf = value => (value.kind === 'personal_recovery' ? 'personal:' + value.member : 'public');
function initialize(l) {
l.db.exec(`
CREATE TABLE IF NOT EXISTS material_usage_sources(usage_id TEXT PRIMARY KEY REFERENCES material_pool_usages(id),sources TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS material_return_sources(return_kind TEXT NOT NULL,return_id TEXT NOT NULL,sources TEXT NOT NULL,PRIMARY KEY(return_kind,return_id));
CREATE TABLE IF NOT EXISTS material_public_substitutions(kind TEXT NOT NULL CHECK(kind IN ('order','priceLock')),source_id TEXT NOT NULL,purchase_id TEXT NOT NULL REFERENCES material_purchases(id),ranges TEXT NOT NULL,PRIMARY KEY(kind,source_id,purchase_id));
`);
}
// 按原耗用位置保存替代区间,短交时不会把已归还的尾料误替换到头部。
function mergeRanges(ranges, quantity = Infinity) {
const result = [];
for (const r of ranges
.map(r => ({ start: Math.max(0, r.start), end: Math.min(quantity, r.end) }))
.filter(r => r.end > r.start)
.sort((a, b) => a.start - b.start)) {
const last = result.at(-1);
if (last && r.start <= last.end) last.end = Math.max(last.end, r.end);
else result.push(r);
}
return result;
}
function publicSubstitutionRanges(l, kind, id) {
return mergeRanges(
l
.rows('SELECT ranges FROM material_public_substitutions WHERE kind=? AND source_id=? ORDER BY rowid', kind, id)
.flatMap(r => JSON.parse(r.ranges)),
);
}
function publicSubstitutionMg(l, kind, id, quantity = Infinity) {
return mergeRanges(publicSubstitutionRanges(l, kind, id), quantity).reduce((n, r) => n + r.end - r.start, 0);
}
function substitutePurchase(l, kind, id, purchaseId, sources) {
let position = 0;
const ranges = [];
for (const s of sources ?? []) {
let offset = 0;
for (const batch of s.batches ?? []) {
if (batch.purchaseId === purchaseId && batch.mg)
ranges.push({ start: position + offset, end: position + offset + batch.mg });
offset += batch.mg;
}
position += s.quantity;
}
if (ranges.length)
l.run(
'INSERT INTO material_public_substitutions VALUES (?,?,?,?) ON CONFLICT(kind,source_id,purchase_id) DO UPDATE SET ranges=excluded.ranges',
kind,
id,
purchaseId,
JSON.stringify(mergeRanges(ranges)),
);
return ranges.length > 0;
}
function usageSources(l, id) {
const r = l.one('SELECT sources FROM material_usage_sources WHERE usage_id=?', id);
return r ? JSON.parse(r.sources) : null;
}
function saveUsage(l, id, sources) {
if (!sources) {
l.run('DELETE FROM material_usage_sources WHERE usage_id=?', id);
return;
}
l.run(
'INSERT INTO material_usage_sources VALUES (?,?) ON CONFLICT(usage_id) DO UPDATE SET sources=excluded.sources',
id,
JSON.stringify(sources),
);
}
function returnSources(l, kind, id) {
const r = l.one('SELECT sources FROM material_return_sources WHERE return_kind=? AND return_id=?', kind, id);
return r ? JSON.parse(r.sources) : null;
}
function saveReturn(l, kind, id, sources) {
if (!sources) {
l.run('DELETE FROM material_return_sources WHERE return_kind=? AND return_id=?', kind, id);
return;
}
l.run(
'INSERT INTO material_return_sources VALUES (?,?,?) ON CONFLICT(return_kind,return_id) DO UPDATE SET sources=excluded.sources',
kind,
id,
JSON.stringify(sources),
);
}
function sourceParts(p) {
return p.allocations ?? [{ payer: p.payer, amount: p.amount }];
}
function amountRange(purchases, start, amount) {
let skip = start,
left = amount,
zeroPayer = null,
lastPayer = null;
const result = [];
for (const purchase of purchases)
for (const part of sourceParts(purchase)) {
lastPayer = part.payer;
if (skip >= part.amount) {
skip -= part.amount;
continue;
}
zeroPayer ??= part.payer;
const taken = Math.min(left, part.amount - skip);
if (taken) result.push({ ...part, amount: taken });
left -= taken;
skip = 0;
}
if (skip || left) throw new Error('料池付款来源金额不足');
if (!amount && !result.length)
result.push({ payer: zeroPayer ?? lastPayer ?? purchases[0]?.payer ?? 'owner', amount: 0 });
return result;
}
function quantityRange(purchases, start, mg) {
let skip = start,
left = mg;
const result = [];
for (const purchase of purchases) {
const batches = purchase.batches ?? [
{
purchaseId: purchase.purchaseId ?? purchase.id,
recoveryId: purchase.recovery_id ?? purchase.recoveryId,
mg: purchase.mg,
},
];
for (const batch of batches) {
if (skip >= batch.mg) {
skip -= batch.mg;
continue;
}
const taken = Math.min(left, batch.mg - skip);
if (taken) result.push({ ...batch, mg: taken });
left -= taken;
skip = 0;
}
}
if (left) throw new Error('料池实际批次克重不足');
return result;
}
function splitParts(parts, amount) {
let left = amount;
const taken = [],
rest = [];
for (const part of parts) {
const n = Math.min(left, part.amount);
if (n) taken.push({ ...part, amount: n });
if (part.amount > n) rest.push({ ...part, amount: part.amount - n });
left -= n;
}
if (left) throw new Error('料池成本分段金额不守恒');
if (!amount && !taken.length) taken.push({ payer: parts[0]?.payer ?? 'owner', amount: 0 });
return { taken, rest };
}
function splitBatches(parts, mg) {
let left = mg;
const taken = [],
rest = [];
for (const p of parts) {
const n = Math.min(left, p.mg);
if (n) taken.push({ ...p, mg: n });
if (p.mg > n) rest.push({ ...p, mg: p.mg - n });
left -= n;
}
if (left) throw new Error('料池批次分段克重不守恒');
return { taken, rest };
}
function asSources(snapshot) {
if (snapshot.materialSources) return snapshot.materialSources;
return [
{
kind: 'public',
member: null,
quantity: snapshot.quantity,
amount: snapshot.amount,
allocations: snapshot.allocations ?? [],
batches: [],
basisAmount: snapshot.basisAmount,
basisMg: snapshot.basisMg,
prefixMg: snapshot.prefixMg,
prefixAmount: snapshot.prefixAmount,
poolId: snapshot.poolId,
averageRate: snapshot.averageRate,
},
];
}
function splitSources(sources, mg) {
let left = mg;
const taken = [],
rest = [];
for (const s of sources) {
const n = Math.min(left, s.quantity);
left -= n;
if (!n) {
rest.push({ ...s });
continue;
}
if (n === s.quantity) {
taken.push({ ...s });
continue;
}
const amount =
s.amount === null ? null : Calc.poolMaterialAmount(s.basisAmount, s.basisMg, s.prefixMg + n) - s.prefixAmount;
const paid = amount === null ? { taken: [], rest: [] } : splitParts(s.allocations, amount),
batches = s.batches?.length ? splitBatches(s.batches, n) : { taken: [], rest: [] };
taken.push({ ...s, quantity: n, amount, allocations: paid.taken, batches: batches.taken });
rest.push({
...s,
quantity: s.quantity - n,
amount: s.amount === null ? null : s.amount - amount,
allocations: paid.rest,
batches: batches.rest,
prefixMg: s.prefixMg + n,
prefixAmount: amount === null ? null : s.prefixAmount + amount,
});
}
if (left) throw new Error('料池分段耗用超过原有克重');
return { taken, rest };
}
function groups(purchases) {
const map = new Map();
for (const p of purchases) {
const member = Amounts.isKey(p.materialOwner) ? p.materialOwner : null,
key = member ? 'personal:' + member : 'public';
if (!map.has(key)) map.set(key, { key, kind: member ? 'personal_recovery' : 'public', member, purchases: [] });
map.get(key).purchases.push(p);
}
if (!map.has('public')) map.set('public', { key: 'public', kind: 'public', member: null, purchases: [] });
return [...map.values()].map(g => {
const totalMg = sum(g.purchases, 'mg'),
totalAmount = g.purchases.some(p => p.amount === null) ? null : sum(g.purchases, 'amount');
return {
...g,
totalMg,
totalAmount,
averageRate: totalMg && totalAmount !== null ? Calc.poolMaterialAmount(totalAmount, totalMg, 1000) : null,
};
});
}
function enabled(pool) {
return pool.materialGroups?.some(g => g.kind === 'personal_recovery');
}
function segment(group, prefixMg, mg) {
const pending = group.totalAmount === null || !group.totalMg || prefixMg + mg > group.totalMg;
const prefixAmount = pending ? null : Calc.poolMaterialAmount(group.totalAmount, group.totalMg, prefixMg),
amount = pending ? null : Calc.poolMaterialAmount(group.totalAmount, group.totalMg, prefixMg + mg) - prefixAmount;
return {
kind: group.kind,
member: group.member,
quantity: mg,
amount,
allocations: amount === null ? [] : amountRange(group.purchases, prefixAmount, amount),
batches: pending ? [] : quantityRange(group.purchases, prefixMg, mg),
basisAmount: group.totalAmount,
basisMg: group.totalMg,
prefixMg,
prefixAmount,
averageRate: group.averageRate,
};
}
function plan(groups, used, member, mg) {
const result = [];
let left = mg;
const personal = groups.find(g => g.kind === 'personal_recovery' && g.member === member),
common = groups.find(g => g.kind === 'public');
if (personal) {
const prefix = used[personal.key] ?? 0,
n = Math.min(left, Math.max(0, personal.totalMg - prefix));
if (n) {
result.push({ group: personal, prefixMg: prefix, mg: n });
left -= n;
}
}
if (left) result.push({ group: common, prefixMg: used.public ?? 0, mg: left });
return result;
}
function paidAmounts(sources) {
const amount = sources.some(s => s.amount === null) ? null : sum(sources, 'amount'),
allocations = sources.flatMap(s => s.allocations);
return { amount, allocations, ...Amounts.fields(allocations, amount), zero_payer: allocations[0]?.payer ?? 'owner' };
}
function rowPlan(groups, used, row, quantity) {
const common = groups.find(g => g.kind === 'public'),
ranges = mergeRanges(
row.publicSubstitutionRanges ?? (row.publicSubstitutionMg ? [{ start: 0, end: row.publicSubstitutionMg }] : []),
quantity,
),
result = [];
let position = 0;
const normal = mg => {
if (!mg) return;
const steps = plan(groups, used, row.member, mg);
for (const step of steps) {
used[step.group.key] = (used[step.group.key] ?? 0) + step.mg;
result.push(step);
}
};
for (const range of ranges) {
normal(range.start - position);
result.push({ group: common, mg: range.end - range.start, substituted: true });
position = range.end;
}
normal(quantity - position);
return result;
}
function allocate(pool, rows) {
const poolGroups = pool.materialGroups ?? groups(pool.purchases),
used = {},
prefixes = [],
plans = rows.map(row => {
prefixes.push({ ...used });
return rowPlan(poolGroups, used, row, row.mg);
}),
hasSubstitutions = rows.some(r => r.publicSubstitutionRanges?.length || r.publicSubstitutionMg > 0);
// 先满足原有公共用量,再分配取消回收追加的公共替代量,不抢无关订单已经核算的料。
let replacementPrefix = used.public ?? 0;
const replacementStarts = [];
for (const steps of plans) {
replacementStarts.push(replacementPrefix);
for (const step of steps)
if (step.substituted) {
step.prefixMg = replacementPrefix;
replacementPrefix += step.mg;
}
}
const publicMissing =
!hasSubstitutions && (used.public ?? 0) > (poolGroups.find(g => g.kind === 'public')?.totalMg ?? 0);
const render = steps =>
steps.map(p => {
const s = segment(p.group, p.prefixMg, p.mg);
return {
...s,
poolId: pool.id,
...(p.group.kind === 'public' && publicMissing ? { amount: null, allocations: [] } : {}),
};
});
return rows.map((row, index) => {
const sources = render(plans[index]),
paid = paidAmounts(sources);
let lockSnapshot;
if (row.kind === 'priceLock') {
const fullPlan = rowPlan(poolGroups, { ...prefixes[index] }, row, row.reserved_mg);
let forcedPrefix = replacementStarts[index];
for (const step of fullPlan)
if (step.substituted) {
step.prefixMg = forcedPrefix;
forcedPrefix += step.mg;
}
let full = render(fullPlan);
if (full.some(s => s.amount === null) && paid.amount !== null && row.reserved_mg > row.mg) {
if (!row.publicSubstitutionRanges?.length && !row.publicSubstitutionMg) {
const old = asSources(row.snapshot),
oldTail = splitSources(old, row.mg).rest;
full = [...sources, ...oldTail];
} else full = [...sources, ...splitSources(full, row.mg).rest];
}
const fullPaid = paidAmounts(full);
lockSnapshot = {
poolId: pool.id,
date: pool.date,
quantity: row.reserved_mg,
amount: fullPaid.amount,
averageRate: fullPaid.amount === null ? null : Calc.poolMaterialAmount(fullPaid.amount, row.reserved_mg, 1000),
allocations: fullPaid.allocations,
materialSources: full,
status: fullPaid.amount === null ? 'pending' : 'allocated',
basisAmount: fullPaid.amount,
basisMg: row.reserved_mg,
prefixMg: 0,
prefixAmount: 0,
rolling: true,
};
}
return { ...row, ...paid, materialSources: sources, ...(lockSnapshot ? { lockSnapshot } : {}) };
});
}
function balances(pool, usages) {
return pool.materialGroups.map(g => {
const consumed = usages
.flatMap(
u =>
u.materialSources ?? [
{ kind: 'public', member: null, quantity: u.mg, amount: u.amount, allocations: Amounts.parts(u) },
],
)
.filter(s => keyOf(s) === g.key),
usedMg = sum(consumed, 'quantity'),
pending = g.totalAmount === null || usedMg > g.totalMg || consumed.some(s => s.amount === null),
consumedCost = pending ? null : sum(consumed, 'amount'),
remainingCost = pending ? null : g.totalAmount - consumedCost;
const allocations = pending ? [] : amountRange(g.purchases, consumedCost, remainingCost),
batches = pending ? [] : quantityRange(g.purchases, usedMg, Math.max(0, g.totalMg - usedMg));
return {
...g,
usedMg,
consumedCost,
remainingMg: Math.max(0, g.totalMg - usedMg),
remainingCost,
remainingAllocations: allocations,
remainingBatches: batches,
shortageMg: Math.max(0, usedMg - g.totalMg),
status: pending ? 'pending' : !usedMg ? 'unused' : usedMg === g.totalMg ? 'exhausted' : 'using',
byPayer: Object.fromEntries(
Amounts.keys(pool.purchases, usages).map(p => {
const purchased = sum(
g.purchases.flatMap(sourceParts).filter(a => a.payer === p),
'amount',
),
spent = pending
? null
: sum(
consumed.flatMap(s => s.allocations).filter(a => a.payer === p),
'amount',
);
return [p, { purchased, consumed: spent, remaining: pending ? null : purchased - spent }];
}),
),
};
});
}
function remainingGroups(pool, usages) {
return balances(pool, usages).map(g => ({
kind: g.kind,
member: g.member,
mg: g.remainingMg,
amount: g.remainingCost,
allocations: g.remainingAllocations,
batches: g.remainingBatches,
}));
}
function expandSource(row) {
if (!row.materialSources) return [row];
return row.materialSources.map((s, index) => ({
...row,
id: row.id + ':material:' + index,
mg: s.quantity,
amount: s.amount,
allocations: s.allocations,
batches: s.batches,
materialKind: s.kind,
materialOwner: s.kind === 'personal_recovery' ? s.member : null,
}));
}
function carrySources(opening, date) {
if (!opening.materialGroups) return null;
return opening.materialGroups
.filter(g => g.mg > 0)
.map(g => ({
id: 'carry:' + date + ':' + keyOf(g),
date,
mg: g.mg,
amount: g.amount,
allocations: g.allocations,
payer: g.allocations?.[0]?.payer ?? g.member ?? 'owner',
batches: g.batches,
materialKind: g.kind,
materialOwner: g.kind === 'personal_recovery' ? g.member : null,
created: date + 'T00:00:00.000Z',
note: g.kind === 'personal_recovery' ? '个人回收料结转' : '以前结转',
sourceKind: 'carry',
cashAmount: 0,
canEdit: false,
}));
}
function eligible(pool, member) {
const own = pool.personalPools?.[member],
common = pool.status === 'pending' ? null : pool,
personal = own?.status === 'pending' ? null : own,
mg = (common?.remainingMg ?? 0) + (personal?.remainingMg ?? 0),
amount = (common?.remainingCost ?? 0) + (personal?.remainingCost ?? 0);
return {
...pool,
eligibleMember: member,
eligibleRemainingMg: mg,
eligibleRemainingAmount: amount,
eligibleAverageRate: personal?.remainingMg ? personal.averageRate : (common?.averageRate ?? null),
eligibleStatus: mg ? 'ready' : 'pending',
};
}
module.exports = {
mergeRanges,
publicSubstitutionRanges,
publicSubstitutionMg,
substitutePurchase,
eligible,
initialize,
usageSources,
saveUsage,
returnSources,
saveReturn,
groups,
enabled,
allocate,
balances,
remainingGroups,
expandSource,
carrySources,
splitSources,
asSources,
paidAmounts,
keyOf,
};
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,246 @@
'use strict';
// 历史采购更正先试算回滚;只在麦麦复核同一依赖版本后重算历史链。
const { randomUUID } = require('node:crypto'),
Rolling = require('./rolling-material-pools');
const Material = () => require('./material-pools'),
LockApprovals = require('../price-locks/price-lock-pool-approvals');
const fields = ['goodsCost', 'profit', 'settlementDue', 'ownerCost', 'total', 'netReceived'];
function atomic(l, fn) {
l.db.exec('SAVEPOINT material_purchase_change_action');
try {
const result = fn();
l.db.exec('RELEASE material_purchase_change_action');
return result;
} catch (error) {
l.db.exec('ROLLBACK TO material_purchase_change_action');
l.db.exec('RELEASE material_purchase_change_action');
throw error;
}
}
function initialize(l) {
l.db.exec(`CREATE TABLE IF NOT EXISTS material_purchase_changes(
id TEXT PRIMARY KEY,purchase_id TEXT NOT NULL,purchase_revision INTEGER NOT NULL,action TEXT NOT NULL,payload TEXT NOT NULL,reason TEXT NOT NULL,snapshot_hash TEXT NOT NULL,preview TEXT NOT NULL,
status TEXT NOT NULL,requester_id TEXT NOT NULL,requester_name TEXT NOT NULL,requester_role TEXT NOT NULL,created TEXT NOT NULL,reviewer_id TEXT,reviewer_name TEXT,reviewed TEXT,note TEXT NOT NULL DEFAULT '');
CREATE UNIQUE INDEX IF NOT EXISTS ix_material_change_pending ON material_purchase_changes(purchase_id) WHERE status='pending';`);
}
function active(a, e) {
if (!a || !['owner', 'assistant'].includes(a.role)) e.fail('请登录后处理购料更正', 403);
}
function finance(l) {
return l.scope(
null,
() =>
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,
...Object.fromEntries(fields.map(k => [k, o[k]])),
},
];
}),
),
null,
);
}
function summary(before, after) {
const relatedOrders = [];
for (const [id, b] of before) {
const a = after.get(id);
if (JSON.stringify(b) !== JSON.stringify(a))
relatedOrders.push({
id,
number: b.number,
date: b.date,
member: b.member,
before: Object.fromEntries(fields.map(k => [k, b[k]])),
after: Object.fromEntries(fields.map(k => [k, a[k]])),
});
}
return {
relatedOrders,
affectedDates: [...new Set(relatedOrders.map(r => r.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),
},
};
}
function apply(l, id, action, payload, actor, env) {
return Rolling.withHistorical(l, () =>
l.scope(
null,
() => {
const result =
action === 'delete'
? Material().deletePurchase(l, id, payload, actor, env)
: Material().editPurchase(l, id, payload, actor, env);
Rolling.rebuild(l, actor, env);
return result;
},
null,
),
);
}
function preview(l, id, action, payload, actor, env) {
const compact = p =>
Object.fromEntries(['id', 'date', 'mg', 'amount', 'payer', 'note', 'revision'].map(k => [k, p[k]]));
const before = compact(Material().purchaseDetail(l, id, env).purchase),
old = finance(l),
oldLocks = LockApprovals.finance(l);
l.db.exec('SAVEPOINT material_change_preview');
try {
apply(l, id, action, payload, { ...actor, role: 'owner' }, env);
l.syncTeamFunds({ ...actor, role: 'owner' });
const after = action === 'delete' ? null : compact(Material().purchaseDetail(l, id, env).purchase);
const result = { before, after, ...summary(old, finance(l)) },
relatedPriceLocks = LockApprovals.changes(oldLocks, LockApprovals.finance(l));
if (relatedPriceLocks.length) {
result.relatedPriceLocks = relatedPriceLocks;
result.affectedDates = [...new Set([...result.affectedDates, ...relatedPriceLocks.map(r => r.date)])].sort();
result.summary.affectedPriceLockCount = relatedPriceLocks.length;
}
return result;
} finally {
l.db.exec('ROLLBACK TO material_change_preview');
l.db.exec('RELEASE material_change_preview');
}
}
function read(l, id, actor, env) {
active(actor, env);
const r = l.one('SELECT * FROM material_purchase_changes WHERE id=?', id);
if (!r || (actor.role !== 'owner' && r.requester_id !== actor.id)) env.fail('购料更正申请不存在或无权访问', 404);
return r;
}
function dto(l, r, actor) {
const { payload, preview: raw, snapshot_hash, ...rest } = r,
preview = JSON.parse(raw),
stale = r.status === 'pending' && Rolling.dependency(l) !== snapshot_hash;
if (actor.role !== 'owner') {
preview.relatedOrders = preview.relatedOrders.filter(o => l.canAccess('order', o.id, actor));
if (preview.relatedPriceLocks)
preview.relatedPriceLocks = LockApprovals.visibleChanges(l, preview.relatedPriceLocks, actor);
preview.summary = { affectedOrderCount: preview.summary.affectedOrderCount };
}
return { ...rest, stale, canApprove: actor.role === 'owner' && r.status === 'pending' && !stale, preview };
}
function detail(l, id, actor, env) {
return dto(l, read(l, id, actor, env), actor);
}
function list(l, query, actor, env) {
active(actor, env);
const status = query.status || 'pending';
if (!['all', 'pending', 'approved', 'rejected'].includes(status)) env.fail('更正申请状态无效');
const all = l
.rows('SELECT * FROM material_purchase_changes ORDER BY created DESC,rowid DESC')
.filter(r => actor.role === 'owner' || r.requester_id === actor.id);
return {
rows: all.filter(r => status === 'all' || r.status === status).map(r => dto(l, r, actor)),
counts: Object.fromEntries(
['pending', 'approved', 'rejected'].map(s => [s, all.filter(r => r.status === s).length]),
),
};
}
function request(l, id, input, actor, env) {
active(actor, env);
l.assertAccess('material_purchase', id, actor);
const purchase = Material().purchaseDetail(l, id, env).purchase;
if (!Rolling.enabled(l) || purchase.date === env.today()) env.fail('当天购料可直接修改,历史更正用于已结转日期');
if (purchase.recovery_id) env.fail('回收/置换关联购料不能独立更正', 409);
if (purchase.deleted_at) env.fail('采购已经删除', 409);
if (input.revision !== purchase.revision || !Number.isSafeInteger(input.revision))
env.fail('购料版本已有变动,请重新读取', 409);
if (!['edit', 'delete'].includes(input.action)) env.fail('购料更正动作无效');
if (input.verified !== true) env.fail('请核实更正内容后提交');
if (l.one("SELECT id FROM material_purchase_changes WHERE purchase_id=? AND status='pending'", id))
env.fail('这笔购料已有待复核申请', 409);
const reason = env.text(input.reason, '历史更正原因', 200),
payload = Object.fromEntries(
['revision', 'date', 'grams', 'total', 'payer', 'note']
.filter(k => Object.hasOwn(input, k))
.map(k => [k, input[k]]),
);
const snapshot = Rolling.dependency(l),
result = preview(l, id, input.action, payload, actor, env),
requestId = randomUUID();
l.run(
'INSERT INTO material_purchase_changes(id,purchase_id,purchase_revision,action,payload,reason,snapshot_hash,preview,status,requester_id,requester_name,requester_role,created) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)',
requestId,
id,
purchase.revision,
input.action,
JSON.stringify(payload),
reason,
snapshot,
JSON.stringify(result),
'pending',
actor.id,
actor.name,
actor.role,
env.now(),
);
l.audit('material-purchase-change:' + requestId, '申请历史购料更正', actor, {
purchase_id: id,
action: input.action,
reason,
});
return detail(l, requestId, actor, env);
}
function approve(l, id, input, actor, env) {
active(actor, env);
if (actor.role !== 'owner') env.fail('历史购料更正须由麦麦批准', 403);
const r = read(l, id, actor, env);
if (r.status !== 'pending') env.fail('申请已经处理', 409);
if (input.revision !== r.purchase_revision || Rolling.dependency(l) !== r.snapshot_hash)
env.fail('账目或料池已有变动,申请已过期,请重新提交', 409);
if (input.verified !== true) env.fail('请核实影响范围与金额后批准');
const payload = JSON.parse(r.payload),
now = preview(l, r.purchase_id, r.action, payload, actor, env);
if (JSON.stringify(now) !== r.preview) env.fail('更正试算结果已有变动,请重新提交', 409);
apply(l, r.purchase_id, r.action, payload, actor, env);
l.run(
"UPDATE material_purchase_changes SET status='approved',reviewer_id=?,reviewer_name=?,reviewed=?,note=? WHERE id=?",
actor.id,
actor.name,
env.now(),
env.text(input.note, '复核说明', 200, true),
id,
);
l.audit('material-purchase-change:' + id, '批准历史购料更正', actor, {
purchase_id: r.purchase_id,
preview: now,
notice: '原核对快照保留,受影响日期标记过期',
});
return detail(l, id, actor, env);
}
function reject(l, id, input, actor, env) {
active(actor, env);
if (actor.role !== 'owner') env.fail('历史购料更正须由麦麦处理', 403);
const r = read(l, id, actor, env);
if (r.status !== 'pending') env.fail('申请已经处理', 409);
const note = env.text(input.note, '驳回原因', 200);
l.run(
"UPDATE material_purchase_changes SET status='rejected',reviewer_id=?,reviewer_name=?,reviewed=?,note=? WHERE id=?",
actor.id,
actor.name,
env.now(),
note,
id,
);
l.audit('material-purchase-change:' + id, '驳回历史购料更正', actor, { note });
return detail(l, id, actor, env);
}
module.exports = {
initialize,
request: (l, ...args) => atomic(l, () => request(l, ...args)),
list,
detail,
approve: (l, ...args) => atomic(l, () => approve(l, ...args)),
reject: (l, ...args) => atomic(l, () => reject(l, ...args)),
};
File diff suppressed because it is too large. Load diff