目录重组:后端按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,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