- 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>
689 lines
27 KiB
JavaScript
689 lines
27 KiB
JavaScript
'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 };
|