2026-10-17 19:50:24 +08:00
|
|
|
|
'use strict';
|
|
|
|
|
|
// 浏览器预览和服务器记账共用整数算法;每行销售额最后统一四舍五入到分。
|
2026-12-05 08:00:41 -08:00
|
|
|
|
/**
|
|
|
|
|
|
* @typedef {{id?: string, name?: string, amount?: string|number|null, costRemoved?: boolean}} ChargeInput
|
|
|
|
|
|
* @typedef {{mode?: string, rate?: string|number|null, poolId?: string}} CostEntry
|
|
|
|
|
|
* @typedef {{
|
|
|
|
|
|
* unit?: string, name?: string, quantity?: string|number, pricingMode?: string,
|
|
|
|
|
|
* baseSale?: string|number, sale?: string|number, charges?: ChargeInput[], goldPrice?: string|number,
|
|
|
|
|
|
* laborRate?: string|number, laborMode?: string, pieces?: string|number,
|
|
|
|
|
|
* costParts?: Record<string,string|number|null>, costMaterial?: CostEntry, costLabor?: CostEntry,
|
|
|
|
|
|
* materialPool?: {amount?: number|null}
|
|
|
|
|
|
* }} SaleInput
|
|
|
|
|
|
* @typedef {{mg: number, active?: boolean, order_id?: string, line_index?: number,
|
|
|
|
|
|
* created?: string, fifo_sequence?: number}} PoolUsage
|
|
|
|
|
|
* @typedef {{appended: true, previewIndex: number, mg: number}} NewUsage
|
|
|
|
|
|
* @typedef {PoolUsage & {appended?: false, previewIndex?: number}} ExistingUsage
|
|
|
|
|
|
* @typedef {ExistingUsage | NewUsage} PreviewUsage
|
|
|
|
|
|
* @typedef {(ExistingUsage & {created: string, fifo_sequence: number}) | NewUsage} SortedUsage
|
|
|
|
|
|
* @typedef {{totalMg: number, totalAmount: number|null, usages: PoolUsage[]}} PreviewPool
|
|
|
|
|
|
* @typedef {{key: string, note: string, payer: string, amount: number|null, status?: string}} RecordedFee
|
|
|
|
|
|
* @typedef {{rate?: number|null, mode?: string, poolId?: string}} RecordedCostMode
|
|
|
|
|
|
* @typedef {{poolId: string, amount: number|null}} LockPool
|
|
|
|
|
|
* @typedef {{payer: string, amount: number}} Allocation
|
|
|
|
|
|
* @typedef {{
|
|
|
|
|
|
* name: string, payer: string, quantity: number, cost?: number|null, costParts?: Record<string,number|null>,
|
|
|
|
|
|
* costPayers?: Record<string,string>, priceLockPool?: LockPool, priceLockExtraPool?: LockPool,
|
|
|
|
|
|
* costMaterial?: RecordedCostMode, costLabor?: RecordedCostMode,
|
|
|
|
|
|
* materialPool?: {allocations: Allocation[], averageRate: number|null, quantity?: number, revision?: string|number},
|
|
|
|
|
|
* materialAllocations?: (Allocation & {source: string, quantity: number, rate: number, weighted?: boolean, poolId?: string})[],
|
|
|
|
|
|
* returnedStock?: boolean, returnedStockId?: string, recovery_id?: string, recoveryMaterialMg?: number,
|
|
|
|
|
|
* charges?: {id:string}[]
|
|
|
|
|
|
* }} RecordedLine
|
|
|
|
|
|
* @typedef {{status: string, lines: RecordedLine[], corrections?: {type:string,target:string}[],
|
|
|
|
|
|
* expenses?: {id:string,note:string,date:string,amount:number,payer:string}[],
|
|
|
|
|
|
* pendingFees?: RecordedFee[], fee_items?: RecordedFee[]}} RecordedOrder
|
|
|
|
|
|
* @typedef {({kind: 'paid'|'zero', amount: number} | {kind: 'goods'|'pending', amount: number|null}) & {
|
|
|
|
|
|
* payer: string, name: string, source: string, excluded?: boolean, component?: string,
|
|
|
|
|
|
* materialPoolId?: string, materialPoolRevision?: string|number, poolPending?: boolean,
|
|
|
|
|
|
* calculation?: {rate?: number|null, quantity?: number, weighted?: boolean}|null,
|
|
|
|
|
|
* priceLockSource?: string, inheritedStockCost?: boolean, returnedStockId?: string
|
|
|
|
|
|
* }} CostRow
|
|
|
|
|
|
*/
|
2026-10-17 19:50:24 +08:00
|
|
|
|
(function (root) {
|
2026-12-05 08:00:41 -08:00
|
|
|
|
const validMember = (/** @type {string} */ value) =>
|
2026-11-14 01:16:35 +08:00
|
|
|
|
['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);
|
2026-12-05 08:00:41 -08:00
|
|
|
|
/**
|
|
|
|
|
|
* @param {unknown} value
|
|
|
|
|
|
* @param {number} places
|
|
|
|
|
|
* @param {string} name
|
|
|
|
|
|
*/
|
2026-10-17 19:50:24 +08:00
|
|
|
|
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;
|
|
|
|
|
|
}
|
2026-12-05 08:00:41 -08:00
|
|
|
|
/** @param {unknown} v */
|
2026-10-17 19:50:24 +08:00
|
|
|
|
function cents(v, name = '金额') {
|
|
|
|
|
|
return Number(fixed(v, 2, name));
|
|
|
|
|
|
}
|
2026-12-05 08:00:41 -08:00
|
|
|
|
const isSilver = (/** @type {string|undefined} */ name) => name === '足银999' || name === '纯银925';
|
|
|
|
|
|
/** @param {ChargeInput[]} [raw] */
|
2026-10-17 19:50:24 +08:00
|
|
|
|
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('附加项目标识无效');
|
2026-11-20 00:43:55 +08:00
|
|
|
|
if (item.costRemoved !== undefined && typeof item.costRemoved !== 'boolean')
|
|
|
|
|
|
throw new Error('内部成本移除标记无效');
|
2026-10-17 19:50:24 +08:00
|
|
|
|
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字');
|
2026-11-20 00:43:55 +08:00
|
|
|
|
const amount = blank ? null : cents(item.amount, '附加项目金额');
|
|
|
|
|
|
items.push({ ...(id ? { id } : {}), name, amount, ...(item.costRemoved === true ? { costRemoved: true } : {}) });
|
|
|
|
|
|
total += amount || 0;
|
2026-10-17 19:50:24 +08:00
|
|
|
|
}
|
|
|
|
|
|
if (total > 100000000000) throw new Error('附加项目合计超出支持范围');
|
|
|
|
|
|
return { items, total };
|
|
|
|
|
|
}
|
2026-12-05 08:00:41 -08:00
|
|
|
|
/** @param {SaleInput} line */
|
2026-10-17 19:50:24 +08:00
|
|
|
|
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 };
|
|
|
|
|
|
}
|
2026-12-05 08:00:41 -08:00
|
|
|
|
/** @param {number[]} lineAmounts */
|
2026-10-17 19:50:24 +08:00
|
|
|
|
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),
|
|
|
|
|
|
};
|
|
|
|
|
|
}
|
2026-12-05 08:00:41 -08:00
|
|
|
|
/** @param {SaleInput} line */
|
2026-10-17 19:50:24 +08:00
|
|
|
|
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, '销售工费');
|
2026-12-05 08:00:41 -08:00
|
|
|
|
if (line.laborMode !== 'gram' && line.laborMode !== 'piece') throw new Error('请选择克工费或件工费');
|
2026-10-17 19:50:24 +08:00
|
|
|
|
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),
|
|
|
|
|
|
};
|
|
|
|
|
|
}
|
2026-12-05 08:00:41 -08:00
|
|
|
|
/** @type {Record<string,string>} */
|
2026-10-17 19:50:24 +08:00
|
|
|
|
const costLabels = { material: '料费成本', labor: '进货工费', accessories: '配件成本', other: '其他货品成本' };
|
2026-12-05 08:00:41 -08:00
|
|
|
|
/** @param {Record<string,string> | undefined} raw
|
|
|
|
|
|
* @returns {{material:string,labor:string,[key:string]:string|undefined} | undefined} */
|
2026-10-17 19:50:24 +08:00
|
|
|
|
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))
|
2026-12-04 08:58:53 -08:00
|
|
|
|
)
|
2026-10-17 19:50:24 +08:00
|
|
|
|
throw new Error('料费和进货工费付款人无效');
|
2026-11-14 01:16:35 +08:00
|
|
|
|
for (const key of ['material', 'labor'])
|
|
|
|
|
|
if (!Object.hasOwn(raw, key) || !validMember(raw[key])) throw new Error(costLabels[key] + '付款人无效');
|
2026-10-17 19:50:24 +08:00
|
|
|
|
return { material: raw.material, labor: raw.labor };
|
|
|
|
|
|
}
|
2026-12-05 08:00:41 -08:00
|
|
|
|
/** @param {Record<string,string|number|null>|undefined} raw */
|
2026-10-17 19:50:24 +08:00
|
|
|
|
function costs(raw) {
|
2026-12-05 08:00:41 -08:00
|
|
|
|
/** @type {Record<string,number|null>} */
|
2026-10-17 19:50:24 +08:00
|
|
|
|
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 };
|
|
|
|
|
|
}
|
2026-12-05 08:00:41 -08:00
|
|
|
|
/** @param {SaleInput} line */
|
2026-10-17 19:50:24 +08:00
|
|
|
|
function purchaseCosts(line) {
|
|
|
|
|
|
const parts = { ...line.costParts };
|
2026-12-05 08:00:41 -08:00
|
|
|
|
/** @param {string} key
|
|
|
|
|
|
* @param {CostEntry|undefined} metadata
|
|
|
|
|
|
* @param {string} rateLabel
|
|
|
|
|
|
* @param {string} totalLabel
|
|
|
|
|
|
* @param {string} modeError
|
|
|
|
|
|
* @param {string} unitError */
|
2026-10-17 19:50:24 +08:00
|
|
|
|
const perGram = (key, metadata, rateLabel, totalLabel, modeError, unitError) => {
|
|
|
|
|
|
// 旧单没有计价元数据时,原分项金额始终是总额,不能再乘克重。
|
|
|
|
|
|
const mode = metadata?.mode || 'total';
|
|
|
|
|
|
if (!['gram', 'total'].includes(mode)) throw new Error(modeError);
|
2026-12-05 08:00:41 -08:00
|
|
|
|
/** @type {{mode:string,rate?:number|null}} */
|
2026-10-17 19:50:24 +08:00
|
|
|
|
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 =
|
2026-12-05 08:00:41 -08:00
|
|
|
|
typeof previewAmount === 'number' && Number.isSafeInteger(previewAmount) && previewAmount >= 0
|
|
|
|
|
|
? (previewAmount / 100).toFixed(2)
|
|
|
|
|
|
: '';
|
2026-10-21 01:32:49 +08:00
|
|
|
|
} else
|
|
|
|
|
|
costMaterial = perGram(
|
|
|
|
|
|
'material',
|
|
|
|
|
|
line.costMaterial,
|
|
|
|
|
|
'进货料价',
|
|
|
|
|
|
'料费总成本',
|
|
|
|
|
|
'请选择每克料价或料费总成本',
|
|
|
|
|
|
'每克料价需要克重,按件商品请填写料费总成本',
|
|
|
|
|
|
);
|
2026-10-17 19:50:24 +08:00
|
|
|
|
const costLabor = perGram(
|
|
|
|
|
|
'labor',
|
|
|
|
|
|
line.costLabor,
|
|
|
|
|
|
'进货克工费',
|
|
|
|
|
|
'进货总工费',
|
|
|
|
|
|
'请选择进货克工费或总工费',
|
|
|
|
|
|
'进货克工费需要克重,按件商品请填写总工费',
|
|
|
|
|
|
);
|
|
|
|
|
|
return { ...costs(parts), costMaterial, costLabor };
|
|
|
|
|
|
}
|
2026-10-21 01:32:49 +08:00
|
|
|
|
// 先用实际总金额与总毫克计算,展示用均价不可参与成本分摊。
|
2026-12-05 08:00:41 -08:00
|
|
|
|
/**
|
|
|
|
|
|
* @param {number} totalAmount
|
|
|
|
|
|
* @param {number} totalMg
|
|
|
|
|
|
* @param {number} quantityMg
|
|
|
|
|
|
*/
|
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);
|
|
|
|
|
|
}
|
2026-10-23 00:14:29 +08:00
|
|
|
|
// 同池先按完整耗用顺序累计取整,再取相邻差额;编辑沿用原行身份,新增行追加。
|
2026-12-05 08:00:41 -08:00
|
|
|
|
/**
|
|
|
|
|
|
* @param {PreviewPool} pool
|
|
|
|
|
|
* @param {{lineIndex:number,mg:number}[]} entries
|
|
|
|
|
|
* @param {{orderId?:string|null,allUsages?:PoolUsage[]}} [options]
|
|
|
|
|
|
*/
|
2026-10-23 00:14:29 +08:00
|
|
|
|
function poolMaterialPreview(pool, entries, { orderId = null, allUsages = pool.usages || [] } = {}) {
|
2026-12-05 08:00:41 -08:00
|
|
|
|
/** @param {number|null} value @returns {value is number} */
|
|
|
|
|
|
const valid = value => value !== null && Number.isSafeInteger(value) && value >= 0 && value <= 100000000000;
|
2026-10-23 00:14:29 +08:00
|
|
|
|
if (
|
|
|
|
|
|
!valid(pool.totalAmount) ||
|
|
|
|
|
|
!valid(pool.totalMg) ||
|
|
|
|
|
|
!Array.isArray(entries) ||
|
|
|
|
|
|
!Array.isArray(pool.usages) ||
|
|
|
|
|
|
!Array.isArray(allUsages)
|
2026-12-04 08:58:53 -08:00
|
|
|
|
)
|
2026-10-23 00:14:29 +08:00
|
|
|
|
throw new Error('日购料预估记录无效,请刷新料价');
|
2026-12-05 08:00:41 -08:00
|
|
|
|
const indices = /** @type {Set<number>} */ (new Set());
|
2026-10-23 00:14:29 +08:00
|
|
|
|
for (const entry of entries) {
|
|
|
|
|
|
if (
|
|
|
|
|
|
!Number.isSafeInteger(entry.lineIndex) ||
|
|
|
|
|
|
entry.lineIndex < 0 ||
|
|
|
|
|
|
indices.has(entry.lineIndex) ||
|
|
|
|
|
|
!valid(entry.mg) ||
|
|
|
|
|
|
!entry.mg
|
2026-12-04 08:58:53 -08:00
|
|
|
|
)
|
2026-10-23 00:14:29 +08:00
|
|
|
|
throw new Error('日购料预估克重或商品行无效');
|
|
|
|
|
|
indices.add(entry.lineIndex);
|
|
|
|
|
|
}
|
|
|
|
|
|
const originals = orderId ? allUsages.filter(usage => usage.order_id === orderId) : [];
|
2026-12-05 08:00:41 -08:00
|
|
|
|
/** @type {PreviewUsage[]} */
|
2026-11-02 19:30:28 +08:00
|
|
|
|
const usages = pool.usages
|
|
|
|
|
|
.filter(usage => usage.active && (!orderId || usage.order_id !== orderId))
|
|
|
|
|
|
.map(usage => ({ ...usage }));
|
2026-10-23 00:14:29 +08:00
|
|
|
|
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,
|
2026-12-05 08:00:41 -08:00
|
|
|
|
amounts = /** @type {Record<number,number|null>} */ (
|
|
|
|
|
|
Object.fromEntries(entries.map(entry => [entry.lineIndex, null]))
|
|
|
|
|
|
);
|
2026-10-23 00:14:29 +08:00
|
|
|
|
for (const entry of entries) {
|
|
|
|
|
|
const original = originals.find(usage => usage.line_index === entry.lineIndex);
|
2026-12-05 08:00:41 -08:00
|
|
|
|
usages.push(
|
|
|
|
|
|
original
|
|
|
|
|
|
? { ...original, mg: entry.mg, previewIndex: entry.lineIndex, appended: false }
|
|
|
|
|
|
: { mg: entry.mg, previewIndex: entry.lineIndex, appended: true },
|
|
|
|
|
|
);
|
2026-10-23 00:14:29 +08:00
|
|
|
|
}
|
2026-12-05 08:00:41 -08:00
|
|
|
|
/** @param {PreviewUsage} usage @returns {usage is SortedUsage} */
|
|
|
|
|
|
const sortable = usage =>
|
|
|
|
|
|
valid(usage.mg) &&
|
|
|
|
|
|
usage.mg > 0 &&
|
|
|
|
|
|
(usage.appended === true ||
|
|
|
|
|
|
(typeof usage.fifo_sequence === 'number' &&
|
|
|
|
|
|
Number.isSafeInteger(usage.fifo_sequence) &&
|
|
|
|
|
|
usage.fifo_sequence >= 1 &&
|
|
|
|
|
|
typeof usage.created === 'string' &&
|
|
|
|
|
|
usage.created.length > 0));
|
|
|
|
|
|
if (!usages.every(sortable)) throw new Error('日购料耗用顺序尚未读到,请刷新料价');
|
|
|
|
|
|
usages.sort((a, b) => {
|
|
|
|
|
|
if (a.appended) return b.appended ? a.previewIndex - b.previewIndex : 1;
|
|
|
|
|
|
if (b.appended) return -1;
|
|
|
|
|
|
return a.created < b.created ? -1 : a.created > b.created ? 1 : a.fifo_sequence - b.fifo_sequence;
|
|
|
|
|
|
});
|
2026-10-23 00:14:29 +08:00
|
|
|
|
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-12-05 08:00:41 -08:00
|
|
|
|
/** @param {{lockedQuantity:unknown,quantity:unknown,buyRate:unknown,extraBuyRate?:unknown}} input */
|
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');
|
2026-12-05 08:00:41 -08:00
|
|
|
|
const amount = (/** @type {bigint} */ quantity, /** @type {bigint} */ rate) => (quantity * rate + 500n) / 1000n;
|
2026-10-21 01:32:49 +08:00
|
|
|
|
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),
|
|
|
|
|
|
};
|
|
|
|
|
|
}
|
2026-10-17 19:50:24 +08:00
|
|
|
|
// 订单内部对账用,输入为账本已保存的整数分;预估费用与实际支出分开。
|
2026-12-05 08:00:41 -08:00
|
|
|
|
/** @param {RecordedOrder} order */
|
2026-10-17 19:50:24 +08:00
|
|
|
|
function orderCosts(order) {
|
|
|
|
|
|
const empty = () => ({
|
|
|
|
|
|
goods: 0,
|
|
|
|
|
|
goodsMissing: 0,
|
|
|
|
|
|
paidFees: 0,
|
|
|
|
|
|
pendingFees: 0,
|
|
|
|
|
|
pendingMissing: 0,
|
|
|
|
|
|
total: 0,
|
|
|
|
|
|
missing: 0,
|
|
|
|
|
|
});
|
2026-12-05 08:00:41 -08:00
|
|
|
|
const byPayer = /** @type {Record<string, ReturnType<typeof empty>>} */ ({
|
|
|
|
|
|
owner: empty(),
|
|
|
|
|
|
assistant: empty(),
|
|
|
|
|
|
assistant2: empty(),
|
|
|
|
|
|
}),
|
|
|
|
|
|
rows = /** @type {CostRow[]} */ ([]);
|
2026-10-17 19:50:24 +08:00
|
|
|
|
const goodsExcluded = ['returned', 'cancelled'].includes(order.status);
|
2026-12-05 08:00:41 -08:00
|
|
|
|
const add = (/** @type {CostRow} */ row) => {
|
2026-10-17 19:50:24 +08:00
|
|
|
|
rows.push(row);
|
|
|
|
|
|
if (row.excluded) return;
|
2026-11-14 01:16:35 +08:00
|
|
|
|
if (!validMember(row.payer)) throw new Error('成本付款人无效');
|
|
|
|
|
|
const s = byPayer[row.payer] || (byPayer[row.payer] = empty());
|
2026-10-17 19:50:24 +08:00
|
|
|
|
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
|
2026-12-05 08:00:41 -08:00
|
|
|
|
? Object.entries(costLabels).map(([key, name]) => ({ key, name, amount: line.costParts?.[key] ?? null }))
|
2026-10-17 19:50:24 +08:00
|
|
|
|
: [{ key: 'total', name: '货品成本(原单未分项)', amount: line.cost ?? null }];
|
2026-12-05 08:00:41 -08:00
|
|
|
|
const lockPool =
|
|
|
|
|
|
line.priceLockExtraPool?.amount === null
|
|
|
|
|
|
? line.priceLockExtraPool
|
|
|
|
|
|
: line.priceLockPool || line.priceLockExtraPool;
|
2026-10-21 01:32:49 +08:00
|
|
|
|
for (const part of parts) {
|
2026-12-05 08:00:41 -08:00
|
|
|
|
if (part.key === 'material' && lockPool && part.amount === null) {
|
2026-11-30 16:40:30 +08:00
|
|
|
|
add({
|
|
|
|
|
|
kind: 'goods',
|
|
|
|
|
|
component: 'material',
|
|
|
|
|
|
name: part.name,
|
|
|
|
|
|
source: '锁价料池成本待补',
|
|
|
|
|
|
amount: null,
|
|
|
|
|
|
payer: payers?.material ?? line.payer,
|
|
|
|
|
|
excluded: goodsExcluded,
|
2026-12-05 08:00:41 -08:00
|
|
|
|
materialPoolId: lockPool.poolId,
|
2026-11-30 16:40:30 +08:00
|
|
|
|
poolPending: true,
|
|
|
|
|
|
calculation: null,
|
|
|
|
|
|
});
|
2026-11-02 19:30:28 +08:00
|
|
|
|
} else if (part.key === 'material' && line.costMaterial?.mode === 'pool') {
|
2026-12-05 08:00:41 -08:00
|
|
|
|
const pool = line.materialPool;
|
|
|
|
|
|
if (part.amount === null || !pool?.allocations?.length) {
|
2026-10-21 01:32:49 +08:00
|
|
|
|
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 {
|
2026-12-05 08:00:41 -08:00
|
|
|
|
const allocations = pool.allocations;
|
2026-11-14 01:16:35 +08:00
|
|
|
|
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
|
2026-12-04 08:58:53 -08:00
|
|
|
|
)
|
2026-11-14 01:16:35 +08:00
|
|
|
|
throw new Error('日购料分项成本记录无效');
|
2026-10-26 14:44:07 +08:00
|
|
|
|
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;
|
2026-11-14 01:16:35 +08:00
|
|
|
|
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
|
2026-12-04 08:58:53 -08:00
|
|
|
|
)
|
2026-11-14 01:16:35 +08:00
|
|
|
|
throw new Error('锁价分项料费记录无效');
|
2026-11-30 16:40:30 +08:00
|
|
|
|
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,
|
2026-11-02 19:30:28 +08:00
|
|
|
|
priceLockSource: item.source,
|
|
|
|
|
|
...(item.poolId ? { materialPoolId: item.poolId } : {}),
|
|
|
|
|
|
calculation: { rate: item.rate, quantity: item.quantity, ...(item.weighted ? { weighted: true } : {}) },
|
|
|
|
|
|
});
|
2026-11-10 02:54:58 +08:00
|
|
|
|
} 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 }
|
|
|
|
|
|
: {}),
|
2026-10-26 14:44:07 +08:00
|
|
|
|
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
|
|
|
|
}
|
2026-10-17 19:50:24 +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 });
|
2026-12-05 08:00:41 -08:00
|
|
|
|
const sourceFor = (/** @type {RecordedFee} */ fee) => {
|
2026-10-17 19:50:24 +08:00
|
|
|
|
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;
|
2026-12-05 08:00:41 -08:00
|
|
|
|
for (const key of /** @type {(keyof typeof total)[]} */ (Object.keys(total))) total[key] += s[key];
|
2026-10-17 19:50:24 +08:00
|
|
|
|
}
|
|
|
|
|
|
return { byPayer, total, rows, goodsExcluded, pendingCount: (order.pendingFees || []).length };
|
|
|
|
|
|
}
|
2026-10-25 14:19:24 +08:00
|
|
|
|
const api = {
|
|
|
|
|
|
calculate,
|
|
|
|
|
|
cents,
|
|
|
|
|
|
isSilver,
|
|
|
|
|
|
costs,
|
|
|
|
|
|
costLabels,
|
|
|
|
|
|
costPayers,
|
|
|
|
|
|
normalizeCostPayers: costPayers,
|
|
|
|
|
|
charges,
|
|
|
|
|
|
sale,
|
|
|
|
|
|
orderTotal,
|
|
|
|
|
|
purchaseCosts,
|
|
|
|
|
|
poolMaterialAmount,
|
|
|
|
|
|
poolMaterialPreview,
|
|
|
|
|
|
priceLockCost,
|
|
|
|
|
|
orderCosts,
|
|
|
|
|
|
};
|
2026-10-17 19:50:24 +08:00
|
|
|
|
if (typeof module === 'object' && module.exports) module.exports = api;
|
2026-12-05 08:00:41 -08:00
|
|
|
|
else Object.assign(root, { LedgerCalc: api });
|
2026-10-17 19:50:24 +08:00
|
|
|
|
})(typeof globalThis === 'object' ? globalThis : this);
|