- 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>
947 lines
37 KiB
JavaScript
947 lines
37 KiB
JavaScript
'use strict';
|
||
// 回收与置换的金额、实物和现金分别保存;关联记录始终在同一保存点内生成。
|
||
const { randomUUID } = require('node:crypto');
|
||
const Calc = require('../../public/calculations');
|
||
const CreditCardRates = require('../team/credit-card-rates'),
|
||
CreditCardFees = require('../../public/credit-card-fees');
|
||
const MaterialPools = require('../materials/material-pools');
|
||
const TeamFunds = require('../funds/team-funds');
|
||
const RecoveryMaterial = require('./recovery-material'),
|
||
CustomerMaterials = require('./customer-materials');
|
||
const LIMIT = 100000000000;
|
||
const IMMUTABLE_REASON =
|
||
'本单关联黄金回收/置换、购料及库存,暂不支持普通订单修改、取消、退款、退货或费用变更,请保留原关联记录';
|
||
const sum = (rows, key) => rows.reduce((total, row) => total + (row[key] ?? 0), 0);
|
||
const amountInput = value => (value / 100).toFixed(2),
|
||
weightInput = value => (value / 1000).toFixed(3);
|
||
function initialize(ledger) {
|
||
ledger.db.exec(`
|
||
CREATE TABLE IF NOT EXISTS recoveries(
|
||
id TEXT PRIMARY KEY,number TEXT UNIQUE NOT NULL,mode TEXT NOT NULL CHECK(mode IN ('direct','exchange')),
|
||
date TEXT NOT NULL,customer TEXT NOT NULL,salesperson TEXT NOT NULL,member TEXT NOT NULL,note TEXT NOT NULL,
|
||
old_lines TEXT NOT NULL,data TEXT NOT NULL,order_id TEXT UNIQUE REFERENCES orders(id),purchase_id TEXT UNIQUE REFERENCES material_purchases(id),
|
||
inventory_group TEXT NOT NULL UNIQUE,actor TEXT NOT NULL,created TEXT NOT NULL,revision INTEGER NOT NULL DEFAULT 1);
|
||
CREATE INDEX IF NOT EXISTS ix_recoveries_date ON recoveries(date,created);
|
||
CREATE TABLE IF NOT EXISTS recovery_purchase_sources(
|
||
purchase_id TEXT PRIMARY KEY REFERENCES material_purchases(id),recovery_id TEXT NOT NULL UNIQUE REFERENCES recoveries(id),
|
||
cash_amount INTEGER NOT NULL CHECK(cash_amount>=0),offset_amount INTEGER NOT NULL CHECK(offset_amount>=0),allocations TEXT NOT NULL);
|
||
`);
|
||
CustomerMaterials.initialize(ledger);
|
||
}
|
||
function atomic(ledger, fn) {
|
||
ledger.db.exec('SAVEPOINT recovery_action');
|
||
try {
|
||
const result = fn();
|
||
ledger.db.exec('RELEASE recovery_action');
|
||
return result;
|
||
} catch (error) {
|
||
ledger.db.exec('ROLLBACK TO recovery_action');
|
||
ledger.db.exec('RELEASE recovery_action');
|
||
throw error;
|
||
}
|
||
}
|
||
function active(actor, env) {
|
||
if (!actor || !['owner', 'assistant'].includes(actor.role)) env.fail('请登录后登记回收或置换', 403);
|
||
}
|
||
function product(value, name, max, env) {
|
||
if (typeof value !== 'string') env.fail(name + '须填写文字');
|
||
return env.text(value, name, max);
|
||
}
|
||
function safe(value, env, label = '回收/置换合计') {
|
||
if (!Number.isSafeInteger(value) || Math.abs(value) > LIMIT) env.fail(label + '超出支持范围');
|
||
return value;
|
||
}
|
||
function multiply(mg, rate, env) {
|
||
return safe(Number((BigInt(mg) * BigInt(rate) + 500n) / 1000n), env);
|
||
}
|
||
function normalizeOld(lines, env) {
|
||
if (!Array.isArray(lines) || !lines.length || lines.length > 60) env.fail('每单需要1~60行旧料');
|
||
return lines.map((line, index) => {
|
||
if (!line || typeof line !== 'object' || Array.isArray(line)) env.fail('旧料记录格式无效');
|
||
const name = env.text(line.name ?? 'Au旧料', '旧料名称', 60),
|
||
incomingMg = env.weight(line.incoming_weight, '来料重量'),
|
||
meltedMg = env.weight(line.melted_weight, '熔后重量');
|
||
const purityUnits = env.weight(line.purity, '成色百分数');
|
||
if (incomingMg <= 0 || meltedMg <= 0 || meltedMg > incomingMg)
|
||
env.fail(`第${index + 1}行来料与熔后重量须大于0,熔后重量不能超过来料重量`);
|
||
if (purityUnits <= 0 || purityUnits > 100000) env.fail('成色须大于0且不超过100%,例如99表示99%');
|
||
const foldedMg = Number((BigInt(meltedMg) * BigInt(purityUnits) + 50000n) / 100000n);
|
||
if (foldedMg <= 0) env.fail('折后重量小于0.001克,请核对熔后重量和成色');
|
||
return { name, incomingMg, meltedMg, purity: purityUnits / 1000, foldedMg };
|
||
});
|
||
}
|
||
function orderTotal(subtotal, discount, mode, env) {
|
||
if (discount > subtotal) env.fail('整单优惠不能超过置换应收项目合计');
|
||
env.pick(mode, ['cent', 'yuan'], '整单取整方式');
|
||
if (subtotal === discount) return { total: 0, rounding_adjustment: 0 };
|
||
return Calc.orderTotal([subtotal], discount, mode);
|
||
}
|
||
// 多商品共用旧料、补金单价与整单费用;各件工费和库存独立保存。
|
||
function products(q) {
|
||
return q.newProducts ?? (q.newProduct ? [q.newProduct] : []);
|
||
}
|
||
function split(total, weights) {
|
||
const sum = weights.reduce((a, b) => a + b, 0);
|
||
let cumulative = 0,
|
||
previous = 0;
|
||
return weights.map(weight => {
|
||
cumulative += weight;
|
||
const next = sum ? Number((BigInt(total) * BigInt(cumulative) + BigInt(sum) / 2n) / BigInt(sum)) : 0;
|
||
const part = next - previous;
|
||
previous = next;
|
||
return part;
|
||
});
|
||
}
|
||
function normalizeProducts(ledger, input, existing, date, env, { creating }) {
|
||
if (!Array.isArray(input) || !input.length || input.length > 60) env.fail('置换新货需要1~60件商品');
|
||
return input.map((row, index) => {
|
||
if (!row || typeof row !== 'object' || Array.isArray(row)) env.fail('置换新货格式无效');
|
||
const original = existing ? products(existing)[index] : null;
|
||
const name = env.text(row.name, '新货名称', 60),
|
||
quantity = env.weight(row.quantity, '新货克重');
|
||
if (quantity <= 0 || Calc.isSilver(name)) env.fail('置换新货须为大于0克的黄金商品');
|
||
const pocket =
|
||
row.pocket === '' ? '' : ledger.validatePocket(row.pocket, { original: original?.pocket, name: '新货货盘' });
|
||
const same = !!original && original.pocket === pocket;
|
||
const stockCount = ledger.validateStockCount(pocket, row.stockCount, {
|
||
original: same ? (original.stockCount ?? null) : null,
|
||
allowLegacy: same,
|
||
});
|
||
if (stockCount !== null && ledger.pocket(pocket)?.countSince > date) env.fail('出库日期不能早于货盘对数基准');
|
||
const laborMode = env.pick(row.labor_mode ?? 'gram', ['gram', 'total'], '销售工费方式'),
|
||
laborRate = env.money(row.labor_rate, '销售工费');
|
||
let costLabor = null,
|
||
laborCost = null;
|
||
if (row.cost_labor) {
|
||
const mode = env.pick(row.cost_labor.mode, ['gram', 'total'], '进货工费方式'),
|
||
amount = env.money(mode === 'gram' ? row.cost_labor.rate : row.cost_labor.amount, '进货工费');
|
||
costLabor = { mode, ...(mode === 'gram' ? { rate: amount } : { amount }) };
|
||
laborCost = mode === 'gram' ? multiply(quantity, amount, env) : amount;
|
||
} else if (creating) env.fail('请逐件填写进货工费,没有发生的填0');
|
||
const laborPayer = ledger.validateMember(row.cost_labor_payer, '工费付款人', { original: original?.laborPayer });
|
||
return {
|
||
name,
|
||
quantity,
|
||
pocket,
|
||
...(stockCount === null ? {} : { stockCount }),
|
||
laborMode,
|
||
laborRate,
|
||
laborAmount: laborMode === 'gram' ? multiply(quantity, laborRate, env) : laborRate,
|
||
costLabor,
|
||
laborCost,
|
||
laborPayer,
|
||
};
|
||
});
|
||
}
|
||
function productParts(q) {
|
||
if (q.exchangeItems) return q.exchangeItems.map((p, i) => ({ ...p, charges: i === 0 ? q.charges : [] }));
|
||
if (!q.newProducts) return [q];
|
||
const rows = q.newProducts,
|
||
weights = rows.map(row => row.quantity),
|
||
difference = split(q.differenceMg, weights),
|
||
gold = split(q.goldAmount, difference),
|
||
depreciation = split(q.depreciationAmount, weights),
|
||
material = q.materialCost === null ? rows.map(() => null) : split(q.materialCost, difference);
|
||
return rows.map((row, i) => ({
|
||
...q,
|
||
newProducts: undefined,
|
||
newProduct: row,
|
||
newMg: row.quantity,
|
||
differenceMg: difference[i],
|
||
goldAmount: gold[i],
|
||
depreciationAmount: depreciation[i],
|
||
laborAmount: row.laborAmount,
|
||
laborCost: row.laborCost,
|
||
materialCost: material[i],
|
||
charges: i === 0 ? q.charges : [],
|
||
exchange: {
|
||
...q.exchange,
|
||
costLabor: row.costLabor ?? { mode: 'total' },
|
||
costPayers: { ...q.exchange.costPayers, labor: row.laborPayer },
|
||
costMaterial: difference[i]
|
||
? { ...q.exchange.costMaterial, consumptionMg: difference[i] }
|
||
: { mode: 'total', consumptionMg: 0 },
|
||
},
|
||
}));
|
||
}
|
||
function applyOrderMetadata(ledger, lines, q, recoveryId, env, orderId) {
|
||
const parts = productParts(q);
|
||
for (const [i, saved] of lines.entries()) {
|
||
const part = parts[i];
|
||
saved.recoveryMaterialMg = part.differenceMg;
|
||
saved.recovery_id = recoveryId;
|
||
saved.costMaterial = part.exchange.costMaterial;
|
||
saved.costLabor = part.exchange.costLabor;
|
||
}
|
||
if (lines.some(line => line.costMaterial.mode === 'pool'))
|
||
MaterialPools.prepareLines(ledger, lines, q.date, env, { orderId, member: q.member });
|
||
}
|
||
function quote(ledger, input, actor, env, { creating = false, orderId = null, existingRecovery = null } = {}) {
|
||
active(actor, env);
|
||
if (!input || typeof input !== 'object' || Array.isArray(input)) env.fail('回收/置换记录格式无效');
|
||
if (input.mode === 'exchange' && input.exchange?.items !== undefined)
|
||
return require('./recovery-exchange-items').quote(
|
||
ledger,
|
||
input,
|
||
actor,
|
||
env,
|
||
{ creating, orderId, existingRecovery },
|
||
module.exports,
|
||
);
|
||
const mode = env.pick(input.mode, ['direct', 'exchange'], '回收方式'),
|
||
date = env.day(input.date || env.today()),
|
||
member = ledger.selectedMember(input, actor, existingRecovery?.member ?? null);
|
||
const customerDeposit = CustomerMaterials.resolve(ledger, input, env);
|
||
if (customerDeposit)
|
||
input = {
|
||
...input,
|
||
old_lines: [
|
||
{
|
||
name: '客户寄存料',
|
||
incoming_weight: weightInput(customerDeposit.mg),
|
||
melted_weight: weightInput(customerDeposit.mg),
|
||
purity: '100',
|
||
},
|
||
],
|
||
};
|
||
const old_lines = normalizeOld(input.old_lines, env),
|
||
oldMg = safe(sum(old_lines, 'foldedMg'), env, '旧料折后总重量');
|
||
const originalOldPocket = existingRecovery ? (existingRecovery.oldPocket ?? '回收旧料') : null;
|
||
const oldPocket = ledger.validatePocket(
|
||
input.old_pocket === undefined ? (originalOldPocket ?? '回收旧料') : input.old_pocket,
|
||
{ original: originalOldPocket, name: '旧料入库货盘' },
|
||
),
|
||
sameOldPocket = !!existingRecovery && oldPocket === originalOldPocket;
|
||
const oldStockCount = ledger.validateStockCount(oldPocket, input.old_stock_count, {
|
||
original: sameOldPocket ? (existingRecovery.oldStockCount ?? null) : null,
|
||
allowLegacy: sameOldPocket,
|
||
name: '旧料入库数量(对)',
|
||
});
|
||
if (oldStockCount !== null && ledger.pocket(oldPocket)?.countSince > date)
|
||
env.fail('旧料入库日期不能早于' + ledger.pocket(oldPocket).countSince + '对数盘点基准');
|
||
const customer = creating
|
||
? product(input.customer, '客户称呼/代号', 60, env)
|
||
: env.text(input.customer, '客户称呼/代号', 60, true);
|
||
const salesperson = creating
|
||
? product(input.salesperson, '开单人', 30, env)
|
||
: env.text(input.salesperson, '开单人', 30, true);
|
||
const note = env.text(input.note, '备注', 240, true),
|
||
payer = ledger.validateMember(input.payer ?? member, '回收付款人', { original: existingRecovery?.payer });
|
||
const payment_account = env.paymentAccount(input.payment_account || '麦麦微信', {
|
||
original: existingRecovery?.payment_account,
|
||
});
|
||
const credit_card_rate_permille = existingRecovery
|
||
? (existingRecovery.credit_card_rate_permille ??
|
||
(orderId ? CreditCardRates.read(ledger, 'order', orderId) : CreditCardFees.ratePermille))
|
||
: CreditCardRates.current(ledger);
|
||
const result = {
|
||
mode,
|
||
date,
|
||
customer,
|
||
customer_type: require('../funds/private-operations').customerType(input.customer_type),
|
||
salesperson,
|
||
member,
|
||
note,
|
||
old_lines,
|
||
oldMg,
|
||
oldPocket,
|
||
...(oldStockCount === null ? {} : { oldStockCount }),
|
||
credit_card_rate_permille,
|
||
newMg: 0,
|
||
matchedMg: 0,
|
||
differenceMg: 0,
|
||
surplusMg: mode === 'direct' ? oldMg : 0,
|
||
goldRate: 0,
|
||
laborRate: 0,
|
||
laborMode: 'gram',
|
||
depreciationRate: 0,
|
||
depreciationMg: 0,
|
||
goldAmount: 0,
|
||
laborAmount: 0,
|
||
depreciationAmount: 0,
|
||
charges: [],
|
||
chargesAmount: 0,
|
||
discount: 0,
|
||
rounding_mode: 'cent',
|
||
rounding_adjustment: 0,
|
||
receivable: 0,
|
||
payer,
|
||
payment_account,
|
||
materialCost: 0,
|
||
laborCost: 0,
|
||
goodsCost: 0,
|
||
directCost: 0,
|
||
profit: 0,
|
||
};
|
||
if (mode === 'exchange') {
|
||
let e = input.exchange;
|
||
if (!e || typeof e !== 'object' || Array.isArray(e)) env.fail('请填写换出的新货');
|
||
const multi =
|
||
e.products === undefined
|
||
? null
|
||
: normalizeProducts(ledger, e.products, existingRecovery, date, env, { creating });
|
||
if (multi) {
|
||
const laborCost = multi.some(row => row.laborCost === null) ? null : safe(sum(multi, 'laborCost'), env);
|
||
e = {
|
||
...e,
|
||
name: multi[0].name,
|
||
pocket: multi[0].pocket,
|
||
stockCount: multi[0].stockCount,
|
||
quantity: weightInput(safe(sum(multi, 'quantity'), env)),
|
||
labor_mode: 'total',
|
||
labor_rate: amountInput(safe(sum(multi, 'laborAmount'), env)),
|
||
cost_labor: laborCost === null ? undefined : { mode: 'total', amount: amountInput(laborCost) },
|
||
};
|
||
}
|
||
const newMg = env.weight(e.quantity, '新货克重');
|
||
if (newMg <= 0) env.fail('新货克重须大于0');
|
||
const newProduct = {
|
||
name: env.text(e.name ?? '足金', '新货名称', 60),
|
||
quantity: newMg,
|
||
pocket:
|
||
e.pocket === ''
|
||
? ''
|
||
: ledger.validatePocket(e.pocket, { original: existingRecovery?.newProduct?.pocket, name: '新货货盘' }),
|
||
};
|
||
const samePocket = !!existingRecovery && newProduct.pocket === existingRecovery.newProduct?.pocket,
|
||
stockCount = ledger.validateStockCount(newProduct.pocket, e.stockCount, {
|
||
original: samePocket ? (existingRecovery.newProduct?.stockCount ?? null) : null,
|
||
allowLegacy: samePocket,
|
||
});
|
||
if (stockCount !== null) newProduct.stockCount = stockCount;
|
||
if (Calc.isSilver(newProduct.name)) env.fail('黄金置换暂只支持按克黄金商品');
|
||
const matchedMg = Math.min(newMg, oldMg),
|
||
differenceMg = Math.max(newMg - oldMg, 0),
|
||
surplusMg = Math.max(oldMg - newMg, 0);
|
||
const goldRate = env.money(e.gold_price ?? '0', '销售金价'),
|
||
laborRate = env.money(e.labor_rate ?? '0', '销售工费'),
|
||
laborMode = env.pick(e.labor_mode ?? 'gram', ['gram', 'total'], '销售工费方式');
|
||
if (differenceMg && goldRate <= 0) env.fail('新货补差重量对应的销售金价须大于0');
|
||
const depreciationMg =
|
||
e.depreciation_weight === undefined || e.depreciation_weight === ''
|
||
? matchedMg
|
||
: env.weight(e.depreciation_weight, '折旧计费克重');
|
||
const depreciationRate = env.money(e.depreciation_rate ?? '10', '折旧单价');
|
||
const goldAmount = multiply(differenceMg, goldRate, env),
|
||
laborAmount = laborMode === 'gram' ? multiply(newMg, laborRate, env) : laborRate;
|
||
const depreciationAmount = multiply(depreciationMg, depreciationRate, env),
|
||
charges = Calc.charges(e.charges).items;
|
||
if (charges.some(charge => charge.amount === null)) env.fail('请填写每项附加收费金额,没有发生的填0');
|
||
const chargesAmount = sum(charges, 'amount'),
|
||
discount = env.money(e.discount ?? '0', '整单优惠'),
|
||
rounding_mode = e.rounding_mode ?? 'yuan';
|
||
const total = orderTotal(
|
||
safe(goldAmount + laborAmount + depreciationAmount + chargesAmount, env),
|
||
discount,
|
||
rounding_mode,
|
||
env,
|
||
);
|
||
let materialCost = 0,
|
||
costMaterial = { mode: 'total' };
|
||
if (differenceMg) {
|
||
if (!e.cost_material) {
|
||
if (creating) env.fail('请填写差重的进货料价或选择日购料池');
|
||
materialCost = null;
|
||
} else if (e.cost_material.mode === 'pool') {
|
||
const poolId = env.day(e.cost_material.poolId);
|
||
if (poolId > date) env.fail('日购料日期不能晚于置换日期');
|
||
costMaterial = { mode: 'pool', poolId, consumptionMg: differenceMg };
|
||
const probe = {
|
||
name: newProduct.name,
|
||
unit: 'g',
|
||
quantity: newMg,
|
||
cost: 0,
|
||
costParts: { material: null, labor: 0, accessories: 0, other: 0 },
|
||
costMaterial,
|
||
};
|
||
MaterialPools.prepareLines(ledger, [probe], date, env, { orderId, member });
|
||
materialCost = probe.costParts.material;
|
||
if (probe.materialPool?.materialSources) costMaterial.materialSources = probe.materialPool.materialSources;
|
||
} else {
|
||
env.pick(e.cost_material.mode, ['gram'], '差重料费方式');
|
||
const rate = env.money(e.cost_material.rate, '进货料价');
|
||
if (rate <= 0) env.fail('进货料价须大于0');
|
||
materialCost = multiply(differenceMg, rate, env);
|
||
costMaterial = { mode: 'total', rate, consumptionMg: differenceMg };
|
||
}
|
||
}
|
||
let laborCost = null,
|
||
costLabor = { mode: 'total' };
|
||
if (e.cost_labor) {
|
||
const laborMode = env.pick(e.cost_labor.mode, ['gram', 'total'], '进货工费方式');
|
||
const rate = env.money(laborMode === 'gram' ? e.cost_labor.rate : e.cost_labor.amount, '进货工费');
|
||
laborCost = laborMode === 'gram' ? multiply(newMg, rate, env) : rate;
|
||
costLabor = { mode: laborMode, ...(laborMode === 'gram' ? { rate } : { amount: rate }) };
|
||
} else if (creating) env.fail('请填写进货工费;没有发生的填0');
|
||
const costPayer = ledger.validateMember(e.cost_payer ?? member, '货品成本付款人', {
|
||
original: existingRecovery?.exchange?.costPayer,
|
||
});
|
||
const costPayers = {
|
||
material: ledger.validateMember(e.cost_material_payer ?? costPayer, '料费付款人', {
|
||
original: existingRecovery?.exchange?.costPayers?.material,
|
||
}),
|
||
labor: ledger.validateMember(e.cost_labor_payer ?? costPayer, '进货工费付款人', {
|
||
original: existingRecovery?.exchange?.costPayers?.labor,
|
||
}),
|
||
};
|
||
const fee_items = ledger.validateFees(
|
||
(e.fee_items ?? []).map(fee => ({ ...fee, status: 'estimated' })),
|
||
{ historicalFees: existingRecovery?.exchange?.fee_items ?? [] },
|
||
);
|
||
if (fee_items.some(fee => fee.amount === null)) env.fail('请补齐实际费用,没有发生的填0');
|
||
const directCost = safe(sum(fee_items, 'amount'), env),
|
||
goodsCost = materialCost === null || laborCost === null ? null : safe(materialCost + laborCost, env);
|
||
Object.assign(result, {
|
||
newMg,
|
||
newProduct,
|
||
matchedMg,
|
||
differenceMg,
|
||
surplusMg,
|
||
goldRate,
|
||
laborRate,
|
||
laborMode,
|
||
depreciationRate,
|
||
depreciationMg,
|
||
goldAmount,
|
||
laborAmount,
|
||
depreciationAmount,
|
||
charges,
|
||
chargesAmount,
|
||
discount,
|
||
rounding_mode,
|
||
rounding_adjustment: total.rounding_adjustment,
|
||
receivable: total.total,
|
||
materialCost,
|
||
laborCost,
|
||
goodsCost,
|
||
directCost,
|
||
exchange: { costMaterial, costLabor, costPayer, costPayers, fee_items },
|
||
});
|
||
if (multi) {
|
||
result.newProducts = multi;
|
||
result.newProduct = multi[0];
|
||
}
|
||
}
|
||
const surplusMode = env.pick(input.surplus_mode || 'buy', ['buy', 'deposit'], '余料处理');
|
||
if (mode !== 'exchange' && surplusMode === 'deposit') env.fail('只有置换余料可以暂不结算寄存');
|
||
const depositMg = surplusMode === 'deposit' ? result.surplusMg : 0;
|
||
if (surplusMode === 'deposit')
|
||
Object.assign(result, { surplusMode, depositMg, surplusMemo: env.text(input.surplus_memo, '寄存备忘', 160, true) });
|
||
const purchaseMg = mode === 'direct' ? oldMg : result.surplusMg - depositMg,
|
||
buyRate = purchaseMg ? env.money(input.buy_rate ?? '0', '回收单价') : 0;
|
||
if (purchaseMg && buyRate <= 0) env.fail('回收单价须大于0');
|
||
const calculatedPurchaseAmount = multiply(purchaseMg, buyRate, env);
|
||
const purchaseAmount = purchaseMg
|
||
? input.buy_total === undefined || input.buy_total === ''
|
||
? calculatedPurchaseAmount
|
||
: env.money(input.buy_total, '最终回收总金额')
|
||
: 0;
|
||
if (purchaseMg && purchaseAmount <= 0) env.fail('最终回收总金额须大于0');
|
||
if (
|
||
!purchaseMg &&
|
||
surplusMode !== 'deposit' &&
|
||
input.buy_total !== undefined &&
|
||
input.buy_total !== '' &&
|
||
env.money(input.buy_total, '最终回收总金额') !== 0
|
||
)
|
||
env.fail('没有余料,不能另计回收购料金额');
|
||
const netSettlement = result.receivable - purchaseAmount,
|
||
cashReceipt = Math.max(netSettlement, 0),
|
||
cashPayment = Math.max(-netSettlement, 0),
|
||
offsetAmount = Math.min(result.receivable, purchaseAmount);
|
||
if (cashPayment && payment_account.endsWith('信用卡')) env.fail('回收付款不支持信用卡,请选择实际付款方式');
|
||
if (creating && cashPayment && TeamFunds.accountMember(payment_account, ledger) !== payer)
|
||
env.fail('实际付款账户须与回收付款人一致');
|
||
const cardFee =
|
||
cashReceipt && payment_account.endsWith('信用卡') ? env.cardFee(cashReceipt, credit_card_rate_permille) : 0;
|
||
Object.assign(result, {
|
||
purchaseMg,
|
||
buyRate,
|
||
calculatedPurchaseAmount,
|
||
purchaseAmount,
|
||
actualBuyRate: purchaseMg
|
||
? Number((BigInt(purchaseAmount) * 1000n + BigInt(purchaseMg) / 2n) / BigInt(purchaseMg))
|
||
: null,
|
||
offsetAmount,
|
||
netSettlement,
|
||
cashReceipt,
|
||
cashPayment,
|
||
cardFee,
|
||
directCost: result.directCost + cardFee,
|
||
profit:
|
||
mode === 'exchange'
|
||
? result.goodsCost === null
|
||
? null
|
||
: result.receivable - result.goodsCost - result.directCost - cardFee
|
||
: 0,
|
||
paymentMethods: cashReceipt || cashPayment ? [TeamFunds.accountChannel(payment_account)] : [],
|
||
});
|
||
if (customerDeposit) {
|
||
if (customerDeposit.mg > result.newMg) env.fail('本次寄存用量不能超过新货克重,未使用的料继续寄存');
|
||
result.customerDeposit = customerDeposit;
|
||
CustomerMaterials.validate(ledger, result, env, { orderId });
|
||
}
|
||
return result;
|
||
}
|
||
function nextNumber(ledger, date, env) {
|
||
const key = 'recovery-sequence',
|
||
seq = ledger.meta(key, 0) + 1;
|
||
if (!Number.isSafeInteger(seq)) env.fail('回收单号超出支持范围');
|
||
ledger.setMeta(key, seq);
|
||
return 'HS' + date.replaceAll('-', '') + String(seq).padStart(4, '0');
|
||
}
|
||
function orderInput(q) {
|
||
if (q.newProducts) {
|
||
const first = orderInput(productParts(q)[0]);
|
||
return {
|
||
...first,
|
||
discount: amountInput(q.discount),
|
||
rounding_mode: q.rounding_mode,
|
||
payment_account: q.payment_account,
|
||
fee_items: q.exchange.fee_items.map(f => ({ ...f, amount: amountInput(f.amount) })),
|
||
lines: productParts(q).flatMap(part => orderInput(part).lines),
|
||
};
|
||
}
|
||
return {
|
||
date: q.date,
|
||
member: q.member,
|
||
customer: q.customer,
|
||
customer_type: q.customer_type,
|
||
salesperson: q.salesperson,
|
||
note: q.note,
|
||
lines: [
|
||
{
|
||
name: q.newProduct.name,
|
||
unit: 'g',
|
||
quantity: weightInput(q.newMg),
|
||
pocket: q.newProduct.pocket,
|
||
...(q.newProduct.stockCount == null ? {} : { stockCount: q.newProduct.stockCount }),
|
||
payer: q.exchange.costPayer,
|
||
costPayers: q.exchange.costPayers,
|
||
pricingMode: 'manual',
|
||
sale: amountInput(q.goldAmount + q.laborAmount + q.depreciationAmount),
|
||
charges: q.charges.map(charge => ({ ...charge, amount: amountInput(charge.amount) })),
|
||
costParts: {
|
||
material: amountInput(q.materialCost ?? 0),
|
||
labor: amountInput(q.laborCost),
|
||
accessories: '0',
|
||
other: '0',
|
||
},
|
||
priceNote: `补金 ${weightInput(q.differenceMg)}克 × ${amountInput(q.goldRate)}元;新货工费 ${amountInput(q.laborAmount)}元;折旧 ${amountInput(q.depreciationAmount)}元`,
|
||
},
|
||
],
|
||
discount: amountInput(q.discount),
|
||
rounding_mode: q.rounding_mode,
|
||
payment_account: q.payment_account,
|
||
fee_items: q.exchange.fee_items.map(fee => ({ ...fee, amount: amountInput(fee.amount) })),
|
||
};
|
||
}
|
||
function inputFor(q) {
|
||
const input = {
|
||
mode: q.mode,
|
||
date: q.date,
|
||
customer: q.customer,
|
||
customer_type: q.customer_type,
|
||
salesperson: q.salesperson,
|
||
member: q.member,
|
||
note: q.note,
|
||
old_pocket: q.oldPocket ?? '回收旧料',
|
||
...(q.oldStockCount == null ? {} : { old_stock_count: q.oldStockCount }),
|
||
old_lines: q.old_lines.map(line => ({
|
||
name: line.name,
|
||
incoming_weight: weightInput(line.incomingMg),
|
||
melted_weight: weightInput(line.meltedMg),
|
||
purity: String(line.purity),
|
||
})),
|
||
buy_rate: amountInput(q.buyRate),
|
||
buy_total: amountInput(q.purchaseAmount),
|
||
payer: q.payer,
|
||
payment_account: q.payment_account,
|
||
verified: true,
|
||
};
|
||
if (q.surplusMode === 'deposit') Object.assign(input, { surplus_mode: 'deposit', surplus_memo: q.surplusMemo || '' });
|
||
if (q.mode === 'exchange') {
|
||
const e = q.exchange;
|
||
input.exchange = {
|
||
name: q.newProduct.name,
|
||
quantity: weightInput(q.newMg),
|
||
pocket: q.newProduct.pocket,
|
||
...(q.newProduct.stockCount == null ? {} : { stockCount: q.newProduct.stockCount }),
|
||
gold_price: amountInput(q.goldRate),
|
||
labor_rate: amountInput(q.laborRate),
|
||
labor_mode: q.laborMode,
|
||
depreciation_weight: weightInput(q.depreciationMg),
|
||
depreciation_rate: amountInput(q.depreciationRate),
|
||
charges: q.charges.map(charge => ({ ...charge, amount: amountInput(charge.amount) })),
|
||
discount: amountInput(q.discount),
|
||
rounding_mode: q.rounding_mode,
|
||
cost_material:
|
||
e.costMaterial.mode === 'pool'
|
||
? { mode: 'pool', poolId: e.costMaterial.poolId }
|
||
: { mode: 'gram', rate: amountInput(e.costMaterial.rate ?? 0) },
|
||
cost_labor:
|
||
e.costLabor.mode === 'gram'
|
||
? { mode: 'gram', rate: amountInput(e.costLabor.rate) }
|
||
: { mode: 'total', amount: amountInput(e.costLabor.amount ?? q.laborCost) },
|
||
cost_payer: e.costPayer,
|
||
cost_material_payer: e.costPayers.material,
|
||
cost_labor_payer: e.costPayers.labor,
|
||
fee_items: e.fee_items.map(fee => ({
|
||
key: fee.key,
|
||
note: fee.note,
|
||
amount: amountInput(fee.amount),
|
||
payer: fee.payer,
|
||
})),
|
||
};
|
||
}
|
||
if (q.newProducts)
|
||
input.exchange.products = q.newProducts.map(row => ({
|
||
name: row.name,
|
||
quantity: weightInput(row.quantity),
|
||
pocket: row.pocket,
|
||
...(row.stockCount == null ? {} : { stockCount: row.stockCount }),
|
||
labor_mode: row.laborMode,
|
||
labor_rate: amountInput(row.laborRate),
|
||
cost_labor:
|
||
row.costLabor?.mode === 'gram'
|
||
? { mode: 'gram', rate: amountInput(row.costLabor.rate) }
|
||
: { mode: 'total', amount: amountInput(row.laborCost ?? 0) },
|
||
cost_labor_payer: row.laborPayer,
|
||
}));
|
||
if (q.exchangeItems) {
|
||
delete input.exchange.products;
|
||
input.exchange.items = q.exchangeItems.map(p => {
|
||
const v = inputFor(p);
|
||
return {
|
||
...(v.surplus_mode ? { surplus_mode: v.surplus_mode, surplus_memo: v.surplus_memo } : {}),
|
||
...(v.old_source
|
||
? { old_source: v.old_source, deposit_id: v.deposit_id, deposit_weight: v.deposit_weight }
|
||
: {}),
|
||
old_lines: v.old_lines,
|
||
old_pocket: v.old_pocket,
|
||
...(v.old_stock_count == null ? {} : { old_stock_count: v.old_stock_count }),
|
||
buy_rate: v.buy_rate,
|
||
buy_total: v.buy_total,
|
||
exchange: v.exchange,
|
||
};
|
||
});
|
||
}
|
||
if (q.customerDeposit)
|
||
Object.assign(input, {
|
||
old_source: 'deposit',
|
||
deposit_id: q.customerDeposit.id,
|
||
deposit_weight: weightInput(q.customerDeposit.mg),
|
||
});
|
||
return input;
|
||
}
|
||
function oldInventory(q) {
|
||
return (q.exchangeItems ?? [q]).map(p => ({
|
||
pocket: p.oldPocket ?? '回收旧料',
|
||
mg: p.oldMg - (p.depositMg || 0),
|
||
stockCount: p.oldStockCount ?? null,
|
||
cost: p.purchaseAmount || null,
|
||
}));
|
||
}
|
||
function create(ledger, input, actor, env) {
|
||
return atomic(ledger, () => {
|
||
const q = quote(ledger, input, actor, env, { creating: true });
|
||
if (input.verified !== true) env.fail('请核实旧料、新货及实际收付款后确认');
|
||
const id = randomUUID(),
|
||
number = nextNumber(ledger, q.date, env),
|
||
inventory_group = randomUUID(),
|
||
created = env.now();
|
||
let order_id = null;
|
||
if (q.mode === 'exchange') {
|
||
order_id = env.saveRecoveryOrder(orderInput(q)).id;
|
||
const order = ledger.rawOrder(order_id);
|
||
applyOrderMetadata(ledger, order.lines, q, id, env, order_id);
|
||
ledger.run('UPDATE orders SET lines=? WHERE id=?', JSON.stringify(order.lines), order_id);
|
||
}
|
||
ledger.run(
|
||
'INSERT INTO recoveries(id,number,mode,date,customer,salesperson,member,note,old_lines,data,order_id,inventory_group,actor,created) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
|
||
id,
|
||
number,
|
||
q.mode,
|
||
q.date,
|
||
q.customer,
|
||
q.salesperson,
|
||
q.member,
|
||
q.note,
|
||
JSON.stringify(q.old_lines),
|
||
JSON.stringify(q),
|
||
order_id,
|
||
inventory_group,
|
||
actor.name,
|
||
created,
|
||
);
|
||
ledger.assignMember('recovery', id, q.member);
|
||
CustomerMaterials.apply(ledger, id, q, actor, env);
|
||
// 扣除客户寄存余料后才进入店铺自有库存;匹配置换部分不进入日料池。
|
||
for (const old of oldInventory(q))
|
||
ledger.move(
|
||
{
|
||
group: inventory_group,
|
||
order: order_id,
|
||
date: q.date,
|
||
...old,
|
||
kind: 'recovery',
|
||
note: number,
|
||
member: q.member,
|
||
},
|
||
actor,
|
||
);
|
||
let purchase_id = null;
|
||
if (q.purchaseMg) {
|
||
const allocations = [
|
||
...(q.offsetAmount ? [{ payer: q.member, amount: q.offsetAmount, source: 'offset' }] : []),
|
||
...(q.cashPayment ? [{ payer: q.payer, amount: q.cashPayment, source: 'cash' }] : []),
|
||
];
|
||
const purchase = MaterialPools.purchase(
|
||
ledger,
|
||
{
|
||
date: q.date,
|
||
grams: weightInput(q.purchaseMg),
|
||
total: amountInput(q.purchaseAmount),
|
||
payer: q.payer,
|
||
note: (q.mode === 'direct' ? '直接回收' : '置换余料') + ' · ' + number,
|
||
},
|
||
actor,
|
||
env,
|
||
{
|
||
member: q.member,
|
||
source: {
|
||
recoveryId: id,
|
||
member: q.member,
|
||
cashAmount: q.cashPayment,
|
||
offsetAmount: q.offsetAmount,
|
||
allocations,
|
||
},
|
||
},
|
||
);
|
||
purchase_id = purchase.id;
|
||
ledger.run('UPDATE recoveries SET purchase_id=? WHERE id=?', purchase_id, id);
|
||
}
|
||
if (order_id) {
|
||
env.recoveryOrderAction(order_id, 'confirm', { date: q.date });
|
||
if (q.cashReceipt)
|
||
env.recoveryOrderAction(order_id, 'receipt', {
|
||
date: q.date,
|
||
amount: amountInput(q.cashReceipt),
|
||
account: q.payment_account,
|
||
credit_card_fee_payer: 'owner',
|
||
verified: true,
|
||
reference: '置换差额实际收款 · ' + number,
|
||
});
|
||
env.recoveryOrderAction(order_id, 'complete', { date: q.date, verified: true });
|
||
ledger.audit(order_id, '关联黄金置换', actor, {
|
||
recovery_id: id,
|
||
number,
|
||
receivable: q.receivable,
|
||
purchaseAmount: q.purchaseAmount,
|
||
offsetAmount: q.offsetAmount,
|
||
cashReceipt: q.cashReceipt,
|
||
cashPayment: q.cashPayment,
|
||
});
|
||
}
|
||
ledger.dirty(q.date);
|
||
ledger.audit('recovery:' + id, q.mode === 'direct' ? '登记直接回收' : '登记黄金置换', actor, {
|
||
...q,
|
||
order_id,
|
||
purchase_id,
|
||
});
|
||
return detail(ledger, id, actor, env);
|
||
});
|
||
}
|
||
function raw(ledger, id, actor, env) {
|
||
ledger.assertAccess('recovery', id, actor);
|
||
const row = ledger.one('SELECT * FROM recoveries WHERE id=?', id);
|
||
if (!row) env.fail('回收/置换记录不存在或无权访问', 404);
|
||
return row;
|
||
}
|
||
function detail(ledger, id, actor, env) {
|
||
active(actor, env);
|
||
const row = raw(ledger, id, actor, env),
|
||
saved = JSON.parse(row.data);
|
||
const order = row.order_id ? ledger.detail(row.order_id) : null;
|
||
const materialBatch = row.purchase_id ? RecoveryMaterial.purchaseStatus(ledger, row.purchase_id) : null;
|
||
return {
|
||
...saved,
|
||
oldPocket: saved.oldPocket ?? '回收旧料',
|
||
credit_card_rate_permille:
|
||
saved.credit_card_rate_permille ?? order?.credit_card_rate_permille ?? CreditCardFees.ratePermille,
|
||
id: row.id,
|
||
number: row.number,
|
||
order_id: row.order_id,
|
||
purchase_id: row.purchase_id,
|
||
created: row.created,
|
||
actor: row.actor,
|
||
revision: row.revision,
|
||
...(materialBatch ? { materialBatch } : {}),
|
||
...(saved.exchangeItems && order
|
||
? {
|
||
exchangeItems: saved.exchangeItems.map((p, i) => {
|
||
const line = order.lines[i];
|
||
return {
|
||
...p,
|
||
materialCost: line.costParts.material,
|
||
goodsCost: line.cost,
|
||
profit: line.cost === null ? null : p.receivable - line.cost,
|
||
exchange: {
|
||
...p.exchange,
|
||
costMaterial: {
|
||
...p.exchange.costMaterial,
|
||
...(line.materialPool?.materialSources ? { materialSources: line.materialPool.materialSources } : {}),
|
||
},
|
||
},
|
||
};
|
||
}),
|
||
}
|
||
: {}),
|
||
...(order
|
||
? {
|
||
paper_number: order.paper_number,
|
||
materialCost: order.lines.some(line => line.costParts.material === null)
|
||
? null
|
||
: order.lines.reduce((n, line) => n + line.costParts.material, 0),
|
||
goodsCost: order.goodsCost,
|
||
directCost: order.directCost,
|
||
profit: order.profit,
|
||
materialCostPending: order.materialCostPending,
|
||
}
|
||
: {}),
|
||
...require('./recovery-changes').projection(ledger, row, actor, env),
|
||
immutableReason: IMMUTABLE_REASON,
|
||
};
|
||
}
|
||
function list(ledger, query, actor, env) {
|
||
active(actor, env);
|
||
const date = env.day(query.to ?? query.date ?? env.today()),
|
||
from = env.day(query.from ?? date);
|
||
if (from > date) env.fail('开始日期不能晚于结束日期');
|
||
const mode = query.mode ? env.pick(query.mode, ['direct', 'exchange'], '回收方式') : null,
|
||
member = ledger.queryMember(query, actor),
|
||
q = String(query.q ?? '').trim();
|
||
if (q.length > 100) env.fail('搜索内容不能超过100字');
|
||
const rows = ledger
|
||
.visibleRows(
|
||
'recovery',
|
||
ledger.rows('SELECT * FROM recoveries WHERE date>=? AND date<=? ORDER BY created DESC,rowid DESC', from, date),
|
||
'id',
|
||
actor,
|
||
member,
|
||
)
|
||
.filter(
|
||
row =>
|
||
(!mode || row.mode === mode) &&
|
||
(!q || [row.number, row.customer, row.salesperson, row.note].some(value => value.includes(q))),
|
||
)
|
||
.map(row => detail(ledger, row.id, actor, env));
|
||
const effective = rows.filter(row => row.status !== 'cancelled');
|
||
return {
|
||
from,
|
||
date,
|
||
rows,
|
||
summary: {
|
||
count: effective.length,
|
||
cancelledCount: rows.length - effective.length,
|
||
directCount: effective.filter(row => row.mode === 'direct').length,
|
||
exchangeCount: effective.filter(row => row.mode === 'exchange').length,
|
||
oldMg: sum(effective, 'oldMg'),
|
||
newMg: sum(effective, 'newMg'),
|
||
purchaseMg: sum(effective, 'purchaseMg'),
|
||
purchaseAmount: sum(effective, 'purchaseAmount'),
|
||
receivable: sum(effective, 'receivable'),
|
||
offsetAmount: sum(effective, 'offsetAmount'),
|
||
cashReceipt: sum(effective, 'cashReceipt'),
|
||
cashPayment: sum(effective, 'cashPayment'),
|
||
},
|
||
};
|
||
}
|
||
function forOrder(ledger, id) {
|
||
const row = ledger.one('SELECT id,data,status FROM recoveries WHERE order_id=?', id);
|
||
return row
|
||
? {
|
||
id: row.id,
|
||
...JSON.parse(row.data),
|
||
...(row.status === 'cancelled' ? { offsetAmount: 0, cashPayment: 0, netSettlement: 0 } : {}),
|
||
}
|
||
: null;
|
||
}
|
||
function guardOrder(ledger, id, env) {
|
||
if (forOrder(ledger, id)) env.fail(IMMUTABLE_REASON, 409);
|
||
}
|
||
function publicDetail(ledger, id, actor, env) {
|
||
const result = detail(ledger, id, actor, env),
|
||
keys = [
|
||
'id',
|
||
'number',
|
||
'mode',
|
||
'status',
|
||
'date',
|
||
'customer',
|
||
'salesperson',
|
||
'note',
|
||
'old_lines',
|
||
'oldMg',
|
||
'newMg',
|
||
'matchedMg',
|
||
'differenceMg',
|
||
'surplusMg',
|
||
'depositMg',
|
||
'surplusMode',
|
||
'newProduct',
|
||
'goldRate',
|
||
'laborRate',
|
||
'laborMode',
|
||
'depreciationMg',
|
||
'depreciationRate',
|
||
'buyRate',
|
||
'goldAmount',
|
||
'laborAmount',
|
||
'depreciationAmount',
|
||
'charges',
|
||
'chargesAmount',
|
||
'discount',
|
||
'rounding_mode',
|
||
'rounding_adjustment',
|
||
'calculatedPurchaseAmount',
|
||
'receivable',
|
||
'purchaseAmount',
|
||
'offsetAmount',
|
||
'netSettlement',
|
||
'cashReceipt',
|
||
'cashPayment',
|
||
'paymentMethods',
|
||
'order_id',
|
||
'purchase_id',
|
||
];
|
||
const dto = Object.fromEntries(keys.filter(key => result[key] !== undefined).map(key => [key, result[key]]));
|
||
if (dto.newProduct) dto.newProduct = { name: dto.newProduct.name, quantity: dto.newProduct.quantity };
|
||
if (result.newProducts)
|
||
dto.new_lines = result.newProducts.map(row => ({
|
||
name: row.name,
|
||
quantity: row.quantity,
|
||
laborMode: row.laborMode,
|
||
laborRate: row.laborRate,
|
||
laborAmount: row.laborAmount,
|
||
}));
|
||
if (result.exchangeItems) dto.exchange_items = require('./recovery-exchange-items').publicItems(result);
|
||
return dto;
|
||
}
|
||
module.exports = {
|
||
initialize,
|
||
quote,
|
||
create,
|
||
detail,
|
||
list,
|
||
publicDetail,
|
||
forOrder,
|
||
guardOrder,
|
||
IMMUTABLE_REASON,
|
||
inputFor,
|
||
orderInput,
|
||
products,
|
||
oldInventory,
|
||
applyOrderMetadata,
|
||
};
|