目录重组:后端按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:
1 parent
95c481c74a
commit
9ec37196d4
172 files changed
+458
-384
No files matched your search
@@ -0,0 +1,688 @@
|
||||
'use strict';
|
||||
// 待交付锁价单的录入更正与录错作废。旧事件保留,作废标记只撤销有效记账,不模拟真实退款。
|
||||
const { randomUUID, createHash } = require('node:crypto');
|
||||
const PriceLocks = require('./price-locks'),
|
||||
LockLines = require('./price-lock-lines'),
|
||||
LockPools = require('./price-lock-pools'),
|
||||
MaterialPools = require('../materials/material-pools'),
|
||||
Rolling = require('../materials/rolling-material-pools'),
|
||||
LockApprovals = require('./price-lock-pool-approvals'),
|
||||
OrderCopy = require('../../public/order-copy');
|
||||
const CreditCardRates = require('../team/credit-card-rates');
|
||||
const clone = value => JSON.parse(JSON.stringify(value)),
|
||||
hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex'),
|
||||
yuan = value => (value == null ? '' : (value / 100).toFixed(2));
|
||||
function atomic(l, fn) {
|
||||
l.db.exec('SAVEPOINT price_lock_change_action');
|
||||
try {
|
||||
const value = fn();
|
||||
l.db.exec('RELEASE price_lock_change_action');
|
||||
return value;
|
||||
} catch (error) {
|
||||
l.db.exec('ROLLBACK TO price_lock_change_action;RELEASE price_lock_change_action');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
function initialize(l) {
|
||||
l.db.exec(`CREATE TABLE IF NOT EXISTS price_lock_changes(
|
||||
id TEXT PRIMARY KEY,price_lock_id TEXT NOT NULL REFERENCES price_locks(id),price_lock_revision INTEGER NOT NULL,action TEXT NOT NULL CHECK(action IN ('edit','cancel')),
|
||||
reason TEXT NOT NULL,payload TEXT NOT NULL,snapshot TEXT NOT NULL,snapshot_hash TEXT NOT NULL,preview TEXT NOT NULL,effect_hash TEXT NOT NULL,
|
||||
status TEXT NOT NULL CHECK(status IN ('pending','approved','rejected')),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_price_lock_change_pending ON price_lock_changes(price_lock_id) WHERE status='pending';
|
||||
CREATE INDEX IF NOT EXISTS ix_price_lock_change_status ON price_lock_changes(status,created);`);
|
||||
}
|
||||
function active(actor, env) {
|
||||
if (!actor || !['owner', 'assistant'].includes(actor.role)) env.fail('请使用麦麦或助理账号处理锁价单', 403);
|
||||
}
|
||||
function owner(actor, env) {
|
||||
active(actor, env);
|
||||
if (actor.role !== 'owner') env.fail('锁价修改或取消申请必须由麦麦审批', 403);
|
||||
}
|
||||
function pending(l, id) {
|
||||
return l.one("SELECT * FROM price_lock_changes WHERE price_lock_id=? AND status='pending'", id) || null;
|
||||
}
|
||||
function getLock(l, id, actor, env) {
|
||||
active(actor, env);
|
||||
l.assertAccess('price_lock', id, actor);
|
||||
return PriceLocks.detail(l, id, env);
|
||||
}
|
||||
function dates(lock, input = {}) {
|
||||
return [
|
||||
...new Set(
|
||||
[
|
||||
lock.date,
|
||||
input.date,
|
||||
...lock.material_events.map(row => row.date),
|
||||
...lock.lines.map(row => row.material_pool_id),
|
||||
...(input.lines ?? []).map(row => (row.material?.source === 'pool' ? row.material.poolId : null)),
|
||||
].filter(Boolean),
|
||||
),
|
||||
];
|
||||
}
|
||||
function inputs(l, lock, env) {
|
||||
const sale = OrderCopy.inputs({ lines: lock.lines.map(row => row.line), fee_items: [], discount: lock.discount }),
|
||||
payment = lock.cash_events.find(row => row.kind === 'receipt');
|
||||
return {
|
||||
date: lock.date,
|
||||
customer: lock.customer,
|
||||
salesperson: lock.salesperson,
|
||||
note: lock.note,
|
||||
discount: yuan(lock.discount),
|
||||
...(l.teamMode ? { member: lock.member } : {}),
|
||||
payment: {
|
||||
amount: yuan(lock.netReceived),
|
||||
account: payment?.account ?? '助理微信',
|
||||
...(payment?.card_fee_payer ? { credit_card_fee_payer: payment.card_fee_payer } : {}),
|
||||
verified: true,
|
||||
},
|
||||
lines: sale.lines.map((line, index) => {
|
||||
const row = lock.lines[index],
|
||||
fields = ['name', 'code', 'unit', 'quantity', 'goldPrice', 'laborRate', 'laborMode', 'pieces', 'charges'];
|
||||
const pool =
|
||||
row.material_source === 'pool'
|
||||
? MaterialPools.readPool(l, row.material_pool_id ?? lock.date, env, {
|
||||
internal: true,
|
||||
member: lock.member ?? l.entityMember('price_lock', lock.id),
|
||||
})
|
||||
: null;
|
||||
return {
|
||||
...Object.fromEntries(fields.filter(key => Object.hasOwn(line, key)).map(key => [key, line[key]])),
|
||||
lineId: row.id,
|
||||
material: pool
|
||||
? { source: 'pool', poolId: pool.id, revision: pool.revision }
|
||||
: { source: 'manual', rate: yuan(row.buy_rate), payer: row.buy_payer, verified: true },
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
function detail(l, id, actor, env) {
|
||||
const lock = getLock(l, id, actor, env),
|
||||
request = pending(l, id),
|
||||
eligible = lock.status === 'pending' && !lock.final_order_id && !request;
|
||||
return {
|
||||
eligible,
|
||||
revision: lock.revision,
|
||||
requiresApproval: actor.role === 'assistant' && dates(lock).some(date => date !== env.today()),
|
||||
reason:
|
||||
lock.status !== 'pending'
|
||||
? '只有待交付锁价单可以修改或取消'
|
||||
: request
|
||||
? '本单有待审批修改或取消申请,请先由麦麦复核'
|
||||
: '',
|
||||
inputs: inputs(l, lock, env),
|
||||
lock,
|
||||
changePending: request
|
||||
? {
|
||||
id: request.id,
|
||||
requestId: request.id,
|
||||
action: request.action,
|
||||
status: request.status,
|
||||
reason: request.reason,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
function guard(l, id, input, actor, env, { approvalId = null } = {}) {
|
||||
const lock = getLock(l, id, actor, env);
|
||||
if (lock.status !== 'pending' || lock.final_order_id) env.fail('只有待交付锁价单可以修改或取消', 409);
|
||||
const request = pending(l, id);
|
||||
if (request && request.id !== approvalId) env.fail('本单有待审批修改或取消申请,请先由麦麦复核', 409);
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) env.fail('锁价修改资料无效');
|
||||
if (input.revision !== lock.revision) env.fail('锁价单已更新,请刷新后再操作', 409);
|
||||
if (input.verified !== true) env.fail('请核实锁价单及本次更正的有效记账');
|
||||
env.text(input.reason, '修改或取消原因', 240);
|
||||
if (Object.hasOwn(input, 'member')) l.selectedMember(input, actor, l.entityMember('price_lock', id));
|
||||
if (actor.role === 'assistant' && dates(lock, input).some(date => date !== env.today()))
|
||||
env.fail('历史锁价单修改或取消须提交申请,由麦麦复核', 403);
|
||||
return lock;
|
||||
}
|
||||
function voidEvents(l, id, reason, env, ids = null) {
|
||||
const rows = l
|
||||
.rows('SELECT * FROM price_lock_events WHERE price_lock_id=? AND voided=0 ORDER BY rowid', id)
|
||||
.filter(row => !ids || ids.has(row.id));
|
||||
for (const row of rows)
|
||||
l.run('UPDATE price_lock_events SET voided=1,void_reason=?,voided_at=? WHERE id=?', reason, env.now(), row.id);
|
||||
for (const date of new Set(rows.map(row => row.date))) l.dirty(date);
|
||||
return rows;
|
||||
}
|
||||
function release(l, lock, actor, env) {
|
||||
const rows = LockPools.findAll(l, lock.id),
|
||||
states = rows.map(row => ({
|
||||
...row,
|
||||
sequence: l.one("SELECT sequence FROM material_usage_order WHERE kind='priceLock' AND source_id=?", row.id)
|
||||
?.sequence,
|
||||
substitutions: l.rows(
|
||||
"SELECT * FROM material_public_substitutions WHERE kind='priceLock' AND source_id=? ORDER BY rowid",
|
||||
row.id,
|
||||
),
|
||||
}));
|
||||
for (const row of rows)
|
||||
LockPools.releaseForOrderEdit(l, lock, actor, env, { lineIndex: row.line_index, preservePriceLockIds: [lock.id] });
|
||||
return states;
|
||||
}
|
||||
function restorePoolIdentity(l, oldLock, newLock, states) {
|
||||
for (const old of states) {
|
||||
const oldEntry = oldLock.lines[old.line_index],
|
||||
entry = newLock.lines.find(row => row.id === oldEntry.id);
|
||||
if (!entry) continue;
|
||||
const next = LockPools.find(l, newLock.id, entry.line_index);
|
||||
if (!next) continue;
|
||||
l.run("DELETE FROM material_usage_order WHERE kind='priceLock' AND source_id=?", next.id);
|
||||
l.run('UPDATE price_lock_pool_reservations SET id=?,created=? WHERE id=?', old.id, old.created, next.id);
|
||||
if (old.sequence)
|
||||
l.run("INSERT INTO material_usage_order(sequence,kind,source_id) VALUES (?,'priceLock',?)", old.sequence, old.id);
|
||||
else LockPools.sequence(l, 'priceLock', old.id);
|
||||
for (const source of old.substitutions)
|
||||
l.run(
|
||||
'INSERT INTO material_public_substitutions(kind,source_id,purchase_id,ranges) VALUES (?,?,?,?)',
|
||||
source.kind,
|
||||
old.id,
|
||||
source.purchase_id,
|
||||
source.ranges,
|
||||
);
|
||||
}
|
||||
}
|
||||
function rebuild(l, affected, actor, env) {
|
||||
const ds = [...new Set(affected.filter(Boolean))].sort();
|
||||
if (!ds.length) return;
|
||||
if (Rolling.enabled(l)) Rolling.rebuildFrom(l, ds[0], actor, env, { ensureDates: ds });
|
||||
else for (const date of ds) MaterialPools.reconcile(l, date, date, actor, env);
|
||||
}
|
||||
function sameEvent(before, after, oldLock, newLock) {
|
||||
const keys = ['date', 'kind', 'amount', 'account', 'payer', 'source', 'quantity', 'rate', 'card_fee_payer'];
|
||||
if (!keys.every(key => before[key] === after[key])) return false;
|
||||
return (
|
||||
before.kind !== 'material' || oldLock.lines[before.line_index ?? 0]?.id === newLock.lines[after.line_index ?? 0]?.id
|
||||
);
|
||||
}
|
||||
function replaceEvents(l, lock, next, oldEvents, reason, env) {
|
||||
const newEvents = l.rows(
|
||||
'SELECT * FROM price_lock_events WHERE price_lock_id=? AND voided=0 ORDER BY rowid',
|
||||
next.id,
|
||||
),
|
||||
used = new Set();
|
||||
for (const event of newEvents) {
|
||||
const previous = oldEvents.find(row => !used.has(row.id) && sameEvent(row, event, lock, next));
|
||||
if (previous) {
|
||||
used.add(previous.id);
|
||||
l.run('DELETE FROM price_lock_events WHERE id=?', event.id);
|
||||
l.run(
|
||||
'UPDATE price_lock_events SET number=?,customer=?,product=?,line_index=? WHERE id=?',
|
||||
lock.number,
|
||||
next.customer,
|
||||
event.product,
|
||||
event.line_index,
|
||||
previous.id,
|
||||
);
|
||||
} else {
|
||||
// 只变付款人或客户资料时沿用原手续费费率和金额,避免历史规则被当前费率重算。
|
||||
const original =
|
||||
event.kind === 'receipt'
|
||||
? oldEvents.find(
|
||||
row =>
|
||||
row.kind === 'receipt' &&
|
||||
row.date === event.date &&
|
||||
row.amount === event.amount &&
|
||||
row.account === event.account,
|
||||
)
|
||||
: null;
|
||||
if (original && original.card_fee_amount !== null)
|
||||
l.run(
|
||||
'UPDATE price_lock_events SET card_fee_amount=?,card_fee_rate=?,card_fee_note=? WHERE id=?',
|
||||
original.card_fee_amount,
|
||||
original.card_fee_rate,
|
||||
original.card_fee_note,
|
||||
event.id,
|
||||
);
|
||||
l.run('UPDATE price_lock_events SET price_lock_id=?,number=? WHERE id=?', lock.id, lock.number, event.id);
|
||||
}
|
||||
}
|
||||
voidEvents(l, lock.id, reason, env, new Set(oldEvents.filter(row => !used.has(row.id)).map(row => row.id)));
|
||||
}
|
||||
function editAction(l, id, input, actor, env, options = {}) {
|
||||
const lock = guard(l, id, input, actor, env, options),
|
||||
reason = env.text(input.reason, '修改原因', 240),
|
||||
payload = clone(input);
|
||||
if (!Array.isArray(payload.lines) || !payload.lines.length || payload.lines.length > 60)
|
||||
env.fail('锁价单需要1~60件按克黄金商品');
|
||||
const seen = new Set(),
|
||||
lineIds = payload.lines.map(row => {
|
||||
if (!row || typeof row !== 'object' || Array.isArray(row)) env.fail('锁价商品资料无效');
|
||||
const lineId = row.lineId;
|
||||
if (lineId !== undefined) {
|
||||
if (typeof lineId !== 'string' || seen.has(lineId) || !lock.lines.some(item => item.id === lineId))
|
||||
env.fail('锁价商品身份已变化,请刷新后核对', 409);
|
||||
seen.add(lineId);
|
||||
}
|
||||
return lineId ?? randomUUID();
|
||||
});
|
||||
const poolInputs = payload.lines.filter(row => row.material?.source === 'pool');
|
||||
// 刷新令牌在解除原预留前校验;解除后内部重读均价,不拿自己的释放动作误判为并发。
|
||||
for (const row of poolInputs) {
|
||||
const pool = MaterialPools.readPool(l, env.day(row.material.poolId), env, {
|
||||
internal: true,
|
||||
member: lock.member ?? l.entityMember('price_lock', id),
|
||||
});
|
||||
if (row.material.revision !== pool.revision) env.fail('料池已有变动,请刷新料价后修改', 409);
|
||||
}
|
||||
const oldEvents = l.rows('SELECT * FROM price_lock_events WHERE price_lock_id=? AND voided=0 ORDER BY rowid', id),
|
||||
states = release(l, lock, actor, env);
|
||||
for (const row of poolInputs)
|
||||
row.material.revision = MaterialPools.readPool(l, row.material.poolId, env, {
|
||||
internal: true,
|
||||
member: lock.member ?? l.entityMember('price_lock', id),
|
||||
}).revision;
|
||||
const made = PriceLocks.create(l, { ...payload, ...(l.teamMode ? { member: lock.member } : {}) }, actor, env, {
|
||||
historical: true,
|
||||
lineIds,
|
||||
originalLock: lock,
|
||||
temporary: true,
|
||||
creditCardRatePermille: lock.credit_card_rate_permille,
|
||||
}),
|
||||
next = PriceLocks.detail(l, made.id, env),
|
||||
row = l.one('SELECT * FROM price_locks WHERE id=?', made.id);
|
||||
replaceEvents(l, lock, next, oldEvents, reason, env);
|
||||
l.run('UPDATE price_lock_pool_reservations SET price_lock_id=? WHERE price_lock_id=?', id, made.id);
|
||||
const fields = [
|
||||
'date',
|
||||
'customer',
|
||||
'salesperson',
|
||||
'note',
|
||||
'line',
|
||||
'lines',
|
||||
'locked_mg',
|
||||
'sell_rate',
|
||||
'buy_rate',
|
||||
'buy_payer',
|
||||
'material_amount',
|
||||
'estimated_total',
|
||||
'discount',
|
||||
];
|
||||
l.run(
|
||||
'UPDATE price_locks SET ' + fields.map(key => key + '=?').join(',') + ',revision=revision+1,updated=? WHERE id=?',
|
||||
...fields.map(key => row[key]),
|
||||
env.now(),
|
||||
id,
|
||||
);
|
||||
l.run("DELETE FROM team_fund_sources WHERE kind='price_lock' AND source_id=?", made.id);
|
||||
l.run('DELETE FROM audit WHERE entity=?', 'price-lock:' + made.id);
|
||||
l.run("DELETE FROM team_entities WHERE kind='price_lock' AND entity_id=?", made.id);
|
||||
l.run('DELETE FROM price_locks WHERE id=?', made.id);
|
||||
CreditCardRates.remove(l, 'price_lock', made.id);
|
||||
restorePoolIdentity(l, lock, { ...next, id }, states);
|
||||
rebuild(l, [...states.map(row => row.pool_id), ...poolInputs.map(row => row.material.poolId)], actor, env);
|
||||
l.dirty(lock.date);
|
||||
l.dirty(row.date);
|
||||
const after = PriceLocks.detail(l, id, env);
|
||||
l.audit('price-lock:' + id, '修改待交付锁价单', actor, {
|
||||
reason,
|
||||
before: lock,
|
||||
after,
|
||||
notice: '更正有效收款与购料记账,原单号及原事件保留;不代表实际退款或再次支付原料款',
|
||||
});
|
||||
return { id, price_lock_id: id, status: 'pending', revision: after.revision, lock: clone(after) };
|
||||
}
|
||||
function cancelAction(l, id, input, actor, env, options = {}) {
|
||||
const lock = guard(l, id, input, actor, env, options),
|
||||
reason = env.text(input.reason, '取消原因', 240),
|
||||
materialReturn = LockPools.cancelReservations(l, lock, actor, env);
|
||||
voidEvents(l, id, reason, env);
|
||||
l.run(
|
||||
"UPDATE price_locks SET status='cancelled',revision=revision+1,cancelled_at=?,cancelled_reason=?,updated=? WHERE id=?",
|
||||
env.now(),
|
||||
reason,
|
||||
env.now(),
|
||||
id,
|
||||
);
|
||||
l.dirty(lock.date);
|
||||
const after = PriceLocks.detail(l, id, env);
|
||||
l.audit('price-lock:' + id, '录错作废待交付锁价单', actor, {
|
||||
reason,
|
||||
before: lock,
|
||||
after,
|
||||
materialReturn,
|
||||
notice:
|
||||
'撤销本单有效收款、手填购料及信用卡手续费;同日料池释放预留,跨天按原克重原成本回实际生效日料池,保留历史耗用成本;无新增现金或实物流水',
|
||||
});
|
||||
return { id, price_lock_id: id, status: 'cancelled', revision: after.revision, lock: clone(after) };
|
||||
}
|
||||
function apply(l, id, input, actor, env, action, options = {}) {
|
||||
return atomic(l, () => {
|
||||
active(actor, env);
|
||||
const fn = () =>
|
||||
action === 'edit'
|
||||
? editAction(l, id, input, actor, env, options)
|
||||
: cancelAction(l, id, input, actor, env, options);
|
||||
return actor.role === 'owner' && input?.verified === true ? Rolling.withHistorical(l, fn) : fn();
|
||||
});
|
||||
}
|
||||
function edit(l, id, input, actor, env) {
|
||||
return apply(l, id, input, actor, env, 'edit');
|
||||
}
|
||||
function cancel(l, id, input, actor, env) {
|
||||
return apply(l, id, input, actor, env, 'cancel');
|
||||
}
|
||||
function snapshot(l, id) {
|
||||
return l.scope(
|
||||
null,
|
||||
() => ({
|
||||
lock: l.one('SELECT * FROM price_locks WHERE id=?', id),
|
||||
events: l.rows('SELECT * FROM price_lock_events WHERE price_lock_id=? ORDER BY rowid', id),
|
||||
member: l.entityMember('price_lock', id),
|
||||
...LockApprovals.snapshot(l, { priceLockId: id }),
|
||||
...(Rolling.enabled(l) ? { rolling: Rolling.dependency(l) } : {}),
|
||||
}),
|
||||
null,
|
||||
);
|
||||
}
|
||||
function orderFinance(l) {
|
||||
return new Map(
|
||||
l.rows('SELECT id FROM orders ORDER BY rowid').map(({ id }) => {
|
||||
const row = l.detail(id);
|
||||
return [
|
||||
id,
|
||||
{
|
||||
id,
|
||||
number: row.paper_number || row.number,
|
||||
date: row.date,
|
||||
member: row.member,
|
||||
goodsCost: row.goodsCost,
|
||||
profit: row.profit,
|
||||
total: row.total,
|
||||
netReceived: row.netReceived,
|
||||
settlementDue: row.settlementDue,
|
||||
},
|
||||
];
|
||||
}),
|
||||
);
|
||||
}
|
||||
function related(before, after) {
|
||||
const fields = ['goodsCost', 'profit', 'total', 'netReceived', 'settlementDue'];
|
||||
return [...before].flatMap(([id, b]) => {
|
||||
const a = after.get(id);
|
||||
return a && fields.some(key => a[key] !== b[key])
|
||||
? [
|
||||
{
|
||||
id,
|
||||
number: b.number,
|
||||
date: b.date,
|
||||
member: b.member,
|
||||
before: Object.fromEntries(fields.map(key => [key, b[key]])),
|
||||
after: Object.fromEntries(fields.map(key => [key, a[key]])),
|
||||
},
|
||||
]
|
||||
: [];
|
||||
});
|
||||
}
|
||||
function businessEffect(l, id) {
|
||||
return l.scope(
|
||||
null,
|
||||
() => {
|
||||
const lock = PriceLocks.detail(l, id, {
|
||||
fail: (message, status) => {
|
||||
const error = new Error(message);
|
||||
error.status = status;
|
||||
throw error;
|
||||
},
|
||||
today: () => '',
|
||||
});
|
||||
const clean = (key, value) =>
|
||||
[
|
||||
'id',
|
||||
'lineId',
|
||||
'revision',
|
||||
'created',
|
||||
'updated',
|
||||
'actor',
|
||||
'voided_at',
|
||||
'cancelled_at',
|
||||
'source_id',
|
||||
'source_sequence',
|
||||
'price_lock_id',
|
||||
'number',
|
||||
].includes(key)
|
||||
? undefined
|
||||
: value;
|
||||
return JSON.parse(
|
||||
JSON.stringify(
|
||||
{
|
||||
lock: {
|
||||
date: lock.date,
|
||||
status: lock.status,
|
||||
customer: lock.customer,
|
||||
salesperson: lock.salesperson,
|
||||
note: lock.note,
|
||||
lines: lock.lines.map(row => ({ ...row, delivery: undefined })),
|
||||
estimated_total: lock.estimated_total,
|
||||
discount: lock.discount,
|
||||
netReceived: lock.netReceived,
|
||||
cash_events: lock.cash_events,
|
||||
material_events: lock.material_events,
|
||||
credit_card_fee_total: lock.credit_card_fee_total,
|
||||
cancellationReturns: lock.cancellationReturns,
|
||||
},
|
||||
orders: [...orderFinance(l).values()].map(row => ({ ...row, lines: l.rawOrder(row.id).lines })),
|
||||
pools: l.rows('SELECT date,opening,snapshot FROM material_rolling_days ORDER BY date').map(row => {
|
||||
const pool = row.snapshot ? JSON.parse(row.snapshot) : null,
|
||||
fields = [
|
||||
'totalMg',
|
||||
'totalAmount',
|
||||
'usedMg',
|
||||
'remainingMg',
|
||||
'shortageMg',
|
||||
'consumedCost',
|
||||
'remainingCost',
|
||||
'averageRate',
|
||||
'status',
|
||||
'byPayer',
|
||||
'remainingAllocations',
|
||||
'remainingMaterialGroups',
|
||||
];
|
||||
return {
|
||||
date: row.date,
|
||||
opening: JSON.parse(row.opening),
|
||||
snapshot: pool ? Object.fromEntries(fields.map(key => [key, pool[key]])) : null,
|
||||
};
|
||||
}),
|
||||
},
|
||||
clean,
|
||||
),
|
||||
);
|
||||
},
|
||||
null,
|
||||
);
|
||||
}
|
||||
function preview(l, id, payload, actor, env, action, options = {}) {
|
||||
return l.scope(
|
||||
null,
|
||||
() => {
|
||||
const before = PriceLocks.detail(l, id, env),
|
||||
finance = orderFinance(l),
|
||||
lockFinance = LockApprovals.finance(l);
|
||||
l.db.exec('SAVEPOINT price_lock_change_preview');
|
||||
try {
|
||||
const result = apply(l, id, payload, { ...actor, role: 'owner' }, env, action, options),
|
||||
after = result.lock,
|
||||
fields = [
|
||||
'date',
|
||||
'customer',
|
||||
'salesperson',
|
||||
'note',
|
||||
'lines',
|
||||
'discount',
|
||||
'estimated_total',
|
||||
'netReceived',
|
||||
'material_amount',
|
||||
'status',
|
||||
];
|
||||
return {
|
||||
before,
|
||||
after,
|
||||
...(action === 'cancel' ? { materialReturnDate: env.today() } : {}),
|
||||
changes: fields
|
||||
.filter(key => JSON.stringify(before[key]) !== JSON.stringify(after[key]))
|
||||
.map(field => ({ field, before: before[field], after: after[field] })),
|
||||
relatedOrders: related(finance, orderFinance(l)),
|
||||
relatedPriceLocks: LockApprovals.changes(lockFinance, LockApprovals.finance(l)).filter(row => row.id !== id),
|
||||
effectHash: hash(businessEffect(l, id)),
|
||||
};
|
||||
} finally {
|
||||
l.db.exec('ROLLBACK TO price_lock_change_preview;RELEASE price_lock_change_preview');
|
||||
}
|
||||
},
|
||||
null,
|
||||
);
|
||||
}
|
||||
function stale(l, row) {
|
||||
return row.status === 'pending' && hash(snapshot(l, row.price_lock_id)) !== row.snapshot_hash;
|
||||
}
|
||||
function read(l, id, actor, env) {
|
||||
active(actor, env);
|
||||
const row = l.one('SELECT * FROM price_lock_changes WHERE id=?', id);
|
||||
if (!row) env.fail('锁价修改申请不存在', 404);
|
||||
l.assertAccess('price_lock', row.price_lock_id, actor);
|
||||
const stored = JSON.parse(row.preview),
|
||||
current =
|
||||
row.action === 'cancel' && row.status === 'pending' && !stale(l, row) && stored.materialReturnDate !== env.today()
|
||||
? preview(l, row.price_lock_id, JSON.parse(row.payload), actor, env, 'cancel', { approvalId: id })
|
||||
: stored,
|
||||
{ effectHash, ...value } = current,
|
||||
visible =
|
||||
actor.role === 'assistant'
|
||||
? value.relatedOrders.filter(item => l.canAccess('order', item.id, actor))
|
||||
: value.relatedOrders;
|
||||
return {
|
||||
...row,
|
||||
id,
|
||||
requestId: id,
|
||||
revision: row.price_lock_revision,
|
||||
payload: JSON.parse(row.payload),
|
||||
snapshot: undefined,
|
||||
preview: undefined,
|
||||
effect_hash: undefined,
|
||||
snapshot_hash: undefined,
|
||||
...value,
|
||||
relatedOrders: visible,
|
||||
relatedPriceLocks: LockApprovals.visibleChanges(l, value.relatedPriceLocks, actor),
|
||||
stale: stale(l, row),
|
||||
};
|
||||
}
|
||||
function request(l, id, input, actor, env) {
|
||||
return atomic(l, () => {
|
||||
active(actor, env);
|
||||
const lock = getLock(l, id, actor, env),
|
||||
action = env.pick(input.action, ['edit', 'cancel'], '锁价申请类型');
|
||||
if (lock.status !== 'pending' || lock.final_order_id) env.fail('只有待交付锁价单可以修改或取消', 409);
|
||||
if (pending(l, id)) env.fail('本单已有待审批申请,请先由麦麦复核', 409);
|
||||
if (input.revision !== lock.revision) env.fail('锁价单已更新,请刷新后再申请', 409);
|
||||
if (input.verified !== true) env.fail('请核实锁价修改资料');
|
||||
const reason = env.text(input.reason, '申请原因', 240);
|
||||
const source = snapshot(l, id),
|
||||
p = clone(input),
|
||||
result = preview(l, id, p, actor, env, action),
|
||||
{ effectHash, ...view } = result,
|
||||
requestId = randomUUID();
|
||||
l.run(
|
||||
"INSERT INTO price_lock_changes(id,price_lock_id,price_lock_revision,action,reason,payload,snapshot,snapshot_hash,preview,effect_hash,status,requester_id,requester_name,requester_role,created) VALUES (?,?,?,?,?,?,?,?,?,?,'pending',?,?,?,?)",
|
||||
requestId,
|
||||
id,
|
||||
lock.revision,
|
||||
action,
|
||||
reason,
|
||||
JSON.stringify(p),
|
||||
JSON.stringify(source),
|
||||
hash(source),
|
||||
JSON.stringify(view),
|
||||
effectHash,
|
||||
actor.id,
|
||||
actor.name,
|
||||
actor.role,
|
||||
env.now(),
|
||||
);
|
||||
l.audit('price-lock:' + id, '申请' + (action === 'cancel' ? '取消' : '修改') + '锁价单', actor, {
|
||||
requestId,
|
||||
reason,
|
||||
before: result.before,
|
||||
after: result.after,
|
||||
});
|
||||
return { id: requestId, requestId, price_lock_id: id, request: read(l, requestId, actor, env) };
|
||||
});
|
||||
}
|
||||
function approve(l, id, input, actor, env) {
|
||||
return atomic(l, () => {
|
||||
owner(actor, env);
|
||||
const row = l.one('SELECT * FROM price_lock_changes WHERE id=?', id);
|
||||
if (!row) env.fail('锁价修改申请不存在', 404);
|
||||
l.assertAccess('price_lock', row.price_lock_id, actor);
|
||||
if (row.status !== 'pending') env.fail('该申请已处理', 409);
|
||||
if (input.verified !== true || input.revision !== row.price_lock_revision)
|
||||
env.fail('请核实当前申请版本后审批', 409);
|
||||
if (stale(l, row)) env.fail('申请依据已过期,请驳回后重新申请', 409);
|
||||
const stored = JSON.parse(row.preview),
|
||||
refreshed =
|
||||
row.action === 'cancel' && stored.materialReturnDate !== env.today()
|
||||
? preview(l, row.price_lock_id, JSON.parse(row.payload), actor, env, 'cancel', { approvalId: id })
|
||||
: null,
|
||||
expectedHash = refreshed?.effectHash ?? row.effect_hash;
|
||||
const result = apply(l, row.price_lock_id, JSON.parse(row.payload), actor, env, row.action, { approvalId: id });
|
||||
if (hash(businessEffect(l, row.price_lock_id)) !== expectedHash)
|
||||
env.fail('本次执行与申请试算结果不一致,请重新申请', 409);
|
||||
if (refreshed) {
|
||||
const { effectHash, ...view } = refreshed;
|
||||
l.run('UPDATE price_lock_changes SET preview=?,effect_hash=? WHERE id=?', JSON.stringify(view), effectHash, id);
|
||||
}
|
||||
l.run(
|
||||
"UPDATE price_lock_changes SET status='approved',reviewer_id=?,reviewer_name=?,reviewed=?,note=? WHERE id=?",
|
||||
actor.id,
|
||||
actor.name,
|
||||
env.now(),
|
||||
env.text(input.note, '审批备注', 240, true),
|
||||
id,
|
||||
);
|
||||
l.audit('price-lock:' + row.price_lock_id, '同意' + (row.action === 'cancel' ? '取消' : '修改') + '锁价单', actor, {
|
||||
requestId: id,
|
||||
reason: row.reason,
|
||||
result,
|
||||
});
|
||||
return { id, requestId: id, price_lock_id: row.price_lock_id, request: read(l, id, actor, env), lock: result.lock };
|
||||
});
|
||||
}
|
||||
function reject(l, id, input, actor, env) {
|
||||
return atomic(l, () => {
|
||||
owner(actor, env);
|
||||
const row = l.one('SELECT * FROM price_lock_changes WHERE id=?', id);
|
||||
if (!row) env.fail('锁价修改申请不存在', 404);
|
||||
l.assertAccess('price_lock', row.price_lock_id, actor);
|
||||
if (row.status !== 'pending') env.fail('该申请已处理', 409);
|
||||
const note = env.text(input.note, '驳回说明', 240);
|
||||
l.run(
|
||||
"UPDATE price_lock_changes SET status='rejected',reviewer_id=?,reviewer_name=?,reviewed=?,note=? WHERE id=?",
|
||||
actor.id,
|
||||
actor.name,
|
||||
env.now(),
|
||||
note,
|
||||
id,
|
||||
);
|
||||
l.audit('price-lock:' + row.price_lock_id, '驳回锁价申请', actor, { requestId: id, note });
|
||||
return { id, requestId: id, request: read(l, id, actor, env) };
|
||||
});
|
||||
}
|
||||
function list(l, query, actor, env) {
|
||||
active(actor, env);
|
||||
const status = env.pick(query.status ?? 'pending', ['pending', 'approved', 'rejected', 'all'], '申请状态'),
|
||||
rows = l
|
||||
.visibleRows(
|
||||
'price_lock',
|
||||
l.rows(
|
||||
'SELECT id,price_lock_id FROM price_lock_changes' +
|
||||
(status === 'all' ? '' : ' WHERE status=?') +
|
||||
' ORDER BY created DESC,rowid DESC',
|
||||
...(status === 'all' ? [] : [status]),
|
||||
),
|
||||
'price_lock_id',
|
||||
)
|
||||
.map(row => read(l, row.id, actor, env));
|
||||
return { rows };
|
||||
}
|
||||
module.exports = { initialize, detail, edit, cancel, pending, request, read, list, approve, reject };
|
||||
@@ -0,0 +1,61 @@
|
||||
'use strict';
|
||||
// 单据级现金与折扣只记录一次;行级锁重、料费及交付使用稳定身份关联。
|
||||
const sum = (rows, key) => rows.reduce((n, row) => n + (row[key] ?? 0), 0);
|
||||
function lines(lock) {
|
||||
const stored = typeof lock.lines === 'string' ? JSON.parse(lock.lines) : lock.lines;
|
||||
if (Array.isArray(stored) && stored.length)
|
||||
return stored.map((row, index) => ({
|
||||
...row,
|
||||
id: row.id ?? (index ? lock.id + ':' + index : lock.id),
|
||||
line_index: index,
|
||||
}));
|
||||
return [
|
||||
{
|
||||
id: lock.id,
|
||||
line_index: 0,
|
||||
line: typeof lock.line === 'string' ? JSON.parse(lock.line) : lock.line,
|
||||
locked_mg: lock.locked_mg,
|
||||
sell_rate: lock.sell_rate,
|
||||
buy_rate: lock.buy_rate,
|
||||
buy_payer: lock.buy_payer,
|
||||
material_amount: lock.material_amount,
|
||||
},
|
||||
];
|
||||
}
|
||||
function deliveryLines(delivery) {
|
||||
const value = typeof delivery === 'string' ? JSON.parse(delivery) : delivery;
|
||||
return !value ? [] : Array.isArray(value.lines) ? value.lines : [value];
|
||||
}
|
||||
function deliveryAt(lock, index = 0) {
|
||||
return deliveryLines(lock.delivery)[index] ?? null;
|
||||
}
|
||||
function aggregateDelivery(delivery, rows) {
|
||||
const result = { ...delivery, lines: rows };
|
||||
for (const key of ['quantity', 'original_used_mg', 'extra_mg', 'leftover_mg']) result[key] = sum(rows, key);
|
||||
result.leftover_cost = rows.some(row => row.leftover_cost === null) ? null : sum(rows, 'leftover_cost');
|
||||
if (rows.length === 1) result.inventory = rows[0].inventory;
|
||||
else delete result.inventory;
|
||||
return result;
|
||||
}
|
||||
function save(ledger, lock, rows) {
|
||||
const first = rows[0],
|
||||
amount = rows.some(row => row.material_amount === null) ? null : sum(rows, 'material_amount');
|
||||
ledger.run(
|
||||
'UPDATE price_locks SET lines=?,line=?,locked_mg=?,sell_rate=?,buy_rate=COALESCE(?,buy_rate),buy_payer=?,material_amount=COALESCE(?,material_amount) WHERE id=?',
|
||||
JSON.stringify(rows),
|
||||
JSON.stringify(first.line),
|
||||
sum(rows, 'locked_mg'),
|
||||
first.sell_rate,
|
||||
first.buy_rate,
|
||||
first.buy_payer,
|
||||
amount,
|
||||
lock.id,
|
||||
);
|
||||
}
|
||||
function product(lock, index = null) {
|
||||
const rows = lines(lock);
|
||||
return index === null
|
||||
? rows.map(row => row.line.name).join('、')
|
||||
: (rows[index]?.line?.name ?? rows[0]?.line?.name ?? '');
|
||||
}
|
||||
module.exports = { lines, deliveryLines, deliveryAt, aggregateDelivery, save, product };
|
||||
@@ -0,0 +1,163 @@
|
||||
'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 };
|
||||
@@ -0,0 +1,882 @@
|
||||
'use strict';
|
||||
// 锁价预留只占用已有料池;不生成采购、现金、销售或实物流水。
|
||||
const { randomUUID } = require('node:crypto'),
|
||||
Calc = require('../../public/calculations'),
|
||||
Allocation = require('../materials/material-pool-allocation'),
|
||||
LockLines = require('./price-lock-lines');
|
||||
const Amounts = require('../materials/material-member-amounts');
|
||||
const sum = (rows, key) => rows.reduce((n, r) => n + (r[key] ?? 0), 0);
|
||||
function initialize(l) {
|
||||
l.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS price_lock_pool_reservations(id TEXT PRIMARY KEY,price_lock_id TEXT NOT NULL REFERENCES price_locks(id),line_index INTEGER NOT NULL DEFAULT 0,pool_id TEXT NOT NULL,mg INTEGER NOT NULL CHECK(mg>0),amount INTEGER,allocations TEXT NOT NULL DEFAULT '[]',snapshot TEXT NOT NULL DEFAULT '{}',revision INTEGER NOT NULL DEFAULT 1,created TEXT NOT NULL,updated TEXT NOT NULL,UNIQUE(price_lock_id,line_index));
|
||||
CREATE TABLE IF NOT EXISTS price_lock_pool_returns(id TEXT PRIMARY KEY,price_lock_id TEXT NOT NULL REFERENCES price_locks(id),line_index INTEGER NOT NULL DEFAULT 0,kind TEXT 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(price_lock_id,line_index,kind));
|
||||
CREATE TABLE IF NOT EXISTS material_usage_order(sequence INTEGER PRIMARY KEY AUTOINCREMENT,kind TEXT NOT NULL,source_id TEXT NOT NULL,UNIQUE(kind,source_id));
|
||||
INSERT INTO material_usage_order(kind,source_id) SELECT 'order',u.id FROM material_pool_usages u WHERE NOT EXISTS(SELECT 1 FROM material_usage_order s WHERE s.kind='order' AND s.source_id=u.id) ORDER BY u.created,u.rowid;
|
||||
`);
|
||||
// 去掉旧表整单唯一约束,行号0完整承接旧单和来源身份。
|
||||
for (const [table, definition, columns] of [
|
||||
[
|
||||
'price_lock_pool_reservations',
|
||||
`id TEXT PRIMARY KEY,price_lock_id TEXT NOT NULL REFERENCES price_locks(id),line_index INTEGER NOT NULL DEFAULT 0,pool_id TEXT NOT NULL,mg INTEGER NOT NULL CHECK(mg>0),amount INTEGER,allocations TEXT NOT NULL DEFAULT '[]',snapshot TEXT NOT NULL DEFAULT '{}',revision INTEGER NOT NULL DEFAULT 1,created TEXT NOT NULL,updated TEXT NOT NULL,UNIQUE(price_lock_id,line_index)`,
|
||||
'id,price_lock_id,pool_id,mg,amount,allocations,snapshot,revision,created,updated',
|
||||
],
|
||||
[
|
||||
'price_lock_pool_returns',
|
||||
`id TEXT PRIMARY KEY,price_lock_id TEXT NOT NULL REFERENCES price_locks(id),line_index INTEGER NOT NULL DEFAULT 0,kind TEXT 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(price_lock_id,line_index,kind)`,
|
||||
'id,price_lock_id,kind,date,mg,amount,allocations,origin_pool_id,same_day,actor,created',
|
||||
],
|
||||
])
|
||||
if (!l.rows('PRAGMA table_info(' + table + ')').some(row => row.name === 'line_index')) {
|
||||
l.db.exec('SAVEPOINT price_lock_multi_upgrade');
|
||||
try {
|
||||
l.db.exec('CREATE TABLE ' + table + '_multi(' + definition + ')');
|
||||
l.db.exec('INSERT INTO ' + table + '_multi(' + columns + ') SELECT ' + columns + ' FROM ' + table);
|
||||
l.db.exec('DROP TABLE ' + table);
|
||||
l.db.exec('ALTER TABLE ' + table + '_multi RENAME TO ' + table);
|
||||
l.db.exec('RELEASE price_lock_multi_upgrade');
|
||||
} catch (error) {
|
||||
l.db.exec('ROLLBACK TO price_lock_multi_upgrade');
|
||||
l.db.exec('RELEASE price_lock_multi_upgrade');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
function sequence(l, kind, id) {
|
||||
if (!l.one('SELECT sequence FROM material_usage_order WHERE kind=? AND source_id=?', kind, id))
|
||||
l.run('INSERT INTO material_usage_order(kind,source_id) VALUES (?,?)', kind, id);
|
||||
return l.one('SELECT sequence FROM material_usage_order WHERE kind=? AND source_id=?', kind, id).sequence;
|
||||
}
|
||||
function substitution(l, kind, id, quantity, reserved) {
|
||||
const ranges = Allocation.publicSubstitutionRanges(l, kind, id);
|
||||
return ranges.length
|
||||
? {
|
||||
publicSubstitutionRanges: ranges,
|
||||
publicSubstitutionMg: Allocation.publicSubstitutionMg(l, kind, id, quantity),
|
||||
...(reserved === undefined
|
||||
? {}
|
||||
: { reservedPublicSubstitutionMg: Allocation.publicSubstitutionMg(l, kind, id, reserved) }),
|
||||
}
|
||||
: {};
|
||||
}
|
||||
function decorate(l, rows) {
|
||||
return rows.map(r => ({
|
||||
...r,
|
||||
fifo_sequence:
|
||||
l.one("SELECT sequence FROM material_usage_order WHERE kind='order' AND source_id=?", r.id)?.sequence ??
|
||||
r.fifo_sequence,
|
||||
...substitution(l, 'order', r.id, r.mg),
|
||||
}));
|
||||
}
|
||||
function decode(r) {
|
||||
return r ? { ...r, allocations: JSON.parse(r.allocations), snapshot: JSON.parse(r.snapshot) } : null;
|
||||
}
|
||||
function find(l, id, lineIndex = 0) {
|
||||
return decode(
|
||||
l.one('SELECT * FROM price_lock_pool_reservations WHERE price_lock_id=? AND line_index=?', id, lineIndex),
|
||||
);
|
||||
}
|
||||
// 原锁预留用非负商品行号;交付补重用 -行号-1,独立保存日期、成本和来源。
|
||||
const extraIndex = index => -index - 1,
|
||||
itemIndex = index => (index < 0 ? -index - 1 : index);
|
||||
function findAll(l, id) {
|
||||
return l.rows('SELECT * FROM price_lock_pool_reservations WHERE price_lock_id=? ORDER BY line_index', id).map(decode);
|
||||
}
|
||||
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({ payer: part.payer, amount: n });
|
||||
if (part.amount > n) rest.push({ payer: part.payer, 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 split(snapshot, used) {
|
||||
if (snapshot.materialSources) {
|
||||
const parts = Allocation.splitSources(snapshot.materialSources, used),
|
||||
actual = Allocation.paidAmounts(parts.taken),
|
||||
leftover = Allocation.paidAmounts(parts.rest);
|
||||
return {
|
||||
usedMg: used,
|
||||
amount: actual.amount,
|
||||
leftoverMg: snapshot.quantity - used,
|
||||
leftoverCost: leftover.amount,
|
||||
allocations: actual.allocations,
|
||||
leftoverAllocations: leftover.allocations,
|
||||
materialSources: parts.taken,
|
||||
leftoverMaterialSources: parts.rest,
|
||||
};
|
||||
}
|
||||
if (snapshot.amount === null)
|
||||
return {
|
||||
usedMg: used,
|
||||
amount: null,
|
||||
leftoverMg: snapshot.quantity - used,
|
||||
leftoverCost: null,
|
||||
allocations: [],
|
||||
leftoverAllocations: [],
|
||||
};
|
||||
const amount =
|
||||
Calc.poolMaterialAmount(snapshot.basisAmount, snapshot.basisMg, snapshot.prefixMg + used) - snapshot.prefixAmount;
|
||||
const parts = splitParts(snapshot.allocations, amount);
|
||||
return {
|
||||
usedMg: used,
|
||||
amount,
|
||||
leftoverMg: snapshot.quantity - used,
|
||||
leftoverCost: snapshot.amount - amount,
|
||||
allocations: parts.taken,
|
||||
leftoverAllocations: parts.rest,
|
||||
};
|
||||
}
|
||||
function detail(l, id, env, lineIndex = 0) {
|
||||
const r = find(l, id, lineIndex);
|
||||
if (!r) return null;
|
||||
return { ...r.snapshot, revision: r.revision, frozen: r.pool_id !== env.today() };
|
||||
}
|
||||
function reservations(l, date) {
|
||||
return l
|
||||
.rows(
|
||||
`SELECT r.*,s.sequence AS fifo_sequence,p.number,p.customer,p.line,p.lines AS lock_lines,p.status,p.delivery,p.final_order_id,o.status AS order_status,o.returned_date FROM price_lock_pool_reservations r JOIN price_locks p ON p.id=r.price_lock_id LEFT JOIN material_usage_order s ON s.kind='priceLock' AND s.source_id=r.id LEFT JOIN orders o ON o.id=p.final_order_id WHERE r.pool_id=? ORDER BY r.created,r.rowid`,
|
||||
date,
|
||||
)
|
||||
.map(r => {
|
||||
const snapshot = JSON.parse(r.snapshot),
|
||||
delivery = LockLines.deliveryLines(r.delivery)[itemIndex(r.line_index)],
|
||||
entry = LockLines.lines({ ...r, id: r.price_lock_id, lines: r.lock_lines })[itemIndex(r.line_index)];
|
||||
let mg = r.mg;
|
||||
if (delivery?.date === date) mg = r.line_index < 0 ? delivery.extra_mg : delivery.original_used_mg;
|
||||
if (r.order_status === 'returned' && r.returned_date === date) mg = 0;
|
||||
const effective =
|
||||
snapshot.amount === undefined
|
||||
? { amount: null, allocations: [] }
|
||||
: mg === r.mg
|
||||
? {
|
||||
amount: r.amount,
|
||||
allocations: JSON.parse(r.allocations),
|
||||
...(snapshot.materialSources ? { materialSources: snapshot.materialSources } : {}),
|
||||
}
|
||||
: split(snapshot, mg);
|
||||
return {
|
||||
...r,
|
||||
kind: 'priceLock',
|
||||
member: l.entityMember('price_lock', r.price_lock_id),
|
||||
...(effective.materialSources ? { materialSources: effective.materialSources } : {}),
|
||||
date,
|
||||
price_lock_id: r.price_lock_id,
|
||||
order_id: r.final_order_id,
|
||||
reserved_mg: r.mg,
|
||||
mg,
|
||||
...substitution(l, 'priceLock', r.id, mg, r.mg),
|
||||
active: mg > 0 ? 1 : 0,
|
||||
amount: effective.amount,
|
||||
snapshot,
|
||||
allocations: effective.allocations,
|
||||
product: entry?.line.name ?? JSON.parse(r.line).name,
|
||||
...Object.fromEntries(
|
||||
Amounts.keys(effective.allocations).map(p => [
|
||||
p + '_amount',
|
||||
effective.amount === null
|
||||
? null
|
||||
: sum(
|
||||
effective.allocations.filter(a => a.payer === p),
|
||||
'amount',
|
||||
),
|
||||
]),
|
||||
),
|
||||
};
|
||||
});
|
||||
}
|
||||
function combined(l, date, rows) {
|
||||
return [...decorate(l, rows), ...reservations(l, date)].sort((a, b) =>
|
||||
a.created < b.created ? -1 : a.created > b.created ? 1 : a.fifo_sequence - b.fifo_sequence,
|
||||
);
|
||||
}
|
||||
function returns(l, date) {
|
||||
return l
|
||||
.rows(
|
||||
'SELECT r.*,p.number,p.customer,p.line,p.lines AS lock_lines FROM price_lock_pool_returns r JOIN price_locks p ON p.id=r.price_lock_id WHERE r.date=? ORDER BY r.created,r.rowid',
|
||||
date,
|
||||
)
|
||||
.map(r => ({
|
||||
...r,
|
||||
allocations: JSON.parse(r.allocations),
|
||||
...(Allocation.returnSources(l, 'lock', r.id)
|
||||
? { materialSources: Allocation.returnSources(l, 'lock', r.id) }
|
||||
: {}),
|
||||
product: LockLines.product({ ...r, id: r.price_lock_id, lines: r.lock_lines }, itemIndex(r.line_index)),
|
||||
sourceKind: 'return',
|
||||
cashAmount: 0,
|
||||
payer: JSON.parse(r.allocations)[0]?.payer ?? 'owner',
|
||||
sameDay: !!r.same_day,
|
||||
note: r.kind === 'cancel' ? '锁价作废回料(原成本)' : r.kind === 'leftover' ? '锁价余料回池' : '锁价退货回料',
|
||||
source_sequence:
|
||||
l.one("SELECT sequence FROM material_rolling_source_order WHERE kind='lock_return' AND source_id=?", r.id)
|
||||
?.sequence ?? 0,
|
||||
}));
|
||||
}
|
||||
function fundingParts(purchases, start, amount) {
|
||||
let skip = start,
|
||||
left = amount;
|
||||
const result = [];
|
||||
for (const p of purchases)
|
||||
for (const part of p.allocations ?? [{ payer: p.payer, amount: p.amount }]) {
|
||||
if (skip >= part.amount) {
|
||||
skip -= part.amount;
|
||||
continue;
|
||||
}
|
||||
const n = Math.min(left, part.amount - skip);
|
||||
if (n) result.push({ payer: part.payer, amount: n });
|
||||
left -= n;
|
||||
skip = 0;
|
||||
}
|
||||
if (left) throw new Error('锁价料池来源金额不足');
|
||||
return result;
|
||||
}
|
||||
function allocate(pool, rows, allocatePayers) {
|
||||
if (
|
||||
Allocation.enabled(pool) ||
|
||||
rows.some(row => row.publicSubstitutionMg > 0 || row.reservedPublicSubstitutionMg > 0)
|
||||
)
|
||||
return Allocation.allocate(
|
||||
{ ...pool, materialGroups: pool.materialGroups ?? Allocation.groups(pool.purchases) },
|
||||
rows,
|
||||
);
|
||||
const missing = pool.totalAmount === null || sum(rows, 'mg') > pool.totalMg;
|
||||
let mg = 0,
|
||||
previous = 0;
|
||||
return rows.map(row => {
|
||||
const prefixMg = mg,
|
||||
prefixAmount = previous;
|
||||
mg += row.mg;
|
||||
const cumulative = missing ? null : Calc.poolMaterialAmount(pool.totalAmount, pool.totalMg, mg),
|
||||
amount = cumulative === null ? null : cumulative - previous;
|
||||
const paid =
|
||||
amount === null
|
||||
? { owner_amount: null, assistant_amount: null, assistant2_amount: null }
|
||||
: allocatePayers(
|
||||
pool.purchases.filter(p => p.amount > 0),
|
||||
previous,
|
||||
amount,
|
||||
);
|
||||
let lockSnapshot;
|
||||
if (row.kind === 'priceLock') {
|
||||
const full = missing
|
||||
? null
|
||||
: Calc.poolMaterialAmount(pool.totalAmount, pool.totalMg, prefixMg + row.reserved_mg) - prefixAmount;
|
||||
let parts = [];
|
||||
if (full !== null) {
|
||||
if (prefixMg + row.reserved_mg <= pool.totalMg)
|
||||
parts = fundingParts(
|
||||
pool.purchases.filter(p => p.amount > 0),
|
||||
prefixAmount,
|
||||
full,
|
||||
);
|
||||
else {
|
||||
// 短交已经释放的尾料可以被前序订单使用;只要求本单实际耗用有真实资金来源。
|
||||
// 原预留与同日回料的尾段保持相同归属,二者净额为零,不能再次占用可用料。
|
||||
parts = fundingParts(
|
||||
pool.purchases.filter(p => p.amount > 0),
|
||||
prefixAmount,
|
||||
amount,
|
||||
);
|
||||
let tail = full - amount;
|
||||
const oldTail = row.snapshot.amount === null ? [] : split(row.snapshot, row.mg).leftoverAllocations;
|
||||
for (const p of oldTail) {
|
||||
const n = Math.min(tail, p.amount);
|
||||
if (n) parts.push({ payer: p.payer, amount: n });
|
||||
tail -= n;
|
||||
}
|
||||
if (tail)
|
||||
parts.push({
|
||||
payer: oldTail.at(-1)?.payer ?? row.snapshot.allocations?.at(-1)?.payer ?? paid.zero_payer ?? 'owner',
|
||||
amount: tail,
|
||||
});
|
||||
}
|
||||
if (full === 0 && !parts.length) parts.push({ payer: paid.zero_payer ?? 'owner', amount: 0 });
|
||||
}
|
||||
lockSnapshot = {
|
||||
poolId: pool.id,
|
||||
date: pool.date,
|
||||
quantity: row.reserved_mg,
|
||||
amount: full,
|
||||
averageRate: pool.averageRate,
|
||||
allocations: parts,
|
||||
status: full === null ? 'pending' : 'allocated',
|
||||
basisAmount: pool.totalAmount,
|
||||
basisMg: pool.totalMg,
|
||||
prefixMg,
|
||||
prefixAmount,
|
||||
rolling: !!pool.rolling,
|
||||
};
|
||||
}
|
||||
previous = cumulative ?? 0;
|
||||
const result = { ...row, amount, ...paid, ...(lockSnapshot ? { lockSnapshot } : {}) };
|
||||
for (const key of Object.keys(result))
|
||||
if (key.endsWith('_amount') && Amounts.isKey(key.slice(0, -7)) && !Object.hasOwn(paid, key)) delete result[key];
|
||||
if (!paid.allocations && row.kind !== 'priceLock') delete result.allocations;
|
||||
return result;
|
||||
});
|
||||
}
|
||||
function returnRow(l, lock, kind, date, mg, amount, allocations, origin, actor, env, materialSources = null) {
|
||||
if (!mg) return;
|
||||
const lineIndex = lock.line_index ?? 0,
|
||||
old = l.one(
|
||||
'SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? AND line_index=? AND kind=?',
|
||||
lock.id,
|
||||
lineIndex,
|
||||
kind,
|
||||
),
|
||||
id = old?.id ?? randomUUID();
|
||||
if (old)
|
||||
l.run(
|
||||
'UPDATE price_lock_pool_returns SET date=?,mg=?,amount=?,allocations=?,origin_pool_id=?,same_day=? WHERE id=?',
|
||||
date,
|
||||
mg,
|
||||
amount,
|
||||
JSON.stringify(allocations),
|
||||
origin,
|
||||
origin === date ? 1 : 0,
|
||||
id,
|
||||
);
|
||||
else {
|
||||
l.run(
|
||||
'INSERT INTO price_lock_pool_returns(id,price_lock_id,line_index,kind,date,mg,amount,allocations,origin_pool_id,same_day,actor,created) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)',
|
||||
id,
|
||||
lock.id,
|
||||
lineIndex,
|
||||
kind,
|
||||
date,
|
||||
mg,
|
||||
amount,
|
||||
JSON.stringify(allocations),
|
||||
origin,
|
||||
origin === date ? 1 : 0,
|
||||
actor.name,
|
||||
env.now(),
|
||||
);
|
||||
require('../materials/rolling-material-pools').registerSource(l, 'lock_return', id);
|
||||
}
|
||||
if (materialSources) Allocation.saveReturn(l, 'lock', id, materialSources);
|
||||
else l.run("DELETE FROM material_return_sources WHERE return_kind='lock' AND return_id=?", id);
|
||||
}
|
||||
function materialAllocations(snapshot, used) {
|
||||
const part = split(snapshot, used);
|
||||
if (part.materialSources)
|
||||
return part.materialSources.flatMap(s =>
|
||||
s.allocations.map(p => ({
|
||||
source: 'original',
|
||||
quantity: s.quantity,
|
||||
rate: s.averageRate ?? snapshot.averageRate,
|
||||
amount: p.amount,
|
||||
payer: p.payer,
|
||||
weighted: true,
|
||||
poolId: s.poolId ?? snapshot.poolId,
|
||||
materialKind: s.kind,
|
||||
materialOwner: s.member,
|
||||
})),
|
||||
);
|
||||
return part.amount === null
|
||||
? []
|
||||
: part.allocations.map(p => ({
|
||||
source: 'original',
|
||||
quantity: used,
|
||||
rate: snapshot.averageRate,
|
||||
amount: p.amount,
|
||||
payer: p.payer,
|
||||
weighted: true,
|
||||
poolId: snapshot.poolId,
|
||||
}));
|
||||
}
|
||||
function update(l, row, pool, actor, env, { skipJournalOrder = null } = {}) {
|
||||
const snapshot = row.lockSnapshot,
|
||||
old = row.snapshot,
|
||||
changed = JSON.stringify(snapshot) !== JSON.stringify(old);
|
||||
if (!changed) return;
|
||||
const revision = row.revision + 1;
|
||||
l.run(
|
||||
'UPDATE price_lock_pool_reservations SET amount=?,allocations=?,snapshot=?,revision=?,updated=? WHERE id=?',
|
||||
snapshot.amount,
|
||||
JSON.stringify(snapshot.allocations),
|
||||
JSON.stringify(snapshot),
|
||||
revision,
|
||||
env.now(),
|
||||
row.id,
|
||||
);
|
||||
l.run('UPDATE price_locks SET revision=revision+1,updated=? WHERE id=?', env.now(), row.price_lock_id);
|
||||
if (row.line_index < 0) {
|
||||
updateExtra(l, row, snapshot, actor, env, skipJournalOrder);
|
||||
return;
|
||||
}
|
||||
const lock = l.one('SELECT * FROM price_locks WHERE id=?', row.price_lock_id),
|
||||
lockedLines = LockLines.lines(lock),
|
||||
entry = lockedLines[row.line_index],
|
||||
lockedLine = entry.line;
|
||||
entry.material_amount = snapshot.amount;
|
||||
entry.buy_rate = snapshot.averageRate;
|
||||
entry.material_source = 'pool';
|
||||
lockedLine.costParts = { ...lockedLine.costParts, material: snapshot.amount };
|
||||
lockedLine.cost = Object.values(lockedLine.costParts).some(v => v === null)
|
||||
? null
|
||||
: sum(
|
||||
Object.values(lockedLine.costParts).map(amount => ({ amount })),
|
||||
'amount',
|
||||
);
|
||||
LockLines.save(l, lock, lockedLines);
|
||||
if (lock.status === 'cancelled') {
|
||||
const returned = l.one(
|
||||
"SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? AND line_index=? AND kind='cancel'",
|
||||
lock.id,
|
||||
row.line_index,
|
||||
);
|
||||
if (returned)
|
||||
returnRow(
|
||||
l,
|
||||
{ ...lock, line_index: row.line_index },
|
||||
'cancel',
|
||||
returned.date,
|
||||
row.mg,
|
||||
snapshot.amount,
|
||||
snapshot.allocations,
|
||||
snapshot.poolId,
|
||||
actor,
|
||||
env,
|
||||
snapshot.materialSources ?? null,
|
||||
);
|
||||
}
|
||||
if (lock.final_order_id) {
|
||||
const order = l.rawOrder(lock.final_order_id),
|
||||
line = order.lines[row.line_index],
|
||||
deliveries = LockLines.deliveryLines(lock.delivery),
|
||||
delivery = deliveries[row.line_index],
|
||||
part = split(snapshot, delivery.original_used_mg),
|
||||
before = line.costParts.material,
|
||||
lineLock = { ...lock, line_index: row.line_index };
|
||||
const extra = (line.materialAllocations ?? []).filter(a => a.source === 'extra');
|
||||
line.materialAllocations = [...materialAllocations(snapshot, delivery.original_used_mg), ...extra];
|
||||
line.priceLockPool = {
|
||||
...snapshot,
|
||||
quantity: delivery.original_used_mg,
|
||||
amount: part.amount,
|
||||
allocations: part.allocations,
|
||||
...(part.materialSources ? { materialSources: part.materialSources } : {}),
|
||||
priceLockId: lock.id,
|
||||
lineId: entry.id,
|
||||
line_index: row.line_index,
|
||||
};
|
||||
line.costParts.material =
|
||||
part.amount === null || line.priceLockExtraPool?.amount === null ? null : part.amount + sum(extra, 'amount');
|
||||
line.cost = Object.values(line.costParts).some(v => v === null)
|
||||
? null
|
||||
: sum(
|
||||
Object.values(line.costParts).map(amount => ({ amount })),
|
||||
'amount',
|
||||
);
|
||||
l.run('UPDATE orders SET lines=? WHERE id=?', JSON.stringify(order.lines), order.id);
|
||||
deliveries[row.line_index] = { ...delivery, leftover_cost: part.leftoverCost };
|
||||
l.run(
|
||||
'UPDATE price_locks SET delivery=? WHERE id=?',
|
||||
JSON.stringify(LockLines.aggregateDelivery(JSON.parse(lock.delivery), deliveries)),
|
||||
lock.id,
|
||||
);
|
||||
returnRow(
|
||||
l,
|
||||
lineLock,
|
||||
'leftover',
|
||||
delivery.date,
|
||||
part.leftoverMg,
|
||||
part.leftoverCost,
|
||||
part.leftoverAllocations,
|
||||
snapshot.poolId,
|
||||
actor,
|
||||
env,
|
||||
part.leftoverMaterialSources,
|
||||
);
|
||||
if (order.status === 'returned')
|
||||
returnRow(
|
||||
l,
|
||||
lineLock,
|
||||
'goods',
|
||||
order.returned_date,
|
||||
delivery.original_used_mg,
|
||||
part.amount,
|
||||
part.allocations,
|
||||
snapshot.poolId,
|
||||
actor,
|
||||
env,
|
||||
part.materialSources,
|
||||
);
|
||||
const delta = (line.costParts.material ?? 0) - (before ?? 0);
|
||||
if (order.id !== skipJournalOrder) {
|
||||
if (delta && order.status === 'delivered')
|
||||
l.journal(order.id, order.delivered_date, '锁价料池成本调整', 0, delta, 0);
|
||||
if (delta && order.status === 'returned') {
|
||||
l.journal(order.id, order.delivered_date, '锁价料池原耗用调整', 0, delta, 0);
|
||||
l.journal(order.id, order.returned_date, '锁价退货成本冲回调整', 0, -delta, 0);
|
||||
}
|
||||
l.touch(order.id);
|
||||
l.dirty(order.date);
|
||||
}
|
||||
}
|
||||
l.dirty(lock.date);
|
||||
l.audit('price-lock:' + lock.id, '锁价料池加权更新', actor, {
|
||||
poolId: pool.id,
|
||||
line_index: row.line_index,
|
||||
before: old,
|
||||
after: snapshot,
|
||||
});
|
||||
}
|
||||
function reserve(l, lock, pool, actor, env) {
|
||||
const available = Allocation.eligible(pool, l.entityMember('price_lock', lock.id) ?? l.memberFor(actor));
|
||||
if (available.eligibleRemainingMg < lock.locked_mg) env.fail('当日料池可用克重不足或成本待补,请先核实购料');
|
||||
const id = randomUUID(),
|
||||
created = env.now();
|
||||
l.run(
|
||||
'INSERT INTO price_lock_pool_reservations(id,price_lock_id,line_index,pool_id,mg,created,updated) VALUES (?,?,?,?,?,?,?)',
|
||||
id,
|
||||
lock.id,
|
||||
lock.line_index ?? 0,
|
||||
pool.id,
|
||||
lock.locked_mg,
|
||||
created,
|
||||
created,
|
||||
);
|
||||
sequence(l, 'priceLock', id);
|
||||
}
|
||||
function prepareDelivery(l, lock, date, used, actor, env) {
|
||||
const reservation = find(l, lock.id, lock.line_index ?? 0);
|
||||
if (!reservation) return null;
|
||||
const snapshot = reservation.snapshot;
|
||||
if (snapshot.amount === null || snapshot.amount === undefined)
|
||||
env.fail('锁价原料池成本待补,请先核实购料后交付', 409);
|
||||
const part = split(snapshot, used);
|
||||
return { ...part, snapshot };
|
||||
}
|
||||
function finishDelivery(l, lock, delivery, actor, env) {
|
||||
const r = find(l, lock.id, lock.line_index ?? 0);
|
||||
if (!r) return;
|
||||
const part = split(r.snapshot, delivery.original_used_mg);
|
||||
returnRow(
|
||||
l,
|
||||
lock,
|
||||
'leftover',
|
||||
delivery.date,
|
||||
part.leftoverMg,
|
||||
part.leftoverCost,
|
||||
part.leftoverAllocations,
|
||||
r.pool_id,
|
||||
actor,
|
||||
env,
|
||||
part.leftoverMaterialSources,
|
||||
);
|
||||
}
|
||||
function updateExtra(l, row, snapshot, actor, env, skipJournalOrder) {
|
||||
const lock = l.one('SELECT * FROM price_locks WHERE id=?', row.price_lock_id),
|
||||
index = itemIndex(row.line_index);
|
||||
if (lock.final_order_id) {
|
||||
const order = l.rawOrder(lock.final_order_id),
|
||||
line = order.lines[index],
|
||||
before = line.costParts.material;
|
||||
line.priceLockExtraPool = { ...snapshot, priceLockId: lock.id, line_index: index };
|
||||
line.materialAllocations = [
|
||||
...(line.materialAllocations ?? []).filter(a => a.source === 'original'),
|
||||
...materialAllocations(snapshot, row.mg).map(a => ({ ...a, source: 'extra' })),
|
||||
];
|
||||
line.costParts.material =
|
||||
snapshot.amount === null || line.priceLockPool?.amount === null ? null : sum(line.materialAllocations, 'amount');
|
||||
line.cost = Object.values(line.costParts).some(v => v === null)
|
||||
? null
|
||||
: Object.values(line.costParts).reduce((a, b) => a + b, 0);
|
||||
l.run('UPDATE orders SET lines=? WHERE id=?', JSON.stringify(order.lines), order.id);
|
||||
if (order.status === 'returned')
|
||||
returnRow(
|
||||
l,
|
||||
{ ...lock, line_index: row.line_index },
|
||||
'goods',
|
||||
order.returned_date,
|
||||
row.reserved_mg,
|
||||
snapshot.amount,
|
||||
snapshot.allocations,
|
||||
snapshot.poolId,
|
||||
actor,
|
||||
env,
|
||||
snapshot.materialSources,
|
||||
);
|
||||
const delta = (line.costParts.material ?? 0) - (before ?? 0);
|
||||
if (order.id !== skipJournalOrder) {
|
||||
if (delta) l.journal(order.id, order.delivered_date, '锁价补重料池成本调整', 0, delta, 0);
|
||||
if (delta && order.status === 'returned')
|
||||
l.journal(order.id, order.returned_date, '锁价补重退货成本冲回', 0, -delta, 0);
|
||||
l.touch(order.id);
|
||||
l.dirty(order.date);
|
||||
}
|
||||
}
|
||||
l.dirty(row.pool_id);
|
||||
l.audit('price-lock:' + lock.id, '交付补重料池加权更新', actor, {
|
||||
line_index: index,
|
||||
poolId: row.pool_id,
|
||||
before: row.snapshot,
|
||||
after: snapshot,
|
||||
});
|
||||
}
|
||||
function recordReturn(l, order, date, input, actor, env) {
|
||||
const lock = l.one('SELECT * FROM price_locks WHERE final_order_id=?', order.id),
|
||||
rows = lock ? findAll(l, lock.id) : [];
|
||||
if (!rows.length) return false;
|
||||
const indices = [...new Set(rows.map(r => itemIndex(r.line_index)))];
|
||||
for (const index of indices) {
|
||||
const line = order.lines[index],
|
||||
destination = input.returnPockets?.[index] ?? line.pocket;
|
||||
if (!env.selfPockets?.includes(destination)) env.fail('料池锁价黄金须退回自有货盘');
|
||||
const delivery = LockLines.deliveryAt(lock, index);
|
||||
for (const source of ['original', 'extra']) {
|
||||
const mg = source === 'original' ? delivery.original_used_mg : delivery.extra_mg;
|
||||
if (!mg) continue;
|
||||
const key = source === 'original' ? index : extraIndex(index),
|
||||
r = rows.find(r => r.line_index === key),
|
||||
lineLock = { ...lock, line_index: key };
|
||||
if (r) {
|
||||
const part = split(r.snapshot, mg);
|
||||
if (part.amount === null) env.fail('锁价料池成本待补,不能退货回料', 409);
|
||||
returnRow(
|
||||
l,
|
||||
lineLock,
|
||||
'goods',
|
||||
date,
|
||||
mg,
|
||||
part.amount,
|
||||
part.allocations,
|
||||
r.pool_id,
|
||||
actor,
|
||||
env,
|
||||
part.materialSources,
|
||||
);
|
||||
} else {
|
||||
const parts = (line.materialAllocations ?? []).filter(a => a.source === source);
|
||||
returnRow(
|
||||
l,
|
||||
{ ...lock, line_index: index },
|
||||
source === 'extra' ? 'extra' : 'manual_original',
|
||||
date,
|
||||
mg,
|
||||
sum(parts, 'amount'),
|
||||
parts.map(a => ({ payer: a.payer, amount: a.amount })),
|
||||
'',
|
||||
actor,
|
||||
env,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return indices;
|
||||
}
|
||||
function atomicEdit(l, fn) {
|
||||
l.db.exec('SAVEPOINT price_lock_pool_order_edit');
|
||||
try {
|
||||
const value = fn();
|
||||
l.db.exec('RELEASE price_lock_pool_order_edit');
|
||||
return value;
|
||||
} catch (error) {
|
||||
l.db.exec('ROLLBACK TO price_lock_pool_order_edit');
|
||||
l.db.exec('RELEASE price_lock_pool_order_edit');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
function editableLock(l, value, actor, env) {
|
||||
if (!actor || !['owner', 'assistant'].includes(actor.role)) env.fail('请使用麦麦或助理账号修改锁价料池', 403);
|
||||
const id = typeof value === 'string' ? value : value?.id;
|
||||
l.assertAccess('price_lock', id, actor);
|
||||
const lock = l.one('SELECT * FROM price_locks WHERE id=?', id);
|
||||
if (!lock) env.fail('锁价单不存在', 404);
|
||||
return lock;
|
||||
}
|
||||
function affectedDates(reservation, rows, extra = []) {
|
||||
return [
|
||||
...new Set(
|
||||
[reservation?.pool_id, ...rows.flatMap(row => [row.origin_pool_id, row.date]), ...extra].filter(Boolean),
|
||||
),
|
||||
].sort();
|
||||
}
|
||||
function assertEditDates(l, dates, actor, env) {
|
||||
const rolling = require('../materials/rolling-material-pools');
|
||||
if (!rolling.enabled(l)) return;
|
||||
if (actor.role !== 'owner' && dates.some(date => date !== env.today())) env.fail('历史锁价料池更正须由麦麦复核', 403);
|
||||
for (const date of dates) rolling.assertDate(l, date, env);
|
||||
}
|
||||
function rebuildAffected(l, dates, actor, env, options = {}) {
|
||||
if (!dates.length) return;
|
||||
const rolling = require('../materials/rolling-material-pools');
|
||||
// 共同料池重算需要读取所有成员来源,写入权限仍在外层按本单及日期检查。
|
||||
return l.scope(
|
||||
null,
|
||||
() => {
|
||||
if (rolling.enabled(l)) {
|
||||
for (const date of dates)
|
||||
if (!rolling.isDay(l, date))
|
||||
require('../materials/material-pools').reconcile(l, date, date, actor, env, options);
|
||||
return rolling.rebuildFrom(l, dates[0], actor, env, { ...options, ensureDates: dates });
|
||||
}
|
||||
for (const date of dates) require('../materials/material-pools').reconcile(l, date, date, actor, env, options);
|
||||
},
|
||||
null,
|
||||
);
|
||||
}
|
||||
// 调用方先保存独立手填的最终成本与商品行;此处只解除池关系,不造采购、现金或实物。
|
||||
function releaseForOrderEdit(l, value, actor, env, options = {}) {
|
||||
return atomicEdit(l, () => {
|
||||
const lock = editableLock(l, value, actor, env),
|
||||
lineIndex = options.lineIndex ?? 0,
|
||||
reservation = find(l, lock.id, lineIndex),
|
||||
rows = l.rows(
|
||||
'SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? AND line_index=? ORDER BY rowid',
|
||||
lock.id,
|
||||
lineIndex,
|
||||
),
|
||||
dates = affectedDates(reservation, rows);
|
||||
if (!reservation && !rows.length)
|
||||
return { released: false, reservation: null, returns: [], affectedDates: [], earliestDate: null };
|
||||
assertEditDates(l, dates, actor, env);
|
||||
for (const row of rows)
|
||||
l.run("DELETE FROM material_return_sources WHERE return_kind='lock' AND return_id=?", row.id);
|
||||
for (const row of rows)
|
||||
l.run("DELETE FROM material_rolling_source_order WHERE kind='lock_return' AND source_id=?", row.id);
|
||||
l.run('DELETE FROM price_lock_pool_returns WHERE price_lock_id=? AND line_index=?', lock.id, lineIndex);
|
||||
if (reservation) {
|
||||
l.run("DELETE FROM material_usage_order WHERE kind='priceLock' AND source_id=?", reservation.id);
|
||||
l.run("DELETE FROM material_public_substitutions WHERE kind='priceLock' AND source_id=?", reservation.id);
|
||||
l.run('DELETE FROM price_lock_pool_reservations WHERE id=?', reservation.id);
|
||||
}
|
||||
rebuildAffected(l, dates, actor, env, options);
|
||||
for (const date of dates) l.dirty(date);
|
||||
return { released: true, reservation, returns: rows, affectedDates: dates, earliestDate: dates[0] };
|
||||
});
|
||||
}
|
||||
// 跨天作废保留原日占用事实,以原成本在实际生效日回料;不倒改历史加权。
|
||||
function cancelReservations(l, value, actor, env) {
|
||||
return atomicEdit(l, () => {
|
||||
const lock = editableLock(l, value, actor, env),
|
||||
date = env.today(),
|
||||
rows = findAll(l, lock.id),
|
||||
cross = rows.filter(row => row.pool_id < date),
|
||||
same = rows.filter(row => row.pool_id === date);
|
||||
if (rows.some(row => row.pool_id > date)) env.fail('锁价料池日期晚于作废日期,请先核对', 409);
|
||||
for (const row of cross) {
|
||||
if (
|
||||
!Number.isSafeInteger(row.amount) ||
|
||||
row.amount < 0 ||
|
||||
row.snapshot.amount !== row.amount ||
|
||||
row.snapshot.quantity !== row.mg ||
|
||||
sum(row.allocations, 'amount') !== row.amount
|
||||
)
|
||||
env.fail('原锁价料费或付款来源待核实,不能按未知成本回池,请先核实原料费', 409);
|
||||
}
|
||||
// 先建立当日结转,冻结的是原日预留仍有效时的剩料,避免回料重复结转。
|
||||
const rolling = require('../materials/rolling-material-pools');
|
||||
if (cross.length && rolling.enabled(l)) rolling.reconcile(l, date, actor, env);
|
||||
for (const row of cross)
|
||||
returnRow(
|
||||
l,
|
||||
{ ...lock, line_index: row.line_index },
|
||||
'cancel',
|
||||
date,
|
||||
row.mg,
|
||||
row.amount,
|
||||
row.allocations,
|
||||
row.pool_id,
|
||||
actor,
|
||||
env,
|
||||
row.snapshot.materialSources ?? null,
|
||||
);
|
||||
for (const row of same)
|
||||
releaseForOrderEdit(l, lock, actor, env, { lineIndex: row.line_index, preservePriceLockIds: [lock.id] });
|
||||
if (cross.length) rebuildAffected(l, [date], actor, env, { preservePriceLockIds: [lock.id] });
|
||||
return {
|
||||
date,
|
||||
returned: cross.map(row => ({
|
||||
lineIndex: row.line_index,
|
||||
mg: row.mg,
|
||||
amount: row.amount,
|
||||
originPoolId: row.pool_id,
|
||||
allocations: row.allocations,
|
||||
})),
|
||||
releasedSameDay: same.map(row => row.line_index),
|
||||
};
|
||||
});
|
||||
}
|
||||
// 仅挪动交付日时原锁定分厘和付款归属冻结;余料沿原回料身份移日,不能成为第二笔采购。
|
||||
function moveDeliveryDate(l, value, nextDate, actor, env, { skipJournalOrder = null } = {}) {
|
||||
return atomicEdit(l, () => {
|
||||
const lock = editableLock(l, value, actor, env),
|
||||
reservations = findAll(l, lock.id);
|
||||
if (!reservations.length) return { moved: false, affectedDates: [], earliestDate: null };
|
||||
const delivery = lock.delivery ? JSON.parse(lock.delivery) : null;
|
||||
if (!delivery || !lock.final_order_id) env.fail('只有已交付锁价单可以调整交付日期');
|
||||
const date = env.day(nextDate, lock.date);
|
||||
if (date < lock.date) env.fail('交付日期不能早于锁价日期');
|
||||
if (date === delivery.date) return { moved: false, affectedDates: [], earliestDate: null };
|
||||
// 两个交付日都跨过原锁日时,原预留占用完全相同;只从余料实际变动的最早日重建。
|
||||
const rows = l.rows('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? ORDER BY rowid', lock.id),
|
||||
dates = [...new Set([delivery.date, date])].sort();
|
||||
assertEditDates(l, dates, actor, env);
|
||||
for (const row of reservations.filter(row => row.line_index < 0))
|
||||
l.run('UPDATE price_lock_pool_reservations SET pool_id=? WHERE id=?', date, row.id);
|
||||
const updated = LockLines.aggregateDelivery(
|
||||
{ ...delivery, date },
|
||||
LockLines.deliveryLines(delivery).map(row => ({ ...row, date })),
|
||||
);
|
||||
l.run('UPDATE price_locks SET delivery=?,updated=? WHERE id=?', JSON.stringify(updated), env.now(), lock.id);
|
||||
for (const row of rows.filter(row => row.kind === 'leftover'))
|
||||
l.run(
|
||||
'UPDATE price_lock_pool_returns SET date=?,same_day=? WHERE id=?',
|
||||
date,
|
||||
row.origin_pool_id === date ? 1 : 0,
|
||||
row.id,
|
||||
);
|
||||
rebuildAffected(l, dates, actor, env, {
|
||||
skipJournalOrder,
|
||||
preservePriceLockIds: [lock.id],
|
||||
repriceExtraPriceLockIds: [lock.id],
|
||||
});
|
||||
for (const row of findAll(l, lock.id).filter(row => row.line_index < 0))
|
||||
if (row.amount === null) env.fail('更改交付日期后补重料池不足或成本待补,请先核实料源', 409);
|
||||
const rolling = require('../materials/rolling-material-pools');
|
||||
if (rolling.enabled(l))
|
||||
for (const row of l.rows('SELECT date FROM material_rolling_days WHERE date>=? ORDER BY date', dates[0])) {
|
||||
const pool = rolling.readPool(l, row.date, env, { internal: true });
|
||||
if (pool.shortageMg > 0)
|
||||
env.fail(
|
||||
'调整交付日期后,' + row.date + '料池短料;原日余料已被其他订单使用,请先核实金料来源后再改交付日期',
|
||||
409,
|
||||
);
|
||||
}
|
||||
for (const date of dates) l.dirty(date);
|
||||
return { moved: true, affectedDates: dates, earliestDate: dates[0], delivery: updated };
|
||||
});
|
||||
}
|
||||
module.exports = {
|
||||
extraIndex,
|
||||
itemIndex,
|
||||
initialize,
|
||||
sequence,
|
||||
decorate,
|
||||
find,
|
||||
findAll,
|
||||
detail,
|
||||
reservations,
|
||||
combined,
|
||||
returns,
|
||||
allocate,
|
||||
update,
|
||||
reserve,
|
||||
split,
|
||||
materialAllocations,
|
||||
prepareDelivery,
|
||||
finishDelivery,
|
||||
recordReturn,
|
||||
releaseForOrderEdit,
|
||||
cancelReservations,
|
||||
moveDeliveryDate,
|
||||
};
|
||||
@@ -0,0 +1,977 @@
|
||||
'use strict';
|
||||
// 锁价采购和客户现金只追加;交付才生成销售、消耗成本和库存流水。
|
||||
const { randomUUID } = require('node:crypto');
|
||||
const Calc = require('../../public/calculations');
|
||||
const CreditCardFees = require('../../public/credit-card-fees');
|
||||
const CreditCardRates = require('../team/credit-card-rates');
|
||||
const TeamMembers = require('../team/team-members');
|
||||
const LockPools = require('./price-lock-pools'),
|
||||
MaterialPools = require('../materials/material-pools'),
|
||||
Rolling = require('../materials/rolling-material-pools'),
|
||||
LockLines = require('./price-lock-lines');
|
||||
const cardFeeNote = event =>
|
||||
event.card_fee_note ||
|
||||
(event.card_fee_rate !== null && event.card_fee_rate !== undefined
|
||||
? CreditCardFees.note(event.card_fee_rate)
|
||||
: '已记录信用卡手续费');
|
||||
const paymentAccount = (value, env, options) =>
|
||||
env.paymentAccount
|
||||
? env.paymentAccount(value, options)
|
||||
: env.pick(CreditCardFees.normalizeAccount(value), env.accounts, '实际收付款账户');
|
||||
const yuan = value => (value / 100).toFixed(2),
|
||||
grams = value => (value / 1000).toFixed(3);
|
||||
function initialize(ledger) {
|
||||
ledger.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS price_locks(
|
||||
id TEXT PRIMARY KEY,number TEXT UNIQUE NOT NULL,date TEXT NOT NULL,customer TEXT NOT NULL,salesperson TEXT NOT NULL,note TEXT NOT NULL,
|
||||
line TEXT NOT NULL,locked_mg INTEGER NOT NULL,sell_rate INTEGER NOT NULL,buy_rate INTEGER NOT NULL,buy_payer TEXT NOT NULL,
|
||||
material_amount INTEGER NOT NULL,estimated_total INTEGER NOT NULL,discount INTEGER NOT NULL,
|
||||
status TEXT NOT NULL CHECK(status IN ('pending','delivered','cancelled')),revision INTEGER NOT NULL,
|
||||
final_order_id TEXT UNIQUE REFERENCES orders(id),delivery TEXT,actor TEXT NOT NULL,created TEXT NOT NULL,updated TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS price_lock_events(
|
||||
id TEXT PRIMARY KEY,price_lock_id TEXT NOT NULL REFERENCES price_locks(id),date TEXT NOT NULL,
|
||||
kind TEXT NOT NULL CHECK(kind IN ('receipt','refund','material')),amount INTEGER NOT NULL CHECK(amount>=0),
|
||||
account TEXT,payer TEXT,source TEXT,quantity INTEGER,rate INTEGER,number TEXT NOT NULL,customer TEXT NOT NULL,product TEXT NOT NULL,
|
||||
actor TEXT NOT NULL,created TEXT NOT NULL);
|
||||
CREATE INDEX IF NOT EXISTS ix_price_lock_events_date ON price_lock_events(date,created,id);
|
||||
CREATE INDEX IF NOT EXISTS ix_price_locks_status ON price_locks(status,date);
|
||||
`);
|
||||
// 初始化迁移时关闭外键检查再重建父表;所有子表仍指向原表名,迁移后立即校验。
|
||||
const lockSchema = ledger.one("SELECT sql FROM sqlite_master WHERE type='table' AND name='price_locks'").sql;
|
||||
if (!lockSchema.includes("'cancelled'")) {
|
||||
const indexes = ledger.rows(
|
||||
"SELECT sql FROM sqlite_master WHERE tbl_name='price_locks' AND type IN ('index','trigger') AND sql IS NOT NULL",
|
||||
);
|
||||
ledger.db.exec('PRAGMA foreign_keys=OFF;SAVEPOINT price_lock_cancel_upgrade');
|
||||
try {
|
||||
ledger.db.exec(
|
||||
lockSchema
|
||||
.replace(/CREATE TABLE\s+(?:"price_locks"|price_locks)/i, 'CREATE TABLE price_locks_cancel_upgrade')
|
||||
.replace("'pending','delivered'", "'pending','delivered','cancelled'"),
|
||||
);
|
||||
ledger.db.exec('INSERT INTO price_locks_cancel_upgrade SELECT * FROM price_locks');
|
||||
ledger.db.exec('DROP TABLE price_locks;ALTER TABLE price_locks_cancel_upgrade RENAME TO price_locks');
|
||||
for (const row of indexes) ledger.db.exec(row.sql);
|
||||
if (ledger.rows('PRAGMA foreign_key_check').length) throw new Error('锁价状态升级后外键校验未通过');
|
||||
ledger.db.exec('RELEASE price_lock_cancel_upgrade');
|
||||
} catch (error) {
|
||||
ledger.db.exec('ROLLBACK TO price_lock_cancel_upgrade;RELEASE price_lock_cancel_upgrade');
|
||||
throw error;
|
||||
} finally {
|
||||
ledger.db.exec('PRAGMA foreign_keys=ON');
|
||||
}
|
||||
}
|
||||
const lockColumns = ledger.rows('PRAGMA table_info(price_locks)').map(row => row.name);
|
||||
for (const [name, definition] of Object.entries({ cancelled_at: 'TEXT', cancelled_reason: 'TEXT' }))
|
||||
if (!lockColumns.includes(name)) ledger.db.exec(`ALTER TABLE price_locks ADD COLUMN ${name} ${definition}`);
|
||||
if (!ledger.rows('PRAGMA table_info(price_locks)').some(row => row.name === 'lines'))
|
||||
ledger.db.exec('ALTER TABLE price_locks ADD COLUMN lines TEXT');
|
||||
const columns = ledger.rows('PRAGMA table_info(price_lock_events)').map(row => row.name);
|
||||
for (const [name, definition] of Object.entries({
|
||||
line_index: 'INTEGER',
|
||||
voided: 'INTEGER NOT NULL DEFAULT 0',
|
||||
void_reason: 'TEXT',
|
||||
voided_at: 'TEXT',
|
||||
card_fee_amount: 'INTEGER',
|
||||
card_fee_payer: 'TEXT',
|
||||
card_fee_expense_id: 'TEXT',
|
||||
card_fee_rate: 'INTEGER',
|
||||
card_fee_note: 'TEXT',
|
||||
}))
|
||||
if (!columns.includes(name)) ledger.db.exec(`ALTER TABLE price_lock_events ADD COLUMN ${name} ${definition}`);
|
||||
}
|
||||
function atomic(ledger, fn) {
|
||||
ledger.db.exec('SAVEPOINT price_lock_action');
|
||||
try {
|
||||
const result = fn();
|
||||
ledger.db.exec('RELEASE price_lock_action');
|
||||
return result;
|
||||
} catch (error) {
|
||||
ledger.db.exec('ROLLBACK TO price_lock_action');
|
||||
ledger.db.exec('RELEASE price_lock_action');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
function raw(ledger, id, env) {
|
||||
ledger.assertAccess('price_lock', id);
|
||||
const row = ledger.one('SELECT * FROM price_locks WHERE id=?', id);
|
||||
if (!row) env.fail('锁价单不存在', 404);
|
||||
return {
|
||||
...row,
|
||||
lines: LockLines.lines(row),
|
||||
...(ledger.teamMode ? { member: ledger.entityMember('price_lock', id) } : {}),
|
||||
kind: 'priceLock',
|
||||
line: JSON.parse(row.line),
|
||||
delivery: row.delivery ? JSON.parse(row.delivery) : null,
|
||||
};
|
||||
}
|
||||
function detail(ledger, id, env) {
|
||||
const row = raw(ledger, id, env),
|
||||
allEvents = ledger.rows('SELECT * FROM price_lock_events WHERE price_lock_id=? ORDER BY date,created,rowid', id),
|
||||
events = allEvents.filter(event => !event.voided);
|
||||
const cash_events = events.filter(event => event.kind !== 'material'),
|
||||
material_events = events.filter(event => event.kind === 'material');
|
||||
const received = cash_events.filter(event => event.kind === 'receipt').reduce((sum, event) => sum + event.amount, 0),
|
||||
refunded = cash_events.filter(event => event.kind === 'refund').reduce((sum, event) => sum + event.amount, 0);
|
||||
const credit_card_fees = events
|
||||
.filter(event => event.card_fee_amount !== null)
|
||||
.map(event => ({
|
||||
key: 'card_fee:' + event.id,
|
||||
system: 'credit_card',
|
||||
source_kind: 'price_lock',
|
||||
source_id: event.id,
|
||||
date: event.date,
|
||||
amount: event.card_fee_amount,
|
||||
payer: event.card_fee_payer,
|
||||
note: cardFeeNote(event),
|
||||
...(event.card_fee_rate !== null ? { rate_permille: event.card_fee_rate } : {}),
|
||||
...(event.card_fee_expense_id ? { expense_id: event.card_fee_expense_id } : {}),
|
||||
}));
|
||||
const reservations = LockPools.findAll(ledger, id).filter(r => r.line_index >= 0),
|
||||
byIndex = new Map(reservations.map(r => [r.line_index, r]));
|
||||
const lines = row.lines.map(item => {
|
||||
const reservation = byIndex.get(item.line_index);
|
||||
return {
|
||||
...item,
|
||||
material_source: reservation ? 'pool' : 'manual',
|
||||
...(reservation
|
||||
? {
|
||||
material_amount: reservation.snapshot.amount ?? null,
|
||||
buy_rate: reservation.snapshot.averageRate ?? null,
|
||||
material_pool_id: reservation.pool_id,
|
||||
materialPool: LockPools.detail(ledger, id, env, item.line_index),
|
||||
}
|
||||
: {}),
|
||||
delivery: LockLines.deliveryAt(row, item.line_index),
|
||||
};
|
||||
});
|
||||
const cancellationReturns = ledger
|
||||
.rows(
|
||||
"SELECT line_index,date,mg,amount,allocations,origin_pool_id FROM price_lock_pool_returns WHERE price_lock_id=? AND kind='cancel' ORDER BY line_index",
|
||||
id,
|
||||
)
|
||||
.map(value => ({ ...value, allocations: JSON.parse(value.allocations) }));
|
||||
const material_source =
|
||||
reservations.length === 0 ? 'manual' : reservations.length === lines.length ? 'pool' : 'mixed',
|
||||
material_amount = lines.some(line => line.material_amount === null)
|
||||
? null
|
||||
: lines.reduce((sum, line) => sum + line.material_amount, 0);
|
||||
return {
|
||||
...row,
|
||||
member: ledger.entityMember('price_lock', id),
|
||||
...(cancellationReturns.length ? { cancellationReturns } : {}),
|
||||
credit_card_rate_permille: CreditCardRates.read(ledger, 'price_lock', id),
|
||||
lines,
|
||||
line: lines[0].line,
|
||||
locked_mg: lines.reduce((sum, line) => sum + line.locked_mg, 0),
|
||||
buy_rate: lines[0].buy_rate,
|
||||
buy_payer: lines[0].buy_payer,
|
||||
material_source,
|
||||
material_amount,
|
||||
...(lines.length === 1 && lines[0].materialPool
|
||||
? { material_pool_id: lines[0].material_pool_id, materialPool: lines[0].materialPool }
|
||||
: {}),
|
||||
cash_events,
|
||||
material_events,
|
||||
voided_events: allEvents.filter(event => event.voided),
|
||||
received,
|
||||
refunded,
|
||||
netReceived: received - refunded,
|
||||
credit_card_fees,
|
||||
credit_card_fee_total: credit_card_fees.reduce((total, fee) => total + fee.amount, 0),
|
||||
};
|
||||
}
|
||||
function list(ledger, 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 status = query.status ?? 'all';
|
||||
env.pick(status, ['all', 'pending', 'delivered', 'cancelled'], '锁价状态');
|
||||
const rows = ledger
|
||||
.visibleRows(
|
||||
'price_lock',
|
||||
ledger.rows(
|
||||
'SELECT id FROM price_locks WHERE date>=? AND date<=?' +
|
||||
(status === 'all' ? '' : ' AND status=?') +
|
||||
' ORDER BY created,rowid',
|
||||
from,
|
||||
date,
|
||||
...(status === 'all' ? [] : [status]),
|
||||
),
|
||||
)
|
||||
.map(({ id }) => detail(ledger, id, env));
|
||||
const counts = { pending: 0, delivered: 0, cancelled: 0 };
|
||||
for (const row of ledger.visibleRows('price_lock', ledger.rows('SELECT id,status FROM price_locks')))
|
||||
counts[row.status]++;
|
||||
return { from, date, rows, counts };
|
||||
}
|
||||
function event(ledger, lock, values, actor, env) {
|
||||
const id = randomUUID();
|
||||
const card = values.kind === 'receipt' && values.amount > 0 && values.account?.endsWith('信用卡');
|
||||
const feeRate = card ? CreditCardRates.read(ledger, 'price_lock', lock.id) : null;
|
||||
const feeAmount = card ? CreditCardFees.amount(values.amount, feeRate) : null,
|
||||
feePayer = card
|
||||
? ledger.validateMember(values.credit_card_fee_payer ?? 'owner', '信用卡手续费付款人', {
|
||||
original: values.originalFeePayer,
|
||||
})
|
||||
: null;
|
||||
ledger.run(
|
||||
'INSERT INTO price_lock_events(id,price_lock_id,date,kind,amount,account,payer,source,quantity,rate,number,customer,product,actor,created) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
|
||||
id,
|
||||
lock.id,
|
||||
values.date,
|
||||
values.kind,
|
||||
values.amount,
|
||||
values.account ? paymentAccount(values.account, env, { original: values.originalAccount }) : null,
|
||||
values.payer ?? null,
|
||||
values.source ?? null,
|
||||
values.quantity ?? null,
|
||||
values.rate ?? null,
|
||||
lock.number,
|
||||
lock.customer,
|
||||
LockLines.product(lock, values.line_index ?? null),
|
||||
actor.name,
|
||||
env.now(),
|
||||
);
|
||||
if (values.kind === 'material')
|
||||
ledger.run('UPDATE price_lock_events SET line_index=? WHERE id=?', values.line_index ?? 0, id);
|
||||
if (card)
|
||||
ledger.run(
|
||||
'UPDATE price_lock_events SET card_fee_amount=?,card_fee_payer=?,card_fee_rate=?,card_fee_note=? WHERE id=?',
|
||||
feeAmount,
|
||||
feePayer,
|
||||
feeRate,
|
||||
CreditCardFees.note(feeRate),
|
||||
id,
|
||||
);
|
||||
return id;
|
||||
}
|
||||
function reviseMaterial(ledger, lock, source, values, actor, env) {
|
||||
env.pick(source, ['original', 'extra'], '锁价购料来源');
|
||||
const lineIndex = values.line_index ?? 0,
|
||||
rows = ledger.rows(
|
||||
"SELECT * FROM price_lock_events WHERE price_lock_id=? AND kind='material' AND voided=0 AND source=? AND COALESCE(line_index,0)=?",
|
||||
lock.id,
|
||||
source,
|
||||
lineIndex,
|
||||
);
|
||||
if (rows.length > 1) env.fail('锁价购料原流水不唯一,请先核对后再修改', 409);
|
||||
const previous = rows[0],
|
||||
next = {
|
||||
date: previous?.date ?? lock.date,
|
||||
amount: values.amount,
|
||||
payer: values.payer,
|
||||
quantity: values.quantity,
|
||||
rate: values.rate,
|
||||
};
|
||||
if (previous && ['amount', 'payer', 'quantity', 'rate'].every(key => previous[key] === next[key])) return previous.id;
|
||||
// 采购来源身份保持稳定,三人往来按此来源追加差额;不再登记一笔相同采购。
|
||||
// 更正前后完整存入审计,实际客户收退款事件不参与此修改。
|
||||
const id =
|
||||
previous?.id ?? event(ledger, lock, { ...next, kind: 'material', source, line_index: lineIndex }, actor, env);
|
||||
if (previous)
|
||||
ledger.run(
|
||||
'UPDATE price_lock_events SET amount=?,payer=?,quantity=?,rate=? WHERE id=?',
|
||||
next.amount,
|
||||
next.payer,
|
||||
next.quantity,
|
||||
next.rate,
|
||||
id,
|
||||
);
|
||||
ledger.dirty(next.date);
|
||||
ledger.audit('price-lock:' + lock.id, '已交付锁价购料更正', actor, {
|
||||
source,
|
||||
line_index: lineIndex,
|
||||
before: previous ?? null,
|
||||
after: ledger.one('SELECT * FROM price_lock_events WHERE id=?', id),
|
||||
});
|
||||
return id;
|
||||
}
|
||||
function lockRemark(lock) {
|
||||
return LockLines.lines(lock).length > 1
|
||||
? `锁价单 ${lock.number};各商品按原锁定金价结算`
|
||||
: `锁价单 ${lock.number};按原锁定金价 ${yuan(lock.sell_rate)}元/克结算`;
|
||||
}
|
||||
function editableCustomerNote(lock, value) {
|
||||
const remark = lockRemark(lock);
|
||||
let note = String(value ?? '').trim();
|
||||
// 来源说明由系统保存;编辑客户备注时剥离旧后缀,避免遗漏或重复拼接。
|
||||
while (note.endsWith(remark))
|
||||
note = note
|
||||
.slice(0, -remark.length)
|
||||
.replace(/;\s*$/, '')
|
||||
.trim();
|
||||
return note;
|
||||
}
|
||||
function customerNote(lock, value, env) {
|
||||
const note = env.text(editableCustomerNote(lock, value === undefined ? lock.note : value), '客户单备注', 240, true);
|
||||
const remark = lockRemark(lock);
|
||||
const final = [note, remark].filter(Boolean).join(';');
|
||||
if (final.length > 240) env.fail(`客户备注请控制在${240 - remark.length - 1}字以内,需为锁价说明预留位置`);
|
||||
return final;
|
||||
}
|
||||
function creationLines(input, env) {
|
||||
if (input.lines !== undefined) {
|
||||
if (input.line !== undefined || !Array.isArray(input.lines) || !input.lines.length || input.lines.length > 60)
|
||||
env.fail('锁价单需要1~60件按克黄金商品');
|
||||
return input.lines;
|
||||
}
|
||||
if (!input.line || typeof input.line !== 'object' || Array.isArray(input.line))
|
||||
env.fail('锁价单请填写一件按克黄金商品');
|
||||
return [{ ...input.line, material: input.material }];
|
||||
}
|
||||
function create(ledger, input, actor, env, options = {}) {
|
||||
return atomic(ledger, () => {
|
||||
if (!actor || !['owner', 'assistant'].includes(actor.role)) env.fail('请使用麦麦或助理账号开锁价单', 403);
|
||||
const inputs = creationLines(input, env),
|
||||
date = env.day(input.date),
|
||||
member = ledger.selectedMember(input, actor, options.originalLock?.member ?? null),
|
||||
id = randomUUID();
|
||||
let pool = null,
|
||||
poolMg = 0;
|
||||
const entries = inputs.map((item, index) => {
|
||||
if (!item || typeof item !== 'object' || Array.isArray(item)) env.fail('锁价商品信息无效');
|
||||
if (item.costMaterial?.mode === 'pool' || item.materialPool !== undefined)
|
||||
env.fail('锁价单使用独立采购料费,不能关联日料池');
|
||||
if (item.unit !== undefined && item.unit !== 'g') env.fail('锁价只支持按克黄金');
|
||||
const name = env.text(item.name, '黄金商品名称', 60);
|
||||
if (Calc.isSilver(name)) env.fail('锁价只支持黄金商品,不支持银饰');
|
||||
const material = item.material,
|
||||
source = env.pick(material?.source ?? 'manual', ['manual', 'pool'], '进货料价来源');
|
||||
if (source === 'pool') {
|
||||
if (!Rolling.enabled(ledger)) env.fail('请先启用统一滚动料池后选择当日加权料价');
|
||||
if (date !== env.today() && !(options.historical && ledger.rollingHistorical))
|
||||
env.fail('料池锁价请使用当前营业日,历史料池已冻结');
|
||||
if (material.poolId !== date) env.fail('料池锁价须选择锁价当日料池');
|
||||
pool ??= MaterialPools.readPool(ledger, date, env, { internal: true, member });
|
||||
if (!pool.eligibleRemainingMg || pool.eligibleStatus === 'pending')
|
||||
env.fail('本人回收料及公共料尚无可用金料或成本待补,请先核实购料');
|
||||
if (material.revision !== pool.revision) env.fail('料池已有变动,请刷新料价后锁定', 409);
|
||||
}
|
||||
const quantity = env.weight(item.quantity, '锁定克重'),
|
||||
sellRate = env.money(item.goldPrice, '锁定销售金价'),
|
||||
buyRate = source === 'pool' ? pool.eligibleAverageRate : env.money(material?.rate, '原进货料价');
|
||||
if (quantity <= 0 || sellRate <= 0 || buyRate <= 0) env.fail('锁定克重、销售金价和进货料价必须大于0');
|
||||
const poolPayer = pool?.purchases[0]?.allocations?.[0]?.payer ?? pool?.purchases[0]?.payer ?? 'owner';
|
||||
const payer =
|
||||
source === 'pool'
|
||||
? TeamMembers.isActive(ledger, poolPayer)
|
||||
? poolPayer
|
||||
: member
|
||||
: ledger.validateMember(material?.payer, '原料付款人', {
|
||||
original: options.originalLock?.lines.find(row => row.id === options.lineIds?.[index])?.buy_payer,
|
||||
});
|
||||
if (source === 'manual' && material?.verified !== true) env.fail('请确认原料款已实际支付');
|
||||
const costs = Calc.priceLockCost({
|
||||
lockedQuantity: item.quantity,
|
||||
quantity: item.quantity,
|
||||
buyRate: yuan(buyRate),
|
||||
});
|
||||
const line = ledger.validateLines(
|
||||
[
|
||||
{
|
||||
...item,
|
||||
name,
|
||||
unit: 'g',
|
||||
pocket: '',
|
||||
pricingMode: 'auto',
|
||||
payer,
|
||||
costParts: { material: yuan(costs.originalPurchase), labor: '0', accessories: '0', other: '0' },
|
||||
costMaterial: { mode: 'total' },
|
||||
costLabor: { mode: 'total' },
|
||||
costPayers: { material: payer, labor: payer },
|
||||
},
|
||||
],
|
||||
options.originalLock?.lines.find(row => row.id === options.lineIds?.[index])
|
||||
? [options.originalLock.lines.find(row => row.id === options.lineIds?.[index]).line]
|
||||
: [],
|
||||
date,
|
||||
{ member },
|
||||
)[0];
|
||||
if (source === 'pool') poolMg += quantity;
|
||||
return {
|
||||
id: options.lineIds?.[index] ?? randomUUID(),
|
||||
line_index: index,
|
||||
line,
|
||||
locked_mg: quantity,
|
||||
sell_rate: sellRate,
|
||||
buy_rate: buyRate,
|
||||
buy_payer: payer,
|
||||
material_amount: costs.originalPurchase,
|
||||
material_source: source,
|
||||
};
|
||||
});
|
||||
if (pool && poolMg > pool.eligibleRemainingMg) env.fail('当日料池可用克重不足或成本待补,请先核实购料');
|
||||
if (input.payment?.verified !== true) env.fail('请核实客户实际付款');
|
||||
const received = env.money(input.payment.amount, '客户实际付款'),
|
||||
account = paymentAccount(input.payment.account, env, {
|
||||
original: options.originalLock?.cash_events.find(row => row.kind === 'receipt')?.account,
|
||||
}),
|
||||
discount = env.money(input.discount ?? '0', '整单优惠'),
|
||||
estimated = Calc.orderTotal(
|
||||
entries.map(item => item.line.sale),
|
||||
discount,
|
||||
'yuan',
|
||||
);
|
||||
const number = 'SJ' + date.replaceAll('-', '') + '-' + id.slice(0, 8).toUpperCase(),
|
||||
timestamp = env.now(),
|
||||
customer = env.orderIdentity(input.customer, '客户称呼/代号', 60),
|
||||
salesperson = env.orderIdentity(input.salesperson, '开单人', 30),
|
||||
note = env.text(input.note, '客户单备注', 240, true),
|
||||
first = entries[0];
|
||||
customerNote({ id, number, sell_rate: first.sell_rate, lines: entries, note }, undefined, env);
|
||||
ledger.run(
|
||||
'INSERT INTO price_locks(id,number,date,customer,salesperson,note,line,lines,locked_mg,sell_rate,buy_rate,buy_payer,material_amount,estimated_total,discount,status,revision,actor,created,updated) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
|
||||
id,
|
||||
number,
|
||||
date,
|
||||
customer,
|
||||
salesperson,
|
||||
note,
|
||||
JSON.stringify(first.line),
|
||||
JSON.stringify(entries),
|
||||
entries.reduce((n, row) => n + row.locked_mg, 0),
|
||||
first.sell_rate,
|
||||
first.buy_rate,
|
||||
first.buy_payer,
|
||||
entries.reduce((n, row) => n + row.material_amount, 0),
|
||||
estimated.total,
|
||||
discount,
|
||||
'pending',
|
||||
1,
|
||||
actor.name,
|
||||
timestamp,
|
||||
timestamp,
|
||||
);
|
||||
CreditCardRates.capture(
|
||||
ledger,
|
||||
'price_lock',
|
||||
id,
|
||||
options.creditCardRatePermille ?? CreditCardRates.current(ledger),
|
||||
);
|
||||
ledger.assignMember('price_lock', id, member, { fresh: !options.temporary });
|
||||
const lock = { id, number, customer, lines: entries, line: first.line };
|
||||
if (received > 0)
|
||||
event(
|
||||
ledger,
|
||||
lock,
|
||||
{
|
||||
date,
|
||||
kind: 'receipt',
|
||||
amount: received,
|
||||
account,
|
||||
credit_card_fee_payer: input.payment.credit_card_fee_payer,
|
||||
originalFeePayer: options.originalLock?.credit_card_fees?.[0]?.payer,
|
||||
originalAccount: options.originalLock?.cash_events.find(row => row.kind === 'receipt')?.account,
|
||||
},
|
||||
actor,
|
||||
env,
|
||||
);
|
||||
for (const entry of entries) {
|
||||
if (entry.material_source === 'pool')
|
||||
LockPools.reserve(ledger, { id, locked_mg: entry.locked_mg, line_index: entry.line_index }, pool, actor, env);
|
||||
else
|
||||
event(
|
||||
ledger,
|
||||
lock,
|
||||
{
|
||||
date,
|
||||
kind: 'material',
|
||||
source: 'original',
|
||||
line_index: entry.line_index,
|
||||
amount: entry.material_amount,
|
||||
payer: entry.buy_payer,
|
||||
quantity: entry.locked_mg,
|
||||
rate: entry.buy_rate,
|
||||
},
|
||||
actor,
|
||||
env,
|
||||
);
|
||||
}
|
||||
if (pool) MaterialPools.reconcile(ledger, date, date, actor, env);
|
||||
ledger.run('UPDATE closes SET stale=1 WHERE date>=?', date);
|
||||
const saved = ledger.one('SELECT revision,material_amount FROM price_locks WHERE id=?', id);
|
||||
ledger.audit('price-lock:' + id, '创建锁价单', actor, {
|
||||
number,
|
||||
date,
|
||||
lines: entries,
|
||||
quantity: entries.reduce((n, row) => n + row.locked_mg, 0),
|
||||
materialAmount: saved.material_amount,
|
||||
received,
|
||||
account,
|
||||
revision: saved.revision,
|
||||
});
|
||||
return { id, price_lock_id: id, status: 'pending', revision: saved.revision };
|
||||
});
|
||||
}
|
||||
function deliveryInputs(input, lock, env) {
|
||||
if (input.lines === undefined) {
|
||||
if (lock.lines.length !== 1 || !input.line || typeof input.line !== 'object' || Array.isArray(input.line))
|
||||
env.fail('请填写全部锁价黄金的实际交付信息');
|
||||
return [
|
||||
{ ...input.line, lineId: lock.lines[0].id, inventory: input.inventory, extraMaterial: input.extraMaterial },
|
||||
];
|
||||
}
|
||||
if (input.line !== undefined || !Array.isArray(input.lines) || input.lines.length !== lock.lines.length)
|
||||
env.fail('锁价单须一次交付全部商品');
|
||||
const selected = new Map();
|
||||
for (const line of input.lines) {
|
||||
if (
|
||||
!line ||
|
||||
typeof line !== 'object' ||
|
||||
!line.lineId ||
|
||||
selected.has(line.lineId) ||
|
||||
!lock.lines.some(row => row.id === line.lineId)
|
||||
)
|
||||
env.fail('锁价商品已变化,请刷新后逐项核对', 409);
|
||||
selected.set(line.lineId, line);
|
||||
}
|
||||
return lock.lines.map(row => selected.get(row.id));
|
||||
}
|
||||
function deliver(ledger, id, input, actor, env) {
|
||||
return atomic(ledger, () => {
|
||||
if (!actor || !['owner', 'assistant'].includes(actor.role)) env.fail('请使用麦麦或助理账号交付锁价单', 403);
|
||||
ledger.assertAccess('price_lock', id, actor);
|
||||
if (Object.hasOwn(input, 'member')) ledger.selectedMember(input, actor, ledger.entityMember('price_lock', id));
|
||||
const lock = detail(ledger, id, env);
|
||||
if (
|
||||
ledger.one("SELECT name FROM sqlite_master WHERE type='table' AND name='price_lock_changes'") &&
|
||||
ledger.one("SELECT id FROM price_lock_changes WHERE price_lock_id=? AND status='pending'", id)
|
||||
)
|
||||
env.fail('本单有待审批修改或取消申请,请先复核后再交付', 409);
|
||||
if (lock.status !== 'pending' || lock.final_order_id) env.fail('这张锁价单已交付,不能重复生成销售单', 409);
|
||||
if (!Number.isSafeInteger(input.revision) || input.revision !== lock.revision)
|
||||
env.fail('锁价单已更新,请刷新后再操作', 409);
|
||||
if (lock.lines.some(row => row.material_source === 'pool' && row.materialPool?.amount == null))
|
||||
env.fail('锁价原料池成本待补,请先核实购料后交付', 409);
|
||||
if (input.verified !== true) env.fail('请核对实物、实际成本及客户补退款后确认交付');
|
||||
const date = env.day(input.date, lock.date),
|
||||
inputs = deliveryInputs(input, lock, env),
|
||||
actualLines = [],
|
||||
results = [];
|
||||
const extraSelections = inputs
|
||||
.map((row, index) => ({
|
||||
row,
|
||||
index,
|
||||
mg: Math.max(0, env.weight(row.quantity, '交付克重') - lock.lines[index].locked_mg),
|
||||
}))
|
||||
.filter(item => item.mg && item.row.extraMaterial?.source === 'pool');
|
||||
if (extraSelections.length) {
|
||||
if (!Rolling.enabled(ledger)) env.fail('请先启用统一滚动料池');
|
||||
if (date !== env.today()) env.fail('补重使用交付当日料池,请选择当前营业日');
|
||||
const pool = MaterialPools.readPool(ledger, date, env, {
|
||||
internal: true,
|
||||
member: ledger.entityMember('price_lock', id),
|
||||
});
|
||||
for (const { row } of extraSelections)
|
||||
if (row.extraMaterial.poolId !== date || row.extraMaterial.revision !== pool.revision)
|
||||
env.fail('补重料池已有变动,请刷新料价后交付', 409);
|
||||
if (extraSelections.reduce((n, r) => n + r.mg, 0) > pool.eligibleRemainingMg || pool.eligibleStatus === 'pending')
|
||||
env.fail('当日料池可用克重不足或成本待补,请先核实购料');
|
||||
for (const { index, mg } of extraSelections)
|
||||
LockPools.reserve(ledger, { id, line_index: LockPools.extraIndex(index), locked_mg: mg }, pool, actor, env);
|
||||
MaterialPools.reconcile(ledger, date, date, actor, env);
|
||||
}
|
||||
for (const [index, entry] of lock.lines.entries()) {
|
||||
const lineInput = inputs[index],
|
||||
extraPool = LockPools.find(ledger, id, LockPools.extraIndex(index));
|
||||
if (lineInput.costMaterial?.mode === 'pool' || lineInput.materialPool !== undefined)
|
||||
env.fail('锁价单使用独立采购料费,不能关联日料池');
|
||||
if (lineInput.goldPrice !== undefined && env.money(lineInput.goldPrice, '销售金价') !== entry.sell_rate)
|
||||
env.fail('锁价销售金价不能修改');
|
||||
if (lineInput.unit !== undefined && lineInput.unit !== 'g') env.fail('锁价交付必须按实际克重');
|
||||
const costs = Calc.priceLockCost({
|
||||
lockedQuantity: grams(entry.locked_mg),
|
||||
quantity: lineInput.quantity,
|
||||
buyRate: yuan(entry.buy_rate),
|
||||
extraBuyRate: extraPool ? yuan(extraPool.snapshot.averageRate) : lineInput.extraMaterial?.rate,
|
||||
}),
|
||||
pooled = LockPools.prepareDelivery(ledger, { ...entry, id }, date, costs.originalUsedMg, actor, env);
|
||||
if (extraPool) {
|
||||
if (extraPool.amount == null) env.fail('补重料池成本待补', 409);
|
||||
costs.extraCost = extraPool.amount;
|
||||
costs.materialCost = costs.originalUsedCost + costs.extraCost;
|
||||
}
|
||||
if (pooled)
|
||||
Object.assign(costs, {
|
||||
originalPurchase: pooled.snapshot.amount,
|
||||
originalUsedCost: pooled.amount,
|
||||
leftoverCost: pooled.leftoverCost,
|
||||
materialCost: pooled.amount + costs.extraCost,
|
||||
});
|
||||
const pocket = ledger.validatePocket(lineInput.inventory?.pocket, { name: '交付货盘' }),
|
||||
originalStock = env.pick(lineInput.inventory?.original, ['receive', 'stocked'], '原锁定黄金库存来源');
|
||||
if (pooled && originalStock !== 'stocked') env.fail('料池锁价使用已有黄金,原锁料不能重复入库');
|
||||
const stockCount = ledger.validateStockCount(pocket, lineInput.stockCount),
|
||||
countSource =
|
||||
ledger.pocket(pocket)?.countUnit === 'pair'
|
||||
? env.pick(lineInput.inventory?.countSource, ['receive', 'stocked'], '成品来源')
|
||||
: null;
|
||||
let extraStock = null,
|
||||
extraPayer = null,
|
||||
extraRate = null;
|
||||
if (costs.extraMg && extraPool) {
|
||||
if (lineInput.inventory?.extra !== 'stocked') env.fail('补重使用已有料池,不可重复入库');
|
||||
extraStock = 'stocked';
|
||||
extraRate = extraPool.snapshot.averageRate;
|
||||
} else if (costs.extraMg) {
|
||||
env.pick(lineInput.extraMaterial?.source ?? 'manual', ['manual'], '补重料费来源');
|
||||
extraStock = env.pick(lineInput.inventory?.extra, ['receive', 'stocked'], '补重黄金库存来源');
|
||||
extraPayer = ledger.validateMember(lineInput.extraMaterial?.payer, '补重料费付款人');
|
||||
extraRate = env.money(lineInput.extraMaterial.rate, '补重进货料价');
|
||||
if (lineInput.extraMaterial?.verified !== true) env.fail('请确认补重原料款已实际支付');
|
||||
}
|
||||
const payers = Calc.costPayers(lineInput.costPayers);
|
||||
if (!pooled && payers && payers.material !== entry.buy_payer) env.fail('原锁价料费付款人不能修改');
|
||||
actualLines.push({
|
||||
...lineInput,
|
||||
stockCount,
|
||||
name: entry.line.name,
|
||||
code: entry.line.code,
|
||||
unit: 'g',
|
||||
pocket,
|
||||
pricingMode: 'auto',
|
||||
goldPrice: yuan(entry.sell_rate),
|
||||
costParts: { ...lineInput.costParts, material: yuan(costs.materialCost) },
|
||||
costMaterial: { mode: 'total' },
|
||||
costPayers: { material: entry.buy_payer, labor: payers?.labor ?? lineInput.payer },
|
||||
});
|
||||
results.push({
|
||||
entry,
|
||||
costs,
|
||||
pooled,
|
||||
extraPool,
|
||||
pocket,
|
||||
stockCount,
|
||||
countSource,
|
||||
originalStock,
|
||||
extraStock,
|
||||
extraPayer,
|
||||
extraRate,
|
||||
});
|
||||
}
|
||||
const discount = env.money(input.discount ?? '0', '整单优惠'),
|
||||
lines = ledger.validateLines(
|
||||
actualLines,
|
||||
lock.lines.map(entry => entry.line),
|
||||
date,
|
||||
{ member: ledger.entityMember('price_lock', id) ?? ledger.memberFor(actor) },
|
||||
),
|
||||
fees = ledger.validateFees((input.fee_items ?? []).map(fee => ({ ...fee, status: 'estimated' })));
|
||||
ledger.validateCompletedCosts(lines, fees);
|
||||
const total = Calc.orderTotal(
|
||||
lines.map(line => line.sale),
|
||||
discount,
|
||||
'yuan',
|
||||
).total,
|
||||
difference = total - lock.netReceived;
|
||||
let settlementAccount = lock.cash_events.find(event => event.kind === 'receipt')?.account ?? '助理微信';
|
||||
if (difference) {
|
||||
if (input.settlement?.verified !== true) env.fail('请确认客户补款或退款已经实际完成');
|
||||
const amount = env.money(input.settlement.amount, '实际补退款金额');
|
||||
if (amount !== Math.abs(difference)) env.fail('实际补退款金额须与最终成交差额一致');
|
||||
settlementAccount = paymentAccount(input.settlement.account, env);
|
||||
} else if (input.settlement?.amount !== undefined && env.money(input.settlement.amount, '实际补退款金额') !== 0)
|
||||
env.fail('本单无需补退款,不能重复记收款');
|
||||
const note = customerNote(lock, input.note, env),
|
||||
normal = {
|
||||
date,
|
||||
customer_type: input.customer_type,
|
||||
customer: lock.customer,
|
||||
salesperson: lock.salesperson,
|
||||
note,
|
||||
discount: yuan(discount),
|
||||
rounding_mode: 'yuan',
|
||||
payment_account: settlementAccount,
|
||||
lines: actualLines,
|
||||
fee_items: fees.map(fee => ({
|
||||
...fee,
|
||||
amount: fee.amount === null ? '' : yuan(fee.amount),
|
||||
status: 'estimated',
|
||||
})),
|
||||
fees_date: date,
|
||||
};
|
||||
const finalId = env.saveDeliveryOrder(normal).id,
|
||||
storedLines = ledger.rawOrder(finalId).lines,
|
||||
deliveryRows = [],
|
||||
group = randomUUID();
|
||||
CreditCardRates.capture(ledger, 'order', finalId, lock.credit_card_rate_permille);
|
||||
for (const [index, result] of results.entries()) {
|
||||
const {
|
||||
entry,
|
||||
costs,
|
||||
pooled,
|
||||
extraPool,
|
||||
pocket,
|
||||
stockCount,
|
||||
countSource,
|
||||
originalStock,
|
||||
extraStock,
|
||||
extraPayer,
|
||||
extraRate,
|
||||
} = result,
|
||||
allocations = pooled
|
||||
? LockPools.materialAllocations(pooled.snapshot, costs.originalUsedMg)
|
||||
: [
|
||||
{
|
||||
source: 'original',
|
||||
quantity: costs.originalUsedMg,
|
||||
rate: entry.buy_rate,
|
||||
amount: costs.originalUsedCost,
|
||||
payer: entry.buy_payer,
|
||||
},
|
||||
];
|
||||
if (extraPool)
|
||||
allocations.push(
|
||||
...LockPools.materialAllocations(extraPool.snapshot, costs.extraMg).map(a => ({ ...a, source: 'extra' })),
|
||||
);
|
||||
else if (costs.extraMg)
|
||||
allocations.push({
|
||||
source: 'extra',
|
||||
quantity: costs.extraMg,
|
||||
rate: extraRate,
|
||||
amount: costs.extraCost,
|
||||
payer: extraPayer,
|
||||
});
|
||||
const storedLine = storedLines[index];
|
||||
storedLine.lineId = entry.id;
|
||||
storedLine.materialAllocations = allocations;
|
||||
if (pooled)
|
||||
storedLine.priceLockPool = {
|
||||
...pooled.snapshot,
|
||||
priceLockId: id,
|
||||
lineId: entry.id,
|
||||
line_index: index,
|
||||
quantity: costs.originalUsedMg,
|
||||
amount: pooled.amount,
|
||||
allocations: pooled.allocations,
|
||||
...(pooled.materialSources ? { materialSources: pooled.materialSources } : {}),
|
||||
};
|
||||
if (extraPool)
|
||||
storedLine.priceLockExtraPool = { ...extraPool.snapshot, priceLockId: id, lineId: entry.id, line_index: index };
|
||||
if (costs.extraMg && !extraPool)
|
||||
event(
|
||||
ledger,
|
||||
lock,
|
||||
{
|
||||
date,
|
||||
kind: 'material',
|
||||
source: 'extra',
|
||||
line_index: index,
|
||||
amount: costs.extraCost,
|
||||
payer: extraPayer,
|
||||
quantity: costs.extraMg,
|
||||
rate: extraRate,
|
||||
},
|
||||
actor,
|
||||
env,
|
||||
);
|
||||
if (originalStock === 'receive')
|
||||
ledger.move(
|
||||
{
|
||||
group,
|
||||
order: finalId,
|
||||
date,
|
||||
pocket,
|
||||
mg: entry.locked_mg,
|
||||
kind: 'lock_purchase',
|
||||
note: lock.number + ' ' + entry.line.name + ' 原锁定黄金入库',
|
||||
cost: entry.material_amount,
|
||||
},
|
||||
actor,
|
||||
);
|
||||
if (extraStock === 'receive')
|
||||
ledger.move(
|
||||
{
|
||||
group,
|
||||
order: finalId,
|
||||
date,
|
||||
pocket,
|
||||
mg: costs.extraMg,
|
||||
kind: 'lock_purchase',
|
||||
note: lock.number + ' ' + entry.line.name + ' 补重黄金入库',
|
||||
cost: costs.extraCost,
|
||||
},
|
||||
actor,
|
||||
);
|
||||
// 原锁料和补重只增加黄金重量;成品对数由明确选择的来源单独入库一次。
|
||||
if (countSource === 'receive')
|
||||
ledger.move(
|
||||
{
|
||||
group,
|
||||
order: finalId,
|
||||
date,
|
||||
pocket,
|
||||
mg: 0,
|
||||
stockCount,
|
||||
kind: 'lock_finished',
|
||||
note: lock.number + ' ' + entry.line.name + ' 锁价成品入库',
|
||||
},
|
||||
actor,
|
||||
);
|
||||
deliveryRows.push({
|
||||
lineId: entry.id,
|
||||
date,
|
||||
quantity: costs.finalMg,
|
||||
...(stockCount === null ? {} : { stockCount }),
|
||||
original_used_mg: costs.originalUsedMg,
|
||||
extra_mg: costs.extraMg,
|
||||
leftover_mg: costs.leftoverMg,
|
||||
leftover_cost: costs.leftoverCost,
|
||||
inventory: {
|
||||
pocket,
|
||||
original: originalStock,
|
||||
...(countSource ? { countSource } : {}),
|
||||
...(extraStock ? { extra: extraStock } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
ledger.run('UPDATE orders SET lines=? WHERE id=?', JSON.stringify(storedLines), finalId);
|
||||
ledger.run('UPDATE price_locks SET final_order_id=? WHERE id=?', finalId, id);
|
||||
if (difference)
|
||||
event(
|
||||
ledger,
|
||||
lock,
|
||||
{
|
||||
date,
|
||||
kind: difference > 0 ? 'receipt' : 'refund',
|
||||
amount: Math.abs(difference),
|
||||
account: settlementAccount,
|
||||
credit_card_fee_payer: input.settlement.credit_card_fee_payer,
|
||||
},
|
||||
actor,
|
||||
env,
|
||||
);
|
||||
for (const payment of ledger.rows(
|
||||
'SELECT * FROM price_lock_events WHERE price_lock_id=? AND voided=0 AND card_fee_amount IS NOT NULL ORDER BY date,created,rowid',
|
||||
id,
|
||||
)) {
|
||||
const fee = ledger.recordCardFee(finalId, payment, actor, {
|
||||
payer: payment.card_fee_payer,
|
||||
sourceKind: 'price_lock',
|
||||
});
|
||||
ledger.run('UPDATE price_lock_events SET card_fee_expense_id=? WHERE id=?', fee.expense_id ?? null, payment.id);
|
||||
}
|
||||
const delivery = LockLines.aggregateDelivery({ date, total, difference }, deliveryRows);
|
||||
ledger.run("UPDATE price_locks SET status='delivered',delivery=? WHERE id=?", JSON.stringify(delivery), id);
|
||||
for (const result of results)
|
||||
if (result.pooled)
|
||||
LockPools.finishDelivery(ledger, { ...result.entry, id }, deliveryRows[result.entry.line_index], actor, env);
|
||||
if (results.some(result => result.pooled || result.extraPool))
|
||||
MaterialPools.reconcile(ledger, date, date, actor, env, { skipJournalOrder: finalId });
|
||||
env.completeNewOrder(finalId, date);
|
||||
// 同日加权重算可能更新行级余料分厘,保留重算后的交付快照。
|
||||
const finalDelivery = ledger.one('SELECT delivery FROM price_locks WHERE id=?', id).delivery;
|
||||
ledger.run(
|
||||
"UPDATE price_locks SET status='delivered',revision=revision+1,delivery=?,updated=? WHERE id=?",
|
||||
finalDelivery,
|
||||
env.now(),
|
||||
id,
|
||||
);
|
||||
ledger.audit('price-lock:' + id, '锁价交付并生成销售单', actor, {
|
||||
...JSON.parse(finalDelivery),
|
||||
final_order_id: finalId,
|
||||
revision: lock.revision + 1,
|
||||
});
|
||||
return {
|
||||
id: finalId,
|
||||
order_id: finalId,
|
||||
price_lock_id: id,
|
||||
status: 'delivered',
|
||||
revision: ledger.one('SELECT revision FROM price_locks WHERE id=?', id).revision,
|
||||
};
|
||||
});
|
||||
}
|
||||
function inheritedPayments(ledger, orderId) {
|
||||
return ledger.rows(
|
||||
"SELECT e.id,? AS order_id,e.date,e.kind,e.amount,e.account,'锁价单实际收退款' AS reference,e.actor,e.created,e.id AS price_lock_event_id FROM price_lock_events e JOIN price_locks l ON l.id=e.price_lock_id WHERE l.final_order_id=? AND e.voided=0 AND e.kind IN ('receipt','refund') ORDER BY e.date,e.created,e.rowid",
|
||||
orderId,
|
||||
orderId,
|
||||
);
|
||||
}
|
||||
function reporting(ledger, query, env) {
|
||||
const to = env.day(query.to ?? query.date ?? env.today()),
|
||||
from = env.day(query.from ?? to);
|
||||
if (from > to) env.fail('开始日期不能晚于结束日期');
|
||||
const rows = ledger.visibleRows(
|
||||
'price_lock',
|
||||
ledger.rows(
|
||||
'SELECT * FROM price_lock_events WHERE date>=? AND date<=? AND voided=0 ORDER BY date,created,rowid',
|
||||
from,
|
||||
to,
|
||||
),
|
||||
'price_lock_id',
|
||||
);
|
||||
const customerCash = rows
|
||||
.filter(event => event.kind !== 'material')
|
||||
.map(
|
||||
({
|
||||
payer,
|
||||
source,
|
||||
quantity,
|
||||
rate,
|
||||
card_fee_amount,
|
||||
card_fee_payer,
|
||||
card_fee_expense_id,
|
||||
card_fee_rate,
|
||||
card_fee_note,
|
||||
...event
|
||||
}) => event,
|
||||
);
|
||||
const materialOutlays = rows
|
||||
.filter(event => event.kind === 'material')
|
||||
.map(
|
||||
({ account, card_fee_amount, card_fee_payer, card_fee_expense_id, card_fee_rate, card_fee_note, ...event }) => ({
|
||||
...event,
|
||||
component: 'material',
|
||||
}),
|
||||
);
|
||||
const directOutlays = ledger
|
||||
.visibleRows(
|
||||
'price_lock',
|
||||
ledger.rows(
|
||||
'SELECT e.*,l.id AS price_lock_id,l.number,l.customer FROM expenses e JOIN price_locks l ON l.final_order_id=e.order_id WHERE e.date>=? AND e.date<=? AND NOT EXISTS(SELECT 1 FROM price_lock_events p WHERE p.card_fee_expense_id=e.id) ORDER BY e.date,e.created,e.rowid',
|
||||
from,
|
||||
to,
|
||||
),
|
||||
'price_lock_id',
|
||||
)
|
||||
.map(row => ({
|
||||
...row,
|
||||
kind: 'fee',
|
||||
component: 'fee',
|
||||
product: LockLines.product(ledger.one('SELECT * FROM price_locks WHERE id=?', row.price_lock_id)),
|
||||
}));
|
||||
// 交付只关联同一笔原日实付,投影的ID及财务字段不随expense关联改变。
|
||||
for (const event of rows)
|
||||
if (event.card_fee_amount > 0)
|
||||
directOutlays.push({
|
||||
id: 'card-fee:' + event.id,
|
||||
price_lock_id: event.price_lock_id,
|
||||
date: event.date,
|
||||
kind: 'fee',
|
||||
component: 'fee',
|
||||
amount: event.card_fee_amount,
|
||||
payer: event.card_fee_payer,
|
||||
note: cardFeeNote(event),
|
||||
actor: event.actor,
|
||||
created: event.created,
|
||||
number: event.number,
|
||||
customer: event.customer,
|
||||
product: event.product,
|
||||
});
|
||||
directOutlays.sort((a, b) => a.date.localeCompare(b.date) || a.created.localeCompare(b.created));
|
||||
return { from, to, customerCash, materialOutlays, directOutlays };
|
||||
}
|
||||
module.exports = {
|
||||
initialize,
|
||||
create,
|
||||
deliver,
|
||||
detail,
|
||||
list,
|
||||
inheritedPayments,
|
||||
reporting,
|
||||
customerNote,
|
||||
editableCustomerNote,
|
||||
reviseMaterial,
|
||||
};
|
||||
Reference in new issue
Block a user