目录重组:后端按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,210 @@
|
||||
'use strict';
|
||||
// 客户寄存料是保管克重,不是店铺自有料,不计采购、资金或利润。
|
||||
const { randomUUID } = require('node:crypto');
|
||||
function initialize(l) {
|
||||
l.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS customer_material_deposits(id TEXT PRIMARY KEY,number TEXT UNIQUE NOT NULL,date TEXT NOT NULL,mg INTEGER NOT NULL CHECK(mg>0),memo TEXT NOT NULL,actor TEXT NOT NULL,actor_id TEXT NOT NULL,created TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS customer_material_events(id TEXT PRIMARY KEY,deposit_id TEXT NOT NULL REFERENCES customer_material_deposits(id),recovery_id TEXT NOT NULL REFERENCES recoveries(id),date TEXT NOT NULL,delta_mg INTEGER NOT NULL CHECK(delta_mg<>0),memo TEXT NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS customer_material_origins(recovery_id TEXT PRIMARY KEY REFERENCES recoveries(id),deposit_id TEXT UNIQUE NOT NULL REFERENCES customer_material_deposits(id),mg INTEGER NOT NULL CHECK(mg>=0));
|
||||
CREATE INDEX IF NOT EXISTS ix_customer_material_events_deposit ON customer_material_events(deposit_id,recovery_id);
|
||||
`);
|
||||
}
|
||||
function active(actor, env) {
|
||||
if (!actor || !['owner', 'assistant'].includes(actor.role)) env.fail('请登录后登记客户寄存料', 403);
|
||||
}
|
||||
function record(l, id, env) {
|
||||
const row = l.one('SELECT * FROM customer_material_deposits WHERE id=?', id);
|
||||
if (!row) env.fail('这笔客户寄存料不存在,请重新选择', 404);
|
||||
return row;
|
||||
}
|
||||
function remaining(l, id, exclude = null) {
|
||||
return l.one(
|
||||
'SELECT mg+(SELECT COALESCE(SUM(delta_mg),0) FROM customer_material_events WHERE deposit_id=d.id AND (? IS NULL OR recovery_id<>?)) AS value FROM customer_material_deposits d WHERE id=?',
|
||||
exclude,
|
||||
exclude,
|
||||
id,
|
||||
)?.value;
|
||||
}
|
||||
function detail(l, id, env) {
|
||||
const row = record(l, id, env),
|
||||
left = remaining(l, id),
|
||||
origin = l.one('SELECT * FROM customer_material_origins WHERE deposit_id=?', id),
|
||||
mg = origin?.mg ?? row.mg;
|
||||
return {
|
||||
id: row.id,
|
||||
number: row.number,
|
||||
date: row.date,
|
||||
mg,
|
||||
remainingMg: left,
|
||||
usedMg: mg - left,
|
||||
...(origin ? { sourceRecoveryId: origin.recovery_id, voided: mg === 0 } : {}),
|
||||
memo: row.memo,
|
||||
actor: row.actor,
|
||||
created: row.created,
|
||||
events: l.rows(
|
||||
'SELECT date,delta_mg AS deltaMg,memo,actor,created FROM customer_material_events WHERE deposit_id=? ORDER BY created,rowid',
|
||||
id,
|
||||
),
|
||||
};
|
||||
}
|
||||
function list(l, query, actor, env) {
|
||||
active(actor, env);
|
||||
const q = env.text(query.q ?? '', '查询', 100, true),
|
||||
rows = l
|
||||
.rows('SELECT id FROM customer_material_deposits ORDER BY date DESC,created DESC,rowid DESC')
|
||||
.map(r => detail(l, r.id, env))
|
||||
.filter(r => !q || [r.number, r.memo, r.actor].some(v => v.includes(q)));
|
||||
return {
|
||||
rows,
|
||||
totalMg: rows.reduce((n, r) => n + r.mg, 0),
|
||||
remainingMg: rows.reduce((n, r) => n + r.remainingMg, 0),
|
||||
usedMg: rows.reduce((n, r) => n + r.usedMg, 0),
|
||||
};
|
||||
}
|
||||
function create(l, input, actor, env) {
|
||||
active(actor, env);
|
||||
const date = env.day(input.date ?? env.today()),
|
||||
mg = env.weight(input.grams, '寄存克重'),
|
||||
memo = env.text(input.memo, '备忘', 240);
|
||||
if (date > env.today()) env.fail('寄存日期不能晚于今天');
|
||||
if (mg <= 0) env.fail('寄存克重须大于0');
|
||||
if (input.verified !== true) env.fail('请确认寄存克重和备忘');
|
||||
const seq = l.meta('customer-material-sequence', 0) + 1;
|
||||
l.setMeta('customer-material-sequence', seq);
|
||||
const id = randomUUID(),
|
||||
number = 'JC' + date.replaceAll('-', '') + String(seq).padStart(4, '0');
|
||||
l.run(
|
||||
'INSERT INTO customer_material_deposits VALUES (?,?,?,?,?,?,?,?)',
|
||||
id,
|
||||
number,
|
||||
date,
|
||||
mg,
|
||||
memo,
|
||||
actor.name,
|
||||
actor.id,
|
||||
env.now(),
|
||||
);
|
||||
l.audit('customer-material:' + id, '登记客户寄存料', actor, {
|
||||
number,
|
||||
date,
|
||||
mg,
|
||||
memo,
|
||||
notice: '只登记保管克重,不计购料、收付、成本或利润',
|
||||
});
|
||||
return detail(l, id, env);
|
||||
}
|
||||
function resolve(l, input, env) {
|
||||
if (input.old_source !== 'deposit') {
|
||||
if (input.old_source !== undefined && input.old_source !== '' && input.old_source !== 'incoming')
|
||||
env.fail('请选择有效旧料来源');
|
||||
return null;
|
||||
}
|
||||
if (input.mode !== 'exchange') env.fail('客户寄存料请从置换入口使用');
|
||||
const row = record(l, input.deposit_id, env),
|
||||
mg = env.weight(input.deposit_weight, '本次使用寄存克重');
|
||||
if (mg <= 0) env.fail('使用寄存克重须大于0');
|
||||
return { id: row.id, number: row.number, mg };
|
||||
}
|
||||
function usages(q) {
|
||||
const map = new Map();
|
||||
for (const part of q?.exchangeItems ?? (q ? [q] : [])) {
|
||||
const d = part.customerDeposit;
|
||||
if (d) map.set(d.id, (map.get(d.id) || 0) + d.mg);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
function validate(l, q, env, { orderId = null, recoveryId = null } = {}) {
|
||||
const exclude = recoveryId ?? (orderId ? l.one('SELECT id FROM recoveries WHERE order_id=?', orderId)?.id : null);
|
||||
for (const [id, mg] of usages(q)) {
|
||||
const row = record(l, id, env);
|
||||
if (exclude && l.one('SELECT 1 FROM customer_material_origins WHERE recovery_id=? AND deposit_id=?', exclude, id))
|
||||
env.fail('不能在原置换单使用本单产生的寄存余料,请另开置换单', 409);
|
||||
if (row.date > q.date) env.fail('寄存料日期晚于置换日期,请核对', 409);
|
||||
if (mg > remaining(l, id, exclude)) env.fail(row.number + ' 的寄存余料不足,请刷新后减少使用克重', 409);
|
||||
}
|
||||
}
|
||||
function apply(l, id, q, actor, env) {
|
||||
validate(l, q, env, { recoveryId: id });
|
||||
const target = usages(q),
|
||||
old = new Map(
|
||||
l
|
||||
.rows(
|
||||
'SELECT deposit_id,SUM(-delta_mg) AS mg FROM customer_material_events WHERE recovery_id=? AND deposit_id NOT IN (SELECT deposit_id FROM customer_material_origins WHERE recovery_id=?) GROUP BY deposit_id',
|
||||
id,
|
||||
id,
|
||||
)
|
||||
.map(r => [r.deposit_id, r.mg]),
|
||||
);
|
||||
for (const depositId of new Set([...old.keys(), ...target.keys()])) {
|
||||
const delta = (old.get(depositId) || 0) - (target.get(depositId) || 0);
|
||||
if (!delta) continue;
|
||||
l.run(
|
||||
'INSERT INTO customer_material_events VALUES (?,?,?,?,?,?,?,?)',
|
||||
randomUUID(),
|
||||
depositId,
|
||||
id,
|
||||
env.today(),
|
||||
delta,
|
||||
delta > 0 ? '置换取消/更正退回寄存料' : '置换使用寄存料',
|
||||
actor.name,
|
||||
env.now(),
|
||||
);
|
||||
}
|
||||
syncSurplus(l, id, q, actor, env);
|
||||
}
|
||||
// 一张置换单的寄存余料汇总为一笔,保留来源和更正流水。
|
||||
function validateSurplus(l, id, q, env) {
|
||||
const origin = l.one('SELECT * FROM customer_material_origins WHERE recovery_id=?', id);
|
||||
if (!origin) return;
|
||||
const target = q?.depositMg ?? 0,
|
||||
used = origin.mg - remaining(l, origin.deposit_id);
|
||||
const rows = l.rows(
|
||||
'SELECT r.id,r.number,r.date,SUM(-e.delta_mg) AS mg FROM customer_material_events e JOIN recoveries r ON r.id=e.recovery_id WHERE e.deposit_id=? AND e.recovery_id<>? GROUP BY r.id HAVING SUM(-e.delta_mg)>0',
|
||||
origin.deposit_id,
|
||||
id,
|
||||
);
|
||||
if (target < used || (q && rows.some(r => r.date < q.date)))
|
||||
env.fail('本单寄存余料已被置换使用,请先更正用料订单:' + rows.map(r => r.number).join('、'), 409);
|
||||
}
|
||||
function syncSurplus(l, id, q, actor, env) {
|
||||
validateSurplus(l, id, q, env);
|
||||
const target = q?.depositMg ?? 0,
|
||||
origin = l.one('SELECT * FROM customer_material_origins WHERE recovery_id=?', id);
|
||||
const source = l.one('SELECT number FROM recoveries WHERE id=?', id),
|
||||
memo = q
|
||||
? (
|
||||
'置换余料 · ' +
|
||||
source.number +
|
||||
' · ' +
|
||||
q.customer +
|
||||
';' +
|
||||
(q.exchangeItems ?? [q])
|
||||
.map(p => p.surplusMemo || '')
|
||||
.filter(Boolean)
|
||||
.join(';')
|
||||
).slice(0, 240)
|
||||
: '';
|
||||
if (!origin) {
|
||||
if (target) {
|
||||
const made = create(l, { date: q.date, grams: (target / 1000).toFixed(3), memo, verified: true }, actor, env);
|
||||
l.run('INSERT INTO customer_material_origins VALUES (?,?,?)', id, made.id, target);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const delta = target - origin.mg;
|
||||
if (delta)
|
||||
l.run(
|
||||
'INSERT INTO customer_material_events VALUES (?,?,?,?,?,?,?,?)',
|
||||
randomUUID(),
|
||||
origin.deposit_id,
|
||||
id,
|
||||
env.today(),
|
||||
delta,
|
||||
q ? '原置换单更正寄存余料' : '原置换单取消,撤回寄存余料',
|
||||
actor.name,
|
||||
env.now(),
|
||||
);
|
||||
l.run('UPDATE customer_material_origins SET mg=? WHERE recovery_id=?', target, id);
|
||||
if (q) l.run('UPDATE customer_material_deposits SET date=?,memo=? WHERE id=?', q.date, memo, origin.deposit_id);
|
||||
}
|
||||
module.exports = { initialize, list, create, resolve, validate, apply, usages, validateSurplus };
|
||||
@@ -0,0 +1,946 @@
|
||||
'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,
|
||||
};
|
||||
@@ -0,0 +1,959 @@
|
||||
'use strict';
|
||||
// 回收专用更正:身份不变、原流水保留;旧账冲正与新账补记和审批在同一事务中。
|
||||
const { randomUUID, createHash } = require('node:crypto');
|
||||
const Recoveries = require('./recoveries'),
|
||||
Material = require('../materials/material-pools'),
|
||||
Rolling = require('../materials/rolling-material-pools'),
|
||||
TeamFunds = require('../funds/team-funds'),
|
||||
Counts = require('../inventory/inventory-counts');
|
||||
const CreditCardRates = require('../team/credit-card-rates');
|
||||
const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
||||
const yuan = value => (value / 100).toFixed(2),
|
||||
sum = (rows, key) => rows.reduce((n, row) => n + (row[key] ?? 0), 0);
|
||||
function atomic(l, fn) {
|
||||
l.db.exec('SAVEPOINT recovery_change');
|
||||
try {
|
||||
const r = fn();
|
||||
l.db.exec('RELEASE recovery_change');
|
||||
return r;
|
||||
} catch (e) {
|
||||
l.db.exec('ROLLBACK TO recovery_change');
|
||||
l.db.exec('RELEASE recovery_change');
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
function initialize(l) {
|
||||
const columns = l.rows('PRAGMA table_info(recoveries)').map(row => row.name);
|
||||
for (const [name, definition] of Object.entries({
|
||||
status: "TEXT NOT NULL DEFAULT 'active'",
|
||||
cancelled_at: "TEXT NOT NULL DEFAULT ''",
|
||||
updated: "TEXT NOT NULL DEFAULT ''",
|
||||
}))
|
||||
if (!columns.includes(name)) l.db.exec(`ALTER TABLE recoveries ADD COLUMN ${name} ${definition}`);
|
||||
l.db.exec(`CREATE TABLE IF NOT EXISTS recovery_changes(
|
||||
id TEXT PRIMARY KEY,recovery_id TEXT NOT NULL REFERENCES recoveries(id),recovery_revision INTEGER NOT NULL,revision INTEGER NOT NULL DEFAULT 1,
|
||||
action TEXT NOT NULL CHECK(action IN ('update','cancel')),status TEXT NOT NULL CHECK(status IN ('pending','approved','rejected')),
|
||||
reason TEXT NOT NULL,before_value TEXT NOT NULL,after_value TEXT,summary TEXT NOT NULL,dependency TEXT NOT NULL,snapshot TEXT NOT NULL,
|
||||
requester_id TEXT NOT NULL,requester_name TEXT NOT NULL,requester_member TEXT NOT NULL,member 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_recovery_changes_pending ON recovery_changes(recovery_id) WHERE status='pending';`);
|
||||
}
|
||||
function active(actor, env) {
|
||||
if (!actor || !['owner', 'assistant'].includes(actor.role)) env.fail('请使用麦麦或助理账号处理回收记录', 403);
|
||||
}
|
||||
function object(input, env) {
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) env.fail('回收更正内容无效');
|
||||
}
|
||||
function rowFor(l, id, actor, env) {
|
||||
active(actor, env);
|
||||
const row = l.one('SELECT * FROM recoveries WHERE id=?', id);
|
||||
if (!row || (actor.role !== 'owner' && (row.member !== l.memberFor(actor) || !l.canAccess('recovery', id, actor))))
|
||||
env.fail('回收记录不存在或无权访问', 404);
|
||||
if (
|
||||
(row.order_id && !l.canAccess('order', row.order_id, actor)) ||
|
||||
(row.purchase_id && !l.canAccess('material_purchase', row.purchase_id, actor))
|
||||
)
|
||||
env.fail('关联记录不存在或无权访问', 404);
|
||||
if (
|
||||
l.teamMode &&
|
||||
[
|
||||
['recovery', row.id],
|
||||
['order', row.order_id],
|
||||
['material_purchase', row.purchase_id],
|
||||
].some(([kind, id]) => id && l.entityMember(kind, id) !== row.member)
|
||||
)
|
||||
env.fail('回收与关联记录归属不一致,请先核对原关联', 409);
|
||||
return row;
|
||||
}
|
||||
function pending(l, id) {
|
||||
return l.one("SELECT * FROM recovery_changes WHERE recovery_id=? AND status='pending'", id) || null;
|
||||
}
|
||||
function materialHook() {
|
||||
try {
|
||||
return require('./recovery-material');
|
||||
} catch (e) {
|
||||
if (e.code === 'MODULE_NOT_FOUND' && e.message.includes("'./recovery-material'")) return null;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
function usageRows(l, row, after, env) {
|
||||
if (!row.purchase_id) return [];
|
||||
const purchase = l.one('SELECT * FROM material_purchases WHERE id=?', row.purchase_id);
|
||||
if (!purchase || purchase.deleted_at) return [];
|
||||
const personal = materialHook()?.blockedUsages?.(l, purchase.id);
|
||||
if (Array.isArray(personal)) return personal;
|
||||
// 历史共享采购只按原池是否仍有足够金料检查,不把旧来源迁成个人批次。
|
||||
const pool = Material.readPool(l, purchase.pool_id, env, { internal: true });
|
||||
const own = l.rows(
|
||||
'SELECT mg FROM material_pool_usages WHERE order_id=? AND active=1 AND pool_id=?',
|
||||
row.order_id ?? '',
|
||||
purchase.pool_id,
|
||||
);
|
||||
const remainingUsed = pool.usedMg - (!after ? sum(own, 'mg') : 0),
|
||||
newSameDate = after?.date === purchase.pool_id ? after.purchaseMg : 0;
|
||||
const affected = [];
|
||||
if (pool.totalMg - purchase.mg + newSameDate < remainingUsed)
|
||||
affected.push(...pool.usages.filter(usage => usage.active && (!after ? usage.order_id !== row.order_id : true)));
|
||||
if (Rolling.enabled(l))
|
||||
for (const day of l.rows('SELECT date FROM material_rolling_days WHERE date>=? ORDER BY date', purchase.date)) {
|
||||
const current = Rolling.readPool(l, day.date, env, { internal: true, live: true }),
|
||||
delta = (after && after.date <= day.date ? after.purchaseMg : 0) - purchase.mg;
|
||||
if (current.remainingMg + delta < 0)
|
||||
affected.push(
|
||||
...current.usages.filter(usage => usage.active && (!after ? usage.order_id !== row.order_id : true)),
|
||||
);
|
||||
}
|
||||
return [...new Map(affected.map(usage => [usage.id, usage])).values()].map(usage => ({
|
||||
orderId: usage.order_id,
|
||||
number: usage.number,
|
||||
mg: usage.mg,
|
||||
...(usage.price_lock_id ? { priceLockId: usage.price_lock_id } : {}),
|
||||
}));
|
||||
}
|
||||
function visibleUsages(l, rows, actor) {
|
||||
return rows.map(row => {
|
||||
const own = row.priceLockId
|
||||
? l.canAccess('price_lock', row.priceLockId, actor)
|
||||
: row.orderId && l.canAccess('order', row.orderId, actor);
|
||||
return actor.role === 'owner' || own ? row : { mg: row.mg, anonymous: true };
|
||||
});
|
||||
}
|
||||
function blocking(l, row, after, actor, env) {
|
||||
const purchase = row.purchase_id && l.one('SELECT * FROM material_purchases WHERE id=?', row.purchase_id),
|
||||
hook = materialHook();
|
||||
const personal = purchase ? hook?.blockedUsages?.(l, purchase.id) : null;
|
||||
const used = Array.isArray(personal) ? sum(personal, 'mg') : 0;
|
||||
const blocked = Array.isArray(personal)
|
||||
? used > 0 && (!after || after.purchaseMg < used || after.date !== purchase.date)
|
||||
? personal
|
||||
: []
|
||||
: usageRows(l, row, after, env);
|
||||
const rows = visibleUsages(l, blocked, actor);
|
||||
if (after && rows.length) {
|
||||
const error = new Error(
|
||||
'回收金料已有用料,不能移走或减少到低于已用量;关联用料:' +
|
||||
rows.map(r => r.number || r.priceLockId || '其他成员订单').join('、'),
|
||||
);
|
||||
error.status = 409;
|
||||
error.code = 'RECOVERY_MATERIAL_IN_USE';
|
||||
error.blockedUsages = rows;
|
||||
throw error;
|
||||
}
|
||||
return blocked;
|
||||
}
|
||||
function snapshot(l, row) {
|
||||
const order = row.order_id ? l.rawOrder(row.order_id) : null,
|
||||
tables = {};
|
||||
for (const table of ['payments', 'expenses', 'settlements', 'journal'])
|
||||
tables[table] = row.order_id
|
||||
? l.rows('SELECT * FROM ' + table + ' WHERE order_id=? ORDER BY rowid', row.order_id)
|
||||
: [];
|
||||
tables.movements = l.rows(
|
||||
'SELECT * FROM movements WHERE group_id=? OR order_id=? ORDER BY rowid',
|
||||
row.inventory_group,
|
||||
row.order_id ?? '',
|
||||
);
|
||||
const movementCounts = Counts.decorate(l, tables.movements)
|
||||
.filter(row => row.stockCount != null)
|
||||
.map(({ id, stockCount, countEffectiveDate }) => ({ id, stockCount, countEffectiveDate }));
|
||||
if (movementCounts.length) tables.movementCounts = movementCounts;
|
||||
tables.usages = row.order_id
|
||||
? l.rows('SELECT * FROM material_pool_usages WHERE order_id=? ORDER BY rowid', row.order_id)
|
||||
: [];
|
||||
tables.purchase = row.purchase_id ? l.one('SELECT * FROM material_purchases WHERE id=?', row.purchase_id) : null;
|
||||
tables.purchaseSource = row.purchase_id
|
||||
? l.one('SELECT * FROM recovery_purchase_sources WHERE purchase_id=?', row.purchase_id)
|
||||
: null;
|
||||
const customerMaterialOrigin = l.one('SELECT * FROM customer_material_origins WHERE recovery_id=?', row.id);
|
||||
if (customerMaterialOrigin) tables.customerMaterialOrigin = customerMaterialOrigin;
|
||||
const customerMaterialEvents = l.rows(
|
||||
'SELECT * FROM customer_material_events WHERE recovery_id=? ORDER BY rowid',
|
||||
row.id,
|
||||
);
|
||||
if (customerMaterialEvents.length) tables.customerMaterialEvents = customerMaterialEvents;
|
||||
return { record: row, order, ...tables };
|
||||
}
|
||||
function dependency(l, row) {
|
||||
const counts = Counts.snapshot(
|
||||
l,
|
||||
l.pocketCatalog().map(row => row.key),
|
||||
),
|
||||
customerMaterials = l.rows('SELECT id FROM customer_material_events ORDER BY rowid');
|
||||
return hash({
|
||||
snapshot: snapshot(l, row),
|
||||
pool: Rolling.dependency(l),
|
||||
inventory: l.rows('SELECT id,date,pocket,mg FROM movements ORDER BY rowid'),
|
||||
...(customerMaterials.length ? { customerMaterials } : {}),
|
||||
...(counts ? { counts } : {}),
|
||||
});
|
||||
}
|
||||
function compact(q) {
|
||||
return q
|
||||
? Object.fromEntries(
|
||||
[
|
||||
'mode',
|
||||
'date',
|
||||
'oldMg',
|
||||
'newMg',
|
||||
'purchaseMg',
|
||||
'purchaseAmount',
|
||||
'receivable',
|
||||
'cashReceipt',
|
||||
'cashPayment',
|
||||
'offsetAmount',
|
||||
'goodsCost',
|
||||
'directCost',
|
||||
'profit',
|
||||
].map(key => [key, q[key]]),
|
||||
)
|
||||
: null;
|
||||
}
|
||||
function dto(l, row, actor, env) {
|
||||
const current = rowFor(l, row.recovery_id, actor, env),
|
||||
stale =
|
||||
row.status === 'pending' &&
|
||||
(current.revision !== row.recovery_revision || dependency(l, current) !== row.dependency);
|
||||
const summary = JSON.parse(row.summary);
|
||||
summary.blockedUsages = visibleUsages(l, summary.blockedUsages ?? [], actor);
|
||||
return {
|
||||
id: row.id,
|
||||
recoveryId: row.recovery_id,
|
||||
revision: row.revision,
|
||||
recoveryRevision: row.recovery_revision,
|
||||
action: row.action,
|
||||
status: row.status,
|
||||
reason: row.reason,
|
||||
before: JSON.parse(row.before_value),
|
||||
after: row.after_value ? JSON.parse(row.after_value) : null,
|
||||
summary,
|
||||
requesterName: row.requester_name,
|
||||
requesterMember: row.requester_member,
|
||||
member: row.member,
|
||||
created: row.created,
|
||||
reviewerName: row.reviewer_name,
|
||||
reviewed: row.reviewed,
|
||||
note: row.note,
|
||||
stale,
|
||||
canApprove: actor.role === 'owner' && row.status === 'pending' && !stale,
|
||||
};
|
||||
}
|
||||
function projection(l, row, actor, env) {
|
||||
const waiting = pending(l, row.id),
|
||||
belongs = actor?.role === 'owner' || (row.member === l.memberFor(actor) && l.canAccess('recovery', row.id, actor)),
|
||||
enabled = belongs && row.status !== 'cancelled' && !waiting;
|
||||
return {
|
||||
status: row.status ?? 'active',
|
||||
cancelledAt: row.cancelled_at ?? '',
|
||||
canEdit: enabled,
|
||||
canCancel: enabled,
|
||||
pendingRequestId: waiting?.id ?? null,
|
||||
};
|
||||
}
|
||||
function detail(l, id, actor, env) {
|
||||
const row = rowFor(l, id, actor, env),
|
||||
current = JSON.parse(row.data),
|
||||
waiting = pending(l, id),
|
||||
history = l
|
||||
.rows('SELECT * FROM recovery_changes WHERE recovery_id=? ORDER BY created DESC,rowid DESC', id)
|
||||
.filter(r => actor.role === 'owner' || r.requester_id === actor.id);
|
||||
const usages = usageRows(l, row, null, env),
|
||||
enabled = row.status !== 'cancelled' && !waiting;
|
||||
return {
|
||||
id,
|
||||
revision: row.revision,
|
||||
status: row.status,
|
||||
record: Recoveries.detail(l, id, actor, env),
|
||||
inputs: Recoveries.inputFor(current),
|
||||
permissions: {
|
||||
canEdit: enabled,
|
||||
canCancel: enabled,
|
||||
canDirect: enabled && (actor.role === 'owner' || row.date === env.today()),
|
||||
requiresApproval: actor.role === 'assistant' && row.date !== env.today(),
|
||||
...legacyCountInfo(l, row),
|
||||
reason:
|
||||
row.status === 'cancelled'
|
||||
? '本单已经取消'
|
||||
: waiting
|
||||
? '本单有待审批更正'
|
||||
: usages.length
|
||||
? '取消后关联用料改用公共料,公共料不足的订单料费待补;减重或移日仍须先处理关联用料'
|
||||
: '',
|
||||
},
|
||||
blockedUsages: visibleUsages(l, usages, actor),
|
||||
pending: waiting ? dto(l, waiting, actor, env) : null,
|
||||
history: history.filter(r => r.status !== 'pending').map(r => dto(l, r, actor, env)),
|
||||
};
|
||||
}
|
||||
function movements(l, row, after) {
|
||||
const existing = l.rows(
|
||||
'SELECT date,pocket,SUM(mg) AS mg FROM movements WHERE group_id=? OR order_id=? GROUP BY date,pocket HAVING SUM(mg)<>0',
|
||||
row.inventory_group,
|
||||
row.order_id ?? '',
|
||||
);
|
||||
const deltas = existing.map(r => ({ ...r, mg: -r.mg, kind: 'recovery_change_reverse' }));
|
||||
// 对数按自己的生效日净额冲正;旧重量流水没有对数时保持未知,不从克重或工费件数推算。
|
||||
const counts = new Map();
|
||||
for (const movement of Counts.decorate(
|
||||
l,
|
||||
l.rows(
|
||||
'SELECT * FROM movements WHERE group_id=? OR order_id=? ORDER BY rowid',
|
||||
row.inventory_group,
|
||||
row.order_id ?? '',
|
||||
),
|
||||
)) {
|
||||
if (movement.stockCount == null) continue;
|
||||
const key = JSON.stringify([movement.pocket, movement.countEffectiveDate]),
|
||||
value = counts.get(key) ?? { pocket: movement.pocket, date: movement.countEffectiveDate, stockCount: 0 };
|
||||
value.stockCount += movement.stockCount;
|
||||
counts.set(key, value);
|
||||
}
|
||||
for (const count of counts.values())
|
||||
if (count.stockCount) {
|
||||
const matching = deltas.find(
|
||||
movement =>
|
||||
movement.pocket === count.pocket && movement.date === count.date && movement.stockCount === undefined,
|
||||
);
|
||||
if (matching) Object.assign(matching, { stockCount: -count.stockCount, countEffectiveDate: count.date });
|
||||
else
|
||||
deltas.push({
|
||||
...count,
|
||||
mg: 0,
|
||||
stockCount: -count.stockCount,
|
||||
countEffectiveDate: count.date,
|
||||
kind: 'recovery_change_reverse',
|
||||
});
|
||||
}
|
||||
if (after) {
|
||||
for (const old of Recoveries.oldInventory(after))
|
||||
deltas.push({ date: after.date, ...old, kind: 'recovery_change_old' });
|
||||
if (after.mode === 'exchange')
|
||||
for (const product of Recoveries.products(after))
|
||||
if (product.pocket)
|
||||
deltas.push({
|
||||
date: after.date,
|
||||
pocket: product.pocket,
|
||||
mg: -product.quantity,
|
||||
stockCount: product.stockCount == null ? null : -product.stockCount,
|
||||
kind: 'recovery_change_sale',
|
||||
});
|
||||
}
|
||||
return deltas;
|
||||
}
|
||||
function validateInventory(l, deltas, env) {
|
||||
const grouped = new Map();
|
||||
for (const row of [...l.rows('SELECT date,pocket,SUM(mg) AS mg FROM movements GROUP BY date,pocket'), ...deltas]) {
|
||||
const dates = grouped.get(row.pocket) ?? new Map();
|
||||
dates.set(row.date, (dates.get(row.date) ?? 0) + row.mg);
|
||||
grouped.set(row.pocket, dates);
|
||||
}
|
||||
const totals = new Map();
|
||||
for (const [pocket, dates] of grouped) {
|
||||
let mg = 0;
|
||||
for (const [date, delta] of [...dates].sort(([a], [b]) => a.localeCompare(b))) {
|
||||
mg += delta;
|
||||
if (!Number.isSafeInteger(mg) || mg < 0)
|
||||
env.fail(l.pocketLabel(pocket) + '在' + date + '库存不足,不能更正回收记录', 409);
|
||||
}
|
||||
totals.set(pocket, mg);
|
||||
}
|
||||
for (const inventory of l.inventory())
|
||||
if ((totals.get(inventory.pocket) ?? 0) < inventory.reserved)
|
||||
env.fail(l.pocketLabel(inventory.pocket) + '已有预订单占用,不能更正回收库存', 409);
|
||||
l.validateCountInventory(deltas);
|
||||
}
|
||||
function reverseRows(l, id, table, actor, reason, env) {
|
||||
const isPayment = table === 'payments',
|
||||
key = isPayment ? 'account' : 'payer',
|
||||
type = isPayment ? 'payment' : 'expense',
|
||||
label = isPayment ? 'reference' : 'note';
|
||||
const already = new Set(l.rows('SELECT target FROM corrections WHERE type=?', type).map(r => r.target));
|
||||
for (const row of l.rows('SELECT * FROM ' + table + ' WHERE order_id=?', id))
|
||||
if (row.amount > 0 && !already.has(row.id))
|
||||
l.run('INSERT INTO corrections VALUES (?,?,?,?,?)', row.id, type, reason, actor.name, env.now());
|
||||
for (const row of l.rows(
|
||||
`SELECT date,${key}${isPayment ? ',kind' : ''},SUM(amount) AS amount FROM ${table} WHERE order_id=? GROUP BY date,${key}${isPayment ? ',kind' : ''} HAVING SUM(amount)<>0`,
|
||||
id,
|
||||
)) {
|
||||
const newId = randomUUID(),
|
||||
note = '更正冲回:回收专用更正;' + reason;
|
||||
if (isPayment)
|
||||
l.run(
|
||||
'INSERT INTO payments VALUES (?,?,?,?,?,?,?,?,?)',
|
||||
newId,
|
||||
id,
|
||||
row.date,
|
||||
row.kind,
|
||||
-row.amount,
|
||||
row.account,
|
||||
note,
|
||||
actor.name,
|
||||
env.now(),
|
||||
);
|
||||
else
|
||||
l.run(
|
||||
'INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)',
|
||||
newId,
|
||||
id,
|
||||
row.date,
|
||||
-row.amount,
|
||||
row.payer,
|
||||
note,
|
||||
actor.name,
|
||||
env.now(),
|
||||
);
|
||||
if (row.amount < 0)
|
||||
l.run(
|
||||
'INSERT INTO corrections VALUES (?,?,?,?,?)',
|
||||
newId,
|
||||
type,
|
||||
'回收更正对冲行,不是新增收付款或费用',
|
||||
actor.name,
|
||||
env.now(),
|
||||
);
|
||||
}
|
||||
}
|
||||
function purchaseChange(l, row, after, actor, env) {
|
||||
const old = row.purchase_id && l.one('SELECT * FROM material_purchases WHERE id=?', row.purchase_id);
|
||||
if (old) {
|
||||
if (l.teamMode) TeamFunds.activate(l, 'material_purchase', old.id, { legacy: true }, actor, env);
|
||||
if (after?.purchaseMg) {
|
||||
const allocations = [
|
||||
...(after.offsetAmount ? [{ payer: row.member, amount: after.offsetAmount, source: 'offset' }] : []),
|
||||
...(after.cashPayment ? [{ payer: after.payer, amount: after.cashPayment, source: 'cash' }] : []),
|
||||
];
|
||||
if (sum(allocations, 'amount') !== after.purchaseAmount) env.fail('回收购料现金与抵扣不守恒');
|
||||
l.run(
|
||||
"UPDATE material_purchases SET pool_id=?,date=?,mg=?,amount=?,payer=?,deleted_at='',revision=revision+1,updated=? WHERE id=?",
|
||||
after.date,
|
||||
after.date,
|
||||
after.purchaseMg,
|
||||
after.purchaseAmount,
|
||||
after.payer,
|
||||
env.now(),
|
||||
old.id,
|
||||
);
|
||||
l.run(
|
||||
'UPDATE recovery_purchase_sources SET cash_amount=?,offset_amount=?,allocations=? WHERE purchase_id=?',
|
||||
after.cashPayment,
|
||||
after.offsetAmount,
|
||||
JSON.stringify(allocations),
|
||||
old.id,
|
||||
);
|
||||
l.run("INSERT OR IGNORE INTO material_purchase_payment_origins VALUES (?,'purchase')", old.id);
|
||||
} else
|
||||
l.run(
|
||||
'UPDATE material_purchases SET deleted_at=?,revision=revision+1,updated=? WHERE id=?',
|
||||
env.now(),
|
||||
env.now(),
|
||||
old.id,
|
||||
);
|
||||
} else if (after?.purchaseMg) {
|
||||
const allocations = [
|
||||
...(after.offsetAmount ? [{ payer: row.member, amount: after.offsetAmount, source: 'offset' }] : []),
|
||||
...(after.cashPayment ? [{ payer: after.payer, amount: after.cashPayment, source: 'cash' }] : []),
|
||||
];
|
||||
const made = Material.purchase(
|
||||
l,
|
||||
{
|
||||
date: after.date,
|
||||
grams: (after.purchaseMg / 1000).toFixed(3),
|
||||
total: yuan(after.purchaseAmount),
|
||||
payer: after.payer,
|
||||
note: '回收更正 · ' + row.number,
|
||||
},
|
||||
actor,
|
||||
env,
|
||||
{
|
||||
member: row.member,
|
||||
source: {
|
||||
recoveryId: row.id,
|
||||
member: row.member,
|
||||
cashAmount: after.cashPayment,
|
||||
offsetAmount: after.offsetAmount,
|
||||
allocations,
|
||||
},
|
||||
},
|
||||
);
|
||||
l.run('UPDATE recoveries SET purchase_id=? WHERE id=?', made.id, row.id);
|
||||
}
|
||||
return [...new Set([old?.pool_id, after?.purchaseMg ? after.date : null].filter(Boolean))];
|
||||
}
|
||||
function appendOrder(l, row, after, actor, reason, env) {
|
||||
if (!row.order_id) return;
|
||||
const id = row.order_id;
|
||||
if (after) CreditCardRates.capture(l, 'order', id, after.credit_card_rate_permille);
|
||||
reverseRows(l, id, 'payments', actor, reason, env);
|
||||
reverseRows(l, id, 'expenses', actor, reason, env);
|
||||
if (!after) {
|
||||
l.run("UPDATE orders SET status='cancelled',fee_items='[]',reviewed_revision=0 WHERE id=?", id);
|
||||
Material.release(l, l.rawOrder(id), row.date, actor, env, { kind: '回收记录取消释放' });
|
||||
return;
|
||||
}
|
||||
const input = Recoveries.orderInput(after),
|
||||
previous = l.rawOrder(id),
|
||||
lines = l.validateLines(input.lines, previous.lines, after.date, { orderId: id, member: row.member }),
|
||||
line = lines[0];
|
||||
Recoveries.applyOrderMetadata(l, lines, after, row.id, env, id);
|
||||
l.run(
|
||||
"UPDATE orders SET date=?,customer=?,salesperson=?,note=?,lines=?,discount=?,total=?,rounding_mode=?,payment_account=?,fees_date=?,delivered_date=?,fee_items='[]',reviewed_revision=0 WHERE id=?",
|
||||
after.date,
|
||||
after.customer,
|
||||
after.salesperson,
|
||||
after.note,
|
||||
JSON.stringify(lines),
|
||||
after.discount,
|
||||
after.receivable,
|
||||
after.rounding_mode,
|
||||
after.payment_account,
|
||||
after.date,
|
||||
after.date,
|
||||
id,
|
||||
);
|
||||
const fees = [];
|
||||
for (const fee of after.exchange.fee_items) {
|
||||
const expenseId = fee.amount ? randomUUID() : null;
|
||||
if (expenseId)
|
||||
l.run(
|
||||
'INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)',
|
||||
expenseId,
|
||||
id,
|
||||
after.date,
|
||||
fee.amount,
|
||||
fee.payer,
|
||||
fee.note,
|
||||
actor.name,
|
||||
env.now(),
|
||||
);
|
||||
fees.push({ ...fee, status: 'recorded', ...(expenseId ? { expense_id: expenseId } : {}) });
|
||||
}
|
||||
l.run('UPDATE orders SET fee_items=? WHERE id=?', JSON.stringify(fees), id);
|
||||
if (after.cashReceipt) {
|
||||
const payment = {
|
||||
id: randomUUID(),
|
||||
date: after.date,
|
||||
kind: 'receipt',
|
||||
amount: after.cashReceipt,
|
||||
account: after.payment_account,
|
||||
};
|
||||
l.run(
|
||||
'INSERT INTO payments VALUES (?,?,?,?,?,?,?,?,?)',
|
||||
payment.id,
|
||||
id,
|
||||
payment.date,
|
||||
payment.kind,
|
||||
payment.amount,
|
||||
payment.account,
|
||||
'回收更正补记:' + reason,
|
||||
actor.name,
|
||||
env.now(),
|
||||
);
|
||||
l.recordCardFee(id, payment, actor, { payer: 'owner', journal: false });
|
||||
}
|
||||
}
|
||||
function replaceJournal(l, row, after) {
|
||||
if (!row.order_id) return;
|
||||
const id = row.order_id;
|
||||
for (const current of l.rows(
|
||||
'SELECT date,SUM(sales) AS sales,SUM(goods) AS goods,SUM(expense) AS expense FROM journal WHERE order_id=? GROUP BY date',
|
||||
id,
|
||||
))
|
||||
if (current.sales || current.goods || current.expense)
|
||||
l.journal(id, current.date, '回收专用更正冲回', -current.sales, -current.goods, -current.expense);
|
||||
if (after) {
|
||||
const order = l.detail(id);
|
||||
l.journal(
|
||||
id,
|
||||
after.date,
|
||||
'回收专用更正补记',
|
||||
after.receivable,
|
||||
order.goodsCost ?? order.knownGoodsCost,
|
||||
order.directCost,
|
||||
);
|
||||
}
|
||||
l.touch(id);
|
||||
}
|
||||
function financialInput(value) {
|
||||
const { customer, customer_type, salesperson, note, ...rest } = value;
|
||||
return rest;
|
||||
}
|
||||
function inventoryOnlyInput(value) {
|
||||
const { old_pocket, old_stock_count, ...rest } = financialInput(value);
|
||||
if (rest.exchange?.items)
|
||||
rest.exchange = {
|
||||
...rest.exchange,
|
||||
items: rest.exchange.items.map(({ old_pocket, old_stock_count, ...item }) => item),
|
||||
};
|
||||
return rest;
|
||||
}
|
||||
function metadataChangeOnly(row, after) {
|
||||
return (
|
||||
!!after &&
|
||||
hash(financialInput(Recoveries.inputFor(JSON.parse(row.data)))) === hash(financialInput(Recoveries.inputFor(after)))
|
||||
);
|
||||
}
|
||||
function legacyCountInfo(l, row) {
|
||||
const q = JSON.parse(row.data);
|
||||
return Counts.legacyInfo(l, [
|
||||
...Recoveries.products(q)
|
||||
.filter(product => product.stockCount == null)
|
||||
.map(product => ({ id: '', pocket: product.pocket, mg: product.quantity })),
|
||||
...Recoveries.oldInventory(q)
|
||||
.filter(p => p.stockCount == null)
|
||||
.map(p => ({ id: '', pocket: p.pocket, mg: p.mg })),
|
||||
]);
|
||||
}
|
||||
function verifyLegacyCount(l, row, after, input, env) {
|
||||
const info = legacyCountInfo(l, row);
|
||||
if (info.requiresLegacyCountVerified && !metadataChangeOnly(row, after) && input?.legacyCountVerified !== true)
|
||||
env.fail('请核对并确认:' + info.legacyCountNotice);
|
||||
}
|
||||
function execute(l, row, after, actor, reason, env, input = {}) {
|
||||
return Rolling.withHistorical(l, () =>
|
||||
l.scope(
|
||||
null,
|
||||
() => {
|
||||
const before = snapshot(l, row),
|
||||
old = JSON.parse(row.data),
|
||||
metadataOnly =
|
||||
!!after &&
|
||||
hash(financialInput(Recoveries.inputFor(old))) === hash(financialInput(Recoveries.inputFor(after)));
|
||||
const inventoryOnly =
|
||||
!!after &&
|
||||
!metadataOnly &&
|
||||
hash(inventoryOnlyInput(Recoveries.inputFor(old))) === hash(inventoryOnlyInput(Recoveries.inputFor(after)));
|
||||
verifyLegacyCount(l, row, after, input, env);
|
||||
require('./customer-materials').apply(l, row.id, after, actor, env);
|
||||
const deltas = metadataOnly ? [] : movements(l, row, after);
|
||||
validateInventory(l, deltas, env);
|
||||
const changed = l.run(
|
||||
'UPDATE recoveries SET date=?,customer=?,salesperson=?,note=?,old_lines=?,data=?,status=?,cancelled_at=?,updated=?,revision=revision+1 WHERE id=? AND revision=?',
|
||||
after?.date ?? row.date,
|
||||
after?.customer ?? row.customer,
|
||||
after?.salesperson ?? row.salesperson,
|
||||
after?.note ?? row.note,
|
||||
JSON.stringify(after?.old_lines ?? old.old_lines),
|
||||
JSON.stringify(
|
||||
metadataOnly
|
||||
? {
|
||||
...old,
|
||||
customer: after.customer,
|
||||
customer_type: after.customer_type,
|
||||
salesperson: after.salesperson,
|
||||
note: after.note,
|
||||
}
|
||||
: (after ?? old),
|
||||
),
|
||||
after ? 'active' : 'cancelled',
|
||||
after ? '' : env.now(),
|
||||
env.now(),
|
||||
row.id,
|
||||
row.revision,
|
||||
);
|
||||
if (changed.changes !== 1) env.fail('回收记录已有其他更正,请刷新', 409);
|
||||
if (metadataOnly) {
|
||||
if (row.order_id) {
|
||||
l.run(
|
||||
'UPDATE orders SET customer=?,salesperson=?,note=?,reviewed_revision=0 WHERE id=?',
|
||||
after.customer,
|
||||
after.salesperson,
|
||||
after.note,
|
||||
row.order_id,
|
||||
);
|
||||
l.touch(row.order_id);
|
||||
}
|
||||
} else {
|
||||
if (!inventoryOnly) {
|
||||
if (!after && row.purchase_id) materialHook()?.cancelPurchase?.(l, row.purchase_id);
|
||||
appendOrder(l, row, after, actor, reason, env);
|
||||
const pools = purchaseChange(l, row, after, actor, env);
|
||||
if (after && row.order_id) {
|
||||
const order = l.rawOrder(row.order_id);
|
||||
Material.adjust(
|
||||
l,
|
||||
{
|
||||
...order,
|
||||
lines: order.lines.map(line =>
|
||||
line.costMaterial?.mode === 'pool'
|
||||
? { ...line, quantity: line.costMaterial.consumptionMg ?? line.quantity }
|
||||
: line,
|
||||
),
|
||||
},
|
||||
after.date,
|
||||
actor,
|
||||
env,
|
||||
);
|
||||
}
|
||||
for (const pool of pools)
|
||||
Material.reconcile(l, pool, env.today(), actor, env, { skipJournalOrder: row.order_id });
|
||||
if (Rolling.enabled(l))
|
||||
Rolling.rebuildFrom(l, [row.date, after?.date, ...pools].filter(Boolean).sort()[0], actor, env);
|
||||
}
|
||||
for (const movement of deltas) {
|
||||
const id = randomUUID();
|
||||
l.run(
|
||||
'INSERT INTO movements VALUES (?,?,?,?,?,?,?,?,?,?,?)',
|
||||
id,
|
||||
row.inventory_group,
|
||||
row.order_id,
|
||||
movement.date,
|
||||
movement.pocket,
|
||||
movement.mg,
|
||||
movement.kind,
|
||||
'回收更正:' + row.number + ';' + reason,
|
||||
null,
|
||||
actor.name,
|
||||
env.now(),
|
||||
);
|
||||
l.attachMovementCount(id, movement.stockCount, {
|
||||
effectiveDate: movement.countEffectiveDate ?? movement.date,
|
||||
});
|
||||
l.assignMember('movement', id, row.member);
|
||||
}
|
||||
l.validateCountInventory();
|
||||
if (!inventoryOnly) {
|
||||
replaceJournal(l, row, after);
|
||||
const hook = materialHook();
|
||||
hook?.recoveryUpdated?.(l, row.id, actor, env);
|
||||
} else if (
|
||||
row.order_id &&
|
||||
(old.customer !== after.customer || old.salesperson !== after.salesperson || old.note !== after.note)
|
||||
) {
|
||||
l.run(
|
||||
'UPDATE orders SET customer=?,salesperson=?,note=?,reviewed_revision=0 WHERE id=?',
|
||||
after.customer,
|
||||
after.salesperson,
|
||||
after.note,
|
||||
row.order_id,
|
||||
);
|
||||
l.touch(row.order_id);
|
||||
}
|
||||
}
|
||||
if (after && row.order_id)
|
||||
l.run('UPDATE orders SET customer_type=? WHERE id=?', after.customer_type ?? 'unknown', row.order_id);
|
||||
if (metadataOnly) l.run('UPDATE closes SET stale=1 WHERE date IN (?,?)', row.date, after.date);
|
||||
else l.dirtyInventory([row.date, after?.date, ...before.movements.map(r => r.date)].filter(Boolean).sort()[0]);
|
||||
l.syncTeamFunds(actor);
|
||||
if (row.order_id) {
|
||||
const order = l.detail(row.order_id);
|
||||
if (
|
||||
(after &&
|
||||
(order.netReceived !== after.cashReceipt ||
|
||||
order.balance !== 0 ||
|
||||
(order.profit !== null && order.profit !== after.receivable - order.goodsCost - order.directCost))) ||
|
||||
(!after && (order.netReceived !== 0 || order.directCost !== 0 || order.profit !== 0))
|
||||
)
|
||||
env.fail('回收更正后关联订单核对未通过,操作已撤回', 409);
|
||||
}
|
||||
l.audit('recovery:' + row.id, after ? '修改回收/置换记录' : '取消回收/置换记录', actor, {
|
||||
reason,
|
||||
before,
|
||||
after: snapshot(l, l.one('SELECT * FROM recoveries WHERE id=?', row.id)),
|
||||
notice: '原身份与流水保留,追加冲正及补记;不是实际新增收款、退款或重复付款',
|
||||
});
|
||||
return row.id;
|
||||
},
|
||||
null,
|
||||
),
|
||||
);
|
||||
}
|
||||
function normalized(l, row, input, actor, env) {
|
||||
if (input.mode !== row.mode) env.fail('回收方式不能直接互转,请取消原单后新建');
|
||||
if (Object.hasOwn(input, 'member') && input.member !== row.member) env.fail('已有回收记录的归属不能修改', 403);
|
||||
// 历史试算只读;日期许可仍在change/approve决定,不能把试算许可当成落账权限。
|
||||
const previous = JSON.parse(row.data),
|
||||
after = Rolling.withHistorical(l, () =>
|
||||
Recoveries.quote(l, { ...input, member: row.member }, actor, env, {
|
||||
creating: true,
|
||||
orderId: row.order_id,
|
||||
existingRecovery: previous,
|
||||
}),
|
||||
);
|
||||
for (const [index, product] of Recoveries.products(previous).entries())
|
||||
if (product.stockCount == null && l.pocket(product.pocket)?.countUnit === 'pair') {
|
||||
const physical = product =>
|
||||
JSON.stringify([product.name, product.quantity, product.pocket, product.stockCount ?? null]);
|
||||
if (physical(product) !== physical(Recoveries.products(after)[index] ?? {}))
|
||||
env.fail(
|
||||
'启用前已交付的置换新货没有原始对数,只能更正资料和财务;成品变化请先核对实物,再登记今天的数量调整,不能补旧单对数重扣盘点基准',
|
||||
);
|
||||
}
|
||||
for (const [i, old] of Recoveries.oldInventory(previous).entries())
|
||||
if (old.stockCount == null && l.pocket(old.pocket)?.countUnit === 'pair') {
|
||||
const physical = value => JSON.stringify([value?.pocket, value?.mg, value?.stockCount ?? null]);
|
||||
if (physical(old) !== physical(Recoveries.oldInventory(after)[i]))
|
||||
env.fail('启用前的回收旧料没有原始对数,只能更正资料和财务;请先核对实物');
|
||||
}
|
||||
|
||||
return after;
|
||||
}
|
||||
function quote(l, id, input, actor, env) {
|
||||
object(input, env);
|
||||
const row = rowFor(l, id, actor, env);
|
||||
if (row.status === 'cancelled') env.fail('本单已经取消', 409);
|
||||
if (input.revision !== row.revision || !Number.isSafeInteger(input.revision))
|
||||
env.fail('回收记录版本已有变动,请刷新核对', 409);
|
||||
return normalized(l, row, input, actor, env);
|
||||
}
|
||||
function change(l, id, action, input, actor, env) {
|
||||
return atomic(l, () => {
|
||||
object(input, env);
|
||||
const row = rowFor(l, id, actor, env);
|
||||
if (row.status === 'cancelled') env.fail('这笔回收已经取消,不能重复处理', 409);
|
||||
if (!Number.isSafeInteger(input.revision) || input.revision !== row.revision)
|
||||
env.fail('回收记录版本已有变动,请刷新核对', 409);
|
||||
if (pending(l, id)) env.fail('本单已有待审批更正,请先由麦麦处理', 409);
|
||||
if (input.verified !== true) env.fail('请核实关联收付、购料和库存后确认');
|
||||
const reason = env.text(input.reason, '回收更正原因', 200),
|
||||
after = action === 'cancel' ? null : normalized(l, row, input, actor, env),
|
||||
date = after?.date ?? env.day(input.date ?? env.today());
|
||||
verifyLegacyCount(l, row, after, input, env);
|
||||
require('./customer-materials').validateSurplus(l, row.id, after, env);
|
||||
const affected = blocking(l, row, after, actor, env);
|
||||
validateInventory(l, movements(l, row, after), env);
|
||||
const before = Recoveries.inputFor(JSON.parse(row.data)),
|
||||
next = after ? Recoveries.inputFor(after) : null,
|
||||
requestId = randomUUID(),
|
||||
created = env.now(),
|
||||
direct = actor.role === 'owner' || (row.date === env.today() && date === env.today());
|
||||
const summary = {
|
||||
before: compact(Recoveries.detail(l, id, actor, env)),
|
||||
after: compact(after),
|
||||
affectedDates: [...new Set([row.date, date])].sort(),
|
||||
blockedUsages: affected,
|
||||
...legacyCountInfo(l, row),
|
||||
legacyCountVerified: input.legacyCountVerified === true,
|
||||
};
|
||||
l.run(
|
||||
'INSERT INTO recovery_changes(id,recovery_id,recovery_revision,action,status,reason,before_value,after_value,summary,dependency,snapshot,requester_id,requester_name,requester_member,member,created) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
|
||||
requestId,
|
||||
id,
|
||||
row.revision,
|
||||
action,
|
||||
direct ? 'approved' : 'pending',
|
||||
reason,
|
||||
JSON.stringify(before),
|
||||
next ? JSON.stringify(next) : null,
|
||||
JSON.stringify(summary),
|
||||
dependency(l, row),
|
||||
JSON.stringify(snapshot(l, row)),
|
||||
actor.id,
|
||||
actor.name,
|
||||
l.memberFor(actor),
|
||||
row.member,
|
||||
created,
|
||||
);
|
||||
if (direct) {
|
||||
execute(l, row, after, actor, reason, env, input);
|
||||
l.run(
|
||||
'UPDATE recovery_changes SET reviewer_id=?,reviewer_name=?,reviewed=? WHERE id=?',
|
||||
actor.id,
|
||||
actor.name,
|
||||
created,
|
||||
requestId,
|
||||
);
|
||||
} else
|
||||
l.audit('recovery:' + id, action === 'cancel' ? '申请取消回收/置换' : '申请修改回收/置换', actor, {
|
||||
requestId,
|
||||
reason,
|
||||
before,
|
||||
after: next,
|
||||
notice: '审批前不改变有效收付、购料、库存或利润',
|
||||
});
|
||||
return {
|
||||
id,
|
||||
applied: direct,
|
||||
pending: !direct,
|
||||
requestId,
|
||||
request: read(l, requestId, actor, env),
|
||||
recovery: Recoveries.detail(l, id, actor, env),
|
||||
};
|
||||
});
|
||||
}
|
||||
function readRow(l, id, actor, env) {
|
||||
active(actor, env);
|
||||
const row = l.one('SELECT * FROM recovery_changes WHERE id=?', id);
|
||||
if (!row || (actor.role !== 'owner' && row.requester_id !== actor.id)) env.fail('回收更正申请不存在或无权访问', 404);
|
||||
rowFor(l, row.recovery_id, actor, env);
|
||||
return row;
|
||||
}
|
||||
function read(l, id, actor, env) {
|
||||
return dto(l, readRow(l, id, actor, env), actor, env);
|
||||
}
|
||||
function list(l, query, actor, env) {
|
||||
active(actor, env);
|
||||
const status = env.pick(query.status ?? 'pending', ['pending', 'approved', 'rejected', 'all'], '申请状态'),
|
||||
member = l.queryMember(query, actor),
|
||||
rows = l
|
||||
.rows('SELECT * FROM recovery_changes ORDER BY created DESC,rowid DESC')
|
||||
.filter(
|
||||
r =>
|
||||
(actor.role === 'owner' || (r.requester_id === actor.id && r.member === l.memberFor(actor))) &&
|
||||
(!member || r.member === member),
|
||||
);
|
||||
return {
|
||||
requests: rows.filter(r => status === 'all' || r.status === status).map(r => dto(l, r, actor, env)),
|
||||
counts: Object.fromEntries(
|
||||
['pending', 'approved', 'rejected'].map(status => [status, rows.filter(r => r.status === status).length]),
|
||||
),
|
||||
};
|
||||
}
|
||||
function decision(l, id, input, actor, env) {
|
||||
active(actor, env);
|
||||
if (actor.role !== 'owner') env.fail('回收更正申请由麦麦审批', 403);
|
||||
object(input, env);
|
||||
const row = readRow(l, id, actor, env);
|
||||
if (row.status !== 'pending' || input.revision !== row.revision || !Number.isSafeInteger(input.revision))
|
||||
env.fail('申请已经处理或版本已变,请刷新', 409);
|
||||
return row;
|
||||
}
|
||||
function approve(l, id, input, actor, env) {
|
||||
return atomic(l, () => {
|
||||
const request = decision(l, id, input, actor, env),
|
||||
row = rowFor(l, request.recovery_id, actor, env);
|
||||
if (row.revision !== request.recovery_revision || dependency(l, row) !== request.dependency)
|
||||
env.fail('回收关联数据已有变动,申请已过期,请驳回后重新提交', 409);
|
||||
if (input.verified !== true) env.fail('请核实回收更正影响后批准');
|
||||
const after = request.after_value ? normalized(l, row, JSON.parse(request.after_value), actor, env) : null;
|
||||
blocking(l, row, after, actor, env);
|
||||
execute(l, row, after, actor, request.reason, env, {
|
||||
legacyCountVerified: JSON.parse(request.summary).legacyCountVerified === true,
|
||||
});
|
||||
l.run(
|
||||
"UPDATE recovery_changes SET status='approved',revision=revision+1,reviewer_id=?,reviewer_name=?,reviewed=?,note=? WHERE id=? AND status='pending'",
|
||||
actor.id,
|
||||
actor.name,
|
||||
env.now(),
|
||||
env.text(input.note, '审批说明', 200, true),
|
||||
id,
|
||||
);
|
||||
return read(l, id, actor, env);
|
||||
});
|
||||
}
|
||||
function reject(l, id, input, actor, env) {
|
||||
return atomic(l, () => {
|
||||
const request = decision(l, id, input, actor, env),
|
||||
note = env.text(input.note, '驳回原因', 200);
|
||||
l.run(
|
||||
"UPDATE recovery_changes SET status='rejected',revision=revision+1,reviewer_id=?,reviewer_name=?,reviewed=?,note=? WHERE id=?",
|
||||
actor.id,
|
||||
actor.name,
|
||||
env.now(),
|
||||
note,
|
||||
id,
|
||||
);
|
||||
l.audit('recovery:' + request.recovery_id, '驳回回收更正申请', actor, { requestId: id, note });
|
||||
return read(l, id, actor, env);
|
||||
});
|
||||
}
|
||||
module.exports = {
|
||||
initialize,
|
||||
projection,
|
||||
detail,
|
||||
quote,
|
||||
read,
|
||||
list,
|
||||
approve,
|
||||
reject,
|
||||
update: (l, id, input, actor, env) => change(l, id, 'update', input, actor, env),
|
||||
cancel: (l, id, input, actor, env) => change(l, id, 'cancel', input, actor, env),
|
||||
};
|
||||
@@ -0,0 +1,197 @@
|
||||
'use strict';
|
||||
// 每件置换独立计算旧料、差重、单价及来源;仅收付款、优惠和取整整单汇总。
|
||||
const Calc = require('../../public/calculations'),
|
||||
Material = require('../materials/material-pools');
|
||||
const sum = (rows, key) => rows.reduce((n, row) => n + row[key], 0);
|
||||
function quote(l, input, actor, env, options, R) {
|
||||
if (options.creating) {
|
||||
env.text(input.customer, '客户称呼/代号', 60);
|
||||
env.text(input.salesperson, '开单人', 30);
|
||||
}
|
||||
const items = input.exchange.items;
|
||||
if (!Array.isArray(items) || !items.length || items.length > 60) env.fail('请填写1~60件独立置换商品');
|
||||
const parts = items.map((item, i) => {
|
||||
if (
|
||||
!item ||
|
||||
typeof item !== 'object' ||
|
||||
!item.exchange ||
|
||||
item.exchange.items ||
|
||||
item.exchange.products ||
|
||||
(item.old_source !== 'deposit' && (!Array.isArray(item.old_lines) || item.old_lines.length !== 1))
|
||||
)
|
||||
env.fail('第' + (i + 1) + '件置换资料无效');
|
||||
// 内部单件预览不产生收付款,信用卡手续费只按整单实收计算。
|
||||
return R.quote(
|
||||
l,
|
||||
{
|
||||
...input,
|
||||
...item,
|
||||
old_source: item.old_source,
|
||||
deposit_id: item.deposit_id,
|
||||
deposit_weight: item.deposit_weight,
|
||||
old_lines: item.old_lines,
|
||||
old_pocket: item.old_pocket ?? '回收旧料',
|
||||
old_stock_count: item.old_stock_count,
|
||||
buy_rate: item.buy_rate,
|
||||
buy_total: item.buy_total,
|
||||
surplus_mode: item.surplus_mode,
|
||||
surplus_memo: item.surplus_memo,
|
||||
mode: 'exchange',
|
||||
date: input.date,
|
||||
customer: input.customer,
|
||||
salesperson: input.salesperson,
|
||||
member: input.member,
|
||||
note: input.note,
|
||||
payer: input.payer,
|
||||
payment_account: input.payment_account?.endsWith('信用卡') ? '麦麦微信' : input.payment_account,
|
||||
exchange: { ...item.exchange, charges: [], fee_items: [], discount: '0', rounding_mode: 'cent' },
|
||||
},
|
||||
actor,
|
||||
env,
|
||||
{ ...options, creating: false, existingRecovery: options.existingRecovery?.exchangeItems?.[i] ?? null },
|
||||
);
|
||||
});
|
||||
if (
|
||||
options.creating &&
|
||||
parts.some(
|
||||
p =>
|
||||
p.laborCost === null ||
|
||||
(p.differenceMg && !p.exchange.costMaterial.rate && p.exchange.costMaterial.mode !== 'pool'),
|
||||
)
|
||||
)
|
||||
env.fail('请逐件补齐进货工费和差重料费');
|
||||
// 必须一次试算所有用料,避免多件分别试算时重复使用同一笔剩料。
|
||||
const probes = parts.map(p => ({
|
||||
name: p.newProduct.name,
|
||||
unit: 'g',
|
||||
quantity: p.newMg,
|
||||
cost: 0,
|
||||
costParts: { material: p.materialCost, labor: p.laborCost, accessories: 0, other: 0 },
|
||||
costMaterial: p.exchange.costMaterial,
|
||||
}));
|
||||
Material.prepareLines(l, probes, parts[0].date, env, { orderId: options.orderId, member: parts[0].member });
|
||||
for (const [i, p] of parts.entries())
|
||||
if (p.exchange.costMaterial.mode === 'pool') {
|
||||
p.materialCost = probes[i].costParts.material;
|
||||
p.goodsCost = p.materialCost === null || p.laborCost === null ? null : p.materialCost + p.laborCost;
|
||||
if (probes[i].materialPool?.materialSources)
|
||||
p.exchange.costMaterial.materialSources = probes[i].materialPool.materialSources;
|
||||
}
|
||||
const first = parts[0],
|
||||
q = {
|
||||
...first,
|
||||
exchangeItems: parts,
|
||||
newProducts: parts.map(p => ({
|
||||
...p.newProduct,
|
||||
laborMode: p.laborMode,
|
||||
laborRate: p.laborRate,
|
||||
laborAmount: p.laborAmount,
|
||||
costLabor: p.exchange.costLabor,
|
||||
laborCost: p.laborCost,
|
||||
laborPayer: p.exchange.costPayers.labor,
|
||||
})),
|
||||
old_lines: parts.flatMap(p => p.old_lines),
|
||||
payment_account: input.payment_account ?? first.payment_account,
|
||||
};
|
||||
delete q.customerDeposit;
|
||||
delete q.surplusMode;
|
||||
delete q.surplusMemo;
|
||||
if (parts.some(p => p.depositMg)) q.depositMg = parts.reduce((n, p) => n + (p.depositMg || 0), 0);
|
||||
else delete q.depositMg;
|
||||
for (const key of [
|
||||
'oldMg',
|
||||
'newMg',
|
||||
'matchedMg',
|
||||
'differenceMg',
|
||||
'surplusMg',
|
||||
'depreciationMg',
|
||||
'goldAmount',
|
||||
'laborAmount',
|
||||
'depreciationAmount',
|
||||
'purchaseMg',
|
||||
'purchaseAmount',
|
||||
'calculatedPurchaseAmount',
|
||||
])
|
||||
q[key] = sum(parts, key);
|
||||
for (const key of ['materialCost', 'laborCost', 'goodsCost'])
|
||||
q[key] = parts.some(p => p[key] === null) ? null : sum(parts, key);
|
||||
q.charges = Calc.charges(input.exchange.charges ?? []).items;
|
||||
if (q.charges.some(p => p.amount === null)) env.fail('请补齐其他收费');
|
||||
q.chargesAmount = sum(q.charges, 'amount');
|
||||
q.discount = env.money(input.exchange.discount ?? '0', '整单优惠');
|
||||
q.rounding_mode = env.pick(input.exchange.rounding_mode ?? 'yuan', ['cent', 'yuan'], '取整方式');
|
||||
const subtotal = q.goldAmount + q.laborAmount + q.depreciationAmount + q.chargesAmount;
|
||||
if (q.discount > subtotal) env.fail('整单优惠不能超过置换费用');
|
||||
const total =
|
||||
subtotal === q.discount
|
||||
? { total: 0, rounding_adjustment: 0 }
|
||||
: Calc.orderTotal([subtotal], q.discount, q.rounding_mode);
|
||||
q.receivable = total.total;
|
||||
q.rounding_adjustment = total.rounding_adjustment;
|
||||
const fee_items = l.validateFees((input.exchange.fee_items ?? []).map(f => ({ ...f, status: 'estimated' })));
|
||||
if (fee_items.some(f => f.amount === null)) env.fail('请补齐实际费用');
|
||||
q.exchange = { ...first.exchange, fee_items };
|
||||
q.netSettlement = q.receivable - q.purchaseAmount;
|
||||
q.cashReceipt = Math.max(0, q.netSettlement);
|
||||
q.cashPayment = Math.max(0, -q.netSettlement);
|
||||
q.offsetAmount = Math.min(q.receivable, q.purchaseAmount);
|
||||
q.payment_account = env.paymentAccount(q.payment_account, { original: options.existingRecovery?.payment_account });
|
||||
if (q.cashPayment && q.payment_account.endsWith('信用卡')) env.fail('回收付款不支持信用卡');
|
||||
if (
|
||||
options.creating &&
|
||||
q.cashPayment &&
|
||||
require('../funds/team-funds').accountMember(q.payment_account, l) !== q.payer
|
||||
)
|
||||
env.fail('实际付款账户须与回收付款人一致');
|
||||
q.cardFee =
|
||||
q.cashReceipt && q.payment_account.endsWith('信用卡') ? env.cardFee(q.cashReceipt, q.credit_card_rate_permille) : 0;
|
||||
q.directCost = sum(fee_items, 'amount') + q.cardFee;
|
||||
q.profit = q.goodsCost === null ? null : q.receivable - q.goodsCost - q.directCost;
|
||||
q.actualBuyRate = q.purchaseMg
|
||||
? Number((BigInt(q.purchaseAmount) * 1000n + BigInt(q.purchaseMg) / 2n) / BigInt(q.purchaseMg))
|
||||
: null;
|
||||
q.paymentMethods =
|
||||
q.cashReceipt || q.cashPayment ? [require('../funds/team-funds').accountChannel(q.payment_account)] : [];
|
||||
for (const key of [
|
||||
'oldMg',
|
||||
'newMg',
|
||||
'differenceMg',
|
||||
'purchaseAmount',
|
||||
'receivable',
|
||||
'directCost',
|
||||
'goodsCost',
|
||||
'netSettlement',
|
||||
])
|
||||
if (q[key] !== null && (!Number.isSafeInteger(q[key]) || Math.abs(q[key]) > 100000000000))
|
||||
env.fail('置换汇总超出范围');
|
||||
require('./customer-materials').validate(l, q, env, { orderId: options.orderId });
|
||||
return q;
|
||||
}
|
||||
function publicItems(q) {
|
||||
const fields = [
|
||||
'old_lines',
|
||||
'oldMg',
|
||||
'newMg',
|
||||
'matchedMg',
|
||||
'differenceMg',
|
||||
'surplusMg',
|
||||
'depositMg',
|
||||
'surplusMode',
|
||||
'goldRate',
|
||||
'laborRate',
|
||||
'laborMode',
|
||||
'depreciationMg',
|
||||
'depreciationRate',
|
||||
'buyRate',
|
||||
'goldAmount',
|
||||
'laborAmount',
|
||||
'depreciationAmount',
|
||||
'calculatedPurchaseAmount',
|
||||
'purchaseAmount',
|
||||
];
|
||||
return q.exchangeItems.map(p => ({
|
||||
...Object.fromEntries(fields.map(k => [k, p[k]])),
|
||||
newProduct: { name: p.newProduct.name, quantity: p.newMg },
|
||||
}));
|
||||
}
|
||||
module.exports = { quote, publicItems };
|
||||
@@ -0,0 +1,203 @@
|
||||
'use strict';
|
||||
// 只给新回收采购标记个人料来源;既有回收采购没有标记时继续作为历史公共料。
|
||||
const { createHash } = require('node:crypto');
|
||||
const TeamMembers = require('../team/team-members');
|
||||
const exists = (l, table) => !!l.one("SELECT name FROM sqlite_master WHERE type='table' AND name=?", table);
|
||||
function fail(message) {
|
||||
const error = new Error(message);
|
||||
error.status = 409;
|
||||
throw error;
|
||||
}
|
||||
function initialize(l) {
|
||||
l.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS recovery_material_batches(
|
||||
purchase_id TEXT PRIMARY KEY REFERENCES material_purchases(id),recovery_id TEXT NOT NULL REFERENCES recoveries(id),
|
||||
member TEXT NOT NULL,created TEXT NOT NULL);
|
||||
CREATE INDEX IF NOT EXISTS ix_recovery_material_member ON recovery_material_batches(member,purchase_id);
|
||||
`);
|
||||
require('../../core/member-schema').removeMemberCheck(l, 'recovery_material_batches', 'member');
|
||||
}
|
||||
function registerSource(l, purchaseId, { recoveryId, member } = {}) {
|
||||
if (!TeamMembers.keys(l).includes(member)) fail('个人回收料缺少有效业务归属');
|
||||
const purchase = l.one('SELECT id,created FROM material_purchases WHERE id=?', purchaseId),
|
||||
recovery = l.one('SELECT id,member FROM recoveries WHERE id=?', recoveryId);
|
||||
if (!purchase || !recovery || recovery.member !== member) fail('个人回收料与原回收归属不一致');
|
||||
const existing = l.one('SELECT * FROM recovery_material_batches WHERE purchase_id=?', purchaseId);
|
||||
if (existing) {
|
||||
if (existing.recovery_id !== recoveryId || existing.member !== member) fail('已有回收料批次归属不能更换');
|
||||
return false;
|
||||
}
|
||||
l.run('INSERT INTO recovery_material_batches VALUES (?,?,?,?)', purchaseId, recoveryId, member, purchase.created);
|
||||
return true;
|
||||
}
|
||||
function purchaseSource(l, purchaseId) {
|
||||
if (!exists(l, 'recovery_material_batches')) return null;
|
||||
const row = l.one('SELECT recovery_id,member FROM recovery_material_batches WHERE purchase_id=?', purchaseId);
|
||||
return row ? { materialOwner: row.member, materialKind: 'personal_recovery', recoveryId: row.recovery_id } : null;
|
||||
}
|
||||
function sources(value) {
|
||||
if (value === undefined || value === null || value === '') return [];
|
||||
const result = typeof value === 'string' ? JSON.parse(value) : value;
|
||||
if (!Array.isArray(result)) fail('回收料批次追溯资料无效');
|
||||
return result;
|
||||
}
|
||||
function batches(value) {
|
||||
const totals = new Map();
|
||||
for (const source of sources(value))
|
||||
for (const batch of source.batches ?? []) {
|
||||
if (typeof batch.purchaseId !== 'string' || !Number.isSafeInteger(batch.mg) || batch.mg < 0)
|
||||
fail('回收料批次追溯克重无效');
|
||||
totals.set(batch.purchaseId, (totals.get(batch.purchaseId) || 0) + batch.mg);
|
||||
}
|
||||
return totals;
|
||||
}
|
||||
function lockBatches(l, lockId, snapshot, lineIndex = 0) {
|
||||
const result = batches(snapshot.materialSources);
|
||||
if (exists(l, 'material_return_sources'))
|
||||
for (const returned of l.rows(
|
||||
"SELECT s.sources FROM material_return_sources s JOIN price_lock_pool_returns r ON s.return_kind='lock' AND s.return_id=r.id WHERE r.price_lock_id=? AND r.line_index=? ORDER BY r.rowid",
|
||||
lockId,
|
||||
lineIndex,
|
||||
))
|
||||
for (const [purchaseId, mg] of batches(returned.sources))
|
||||
result.set(purchaseId, (result.get(purchaseId) || 0) - mg);
|
||||
for (const mg of result.values()) if (mg < 0) fail('锁价回收料耗用与回料克重不一致,请先核对料池');
|
||||
return result;
|
||||
}
|
||||
function blockedUsages(l, purchaseId) {
|
||||
if (!purchaseSource(l, purchaseId)) return null;
|
||||
const result = new Map();
|
||||
const add = (key, row) => {
|
||||
if (!row.mg) return;
|
||||
const previous = result.get(key);
|
||||
result.set(key, previous ? { ...previous, mg: previous.mg + row.mg } : row);
|
||||
};
|
||||
if (exists(l, 'material_usage_sources'))
|
||||
for (const row of l.rows(
|
||||
'SELECT u.order_id,u.line_index,o.number,s.sources FROM material_usage_sources s JOIN material_pool_usages u ON u.id=s.usage_id JOIN orders o ON o.id=u.order_id WHERE u.active=1 AND instr(s.sources,?)>0 ORDER BY u.created,u.rowid',
|
||||
purchaseId,
|
||||
)) {
|
||||
let mg = batches(row.sources).get(purchaseId) || 0;
|
||||
// 一体售后保留原耗用以锁定历史成本;实物已回流的批次不能仍作为第二份已用量。
|
||||
if (
|
||||
exists(l, 'order_after_sales') &&
|
||||
l.one('SELECT order_id FROM order_after_sales WHERE order_id=?', row.order_id)
|
||||
)
|
||||
for (const returned of l.rows(
|
||||
"SELECT s.sources FROM material_return_sources s JOIN material_rolling_returns r ON s.return_kind='order' AND s.return_id=r.id WHERE r.order_id=? AND r.line_index=?",
|
||||
row.order_id,
|
||||
row.line_index,
|
||||
))
|
||||
mg -= batches(returned.sources).get(purchaseId) || 0;
|
||||
if (mg < 0) fail('售后退回批次超过原实际耗用,请先核对原单与回料');
|
||||
add('order:' + row.order_id, { orderId: row.order_id, number: row.number, mg });
|
||||
}
|
||||
if (exists(l, 'price_lock_pool_reservations'))
|
||||
for (const row of l.rows(
|
||||
'SELECT r.id AS reservation_id,r.line_index,r.snapshot,p.id,p.final_order_id,p.number FROM price_lock_pool_reservations r JOIN price_locks p ON p.id=r.price_lock_id WHERE instr(r.snapshot,?)>0 ORDER BY r.created,r.rowid',
|
||||
purchaseId,
|
||||
))
|
||||
add('lock:' + row.id, {
|
||||
orderId: row.final_order_id ?? null,
|
||||
number: row.number,
|
||||
mg: lockBatches(l, row.id, JSON.parse(row.snapshot), row.line_index).get(purchaseId) || 0,
|
||||
priceLockId: row.id,
|
||||
});
|
||||
return [...result.values()];
|
||||
}
|
||||
function purchaseStatus(l, purchaseId) {
|
||||
const source = purchaseSource(l, purchaseId);
|
||||
if (!source) return null;
|
||||
const purchase = l.one('SELECT mg,deleted_at FROM material_purchases WHERE id=?', purchaseId);
|
||||
if (!purchase) return null;
|
||||
const usages = blockedUsages(l, purchaseId),
|
||||
usedMg = usages.reduce((total, row) => total + row.mg, 0);
|
||||
if (usedMg > purchase.mg) fail('回收批次耗用超过原克重,请先核对料池');
|
||||
return {
|
||||
purchaseId,
|
||||
recoveryId: source.recoveryId,
|
||||
member: source.materialOwner,
|
||||
mg: purchase.mg,
|
||||
usedMg,
|
||||
remainingMg: purchase.deleted_at ? 0 : purchase.mg - usedMg,
|
||||
usages,
|
||||
};
|
||||
}
|
||||
function cancelPurchase(l, purchaseId) {
|
||||
if (!purchaseSource(l, purchaseId)) return;
|
||||
const allocation = require('../materials/material-pool-allocation');
|
||||
// 包含已退回的历史头尾段;重建原日及后续回料时,不能让已取消批次重新流入个人池。
|
||||
for (const row of l.rows(
|
||||
'SELECT u.id,s.sources FROM material_usage_sources s JOIN material_pool_usages u ON u.id=s.usage_id WHERE instr(s.sources,?)>0 ORDER BY u.rowid',
|
||||
purchaseId,
|
||||
))
|
||||
allocation.substitutePurchase(l, 'order', row.id, purchaseId, sources(row.sources));
|
||||
for (const row of l.rows(
|
||||
'SELECT id,snapshot FROM price_lock_pool_reservations WHERE instr(snapshot,?)>0 ORDER BY rowid',
|
||||
purchaseId,
|
||||
))
|
||||
allocation.substitutePurchase(
|
||||
l,
|
||||
'priceLock',
|
||||
row.id,
|
||||
purchaseId,
|
||||
sources(JSON.parse(row.snapshot).materialSources),
|
||||
);
|
||||
}
|
||||
function dependency(l) {
|
||||
if (!exists(l, 'recovery_material_batches') || !l.one('SELECT purchase_id FROM recovery_material_batches LIMIT 1'))
|
||||
return null;
|
||||
const names = ['recovery_material_batches', 'material_usage_sources', 'material_return_sources'].filter(name =>
|
||||
exists(l, name),
|
||||
);
|
||||
if (
|
||||
exists(l, 'material_public_substitutions') &&
|
||||
l.one('SELECT source_id FROM material_public_substitutions LIMIT 1')
|
||||
)
|
||||
names.push('material_public_substitutions');
|
||||
return createHash('sha256')
|
||||
.update(JSON.stringify(names.map(name => [name, l.rows('SELECT * FROM ' + name + ' ORDER BY rowid')])))
|
||||
.digest('hex');
|
||||
}
|
||||
function ownershipReason(l, order, target = null, env) {
|
||||
if (!exists(l, 'recovery_material_batches') || !l.one('SELECT purchase_id FROM recovery_material_batches LIMIT 1'))
|
||||
return '';
|
||||
const usages = exists(l, 'material_usage_sources')
|
||||
? l.rows(
|
||||
'SELECT u.pool_id,s.sources FROM material_pool_usages u JOIN material_usage_sources s ON s.usage_id=u.id WHERE u.order_id=? AND u.active=1',
|
||||
order.id,
|
||||
)
|
||||
: [];
|
||||
const dates = new Set(usages.map(row => row.pool_id));
|
||||
let personal = usages.some(row =>
|
||||
sources(row.sources).some(source => source.kind === 'personal_recovery' && source.quantity > 0),
|
||||
);
|
||||
const reservations = l.rows(
|
||||
'SELECT r.*,p.id AS lock_id FROM price_lock_pool_reservations r JOIN price_locks p ON p.id=r.price_lock_id WHERE p.final_order_id=?',
|
||||
order.id,
|
||||
);
|
||||
for (const reservation of reservations) {
|
||||
dates.add(reservation.pool_id);
|
||||
const net = lockBatches(l, reservation.lock_id, JSON.parse(reservation.snapshot), reservation.line_index);
|
||||
personal ||= [...net].some(([id, mg]) => mg > 0 && purchaseSource(l, id));
|
||||
}
|
||||
if (!personal && target)
|
||||
for (const date of dates) {
|
||||
const pool = require('../materials/material-pools').readPool(l, date, env, { internal: true });
|
||||
if (pool.personalPools?.[target]?.totalMg > 0) {
|
||||
personal = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return personal ? '本单涉及个人回收料,不能直接转给其他归属人;请先更正用料并释放个人料占用,再调整归属。' : '';
|
||||
}
|
||||
module.exports = {
|
||||
initialize,
|
||||
registerSource,
|
||||
purchaseSource,
|
||||
blockedUsages,
|
||||
purchaseStatus,
|
||||
cancelPurchase,
|
||||
dependency,
|
||||
ownershipReason,
|
||||
};
|
||||
Reference in new issue
Block a user