第4项:对页面、表单及两版共享规则启用严格类型检查

This commit is contained in:
黄健铭 committed 2026-12-05 08:01:17 -08:00
1 parent 389952f31c
commit f570929cfe
77 files changed
+7629 -2981

No files matched your search

+148 -59
View File
@@ -1,9 +1,24 @@
// @ts-check
'use strict';
/** @typedef {import('../web/src/pages/Recoveries/types').Draft} Draft */
/** @typedef {import('../web/src/pages/Recoveries/types').OldLine} OldLine */
/** @typedef {import('../web/src/pages/Recoveries/types').Input} Input */
/** @typedef {import('../web/src/pages/Recoveries/types').Product} Product */
/** @typedef {import('../web/src/pages/Recoveries/types').Calculation} Calculation */
/** @typedef {import('../web/src/pages/Recoveries/types').EditDetail} EditDetail */
/** @typedef {import('../web/src/pages/Recoveries/types').ChangeRequest} ChangeRequest */
/** @typedef {import('../web/src/pages/Recoveries/types').ItemInput} ItemInput */
/** @typedef {import('../web/src/pages/Recoveries/types').Exchange} Exchange */
/** @typedef {import('../web/src/pages/Recoveries/types').Material} Material */
/** @typedef {import('../web/src/pages/Recoveries/types').RecoveryContext} RecoveryContext */
/** @typedef {import('../web/src/pages/Recoveries/types').RecoveryModel} RecoveryModel */
/** @typedef {import('../web/src/pages/Recoveries/types').Totals} Totals */
// 两种前端共用的回收规则。金额为分、重量为毫克,新版与历史两种多件置换格式分别结算。
(function (root) {
const recoveryModeNames = { direct: '直接回收', exchange: '置换' };
/** @param {unknown} value */
const recoveryText = value => String(value ?? '').trim();
const recoveryProductFields = [
const recoveryProductFields = /** @type {const} */ ([
'new_name',
'new_quantity',
'pocket',
@@ -13,8 +28,9 @@
'cost_labor_mode',
'cost_labor_value',
'labor_payer',
];
]);
/** @param {unknown} value @param {number} places @param {string} title @returns {number} */
function recoveryUnits(value, places, title, { zero = true } = {}) {
const raw = recoveryText(value),
pattern = new RegExp('^\\d+(?:\\.\\d{1,' + places + '})?$');
@@ -26,16 +42,19 @@
return Number(units);
}
/** @param {number} value @returns {number} */
function recoveryLimit(value, title = '回收/置换合计') {
if (!Number.isSafeInteger(value) || Math.abs(value) > 100000000000)
throw new Error(title + '超出支持范围,请核对。');
return value;
}
/** @param {number} weight @param {number} rate @returns {number} */
function recoveryMul(weight, rate) {
return recoveryLimit(Number((BigInt(weight) * BigInt(rate) + 500n) / 1000n));
}
/** @param {Product} row */
function recoveryProductDraft(row) {
return {
new_name: row.name,
@@ -50,6 +69,7 @@
};
}
/** @param {Draft} draft @returns {number} */
function recoveryNewWeight(draft) {
return [draft, ...(draft.extra_products || [])].reduce(
(n, row) => recoveryLimit(n + recoveryUnits(row.new_quantity, 3, '新货克重', { zero: false })),
@@ -57,13 +77,34 @@
);
}
/** @param {Draft} draft @returns {Draft} */
function recoverySharedOldDraft(draft) {
if (!draft.independent_products) return draft;
return {
...draft,
independent_products: false,
extra_products: (draft.extra_products || []).map(row =>
Object.fromEntries(recoveryProductFields.map(k => [k, row[k]])),
extra_products: (draft.extra_products || []).map(
({
new_name,
new_quantity,
pocket,
stockCount,
labor_mode,
labor_rate,
cost_labor_mode,
cost_labor_value,
labor_payer,
}) => ({
new_name,
new_quantity,
pocket,
stockCount,
labor_mode,
labor_rate,
cost_labor_mode,
cost_labor_value,
labor_payer,
}),
),
...(draft.extra_products?.length ? { buy_total_manual: false, buy_total: '', depreciation_manual: false } : {}),
verified: false,
@@ -71,8 +112,10 @@
};
}
/** @param {Input} input @returns {Calculation} */
function recoveryCalculate(input) {
if (input.mode === 'exchange' && input.exchange?.items) return recoveryItemsCalculate(input);
if (input.mode === 'exchange' && input.exchange?.items)
return recoveryItemsCalculate(input, input.exchange, input.exchange.items);
if (!Object.hasOwn(recoveryModeNames, input.mode)) throw new Error('请选择直接回收或置换。');
const oldLines = (input.old_lines || []).map(line => {
const incomingMg = recoveryUnits(line.incoming_weight, 3, '来料重量', { zero: false }),
@@ -103,6 +146,7 @@
receivable = 0,
roundingAdjustment = 0;
if (input.mode === 'exchange') {
/** @type {Partial<Exchange>} */
const x = input.exchange || {};
newMg = x.products
? recoveryLimit(
@@ -179,8 +223,9 @@
};
}
function recoveryItemsCalculate(input) {
const parts = input.exchange.items.map(row =>
/** @param {Input} input @param {Exchange} exchange @param {ItemInput[]} items @returns {Calculation} */
function recoveryItemsCalculate(input, exchange, items) {
const parts = items.map(row =>
recoveryCalculate({
...input,
...row,
@@ -192,37 +237,48 @@
exchange: row.exchange,
}),
);
const q = { mode: 'exchange', old_lines: parts.flatMap(p => p.old_lines), exchangeItems: parts };
for (const key of [
'oldMg',
'newMg',
'matchedMg',
'differenceMg',
'surplusMg',
'depositMg',
'purchaseMg',
'goldAmount',
'laborAmount',
'depreciationMg',
'depreciationAmount',
'purchaseAmount',
'defaultPurchaseAmount',
])
q[key] = recoveryLimit(parts.reduce((n, p) => n + p[key], 0));
q.chargesAmount = recoveryLimit(
(input.exchange.charges || []).reduce((n, r) => n + recoveryUnits(r.amount, 2, '其他收费'), 0),
/** @param {keyof Pick<Calculation,'oldMg'|'newMg'|'matchedMg'|'differenceMg'|'surplusMg'|'depositMg'|'purchaseMg'|'goldAmount'|'laborAmount'|'depreciationMg'|'depreciationAmount'|'purchaseAmount'|'defaultPurchaseAmount'>} key */
const sum = key => recoveryLimit(parts.reduce((n, p) => n + p[key], 0));
const sums = {
oldMg: sum('oldMg'),
newMg: sum('newMg'),
matchedMg: sum('matchedMg'),
differenceMg: sum('differenceMg'),
surplusMg: sum('surplusMg'),
depositMg: sum('depositMg'),
purchaseMg: sum('purchaseMg'),
goldAmount: sum('goldAmount'),
laborAmount: sum('laborAmount'),
depreciationMg: sum('depreciationMg'),
depreciationAmount: sum('depreciationAmount'),
purchaseAmount: sum('purchaseAmount'),
defaultPurchaseAmount: sum('defaultPurchaseAmount'),
};
const chargesAmount = recoveryLimit(
(exchange.charges || []).reduce((n, r) => n + recoveryUnits(r.amount, 2, '其他收费'), 0),
);
q.discount = recoveryUnits(input.exchange.discount || '0', 2, '整单优惠');
const before = recoveryLimit(q.goldAmount + q.laborAmount + q.depreciationAmount + q.chargesAmount) - q.discount;
const discount = recoveryUnits(exchange.discount || '0', 2, '整单优惠');
const before =
recoveryLimit(sums.goldAmount + sums.laborAmount + sums.depreciationAmount + chargesAmount) - discount;
if (before < 0) throw new Error('优惠金额不能大于置换费用');
q.receivable = input.exchange.rounding_mode === 'yuan' ? Math.floor((before + 50) / 100) * 100 : before;
q.roundingAdjustment = q.receivable - before;
q.netSettlement = q.receivable - q.purchaseAmount;
q.cashReceipt = Math.max(0, q.netSettlement);
q.cashPayment = Math.max(0, -q.netSettlement);
return q;
const receivable = exchange.rounding_mode === 'yuan' ? Math.floor((before + 50) / 100) * 100 : before;
const netSettlement = receivable - sums.purchaseAmount;
return {
mode: 'exchange',
old_lines: parts.flatMap(p => p.old_lines),
exchangeItems: parts,
...sums,
chargesAmount,
discount,
receivable,
roundingAdjustment: receivable - before,
netSettlement,
cashReceipt: Math.max(0, netSettlement),
cashPayment: Math.max(0, -netSettlement),
};
}
/** @param {Draft} draft @returns {OldLine[]} */
function customerMaterialOldLines(draft) {
return [
{ name: '客户寄存料', incoming_weight: draft.deposit_weight, melted_weight: draft.deposit_weight, purity: '100' },
@@ -230,7 +286,12 @@
}
// 页面的成员、货盘和账户策略由调用方提供。originalInput 只在编辑既有单据时参与历史值校验。
/**
* @param {import('../web/src/pages/Recoveries/types').RecoveryContext} context
* @returns {import('../web/src/pages/Recoveries/types').RecoveryModel}
*/
function createModel(context) {
/** @param {import('../web/src/pages/Recoveries/types').ProductDraft} draft @returns {Product} */
function recoveryProductInput(draft) {
return {
name: draft.new_name,
@@ -251,6 +312,7 @@
};
}
/** @param {import('../web/src/pages/Recoveries/types').Mode} [mode] @returns {Draft} */
function recoveryDefaults(mode = 'direct') {
const member = context.currentMember();
return {
@@ -307,11 +369,15 @@
};
}
/** @overload @param {Draft & {mode:'exchange'}} draft @param {{quote?:boolean}} [options] @returns {Input & {exchange:Exchange}} */
/** @overload @param {Draft} draft @param {{quote?:boolean}} [options] @returns {Input} */
/** @param {Draft} draft @returns {Input} */
function recoveryInput(draft, { quote = false } = {}) {
if (draft.mode === 'exchange' && draft.independent_products) return recoveryItemsInput(draft, { quote });
if (draft.mode === 'exchange' && draft.old_source === 'deposit')
draft = { ...draft, old_lines: customerMaterialOldLines(draft) };
const member = context.state.user.role === 'owner' ? draft.member : context.currentMember();
/** @type {Input} */
const input = {
mode: draft.mode,
date: draft.date,
@@ -354,12 +420,14 @@
buy_total: '0',
});
if (draft.mode === 'exchange') {
/** @type {import('../web/src/pages/Recoveries/types').Labor|undefined} */
const costLabor =
draft.cost_labor_value === ''
? undefined
: draft.cost_labor_mode === 'total'
? { mode: 'total', amount: draft.cost_labor_value }
: { mode: 'gram', rate: draft.cost_labor_value };
/** @type {Material|undefined} */
const costMaterial =
draft.material_source === 'pool'
? { mode: 'pool', poolId: draft.material_pool_id || draft.date }
@@ -428,19 +496,22 @@
return input;
}
function validateRecoveryInput(input) {
/** @param {Input} input @returns {Input} */
function validateRecoveryInput(input, itemIndex = -1) {
if (input.exchange?.items) {
for (const [index, row] of input.exchange.items.entries())
validateRecoveryInput({
...input,
...row,
_recoveryItemIndex: index,
buy_total: row.buy_total,
buy_rate: row.buy_rate,
exchange: row.exchange,
payment_account: context.memberAccountPrefix(input.payer) + '微信',
});
if (!context.state.accounts.includes(input.payment_account)) throw new Error('请选择有效收付款账户');
validateRecoveryInput(
{
...input,
...row,
buy_total: row.buy_total,
buy_rate: row.buy_rate,
exchange: row.exchange,
payment_account: context.memberAccountPrefix(input.payer) + '微信',
},
index,
);
if (!context.state.accounts?.includes(input.payment_account)) throw new Error('请选择有效收付款账户');
return input;
}
if (!context.validOrderDate(input.date) || input.date > context.state.today)
@@ -452,7 +523,7 @@
throw new Error('请选择归属成员和实际付款人。');
const calculation = recoveryCalculate(input);
const source = context.originalInput,
item = source?.exchange?.items?.[input._recoveryItemIndex],
item = source?.exchange?.items?.[itemIndex],
oldOriginal = item ? { ...source, ...item } : source;
const oldPocket = input.old_pocket ?? '回收旧料';
if (
@@ -477,10 +548,10 @@
if (recoveryUnits(input.deposit_weight, 3, '使用寄存克重', { zero: false }) > calculation.newMg)
throw new Error('本次寄存用量不能超过新货克重,剩余继续寄存');
}
if (input.mode === 'exchange') {
if (input.mode === 'exchange' && input.exchange) {
const x = input.exchange,
original = oldOriginal?.exchange;
if (context.pocketCountsEnabled(x.pocket))
if (context.pocketCountsEnabled(x.pocket ?? ''))
context.stockCountValue(x.stockCount, {
optional:
!!original &&
@@ -492,7 +563,7 @@
if (!x.name || x.name.length > 60) throw new Error('请填写1~60字的新货商品名称。');
if (
x.pocket !== '' &&
!context.activePocketKeys().includes(x.pocket) &&
!context.activePocketKeys().includes(x.pocket ?? '') &&
!(source && original?.pocket === x.pocket)
)
throw new Error('请选择新货实际出库的已启用货盘。');
@@ -524,18 +595,19 @@
throw new Error('料池日期不能晚于业务日期。');
}
for (const payer of [x.cost_material_payer, x.cost_labor_payer, ...x.fee_items.map(row => row.payer)])
if (!context.teamMemberKeys().includes(payer)) throw new Error('请选择内部成本的实际付款人。');
if (!payer || !context.teamMemberKeys().includes(payer)) throw new Error('请选择内部成本的实际付款人。');
}
if (calculation.netSettlement < 0 && context.isCreditCardAccount(input.payment_account))
throw new Error('向客户付款不能使用信用卡收款账户。');
if (!context.state.accounts.includes(input.payment_account)) throw new Error('请选择有效的收付款方式。');
if (!context.state.accounts?.includes(input.payment_account)) throw new Error('请选择有效的收付款方式。');
if (input.verified !== true) throw new Error('请核实重量、结算金额和实际收付款后,勾选确认再保存。');
return input;
}
/** @param {Draft} draft @returns {Input} */
function recoveryItemsInput(draft, { quote = false } = {}) {
const common = {
mode: 'exchange',
mode: /** @type {const} */ ('exchange'),
date: draft.date,
customer: draft.customer,
customer_type: draft.customer_type,
@@ -579,7 +651,14 @@
};
});
const first = recoveryInput(
{ ...draft, independent_products: false, extra_products: [], discount: '0', rounding_mode: 'cent' },
{
...draft,
mode: 'exchange',
independent_products: false,
extra_products: [],
discount: '0',
rounding_mode: 'cent',
},
{ quote: true },
),
input = {
@@ -609,6 +688,7 @@
return input;
}
/** @param {Input|null} input */
function recoveryInputShape(input) {
return (
input &&
@@ -621,13 +701,17 @@
input.old_lines.length > 0 &&
input.old_lines.every(
row =>
row && ['name', 'incoming_weight', 'melted_weight', 'purity'].every(key => typeof row[key] === 'string'),
row &&
/** @type {const} */ (['name', 'incoming_weight', 'melted_weight', 'purity']).every(
key => typeof row[key] === 'string',
),
) &&
(input.mode === 'direct' ||
(input.exchange && Array.isArray(input.exchange.charges) && Array.isArray(input.exchange.fee_items)))
);
}
/** @param {EditDetail} data @param {string} id @returns {EditDetail} */
function validateRecoveryEditDetail(data, id) {
if (
!data ||
@@ -638,8 +722,10 @@
!['active', 'cancelled'].includes(data.status) ||
!recoveryInputShape(data.inputs) ||
!data.permissions ||
!['canEdit', 'canCancel', 'canDirect', 'requiresApproval'].every(
key => typeof data.permissions[key] === 'boolean',
!(
/** @type {const} */ (['canEdit', 'canCancel', 'canDirect', 'requiresApproval']).every(
key => typeof data.permissions[key] === 'boolean',
)
) ||
!Array.isArray(data.blockedUsages) ||
!Array.isArray(data.history) ||
@@ -655,6 +741,7 @@
return data;
}
/** @param {ChangeRequest} request @returns {ChangeRequest} */
function validateRecoveryChangeRequest(request) {
if (
!request ||
@@ -680,6 +767,7 @@
return request;
}
/** @param {Input} input @returns {Draft} */
function recoveryEditDraft(input) {
if (input.exchange?.items) {
const rows = input.exchange.items.map(row => recoveryEditDraft({ ...input, ...row, exchange: row.exchange })),
@@ -700,8 +788,9 @@
rounding_mode: x.rounding_mode,
};
}
/** @type {Partial<Exchange>} */
const x = input.exchange || {};
const first = input.old_lines[0],
x = input.exchange || {},
charge = x.charges?.[0],
fee = x.fee_items?.[0],
account = input.payment_account || '',
@@ -739,7 +828,7 @@
payout_method: method === '信用卡' ? '微信' : method,
new_name: x.name || '足金999',
new_quantity: x.quantity || '',
pocket: x.pocket ?? context.state.pockets[0] ?? '',
pocket: x.pocket ?? context.state.pockets?.[0] ?? '',
stockCount: x.stockCount ?? '',
gold_price: x.gold_price || '0',
labor_mode: x.labor_mode || 'gram',
@@ -785,5 +874,5 @@
}
const api = { createModel, recoveryModeNames, recoveryProductFields, customerMaterialOldLines };
if (typeof module === 'object' && module.exports) module.exports = api;
else root.RecoveryRules = api;
else /** @type {{RecoveryRules?:object}} */ (root).RecoveryRules = api;
})(typeof globalThis === 'object' ? globalThis : this);