Files
weiguang-jewelry-ledger/新账系统/public/calculations.js
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

477 lines
22 KiB
JavaScript
Raw Normal View History

'use strict';
// 浏览器预览和服务器记账共用整数算法;每行销售额最后统一四舍五入到分。
(function (root) {
const validMember = value =>
['owner', 'assistant', 'assistant2'].includes(value) ||
/^staff_[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value);
function fixed(value, places, name) {
const s = String(value ?? '').trim();
if (!new RegExp('^\\d+(?:\\.\\d{1,' + places + '})?$').test(s))
throw new Error(name + '须为非负数字,最多' + places + '位小数');
const [a, b = ''] = s.split('.'),
n = BigInt(a) * 10n ** BigInt(places) + BigInt(b.padEnd(places, '0'));
if (n > 100000000000n) throw new Error(name + '超出支持范围');
return n;
}
function cents(v, name = '金额') {
return Number(fixed(v, 2, name));
}
const isSilver = name => ['足银999', '纯银925'].includes(name);
function charges(raw = []) {
if (!Array.isArray(raw) || raw.length > 100) throw new Error('每行最多填写100项附加项目');
const items = [];
let total = 0;
for (const item of raw) {
if (!item || typeof item !== 'object') throw new Error('附加项目格式无效');
const id = item.id == null ? '' : String(item.id);
if (id && !/^[a-f0-9-]{36}$/.test(id)) throw new Error('附加项目标识无效');
if (item.costRemoved !== undefined && typeof item.costRemoved !== 'boolean')
throw new Error('内部成本移除标记无效');
const blank = item.amount == null || item.amount === '';
const name = String(item.name ?? '').trim();
if (blank && (!id || !name)) continue;
if (!name || name.length > 40) throw new Error('附加项目名称须为1~40字');
const amount = blank ? null : cents(item.amount, '附加项目金额');
items.push({ ...(id ? { id } : {}), name, amount, ...(item.costRemoved === true ? { costRemoved: true } : {}) });
total += amount || 0;
}
if (total > 100000000000) throw new Error('附加项目合计超出支持范围');
return { items, total };
}
function sale(line) {
const pricing = line.pricingMode === 'auto' ? calculate(line) : null;
const baseSale = pricing ? pricing.sale : cents(line.baseSale ?? line.sale, '商品基础金额');
const extra = charges(line.charges);
const total = baseSale + extra.total;
if (total > 100000000000) throw new Error('本行销售额超出支持范围');
return { ...(pricing || {}), baseSale, charges: extra.items, chargesTotal: extra.total, sale: total };
}
function orderTotal(lineAmounts, discount = 0, roundingMode = 'yuan') {
const limit = 100000000000n;
if (!Array.isArray(lineAmounts) || lineAmounts.length < 1 || lineAmounts.length > 60)
throw new Error('每单需要1~60行商品');
if (!['yuan', 'cent'].includes(roundingMode)) throw new Error('整单金额取整方式无效');
if (!Number.isSafeInteger(discount) || discount < 0 || BigInt(discount) > limit)
throw new Error('整单优惠须为范围内的非负整数分');
let subtotal = 0n;
for (const amount of lineAmounts) {
if (!Number.isSafeInteger(amount) || amount < 0 || BigInt(amount) > limit)
throw new Error('商品行金额须为范围内的非负整数分');
subtotal += BigInt(amount);
}
if (subtotal > limit) throw new Error('整单销售合计超出支持范围');
const unroundedTotal = subtotal - BigInt(discount);
if (unroundedTotal <= 0n) throw new Error('优惠后成交额必须大于0');
// 所有商品和附加项先合计、再减优惠,整张订单只四舍五入一次。
const total = roundingMode === 'yuan' ? ((unroundedTotal + 50n) / 100n) * 100n : unroundedTotal;
if (total <= 0n) throw new Error('整单四舍五入后成交额必须大于0元,请核对销售金额');
if (total > limit) throw new Error('整单销售合计超出支持范围');
return {
subtotal: Number(subtotal),
discount,
unroundedTotal: Number(unroundedTotal),
total: Number(total),
rounding_mode: roundingMode,
rounding_adjustment: Number(total - unroundedTotal),
};
}
function calculate(line) {
if (line.unit !== 'g') throw new Error('按金价计算需要填写克重;按件报价请选择直接填金额');
const mg = fixed(line.quantity, 3, '克重');
if (mg <= 0n) throw new Error('克重必须大于0');
const gold = fixed(line.goldPrice, 2, '金价'),
labor = fixed(line.laborRate, 2, '销售工费');
if (!['gram', 'piece'].includes(line.laborMode)) throw new Error('请选择克工费或件工费');
let pieces = 1n;
if (line.laborMode === 'piece') {
if (!/^\d+$/.test(String(line.pieces ?? '1'))) throw new Error('件数须为正整数');
pieces = BigInt(line.pieces ?? 1);
if (pieces < 1n || pieces > 1000000n) throw new Error('件数须为1~1000000的整数');
}
const numerator = mg * gold + (line.laborMode === 'gram' ? mg * labor : pieces * labor * 1000n);
const result = (numerator + 500n) / 1000n;
if (result > 100000000000n) throw new Error('本行销售额超出支持范围');
return {
sale: Number(result),
goldPrice: Number(gold),
laborRate: Number(labor),
laborMode: line.laborMode,
pieces: Number(pieces),
};
}
const costLabels = { material: '料费成本', labor: '进货工费', accessories: '配件成本', other: '其他货品成本' };
function costPayers(raw) {
// 旧行不补写分项付款人;显式传入时必须完整、有效,不能把无效值当作缺省。
if (raw === undefined) return undefined;
if (
!raw ||
typeof raw !== 'object' ||
Array.isArray(raw) ||
Object.keys(raw).some(key => !['material', 'labor'].includes(key))
)
throw new Error('料费和进货工费付款人无效');
for (const key of ['material', 'labor'])
if (!Object.hasOwn(raw, key) || !validMember(raw[key])) throw new Error(costLabels[key] + '付款人无效');
return { material: raw.material, labor: raw.labor };
}
function costs(raw) {
const parts = {};
let total = 0,
missing = false;
for (const [k, label] of Object.entries(costLabels)) {
parts[k] = raw?.[k] == null || raw[k] === '' ? null : cents(raw[k], label);
if (parts[k] === null) missing = true;
else total += parts[k];
}
if (total > 100000000000) throw new Error('货品成本超出支持范围');
return { parts, total: missing ? null : total };
}
function purchaseCosts(line) {
const parts = { ...line.costParts };
const perGram = (key, metadata, rateLabel, totalLabel, modeError, unitError) => {
// 旧单没有计价元数据时,原分项金额始终是总额,不能再乘克重。
const mode = metadata?.mode || 'total';
if (!['gram', 'total'].includes(mode)) throw new Error(modeError);
const result = { mode };
if (mode === 'gram') {
if (line.unit !== 'g') throw new Error(unitError);
const raw = metadata?.rate,
rate = raw == null || raw === '' ? null : fixed(raw, 2, rateLabel);
result.rate = rate === null ? null : Number(rate);
if (rate === null) parts[key] = '';
else {
const mg = fixed(line.quantity, 3, '克重');
if (mg <= 0n) throw new Error('克重必须大于0');
const total = (mg * rate + 500n) / 1000n;
if (total > 100000000000n) throw new Error(totalLabel + '超出支持范围');
parts[key] = `${total / 100n}.${String(total % 100n).padStart(2, '0')}`;
}
}
return result;
};
2026-10-21 01:32:49 +08:00
let costMaterial;
if (line.costMaterial?.mode === 'pool') {
if (line.unit !== 'g' || isSilver(line.name)) throw new Error('日购料成本只支持按克黄金商品');
const poolId = String(line.costMaterial.poolId ?? '');
if (!/^\d{4}-\d{2}-\d{2}$/.test(poolId)) throw new Error('请选择日购料日期');
costMaterial = { mode: 'pool', poolId };
const previewAmount = line.materialPool?.amount;
parts.material =
Number.isSafeInteger(previewAmount) && previewAmount >= 0 ? (previewAmount / 100).toFixed(2) : '';
} else
costMaterial = perGram(
'material',
line.costMaterial,
'进货料价',
'料费总成本',
'请选择每克料价或料费总成本',
'每克料价需要克重,按件商品请填写料费总成本',
);
const costLabor = perGram(
'labor',
line.costLabor,
'进货克工费',
'进货总工费',
'请选择进货克工费或总工费',
'进货克工费需要克重,按件商品请填写总工费',
);
return { ...costs(parts), costMaterial, costLabor };
}
2026-10-21 01:32:49 +08:00
// 先用实际总金额与总毫克计算,展示用均价不可参与成本分摊。
function poolMaterialAmount(totalAmount, totalMg, quantityMg) {
for (const value of [totalAmount, totalMg, quantityMg])
if (!Number.isSafeInteger(value) || value < 0 || value > 100000000000) throw new Error('日购料金额或克重无效');
if (!totalMg) throw new Error('日购料尚未登记克重');
const amount = (BigInt(totalAmount) * BigInt(quantityMg) + BigInt(totalMg) / 2n) / BigInt(totalMg);
if (amount > 100000000000n) throw new Error('日购料成本超出支持范围');
return Number(amount);
}
// 同池先按完整耗用顺序累计取整,再取相邻差额;编辑沿用原行身份,新增行追加。
function poolMaterialPreview(pool, entries, { orderId = null, allUsages = pool.usages || [] } = {}) {
const valid = value => Number.isSafeInteger(value) && value >= 0 && value <= 100000000000;
if (
!valid(pool.totalAmount) ||
!valid(pool.totalMg) ||
!Array.isArray(entries) ||
!Array.isArray(pool.usages) ||
!Array.isArray(allUsages)
)
throw new Error('日购料预估记录无效,请刷新料价');
const indices = new Set();
for (const entry of entries) {
if (
!Number.isSafeInteger(entry.lineIndex) ||
entry.lineIndex < 0 ||
indices.has(entry.lineIndex) ||
!valid(entry.mg) ||
!entry.mg
)
throw new Error('日购料预估克重或商品行无效');
indices.add(entry.lineIndex);
}
const originals = orderId ? allUsages.filter(usage => usage.order_id === orderId) : [];
const usages = pool.usages
.filter(usage => usage.active && (!orderId || usage.order_id !== orderId))
.map(usage => ({ ...usage }));
const usedMg = usages.reduce((total, usage) => total + usage.mg, 0),
wantedMg = entries.reduce((total, entry) => total + entry.mg, 0);
const covered = pool.totalMg > 0 && usedMg + wantedMg <= pool.totalMg,
amounts = Object.fromEntries(entries.map(entry => [entry.lineIndex, null]));
for (const entry of entries) {
const original = originals.find(usage => usage.line_index === entry.lineIndex);
usages.push({ ...original, mg: entry.mg, previewIndex: entry.lineIndex, appended: !original });
}
for (const usage of usages) {
if (
!valid(usage.mg) ||
!usage.mg ||
(!usage.appended &&
(!Number.isSafeInteger(usage.fifo_sequence) ||
usage.fifo_sequence < 1 ||
typeof usage.created !== 'string' ||
!usage.created))
)
throw new Error('日购料耗用顺序尚未读到,请刷新料价');
}
usages.sort(
(a, b) =>
Number(!!a.appended) - Number(!!b.appended) ||
(a.appended
? a.previewIndex - b.previewIndex
: a.created < b.created
? -1
: a.created > b.created
? 1
: a.fifo_sequence - b.fifo_sequence),
);
if (covered) {
let cumulativeMg = 0,
previousAmount = 0;
for (const usage of usages) {
cumulativeMg += usage.mg;
const cumulativeAmount = poolMaterialAmount(pool.totalAmount, pool.totalMg, cumulativeMg);
if (usage.previewIndex !== undefined) amounts[usage.previewIndex] = cumulativeAmount - previousAmount;
previousAmount = cumulativeAmount;
}
}
return { amounts, usedMg, wantedMg, covered };
}
2026-10-21 01:32:49 +08:00
function priceLockCost(input) {
const locked = fixed(input.lockedQuantity, 3, '锁定克重'),
actual = fixed(input.quantity, 3, '实际克重');
const originalRate = fixed(input.buyRate, 2, '原进货料价');
if (locked <= 0n || actual <= 0n) throw new Error('锁定克重和实际克重必须大于0');
if (originalRate <= 0n) throw new Error('原进货料价必须大于0');
const used = actual < locked ? actual : locked,
extra = actual > locked ? actual - locked : 0n;
const extraRate = extra ? fixed(input.extraBuyRate, 2, '补重进货料价') : 0n;
if (extra && extraRate <= 0n) throw new Error('补重进货料价必须大于0');
const amount = (quantity, rate) => (quantity * rate + 500n) / 1000n;
const originalPurchase = amount(locked, originalRate),
originalUsedCost = amount(used, originalRate),
extraCost = amount(extra, extraRate);
if ([originalPurchase, originalUsedCost + extraCost].some(value => value > 100000000000n))
throw new Error('锁价料费成本超出支持范围');
return {
lockedMg: Number(locked),
finalMg: Number(actual),
originalUsedMg: Number(used),
extraMg: Number(extra),
leftoverMg: Number(locked - used),
originalPurchase: Number(originalPurchase),
originalUsedCost: Number(originalUsedCost),
extraCost: Number(extraCost),
materialCost: Number(originalUsedCost + extraCost),
leftoverCost: Number(originalPurchase - originalUsedCost),
};
}
// 订单内部对账用,输入为账本已保存的整数分;预估费用与实际支出分开。
function orderCosts(order) {
const empty = () => ({
goods: 0,
goodsMissing: 0,
paidFees: 0,
pendingFees: 0,
pendingMissing: 0,
total: 0,
missing: 0,
});
const byPayer = { owner: empty(), assistant: empty(), assistant2: empty() },
rows = [];
const goodsExcluded = ['returned', 'cancelled'].includes(order.status);
const add = row => {
rows.push(row);
if (row.excluded) return;
if (!validMember(row.payer)) throw new Error('成本付款人无效');
const s = byPayer[row.payer] || (byPayer[row.payer] = empty());
if (row.kind === 'goods') {
if (row.amount == null) s.goodsMissing++;
else s.goods += row.amount;
}
if (row.kind === 'paid') s.paidFees += row.amount;
if (row.kind === 'pending') {
if (row.amount == null) s.pendingMissing++;
else s.pendingFees += row.amount;
}
};
for (const [i, line] of order.lines.entries()) {
const payers = costPayers(line.costPayers);
const parts = line.costParts
? Object.entries(costLabels).map(([key, name]) => ({ key, name, amount: line.costParts[key] ?? null }))
: [{ key: 'total', name: '货品成本(原单未分项)', amount: line.cost ?? null }];
2026-10-21 01:32:49 +08:00
for (const part of parts) {
if (part.key === 'material' && (line.priceLockPool || line.priceLockExtraPool) && part.amount === null) {
add({
kind: 'goods',
component: 'material',
name: part.name,
source: '锁价料池成本待补',
amount: null,
payer: payers?.material ?? line.payer,
excluded: goodsExcluded,
materialPoolId: (line.priceLockExtraPool?.amount === null
? line.priceLockExtraPool
: line.priceLockPool || line.priceLockExtraPool
).poolId,
poolPending: true,
calculation: null,
});
} else if (part.key === 'material' && line.costMaterial?.mode === 'pool') {
2026-10-21 01:32:49 +08:00
const pool = line.materialPool,
allocations = pool?.allocations;
if (part.amount === null || !allocations?.length) {
add({
kind: 'goods',
component: 'material',
name: part.name,
source: `商品 ${i + 1} · ${line.name} · ${line.costMaterial.poolId}日购料待补`,
amount: null,
payer: payers?.material ?? line.payer,
excluded: goodsExcluded,
materialPoolId: line.costMaterial.poolId,
materialPoolRevision: pool?.revision,
poolPending: true,
calculation: null,
});
} else {
if (
!Array.isArray(allocations) ||
allocations.some(
item => !validMember(item.payer) || !Number.isSafeInteger(item.amount) || item.amount < 0,
) ||
allocations.reduce((total, item) => total + item.amount, 0) !== part.amount
)
throw new Error('日购料分项成本记录无效');
for (const item of allocations)
add({
kind: 'goods',
component: 'material',
name: part.name,
source: `商品 ${i + 1} · ${line.name} · ${line.costMaterial.poolId}日购料`,
amount: item.amount,
payer: item.payer,
excluded: goodsExcluded,
materialPoolId: line.costMaterial.poolId,
materialPoolRevision: pool?.revision,
calculation: { rate: pool.averageRate, quantity: pool.quantity ?? line.quantity, weighted: true },
});
2026-10-21 01:32:49 +08:00
}
} else if (part.key === 'material' && line.materialAllocations) {
const allocations = line.materialAllocations;
if (
!Array.isArray(allocations) ||
!allocations.length ||
allocations.some(
item =>
!['original', 'extra'].includes(item.source) ||
!validMember(item.payer) ||
!Number.isSafeInteger(item.amount) ||
item.amount < 0 ||
!Number.isSafeInteger(item.quantity) ||
item.quantity <= 0 ||
!Number.isSafeInteger(item.rate) ||
item.rate <= 0,
) ||
allocations.reduce((total, item) => total + item.amount, 0) !== part.amount
)
throw new Error('锁价分项料费记录无效');
for (const item of allocations)
add({
kind: 'goods',
component: 'material',
name: part.name,
source: `商品 ${i + 1} · ${line.name} · ${item.source === 'original' ? (item.weighted ? '原锁日料池' : '原锁价采购') : item.weighted ? '交付日补重料池' : '补重采购'}`,
amount: item.amount,
payer: item.payer,
excluded: goodsExcluded,
priceLockSource: item.source,
...(item.poolId ? { materialPoolId: item.poolId } : {}),
calculation: { rate: item.rate, quantity: item.quantity, ...(item.weighted ? { weighted: true } : {}) },
});
} else
add({
kind: 'goods',
name: part.name,
source:
`商品 ${i + 1} · ${line.name}` +
(part.key === 'labor' && line.returnedStock ? ' · 退回现货继承工费' : ''),
amount: part.amount,
payer: payers?.[part.key] ?? line.payer,
excluded: goodsExcluded,
...(part.key === 'labor' && line.returnedStock
? { inheritedStockCost: true, returnedStockId: line.returnedStockId }
: {}),
calculation:
part.key === 'material' && line.recovery_id && line.costMaterial?.rate !== undefined
? { rate: line.costMaterial.rate, quantity: line.recoveryMaterialMg }
: part.key === 'material' && line.costMaterial?.mode === 'gram'
? { rate: line.costMaterial.rate, quantity: line.quantity }
: part.key === 'labor' && line.costLabor?.mode === 'gram'
? { rate: line.costLabor.rate, quantity: line.quantity }
: null,
});
2026-10-21 01:32:49 +08:00
}
}
// 原费用与冲回行成对抵消,只列最新有效支出,保留原流水供追溯。
const corrected = new Set((order.corrections || []).filter(c => c.type === 'expense').map(c => c.target));
for (const fee of order.expenses || [])
if (fee.amount > 0 && !corrected.has(fee.id))
add({ kind: 'paid', name: fee.note, source: fee.date, amount: fee.amount, payer: fee.payer });
const sourceFor = fee => {
const index = order.lines.findIndex(l => (l.charges || []).some(c => 'charge:' + c.id === fee.key));
return index < 0 ? '整单费用' : `商品 ${index + 1} · ${order.lines[index].name}`;
};
for (const fee of order.pendingFees || [])
add({ kind: 'pending', name: fee.note, source: sourceFor(fee), amount: fee.amount, payer: fee.payer });
// 核实为0不会生成支付流水,仍显示该项目,便于逐项核对。
for (const fee of order.fee_items || [])
if (fee.status === 'recorded' && fee.amount === 0)
add({ kind: 'zero', name: fee.note, source: sourceFor(fee), amount: 0, payer: fee.payer });
const total = empty();
for (const s of Object.values(byPayer)) {
s.total = s.goods + s.paidFees + s.pendingFees;
s.missing = s.goodsMissing + s.pendingMissing;
for (const key of Object.keys(total)) total[key] += s[key];
}
return { byPayer, total, rows, goodsExcluded, pendingCount: (order.pendingFees || []).length };
}
const api = {
calculate,
cents,
isSilver,
costs,
costLabels,
costPayers,
normalizeCostPayers: costPayers,
charges,
sale,
orderTotal,
purchaseCosts,
poolMaterialAmount,
poolMaterialPreview,
priceLockCost,
orderCosts,
};
if (typeof module === 'object' && module.exports) module.exports = api;
else root.LedgerCalc = api;
})(typeof globalThis === 'object' ? globalThis : this);