第4项:对页面、表单及两版共享规则启用严格类型检查
This commit is contained in:
1 parent
389952f31c
commit
f570929cfe
77 files changed
+7629
-2981
No files matched your search
+130
-47
@@ -1,9 +1,54 @@
|
||||
'use strict';
|
||||
// 浏览器预览和服务器记账共用整数算法;每行销售额最后统一四舍五入到分。
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
(function (root) {
|
||||
const validMember = value =>
|
||||
const validMember = (/** @type {string} */ 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);
|
||||
/**
|
||||
* @param {unknown} value
|
||||
* @param {number} places
|
||||
* @param {string} name
|
||||
*/
|
||||
function fixed(value, places, name) {
|
||||
const s = String(value ?? '').trim();
|
||||
if (!new RegExp('^\\d+(?:\\.\\d{1,' + places + '})?$').test(s))
|
||||
@@ -13,10 +58,12 @@
|
||||
if (n > 100000000000n) throw new Error(name + '超出支持范围');
|
||||
return n;
|
||||
}
|
||||
/** @param {unknown} v */
|
||||
function cents(v, name = '金额') {
|
||||
return Number(fixed(v, 2, name));
|
||||
}
|
||||
const isSilver = name => ['足银999', '纯银925'].includes(name);
|
||||
const isSilver = (/** @type {string|undefined} */ name) => name === '足银999' || name === '纯银925';
|
||||
/** @param {ChargeInput[]} [raw] */
|
||||
function charges(raw = []) {
|
||||
if (!Array.isArray(raw) || raw.length > 100) throw new Error('每行最多填写100项附加项目');
|
||||
const items = [];
|
||||
@@ -38,6 +85,7 @@
|
||||
if (total > 100000000000) throw new Error('附加项目合计超出支持范围');
|
||||
return { items, total };
|
||||
}
|
||||
/** @param {SaleInput} line */
|
||||
function sale(line) {
|
||||
const pricing = line.pricingMode === 'auto' ? calculate(line) : null;
|
||||
const baseSale = pricing ? pricing.sale : cents(line.baseSale ?? line.sale, '商品基础金额');
|
||||
@@ -46,6 +94,7 @@
|
||||
if (total > 100000000000) throw new Error('本行销售额超出支持范围');
|
||||
return { ...(pricing || {}), baseSale, charges: extra.items, chargesTotal: extra.total, sale: total };
|
||||
}
|
||||
/** @param {number[]} lineAmounts */
|
||||
function orderTotal(lineAmounts, discount = 0, roundingMode = 'yuan') {
|
||||
const limit = 100000000000n;
|
||||
if (!Array.isArray(lineAmounts) || lineAmounts.length < 1 || lineAmounts.length > 60)
|
||||
@@ -75,13 +124,14 @@
|
||||
rounding_adjustment: Number(total - unroundedTotal),
|
||||
};
|
||||
}
|
||||
/** @param {SaleInput} line */
|
||||
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('请选择克工费或件工费');
|
||||
if (line.laborMode !== 'gram' && line.laborMode !== 'piece') throw new Error('请选择克工费或件工费');
|
||||
let pieces = 1n;
|
||||
if (line.laborMode === 'piece') {
|
||||
if (!/^\d+$/.test(String(line.pieces ?? '1'))) throw new Error('件数须为正整数');
|
||||
@@ -99,7 +149,10 @@
|
||||
pieces: Number(pieces),
|
||||
};
|
||||
}
|
||||
/** @type {Record<string,string>} */
|
||||
const costLabels = { material: '料费成本', labor: '进货工费', accessories: '配件成本', other: '其他货品成本' };
|
||||
/** @param {Record<string,string> | undefined} raw
|
||||
* @returns {{material:string,labor:string,[key:string]:string|undefined} | undefined} */
|
||||
function costPayers(raw) {
|
||||
// 旧行不补写分项付款人;显式传入时必须完整、有效,不能把无效值当作缺省。
|
||||
if (raw === undefined) return undefined;
|
||||
@@ -114,7 +167,9 @@
|
||||
if (!Object.hasOwn(raw, key) || !validMember(raw[key])) throw new Error(costLabels[key] + '付款人无效');
|
||||
return { material: raw.material, labor: raw.labor };
|
||||
}
|
||||
/** @param {Record<string,string|number|null>|undefined} raw */
|
||||
function costs(raw) {
|
||||
/** @type {Record<string,number|null>} */
|
||||
const parts = {};
|
||||
let total = 0,
|
||||
missing = false;
|
||||
@@ -126,12 +181,20 @@
|
||||
if (total > 100000000000) throw new Error('货品成本超出支持范围');
|
||||
return { parts, total: missing ? null : total };
|
||||
}
|
||||
/** @param {SaleInput} line */
|
||||
function purchaseCosts(line) {
|
||||
const parts = { ...line.costParts };
|
||||
/** @param {string} key
|
||||
* @param {CostEntry|undefined} metadata
|
||||
* @param {string} rateLabel
|
||||
* @param {string} totalLabel
|
||||
* @param {string} modeError
|
||||
* @param {string} unitError */
|
||||
const perGram = (key, metadata, rateLabel, totalLabel, modeError, unitError) => {
|
||||
// 旧单没有计价元数据时,原分项金额始终是总额,不能再乘克重。
|
||||
const mode = metadata?.mode || 'total';
|
||||
if (!['gram', 'total'].includes(mode)) throw new Error(modeError);
|
||||
/** @type {{mode:string,rate?:number|null}} */
|
||||
const result = { mode };
|
||||
if (mode === 'gram') {
|
||||
if (line.unit !== 'g') throw new Error(unitError);
|
||||
@@ -157,7 +220,9 @@
|
||||
costMaterial = { mode: 'pool', poolId };
|
||||
const previewAmount = line.materialPool?.amount;
|
||||
parts.material =
|
||||
Number.isSafeInteger(previewAmount) && previewAmount >= 0 ? (previewAmount / 100).toFixed(2) : '';
|
||||
typeof previewAmount === 'number' && Number.isSafeInteger(previewAmount) && previewAmount >= 0
|
||||
? (previewAmount / 100).toFixed(2)
|
||||
: '';
|
||||
} else
|
||||
costMaterial = perGram(
|
||||
'material',
|
||||
@@ -178,6 +243,11 @@
|
||||
return { ...costs(parts), costMaterial, costLabor };
|
||||
}
|
||||
// 先用实际总金额与总毫克计算,展示用均价不可参与成本分摊。
|
||||
/**
|
||||
* @param {number} totalAmount
|
||||
* @param {number} totalMg
|
||||
* @param {number} quantityMg
|
||||
*/
|
||||
function poolMaterialAmount(totalAmount, totalMg, quantityMg) {
|
||||
for (const value of [totalAmount, totalMg, quantityMg])
|
||||
if (!Number.isSafeInteger(value) || value < 0 || value > 100000000000) throw new Error('日购料金额或克重无效');
|
||||
@@ -187,8 +257,14 @@
|
||||
return Number(amount);
|
||||
}
|
||||
// 同池先按完整耗用顺序累计取整,再取相邻差额;编辑沿用原行身份,新增行追加。
|
||||
/**
|
||||
* @param {PreviewPool} pool
|
||||
* @param {{lineIndex:number,mg:number}[]} entries
|
||||
* @param {{orderId?:string|null,allUsages?:PoolUsage[]}} [options]
|
||||
*/
|
||||
function poolMaterialPreview(pool, entries, { orderId = null, allUsages = pool.usages || [] } = {}) {
|
||||
const valid = value => Number.isSafeInteger(value) && value >= 0 && value <= 100000000000;
|
||||
/** @param {number|null} value @returns {value is number} */
|
||||
const valid = value => value !== null && Number.isSafeInteger(value) && value >= 0 && value <= 100000000000;
|
||||
if (
|
||||
!valid(pool.totalAmount) ||
|
||||
!valid(pool.totalMg) ||
|
||||
@@ -197,7 +273,7 @@
|
||||
!Array.isArray(allUsages)
|
||||
)
|
||||
throw new Error('日购料预估记录无效,请刷新料价');
|
||||
const indices = new Set();
|
||||
const indices = /** @type {Set<number>} */ (new Set());
|
||||
for (const entry of entries) {
|
||||
if (
|
||||
!Number.isSafeInteger(entry.lineIndex) ||
|
||||
@@ -210,40 +286,40 @@
|
||||
indices.add(entry.lineIndex);
|
||||
}
|
||||
const originals = orderId ? allUsages.filter(usage => usage.order_id === orderId) : [];
|
||||
/** @type {PreviewUsage[]} */
|
||||
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]));
|
||||
amounts = /** @type {Record<number,number|null>} */ (
|
||||
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 });
|
||||
usages.push(
|
||||
original
|
||||
? { ...original, mg: entry.mg, previewIndex: entry.lineIndex, appended: false }
|
||||
: { mg: entry.mg, previewIndex: entry.lineIndex, appended: true },
|
||||
);
|
||||
}
|
||||
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),
|
||||
);
|
||||
/** @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;
|
||||
});
|
||||
if (covered) {
|
||||
let cumulativeMg = 0,
|
||||
previousAmount = 0;
|
||||
@@ -256,6 +332,7 @@
|
||||
}
|
||||
return { amounts, usedMg, wantedMg, covered };
|
||||
}
|
||||
/** @param {{lockedQuantity:unknown,quantity:unknown,buyRate:unknown,extraBuyRate?:unknown}} input */
|
||||
function priceLockCost(input) {
|
||||
const locked = fixed(input.lockedQuantity, 3, '锁定克重'),
|
||||
actual = fixed(input.quantity, 3, '实际克重');
|
||||
@@ -266,7 +343,7 @@
|
||||
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 amount = (/** @type {bigint} */ quantity, /** @type {bigint} */ rate) => (quantity * rate + 500n) / 1000n;
|
||||
const originalPurchase = amount(locked, originalRate),
|
||||
originalUsedCost = amount(used, originalRate),
|
||||
extraCost = amount(extra, extraRate);
|
||||
@@ -286,6 +363,7 @@
|
||||
};
|
||||
}
|
||||
// 订单内部对账用,输入为账本已保存的整数分;预估费用与实际支出分开。
|
||||
/** @param {RecordedOrder} order */
|
||||
function orderCosts(order) {
|
||||
const empty = () => ({
|
||||
goods: 0,
|
||||
@@ -296,10 +374,14 @@
|
||||
total: 0,
|
||||
missing: 0,
|
||||
});
|
||||
const byPayer = { owner: empty(), assistant: empty(), assistant2: empty() },
|
||||
rows = [];
|
||||
const byPayer = /** @type {Record<string, ReturnType<typeof empty>>} */ ({
|
||||
owner: empty(),
|
||||
assistant: empty(),
|
||||
assistant2: empty(),
|
||||
}),
|
||||
rows = /** @type {CostRow[]} */ ([]);
|
||||
const goodsExcluded = ['returned', 'cancelled'].includes(order.status);
|
||||
const add = row => {
|
||||
const add = (/** @type {CostRow} */ row) => {
|
||||
rows.push(row);
|
||||
if (row.excluded) return;
|
||||
if (!validMember(row.payer)) throw new Error('成本付款人无效');
|
||||
@@ -317,10 +399,14 @@
|
||||
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 }))
|
||||
? Object.entries(costLabels).map(([key, name]) => ({ key, name, amount: line.costParts?.[key] ?? null }))
|
||||
: [{ key: 'total', name: '货品成本(原单未分项)', amount: line.cost ?? null }];
|
||||
const lockPool =
|
||||
line.priceLockExtraPool?.amount === null
|
||||
? line.priceLockExtraPool
|
||||
: line.priceLockPool || line.priceLockExtraPool;
|
||||
for (const part of parts) {
|
||||
if (part.key === 'material' && (line.priceLockPool || line.priceLockExtraPool) && part.amount === null) {
|
||||
if (part.key === 'material' && lockPool && part.amount === null) {
|
||||
add({
|
||||
kind: 'goods',
|
||||
component: 'material',
|
||||
@@ -329,17 +415,13 @@
|
||||
amount: null,
|
||||
payer: payers?.material ?? line.payer,
|
||||
excluded: goodsExcluded,
|
||||
materialPoolId: (line.priceLockExtraPool?.amount === null
|
||||
? line.priceLockExtraPool
|
||||
: line.priceLockPool || line.priceLockExtraPool
|
||||
).poolId,
|
||||
materialPoolId: lockPool.poolId,
|
||||
poolPending: true,
|
||||
calculation: null,
|
||||
});
|
||||
} else if (part.key === 'material' && line.costMaterial?.mode === 'pool') {
|
||||
const pool = line.materialPool,
|
||||
allocations = pool?.allocations;
|
||||
if (part.amount === null || !allocations?.length) {
|
||||
const pool = line.materialPool;
|
||||
if (part.amount === null || !pool?.allocations?.length) {
|
||||
add({
|
||||
kind: 'goods',
|
||||
component: 'material',
|
||||
@@ -354,6 +436,7 @@
|
||||
calculation: null,
|
||||
});
|
||||
} else {
|
||||
const allocations = pool.allocations;
|
||||
if (
|
||||
!Array.isArray(allocations) ||
|
||||
allocations.some(
|
||||
@@ -437,7 +520,7 @@
|
||||
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 sourceFor = (/** @type {RecordedFee} */ 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}`;
|
||||
};
|
||||
@@ -451,7 +534,7 @@
|
||||
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];
|
||||
for (const key of /** @type {(keyof typeof total)[]} */ (Object.keys(total))) total[key] += s[key];
|
||||
}
|
||||
return { byPayer, total, rows, goodsExcluded, pendingCount: (order.pendingFees || []).length };
|
||||
}
|
||||
@@ -473,5 +556,5 @@
|
||||
orderCosts,
|
||||
};
|
||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||
else root.LedgerCalc = api;
|
||||
else Object.assign(root, { LedgerCalc: api });
|
||||
})(typeof globalThis === 'object' ? globalThis : this);
|
||||
Reference in new issue
Block a user