第3项:旧界面与 React 共用对账、回收及基础业务规则

This commit is contained in:
黄健铭 committed 2026-12-05 07:43:18 -08:00
1 parent 54c05879d5
commit 389952f31c
65 files changed
+2265 -3800

No files matched your search

+789
View File
@@ -0,0 +1,789 @@
'use strict';
// 两种前端共用的回收规则。金额为分、重量为毫克,新版与历史两种多件置换格式分别结算。
(function (root) {
const recoveryModeNames = { direct: '直接回收', exchange: '置换' };
const recoveryText = value => String(value ?? '').trim();
const recoveryProductFields = [
'new_name',
'new_quantity',
'pocket',
'stockCount',
'labor_mode',
'labor_rate',
'cost_labor_mode',
'cost_labor_value',
'labor_payer',
];
function recoveryUnits(value, places, title, { zero = true } = {}) {
const raw = recoveryText(value),
pattern = new RegExp('^\\d+(?:\\.\\d{1,' + places + '})?$');
if (!pattern.test(raw))
throw new Error(`${title}请填写${zero ? '不小于0' : '大于0'}的数字,最多保留${places}位小数。`);
const [whole, fraction = ''] = raw.split('.'),
units = BigInt(whole) * 10n ** BigInt(places) + BigInt(fraction.padEnd(places, '0'));
if (units > 100000000000n || (!zero && units === 0n)) throw new Error(`${title}超出范围或尚未填写。`);
return Number(units);
}
function recoveryLimit(value, title = '回收/置换合计') {
if (!Number.isSafeInteger(value) || Math.abs(value) > 100000000000)
throw new Error(title + '超出支持范围,请核对。');
return value;
}
function recoveryMul(weight, rate) {
return recoveryLimit(Number((BigInt(weight) * BigInt(rate) + 500n) / 1000n));
}
function recoveryProductDraft(row) {
return {
new_name: row.name,
new_quantity: row.quantity,
pocket: row.pocket,
stockCount: row.stockCount ?? '',
labor_mode: row.labor_mode,
labor_rate: row.labor_rate,
cost_labor_mode: row.cost_labor?.mode || 'total',
cost_labor_value: row.cost_labor?.mode === 'gram' ? row.cost_labor.rate : (row.cost_labor?.amount ?? ''),
labor_payer: row.cost_labor_payer,
};
}
function recoveryNewWeight(draft) {
return [draft, ...(draft.extra_products || [])].reduce(
(n, row) => recoveryLimit(n + recoveryUnits(row.new_quantity, 3, '新货克重', { zero: false })),
0,
);
}
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]])),
),
...(draft.extra_products?.length ? { buy_total_manual: false, buy_total: '', depreciation_manual: false } : {}),
verified: false,
shared_old_notice: draft.extra_products?.length ? '已恢复为一份来料,沿用上方第一份来料;请核对实际总克重。' : '',
};
}
function recoveryCalculate(input) {
if (input.mode === 'exchange' && input.exchange?.items) return recoveryItemsCalculate(input);
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 }),
meltedMg = recoveryUnits(line.melted_weight, 3, '熔后重量', { zero: false }),
purity = recoveryUnits(line.purity, 3, '成色', { zero: false });
if (meltedMg > incomingMg) throw new Error('熔后重量不能大于来料重量,请核对。');
if (purity > 100000) throw new Error('成色请填写0到100之间的百分数,例如99表示99%。');
const foldedMg = Number((BigInt(meltedMg) * BigInt(purity) + 50000n) / 100000n);
if (foldedMg <= 0) throw new Error('折后重量须至少为0.001g,请核对重量和成色。');
return { ...line, incomingMg, meltedMg, purity: purity / 1000, foldedMg };
});
if (!oldLines.length) throw new Error('请填写旧料重量。');
const oldMg = recoveryLimit(
oldLines.reduce((sum, line) => sum + line.foldedMg, 0),
'旧料总重量',
),
buyRate = recoveryUnits(input.buy_rate, 2, '回收单价');
let newMg = 0,
matchedMg = 0,
differenceMg = 0,
surplusMg = oldMg,
goldAmount = 0,
laborAmount = 0,
depreciationMg = 0,
depreciationAmount = 0,
chargesAmount = 0,
discount = 0,
receivable = 0,
roundingAdjustment = 0;
if (input.mode === 'exchange') {
const x = input.exchange || {};
newMg = x.products
? recoveryLimit(
x.products.reduce((n, row) => n + recoveryUnits(row.quantity, 3, '新货克重', { zero: false }), 0),
)
: recoveryUnits(x.quantity, 3, '新货克重', { zero: false });
matchedMg = Math.min(oldMg, newMg);
differenceMg = Math.max(0, newMg - oldMg);
surplusMg = Math.max(0, oldMg - newMg);
const goldPrice = differenceMg > 0 ? recoveryUnits(x.gold_price, 2, '当天销售金价') : 0,
laborRate = recoveryUnits(x.labor_rate, 2, '销售工费'),
depreciationRate = recoveryUnits(x.depreciation_rate ?? '10', 2, '折旧费单价');
if (differenceMg > 0 && goldPrice <= 0) throw new Error('有补金差重时,请填写大于0的当天销售金价。');
goldAmount = recoveryMul(differenceMg, goldPrice);
laborAmount = x.products
? recoveryLimit(
x.products.reduce((n, row) => {
const rate = recoveryUnits(row.labor_rate, 2, '销售工费');
return (
n + (row.labor_mode === 'total' ? rate : recoveryMul(recoveryUnits(row.quantity, 3, '新货克重'), rate))
);
}, 0),
)
: x.labor_mode === 'total'
? laborRate
: recoveryMul(newMg, laborRate);
depreciationMg =
x.depreciation_weight == null ? matchedMg : recoveryUnits(x.depreciation_weight, 3, '折旧费计费克重');
depreciationAmount = recoveryMul(depreciationMg, depreciationRate);
chargesAmount = recoveryLimit(
(x.charges || []).reduce((sum, row) => sum + recoveryUnits(row.amount, 2, '其他收费'), 0),
);
discount = recoveryUnits(x.discount || '0', 2, '优惠金额');
const before = recoveryLimit(goldAmount + laborAmount + depreciationAmount + chargesAmount) - discount;
if (before < 0) throw new Error('优惠金额不能大于本次置换费用。');
receivable = x.rounding_mode === 'yuan' ? Math.floor((before + 50) / 100) * 100 : before;
roundingAdjustment = receivable - before;
}
const depositMg = input.mode === 'exchange' && input.surplus_mode === 'deposit' ? surplusMg : 0,
purchaseMg = surplusMg - depositMg;
if (purchaseMg > 0 && buyRate <= 0) throw new Error('有回收旧料或余料时,请填写大于0的回收单价。');
const defaultPurchaseAmount = recoveryMul(purchaseMg, buyRate),
purchaseAmount = depositMg
? 0
: input.buy_total == null
? defaultPurchaseAmount
: recoveryUnits(input.buy_total, 2, input.mode === 'direct' ? '回收结算额' : '余料回收款');
if (purchaseMg > 0 && purchaseAmount <= 0) throw new Error('回收结算金额须大于0,请核对。');
if (!surplusMg && purchaseAmount) throw new Error('本次没有余料,余料回收款应为0。');
const netSettlement = recoveryLimit(receivable - purchaseAmount);
return {
mode: input.mode,
old_lines: oldLines,
oldMg,
newMg,
matchedMg,
differenceMg,
surplusMg,
depositMg,
purchaseMg,
goldAmount,
laborAmount,
depreciationMg,
depreciationAmount,
chargesAmount,
discount,
receivable,
purchaseAmount,
defaultPurchaseAmount,
roundingAdjustment,
netSettlement,
cashReceipt: Math.max(0, netSettlement),
cashPayment: Math.max(0, -netSettlement),
};
}
function recoveryItemsCalculate(input) {
const parts = input.exchange.items.map(row =>
recoveryCalculate({
...input,
...row,
buy_total: row.buy_total,
buy_rate: row.buy_rate,
surplus_mode: row.surplus_mode,
surplus_memo: row.surplus_memo,
mode: 'exchange',
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),
);
q.discount = recoveryUnits(input.exchange.discount || '0', 2, '整单优惠');
const before = recoveryLimit(q.goldAmount + q.laborAmount + q.depreciationAmount + q.chargesAmount) - q.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;
}
function customerMaterialOldLines(draft) {
return [
{ name: '客户寄存料', incoming_weight: draft.deposit_weight, melted_weight: draft.deposit_weight, purity: '100' },
];
}
// 页面的成员、货盘和账户策略由调用方提供。originalInput 只在编辑既有单据时参与历史值校验。
function createModel(context) {
function recoveryProductInput(draft) {
return {
name: draft.new_name,
quantity: draft.new_quantity,
pocket: draft.pocket,
...(context.pocketCountsEnabled(draft.pocket) ? { stockCount: draft.stockCount || null } : {}),
labor_mode: draft.labor_mode,
labor_rate: draft.labor_rate,
...(draft.cost_labor_value !== ''
? {
cost_labor:
draft.cost_labor_mode === 'total'
? { mode: 'total', amount: draft.cost_labor_value }
: { mode: 'gram', rate: draft.cost_labor_value },
}
: {}),
cost_labor_payer: draft.labor_payer,
};
}
function recoveryDefaults(mode = 'direct') {
const member = context.currentMember();
return {
independent_products: false,
surplus_mode: 'buy',
surplus_memo: '',
old_source: 'incoming',
deposit_id: '',
deposit_weight: '',
mode,
date: context.state.today,
customer: '',
salesperson: context.defaultSalesperson(),
member,
old_name: 'Au旧料',
incoming_weight: '',
melted_weight: '',
purity: '100',
old_pocket: '回收旧料',
old_stock_count: '',
buy_rate: '',
buy_total: '',
new_name: '足金999',
new_quantity: '',
pocket: '现货',
stockCount: '',
gold_price: '',
labor_mode: 'gram',
labor_rate: '',
depreciation_weight: '',
depreciation_rate: '10',
charge_name: '其他收费',
charge_amount: '0',
discount: '0',
rounding_mode: 'yuan',
material_source: 'pool',
material_pool_id: context.state.today,
material_rate: '',
material_payer: member,
cost_labor_mode: 'gram',
cost_labor_value: '',
labor_payer: member,
fee_note: '其他费用',
fee_amount: '0',
fee_payer: member,
payment_method: '微信',
payment_recipient: context.memberAccountPrefix(member),
payout_method: '微信',
payer: member,
note: '',
buy_total_manual: false,
depreciation_manual: false,
melted_manual: false,
};
}
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();
const input = {
mode: draft.mode,
date: draft.date,
customer: draft.customer,
customer_type: draft.customer_type,
salesperson: draft.salesperson,
member,
note: draft.note,
old_pocket: draft.old_pocket ?? '回收旧料',
...(context.pocketCountsEnabled(draft.old_pocket)
? { old_stock_count: recoveryText(draft.old_stock_count) || null }
: {}),
old_lines: Array.isArray(draft.old_lines)
? draft.old_lines
: [
{
name: draft.old_name || 'Au旧料',
incoming_weight: draft.incoming_weight,
melted_weight: draft.melted_weight,
purity: draft.purity,
},
],
buy_rate: draft.buy_rate,
payer: draft.payer || member,
payment_account: context.memberAccountPrefix(draft.payer || member) + (draft.payout_method || '微信'),
verified: !quote && draft.verified === true,
};
if (draft.mode === 'exchange' && draft.old_source === 'deposit')
Object.assign(input, {
old_source: 'deposit',
deposit_id: draft.deposit_id,
deposit_weight: draft.deposit_weight,
});
if (draft.buy_total_manual && draft.buy_total !== '') input.buy_total = draft.buy_total;
if (draft.mode === 'exchange' && draft.surplus_mode === 'deposit')
Object.assign(input, {
surplus_mode: 'deposit',
surplus_memo: draft.surplus_memo || '',
buy_rate: '0',
buy_total: '0',
});
if (draft.mode === 'exchange') {
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 };
const costMaterial =
draft.material_source === 'pool'
? { mode: 'pool', poolId: draft.material_pool_id || draft.date }
: draft.material_rate === ''
? undefined
: { mode: 'gram', rate: draft.material_rate };
input.exchange = {
name: draft.new_name,
quantity: draft.new_quantity,
pocket: draft.pocket,
...(context.pocketCountsEnabled(draft.pocket)
? {
stockCount:
draft.stockCount == null || String(draft.stockCount).trim() === '' ? null : draft.stockCount,
}
: {}),
gold_price: draft.gold_price,
labor_mode: draft.labor_mode,
labor_rate: draft.labor_rate,
depreciation_rate: draft.depreciation_rate || '0',
...(draft.depreciation_manual ? { depreciation_weight: draft.depreciation_weight } : {}),
...(costMaterial ? { cost_material: costMaterial } : {}),
...(costLabor ? { cost_labor: costLabor } : {}),
cost_payer: draft.cost_payer || draft.labor_payer || member,
cost_material_payer: draft.material_payer || member,
cost_labor_payer: draft.labor_payer || member,
charges: Array.isArray(draft.charges)
? draft.charges
: recoveryText(draft.charge_amount) && recoveryUnits(draft.charge_amount, 2, '其他收费') > 0
? [{ name: draft.charge_name || '其他收费', amount: draft.charge_amount }]
: [],
fee_items: Array.isArray(draft.fee_items)
? draft.fee_items
: recoveryText(draft.fee_amount) && recoveryUnits(draft.fee_amount, 2, '其他内部费用') > 0
? [
{
key: 'other',
note: draft.fee_note || '其他费用',
amount: draft.fee_amount,
payer: draft.fee_payer || member,
},
]
: [],
discount: draft.discount || '0',
rounding_mode: draft.rounding_mode || 'yuan',
};
if (draft.extra_products?.length)
input.exchange.products = [draft, ...draft.extra_products].map(recoveryProductInput);
const old = recoveryCalculate({ ...input, mode: 'direct', buy_rate: '1', buy_total: '1' }),
newMg = recoveryNewWeight(draft);
if (newMg >= old.oldMg) {
input.buy_rate = '0';
input.buy_total = '0';
}
if (newMg <= old.oldMg) {
input.exchange.gold_price = '0';
delete input.exchange.cost_material;
}
const calculation = recoveryCalculate(input);
if (calculation.netSettlement > 0)
input.payment_account =
draft.payment_method === '信用卡'
? '麦麦信用卡'
: (draft.payment_recipient || context.memberAccountPrefix(member)) + (draft.payment_method || '微信');
}
return input;
}
function validateRecoveryInput(input) {
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('请选择有效收付款账户');
return input;
}
if (!context.validOrderDate(input.date) || input.date > context.state.today)
throw new Error('业务日期请选择今天或之前的有效日期。');
if (!input.customer || input.customer.length > 60) throw new Error('请填写1~60字的客户称呼或代号。');
if (!input.salesperson || input.salesperson.length > 30) throw new Error('请填写1~30字的开单人。');
if (input.note.length > 240) throw new Error('备注最多填写240字。');
if (!context.teamMemberKeys().includes(input.member) || !context.teamMemberKeys().includes(input.payer))
throw new Error('请选择归属成员和实际付款人。');
const calculation = recoveryCalculate(input);
const source = context.originalInput,
item = source?.exchange?.items?.[input._recoveryItemIndex],
oldOriginal = item ? { ...source, ...item } : source;
const oldPocket = input.old_pocket ?? '回收旧料';
if (
!context.activePocketKeys().includes(oldPocket) &&
!(oldOriginal && (oldOriginal.old_pocket ?? '回收旧料') === oldPocket)
)
throw new Error('请选择旧料实际入库的已启用货盘。');
if (context.pocketCountsEnabled(oldPocket)) {
context.stockCountValue(input.old_stock_count, {
optional:
!!oldOriginal &&
oldOriginal.old_stock_count == null &&
(oldOriginal.old_pocket ?? '回收旧料') === oldPocket,
title: '旧料入库数量(对)',
});
const since = context.state.pocketCatalog?.find(row => row.key === oldPocket)?.countSince;
if (input.old_stock_count != null && String(input.old_stock_count).trim() !== '' && since && input.date < since)
throw new Error('旧料入库日期不能早于' + since + '对数盘点基准。');
}
if (input.old_source === 'deposit') {
if (!input.deposit_id) throw new Error('请选择寄存记录');
if (recoveryUnits(input.deposit_weight, 3, '使用寄存克重', { zero: false }) > calculation.newMg)
throw new Error('本次寄存用量不能超过新货克重,剩余继续寄存');
}
if (input.mode === 'exchange') {
const x = input.exchange,
original = oldOriginal?.exchange;
if (context.pocketCountsEnabled(x.pocket))
context.stockCountValue(x.stockCount, {
optional:
!!original &&
original.stockCount == null &&
original.pocket === x.pocket &&
Number(original.quantity) === Number(x.quantity),
title: '新货出库数量(对)',
});
if (!x.name || x.name.length > 60) throw new Error('请填写1~60字的新货商品名称。');
if (
x.pocket !== '' &&
!context.activePocketKeys().includes(x.pocket) &&
!(source && original?.pocket === x.pocket)
)
throw new Error('请选择新货实际出库的已启用货盘。');
for (const [index, row] of (x.products || []).entries()) {
const original = source ? (source.exchange?.products ?? [source.exchange])[index] : null;
if (!row.name || row.name.length > 60 || context.isSilver(row.name))
throw new Error('请逐件填写黄金商品名称。');
if (row.pocket !== '' && !context.activePocketKeys().includes(row.pocket) && row.pocket !== original?.pocket)
throw new Error('请选择已启用货盘或外配。');
if (context.pocketCountsEnabled(row.pocket))
context.stockCountValue(row.stockCount, {
optional:
!!original &&
original.stockCount == null &&
original.pocket === row.pocket &&
original.quantity === row.quantity,
});
if (!row.cost_labor) throw new Error('请逐件填写进货工费,没有发生填0。');
recoveryUnits(row.cost_labor.mode === 'gram' ? row.cost_labor.rate : row.cost_labor.amount, 2, '进货工费');
if (!context.teamMemberKeys().includes(row.cost_labor_payer)) throw new Error('请选择工费付款人。');
}
if (!x.cost_labor) throw new Error('请填写进货工费,没有发生请明确填0。');
recoveryUnits(x.cost_labor.mode === 'total' ? x.cost_labor.amount : x.cost_labor.rate, 2, '进货工费');
if (calculation.differenceMg > 0) {
if (!x.cost_material) throw new Error('请填写差重进货料价,或选择每日料池。');
if (x.cost_material.mode === 'gram') {
if (recoveryUnits(x.cost_material.rate, 2, '差重进货料价') <= 0) throw new Error('差重进货料价须大于0。');
} else if (!context.validOrderDate(x.cost_material.poolId) || x.cost_material.poolId > input.date)
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 (calculation.netSettlement < 0 && context.isCreditCardAccount(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;
}
function recoveryItemsInput(draft, { quote = false } = {}) {
const common = {
mode: 'exchange',
date: draft.date,
customer: draft.customer,
customer_type: draft.customer_type,
salesperson: draft.salesperson,
member: draft.member,
payer: draft.payer,
payment_method: draft.payment_method,
payment_recipient: draft.payment_recipient,
payout_method: draft.payout_method,
note: draft.note,
verified: draft.verified,
};
const items = [draft, ...(draft.extra_products || [])].map(row => {
const single = recoveryInput(
{
...recoveryDefaults('exchange'),
...row,
...common,
independent_products: false,
extra_products: [],
charges: [],
fee_items: [],
charge_amount: '0',
fee_amount: '0',
discount: '0',
rounding_mode: 'cent',
},
{ quote },
);
return {
...(single.surplus_mode ? { surplus_mode: single.surplus_mode, surplus_memo: single.surplus_memo } : {}),
...(single.old_source
? { old_source: single.old_source, deposit_id: single.deposit_id, deposit_weight: single.deposit_weight }
: {}),
old_lines: single.old_lines,
old_pocket: single.old_pocket,
...(single.old_stock_count == null ? {} : { old_stock_count: single.old_stock_count }),
buy_rate: single.buy_rate,
...(single.buy_total == null ? {} : { buy_total: single.buy_total }),
exchange: single.exchange,
};
});
const first = recoveryInput(
{ ...draft, independent_products: false, extra_products: [], discount: '0', rounding_mode: 'cent' },
{ quote: true },
),
input = {
...first,
old_lines: items.flatMap(row => row.old_lines),
verified: !quote && draft.verified === true,
exchange: {
items,
charges: first.exchange.charges,
fee_items: first.exchange.fee_items,
discount: draft.discount || '0',
rounding_mode: draft.rounding_mode || 'yuan',
},
};
delete input.old_source;
delete input.deposit_id;
delete input.deposit_weight;
delete input.surplus_mode;
delete input.surplus_memo;
const q = recoveryCalculate(input);
input.payment_account =
q.netSettlement > 0
? draft.payment_method === '信用卡'
? '麦麦信用卡'
: (draft.payment_recipient || context.memberAccountPrefix(draft.member)) + (draft.payment_method || '微信')
: context.memberAccountPrefix(draft.payer || draft.member) + (draft.payout_method || '微信');
return input;
}
function recoveryInputShape(input) {
return (
input &&
Object.hasOwn(recoveryModeNames, input.mode) &&
context.validOrderDate(input.date) &&
typeof input.customer === 'string' &&
typeof input.salesperson === 'string' &&
context.teamMemberKeys().includes(input.member) &&
Array.isArray(input.old_lines) &&
input.old_lines.length > 0 &&
input.old_lines.every(
row =>
row && ['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)))
);
}
function validateRecoveryEditDetail(data, id) {
if (
!data ||
data.id !== id ||
data.record?.id !== id ||
!Number.isSafeInteger(data.revision) ||
data.revision < 1 ||
!['active', 'cancelled'].includes(data.status) ||
!recoveryInputShape(data.inputs) ||
!data.permissions ||
!['canEdit', 'canCancel', 'canDirect', 'requiresApproval'].every(
key => typeof data.permissions[key] === 'boolean',
) ||
!Array.isArray(data.blockedUsages) ||
!Array.isArray(data.history) ||
(context.state.user.role !== 'owner' && data.inputs.member !== context.currentMember())
)
throw new Error('回收更正资料未完整返回或不属于当前成员,请重新读取。');
if (data.record.member !== data.inputs.member || data.record.mode !== data.inputs.mode)
throw new Error('回收记录身份与修改资料不一致。');
if (data.pending && validateRecoveryChangeRequest(data.pending).recoveryId !== id)
throw new Error('回收申请不属于当前记录。');
if (data.history.some(row => validateRecoveryChangeRequest(row).recoveryId !== id))
throw new Error('回收更正历史不属于当前记录。');
return data;
}
function validateRecoveryChangeRequest(request) {
if (
!request ||
typeof request.id !== 'string' ||
!request.id ||
typeof request.recoveryId !== 'string' ||
!Number.isSafeInteger(request.revision) ||
request.revision < 1 ||
!Number.isSafeInteger(request.recoveryRevision) ||
request.recoveryRevision < 1 ||
!['update', 'cancel'].includes(request.action) ||
!['pending', 'approved', 'rejected'].includes(request.status) ||
!recoveryInputShape(request.before) ||
(request.action === 'update' && !recoveryInputShape(request.after)) ||
(request.action === 'cancel' && request.after !== null) ||
typeof request.canApprove !== 'boolean' ||
!request.summary ||
request.member !== request.before.member ||
(request.after && (request.after.member !== request.member || request.after.mode !== request.before.mode)) ||
(context.state.user.role !== 'owner' && request.member !== context.currentMember())
)
throw new Error('回收更正申请未完整返回或不属于当前成员,请重新读取。');
return request;
}
function recoveryEditDraft(input) {
if (input.exchange?.items) {
const rows = input.exchange.items.map(row => recoveryEditDraft({ ...input, ...row, exchange: row.exchange })),
first = rows[0],
x = input.exchange;
return {
...first,
independent_products: rows.length > 1,
extra_products: rows.slice(1),
charges: x.charges,
charge_name: x.charges[0]?.name || '其他收费',
charge_amount: x.charges[0]?.amount || '0',
fee_items: x.fee_items,
fee_note: x.fee_items[0]?.note || '其他费用',
fee_amount: x.fee_items[0]?.amount || '0',
fee_payer: x.fee_items[0]?.payer || input.member,
discount: x.discount,
rounding_mode: x.rounding_mode,
};
}
const first = input.old_lines[0],
x = input.exchange || {},
charge = x.charges?.[0],
fee = x.fee_items?.[0],
account = input.payment_account || '',
identity = context.accountIdentity(account),
recipient = identity ? context.memberAccountPrefix(identity.member) : context.memberAccountPrefix(input.member),
method = identity?.channel || '微信';
return {
...recoveryDefaults(input.mode),
mode: input.mode,
surplus_mode: input.surplus_mode || 'buy',
surplus_memo: input.surplus_memo || '',
old_source: input.old_source || 'incoming',
deposit_id: input.deposit_id || '',
deposit_weight: input.deposit_weight || '',
date: input.date,
customer: input.customer,
salesperson: input.salesperson,
member: input.member,
note: input.note || '',
old_pocket: input.old_pocket ?? '回收旧料',
old_stock_count: input.old_stock_count ?? '',
old_name: first.name,
incoming_weight: first.incoming_weight,
melted_weight: first.melted_weight,
purity: first.purity,
old_lines: JSON.parse(JSON.stringify(input.old_lines)),
buy_rate: input.buy_rate,
buy_total: input.buy_total ?? '',
buy_total_manual: Object.hasOwn(input, 'buy_total'),
melted_manual: true,
depreciation_manual: Object.hasOwn(x, 'depreciation_weight'),
payer: input.payer,
payment_method: method,
payment_recipient: recipient,
payout_method: method === '信用卡' ? '微信' : method,
new_name: x.name || '足金999',
new_quantity: x.quantity || '',
pocket: x.pocket ?? context.state.pockets[0] ?? '',
stockCount: x.stockCount ?? '',
gold_price: x.gold_price || '0',
labor_mode: x.labor_mode || 'gram',
labor_rate: x.labor_rate || '0',
depreciation_weight: x.depreciation_weight ?? '',
depreciation_rate: x.depreciation_rate || '0',
charge_name: charge?.name || '其他收费',
charge_amount: charge?.amount || '0',
charges: JSON.parse(JSON.stringify(x.charges || [])),
discount: x.discount || '0',
rounding_mode: x.rounding_mode || 'cent',
material_source: x.cost_material?.mode === 'pool' ? 'pool' : 'manual',
material_pool_id: x.cost_material?.poolId || input.date,
material_rate: x.cost_material?.rate || '',
material_payer: x.cost_material_payer || input.member,
cost_labor_mode: x.cost_labor?.mode || 'total',
cost_labor_value: x.cost_labor?.mode === 'gram' ? x.cost_labor.rate : (x.cost_labor?.amount ?? ''),
cost_payer: x.cost_payer || input.member,
labor_payer: x.cost_labor_payer || x.cost_payer || input.member,
fee_note: fee?.note || '其他费用',
fee_amount: fee?.amount || '0',
fee_payer: fee?.payer || input.member,
fee_items: JSON.parse(JSON.stringify(x.fee_items || [])),
...(x.products
? { ...recoveryProductDraft(x.products[0]), extra_products: x.products.slice(1).map(recoveryProductDraft) }
: {}),
verified: false,
};
}
return {
defaults: recoveryDefaults,
forEdit: recoveryEditDraft,
sharedDraft: recoverySharedOldDraft,
input: recoveryInput,
calculate: recoveryCalculate,
validate: validateRecoveryInput,
newWeight: recoveryNewWeight,
units: recoveryUnits,
multiply: recoveryMul,
checkEdit: validateRecoveryEditDetail,
checkRequest: validateRecoveryChangeRequest,
};
}
const api = { createModel, recoveryModeNames, recoveryProductFields, customerMaterialOldLines };
if (typeof module === 'object' && module.exports) module.exports = api;
else root.RecoveryRules = api;
})(typeof globalThis === 'object' ? globalThis : this);