Files
weiguang-jewelry-ledger/新账系统/domains/price-locks/price-lock-pool-approvals.js
T
黄健铭andClaude Opus 5.5 9ec37196d4 目录重组:后端按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>
2026-12-04 13:01:19 -08:00

164 lines
6.8 KiB
JavaScript

'use strict';
// 审批依据保留原始来源,结果比较只保留业务值;没有池锁时沿用旧申请哈希。
const LockLines = require('./price-lock-lines');
const exists = (ledger, table) => !!ledger.one("SELECT name FROM sqlite_master WHERE type='table' AND name=?", table);
const allocations = value =>
(typeof value === 'string' ? JSON.parse(value) : (value ?? [])).map(({ payer, amount }) => ({ payer, amount }));
function rows(ledger, { poolId = null, priceLockId = null } = {}) {
if (!exists(ledger, 'price_lock_pool_reservations')) return { reservations: [], returns: [] };
const reservations = ledger.rows(
'SELECT * FROM price_lock_pool_reservations' +
(priceLockId ? ' WHERE price_lock_id=?' : poolId ? ' WHERE pool_id=?' : '') +
' ORDER BY rowid',
...(priceLockId ? [priceLockId] : poolId ? [poolId] : []),
);
const returns = exists(ledger, 'price_lock_pool_returns')
? ledger.rows(
'SELECT * FROM price_lock_pool_returns' +
(priceLockId ? ' WHERE price_lock_id=?' : poolId ? ' WHERE origin_pool_id=? OR date=?' : '') +
' ORDER BY rowid',
...(priceLockId ? [priceLockId] : poolId ? [poolId, poolId] : []),
)
: [];
return { reservations, returns };
}
function snapshot(ledger, query = {}) {
const state = rows(ledger, query);
if (!state.reservations.length && !state.returns.length) return {};
if (query.poolId) {
const ids = [...new Set([...state.reservations, ...state.returns].map(row => row.price_lock_id))];
state.locks = ids.map(id => ledger.one('SELECT * FROM price_locks WHERE id=?', id));
}
if (exists(ledger, 'material_usage_order')) {
const usageIds = new Set(state.reservations.map(row => row.id)),
orderUsageIds = new Set(
query.poolId
? ledger.rows('SELECT id FROM material_pool_usages WHERE pool_id=?', query.poolId).map(row => row.id)
: [],
);
state.usageOrder = ledger
.rows('SELECT * FROM material_usage_order ORDER BY sequence')
.filter(row =>
row.kind === 'priceLock'
? usageIds.has(row.source_id)
: row.kind === 'order' && orderUsageIds.has(row.source_id),
);
}
return { priceLockPool: state };
}
function effect(ledger, poolIds = null) {
const source = poolIds ? poolIds.map(poolId => rows(ledger, { poolId })) : [rows(ledger)];
const unique = values => [...new Map(values.map(row => [row.id, row])).values()];
const reservations = unique(source.flatMap(value => value.reservations)),
returns = unique(source.flatMap(value => value.returns));
if (!reservations.length && !returns.length) return {};
const stable = (key, value) =>
['id', 'revision', 'created', 'updated', 'actor', 'source_sequence', 'source_id'].includes(key) ? undefined : value;
return {
priceLockPool: {
reservations: reservations
.map(row => ({
priceLockId: row.price_lock_id,
lineIndex: row.line_index,
poolId: row.pool_id,
mg: row.mg,
amount: row.amount,
allocations: allocations(row.allocations),
snapshot: JSON.parse(JSON.stringify(JSON.parse(row.snapshot), stable)),
}))
.sort((a, b) => a.priceLockId.localeCompare(b.priceLockId) || a.lineIndex - b.lineIndex),
returns: returns
.map(row => ({
priceLockId: row.price_lock_id,
lineIndex: row.line_index,
date: row.date,
mg: row.mg,
amount: row.amount,
allocations: allocations(row.allocations),
originPoolId: row.origin_pool_id,
...(row.kind !== undefined ? { kind: row.kind } : {}),
...(row.same_day !== undefined ? { sameDay: row.same_day } : {}),
}))
.sort(
(a, b) =>
a.priceLockId.localeCompare(b.priceLockId) ||
a.lineIndex - b.lineIndex ||
String(a.kind ?? '').localeCompare(String(b.kind ?? '')) ||
a.date.localeCompare(b.date),
),
},
};
}
function finance(ledger) {
return ledger.scope(null, () => financeInternal(ledger), null);
}
function financeInternal(ledger) {
const state = rows(ledger),
result = new Map();
for (const reservation of state.reservations) {
const lock = ledger.one('SELECT * FROM price_locks WHERE id=?', reservation.price_lock_id);
if (!lock) continue;
const extra = reservation.line_index < 0,
index = extra ? -reservation.line_index - 1 : reservation.line_index,
delivery = extra ? null : LockLines.deliveryAt(lock, index),
order = lock.final_order_id ? ledger.rawOrder(lock.final_order_id) : null;
const original = order?.lines[index]?.materialAllocations?.filter(
part => part.source === (extra ? 'extra' : 'original'),
);
const row = {
lineIndex: reservation.line_index,
materialAmount: reservation.amount,
usedMaterialAmount: original?.length ? original.reduce((sum, part) => sum + part.amount, 0) : reservation.amount,
leftoverCost: delivery ? (delivery.leftover_cost ?? null) : 0,
allocations: allocations(reservation.allocations),
};
const previous = result.get(lock.id);
if (previous) {
previous.lines ??= [
{
lineIndex: previous.lineIndex,
materialAmount: previous.materialAmount,
usedMaterialAmount: previous.usedMaterialAmount,
leftoverCost: previous.leftoverCost,
allocations: previous.allocations,
},
];
previous.lines.push(row);
for (const key of ['materialAmount', 'usedMaterialAmount', 'leftoverCost'])
previous[key] = previous[key] === null || row[key] === null ? null : previous[key] + row[key];
previous.allocations = [...previous.allocations, ...row.allocations];
} else
result.set(lock.id, {
id: lock.id,
number: lock.number,
date: lock.date,
customer: lock.customer,
member: ledger.entityMember('price_lock', lock.id),
...row,
});
}
return result;
}
function changes(before, after) {
const fields = ['materialAmount', 'usedMaterialAmount', 'leftoverCost', 'allocations', 'lines'];
return [...before].flatMap(([id, previous]) => {
const next = after.get(id);
if (!next || fields.every(key => JSON.stringify(previous[key]) === JSON.stringify(next[key]))) return [];
return [
{
id,
number: previous.number,
date: previous.date,
customer: previous.customer,
member: previous.member,
before: Object.fromEntries(fields.map(key => [key, previous[key]])),
after: Object.fromEntries(fields.map(key => [key, next[key]])),
},
];
});
}
function visibleChanges(ledger, value, actor) {
return actor?.role === 'assistant' ? value.filter(row => ledger.canAccess('price_lock', row.id, actor)) : value;
}
module.exports = { snapshot, effect, finance, changes, visibleChanges };