保存工作区合并前的本地开发现场 ledger-migration-typed-54c0587
This commit is contained in:
1 parent
54c05879d5
commit
d18273ac37
82 files changed
+8878
-4757
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);
|
||||
@@ -1,15 +1,19 @@
|
||||
'use strict';
|
||||
// 手续费预览使用整数分;真实费用由服务端按每笔客户付款生成。
|
||||
(function (root) {
|
||||
/** @param {string} account */
|
||||
const isAccount = account => ['助理信用卡', '助理1信用卡', '麦麦信用卡', '助理2信用卡'].includes(account);
|
||||
const ratePermille = 6;
|
||||
function rate(value = ratePermille) {
|
||||
if (!Number.isSafeInteger(value) || value < 0 || value > 1000) throw new Error('信用卡手续费率须为0~1000的整数‰');
|
||||
return value;
|
||||
}
|
||||
/** @param {string} account */
|
||||
const normalizeAccount = account => (isAccount(account) ? '麦麦信用卡' : account);
|
||||
const note = (value = ratePermille) => `信用卡手续费(${rate(value)}‰)`;
|
||||
/** @param {{system?: string; key?: string} | null | undefined} item */
|
||||
const isFee = item => item?.system === 'credit_card' || String(item?.key || '').startsWith('card_fee:');
|
||||
/** @param {number} cents @param {number} [value] */
|
||||
function amount(cents, value = ratePermille) {
|
||||
if (!Number.isSafeInteger(cents) || cents < 0 || cents > 100000000000) throw new Error('客户付款金额无效');
|
||||
return Number((BigInt(cents) * BigInt(rate(value)) + 500n) / 1000n);
|
||||
@@ -17,4 +21,4 @@
|
||||
const api = { isAccount, isFee, amount, rate, ratePermille, normalizeAccount, note };
|
||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||
else root.CreditCardFees = api;
|
||||
})(typeof globalThis === 'object' ? globalThis : this);
|
||||
})(typeof globalThis === 'object' ? globalThis : /** @type {typeof globalThis} */ (/** @type {unknown} */ (this)));
|
||||
@@ -1,10 +1,30 @@
|
||||
'use strict';
|
||||
// 只生成可修改的预估值,不写支付流水。金额输入与表单一致,使用元的字符串。
|
||||
/**
|
||||
* @typedef {{amount:string,payer:string,name?:string,enabled?:boolean,byQuantity?:boolean}} CostPreset
|
||||
* @typedef {Record<string,CostPreset>} Presets
|
||||
*/
|
||||
/**
|
||||
* @template [Amount=string]
|
||||
* @typedef {{
|
||||
* key: string, note: string, amount: Amount|null, payer: string, edited?: boolean, status?: string,
|
||||
* sourceName?: string, lineNumber?: number, expense_id?: string, funding?: Record<string,unknown>
|
||||
* }} FeeItem
|
||||
*/
|
||||
/**
|
||||
* @typedef {{id?:string,name?:string,costRemoved?:boolean}} SaleCharge
|
||||
* @typedef {{certificate?:string,packaging?:string,shipping?:string,packagingPayer?:string}} ShopCosts
|
||||
*/
|
||||
(function (root) {
|
||||
const Calc = typeof module === 'object' && module.exports ? require('./calculations') : root.LedgerCalc;
|
||||
const Calc =
|
||||
typeof module === 'object' && module.exports
|
||||
? require('./calculations')
|
||||
: /** @type {typeof globalThis} */ (root).LedgerCalc;
|
||||
const defaults = { 证书: '4', 包装: '3', 快递: '6' };
|
||||
const normalize = name => ({ 包装盒: '包装', 快递费: '快递', 运费: '快递' })[name] || name;
|
||||
const normalize = (/** @type {string} */ name) =>
|
||||
/** @type {Record<string,string>} */ ({ 包装盒: '包装', 快递费: '快递', 运费: '快递' })[name] || name;
|
||||
// 勾选成本与客户收费分开。保留旧项目,只有明确勾选的新项目使用这些固定金额。
|
||||
/** @param {unknown} name */
|
||||
function checkboxCategory(name) {
|
||||
const value = String(name || '').trim();
|
||||
if (['快递', '快递费', '运费', '京东快递', '圆通快递'].includes(value)) return 'shipping';
|
||||
@@ -13,6 +33,7 @@
|
||||
if (['银链', '银链(家里)', '银链(家里)'].includes(value)) return 'silverChain';
|
||||
return '';
|
||||
}
|
||||
/** @param {unknown} value */
|
||||
function boxCount(value) {
|
||||
const text = String(value ?? '').trim(),
|
||||
count = Number(text);
|
||||
@@ -20,6 +41,7 @@
|
||||
throw new Error('盒子数量须为支持范围内的正整数');
|
||||
return count;
|
||||
}
|
||||
/** @type {Readonly<Presets>} */
|
||||
const presetDefaults = Object.freeze({
|
||||
jd: { amount: '8', payer: 'owner' },
|
||||
yt: { amount: '6', payer: 'order' },
|
||||
@@ -27,9 +49,11 @@
|
||||
steel: { amount: '7', payer: 'owner' },
|
||||
silver: { amount: '18', payer: 'owner' },
|
||||
});
|
||||
const validMember = value =>
|
||||
const validMember = (/** @type {string} */ value) =>
|
||||
['owner', 'assistant', 'assistant2'].includes(value) || /^staff_[a-f0-9-]{36}$/.test(value);
|
||||
/** @type {Record<string,string>} */
|
||||
const presetNames = { jd: '京东快递', yt: '圆通快递', box: '盒子', steel: '钢绳(店里)', silver: '银链(家里)' };
|
||||
/** @param {Presets} [values] */
|
||||
function presets(values) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(values === undefined ? presetDefaults : values)
|
||||
@@ -37,6 +61,7 @@
|
||||
.map(([kind, row]) => [kind, { ...presetDefaults[kind], ...row }]),
|
||||
);
|
||||
}
|
||||
/** @param {Presets} [values] */
|
||||
function presetCatalog(values) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(presets(values)).map(([kind, row]) => [
|
||||
@@ -45,6 +70,7 @@
|
||||
]),
|
||||
);
|
||||
}
|
||||
/** @param {Presets} [values] */
|
||||
function customPresets(values) {
|
||||
return (
|
||||
(values !== undefined && Object.keys(presetDefaults).some(kind => !Object.hasOwn(values, kind))) ||
|
||||
@@ -55,12 +81,24 @@
|
||||
)
|
||||
);
|
||||
}
|
||||
/** @param {string} kind */
|
||||
function presetKey(kind) {
|
||||
return (
|
||||
{ jd: 'shipping', yt: 'shipping', box: 'box', steel: 'braiding', silver: 'other' }[kind] ||
|
||||
'manual:' + kind.slice(7)
|
||||
/** @type {Record<string,string>} */ ({
|
||||
jd: 'shipping',
|
||||
yt: 'shipping',
|
||||
box: 'box',
|
||||
steel: 'braiding',
|
||||
silver: 'other',
|
||||
})[kind] || 'manual:' + kind.slice(7)
|
||||
);
|
||||
}
|
||||
/**
|
||||
* @param {string} kind
|
||||
* @param {unknown} quantity
|
||||
* @param {string} member
|
||||
* @param {Presets} [values]
|
||||
*/
|
||||
function presetFee(kind, quantity, member, values) {
|
||||
const row = presetCatalog(values)[kind];
|
||||
if (!row || !row.enabled) throw new Error('成本项目已停用,请重新核对');
|
||||
@@ -76,6 +114,10 @@
|
||||
edited: true,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* @param {FeeItem<string|number>} item
|
||||
* @param {Presets} [values]
|
||||
*/
|
||||
function configuredKind(item, values) {
|
||||
for (const [kind, row] of Object.entries(presetCatalog(values))) {
|
||||
if (!row.enabled || item.key !== presetKey(kind)) continue;
|
||||
@@ -92,9 +134,13 @@
|
||||
}
|
||||
return '';
|
||||
}
|
||||
/**
|
||||
* @param {FeeItem<string|number>} item
|
||||
* @param {{recorded?:boolean,presets?:Presets}} [options]
|
||||
*/
|
||||
function presetKind(item, { recorded = false, presets: values } = {}) {
|
||||
const config = presets(values),
|
||||
matchPayer = kind =>
|
||||
matchPayer = (/** @type {string} */ kind) =>
|
||||
config[kind].payer === 'order' ? validMember(item?.payer) : item?.payer === config[kind].payer;
|
||||
if (!item || (item.expense_id && !recorded) || item.funding) return '';
|
||||
if (customPresets(values)) return configuredKind(item, values);
|
||||
@@ -139,16 +185,21 @@
|
||||
}
|
||||
return '';
|
||||
}
|
||||
/**
|
||||
* @param {{shipping?:string,box?:boolean,quantity?:string,steel?:boolean,silver?:boolean}} [selection]
|
||||
* @param {string} [member]
|
||||
* @param {Presets} [values]
|
||||
*/
|
||||
function checkboxFees(
|
||||
{ shipping = '', box = false, quantity = '1', steel = false, silver = false } = {},
|
||||
member = 'assistant',
|
||||
values,
|
||||
) {
|
||||
const config = presets(values),
|
||||
items = [],
|
||||
payer = kind =>
|
||||
items = /** @type {FeeItem[]} */ ([]),
|
||||
payer = (/** @type {string} */ kind) =>
|
||||
config[kind].payer === 'order' ? (validMember(member) ? member : 'assistant') : config[kind].payer;
|
||||
const add = (kind, key, note, count = 1) => {
|
||||
const add = (/** @type {string} */ kind, /** @type {string} */ key, /** @type {string} */ note, count = 1) => {
|
||||
const amount = Calc.cents(String(config[kind].amount), '常用成本') * count;
|
||||
if (!Number.isSafeInteger(amount) || amount > 100000000000) throw new Error('常用成本金额超出支持范围');
|
||||
items.push({
|
||||
@@ -170,23 +221,30 @@
|
||||
if (silver) add('silver', 'other', '银链(家里)');
|
||||
return items;
|
||||
}
|
||||
/**
|
||||
* @template Amount
|
||||
* @param {FeeItem<Amount>[]} existing
|
||||
* @param {{charges?:SaleCharge[]}[]} lines
|
||||
* @param {{addShipping?:boolean,defaultPayer?:string,shopDefaults?:ShopCosts,checkboxCosts?:boolean}} [options]
|
||||
*/
|
||||
function sync(
|
||||
existing,
|
||||
lines,
|
||||
{ addShipping = false, defaultPayer = 'assistant', shopDefaults = {}, checkboxCosts = false } = {},
|
||||
) {
|
||||
/** @type {Record<string,string>} */
|
||||
const configured = {
|
||||
证书: shopDefaults.certificate ?? defaults['证书'],
|
||||
包装: shopDefaults.packaging ?? defaults['包装'],
|
||||
快递: shopDefaults.shipping ?? defaults['快递'],
|
||||
};
|
||||
const packagingPayer =
|
||||
['owner', 'assistant', 'assistant2'].includes(shopDefaults.packagingPayer) ||
|
||||
/^staff_[a-f0-9-]{36}$/.test(shopDefaults.packagingPayer)
|
||||
shopDefaults.packagingPayer !== undefined && validMember(shopDefaults.packagingPayer)
|
||||
? shopDefaults.packagingPayer
|
||||
: 'owner';
|
||||
/** @type {FeeItem<string|Amount>[]} */
|
||||
const remaining = existing.map(r => ({ ...r })),
|
||||
linked = [];
|
||||
linked = /** @type {FeeItem<string|Amount>[]} */ ([]);
|
||||
for (const [index, line] of lines.entries())
|
||||
for (const charge of line.charges || []) {
|
||||
const name = String(charge.name || '').trim();
|
||||
@@ -280,5 +338,5 @@
|
||||
checkboxFees,
|
||||
};
|
||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||
else root.FeeEstimates = api;
|
||||
else Object.assign(root, { FeeEstimates: api });
|
||||
})(typeof globalThis === 'object' ? globalThis : this);
|
||||
@@ -0,0 +1,90 @@
|
||||
'use strict';
|
||||
// 单位换算、业务日期与收款账户识别。页面自行决定币种符号、空值文案和日期范围。
|
||||
(function (root) {
|
||||
/** @param {number} cents @param {number} [places] */
|
||||
const yuan = (cents, places = 2) =>
|
||||
(cents / 100).toLocaleString('zh-CN', { minimumFractionDigits: places, maximumFractionDigits: places });
|
||||
/** @param {number} mg */
|
||||
const grams = mg => (mg / 1000).toFixed(3);
|
||||
|
||||
/** 克输入转为整数毫克。空值、零、超出业务范围或精度的输入返回 null。 @param {unknown} input */
|
||||
function positiveMg(input) {
|
||||
const text = String(input ?? '').trim();
|
||||
if (!/^\d+(?:\.\d{1,3})?$/.test(text)) return null;
|
||||
const [whole, fraction = ''] = text.split('.');
|
||||
const mg = BigInt(whole) * 1000n + BigInt(fraction.padEnd(3, '0'));
|
||||
return mg > 0n && mg <= 100000000000n ? Number(mg) : null;
|
||||
}
|
||||
|
||||
/** @param {unknown} value @returns {value is string} */
|
||||
function validDate(value) {
|
||||
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
|
||||
const date = new Date(value + 'T12:00:00Z');
|
||||
return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value;
|
||||
}
|
||||
|
||||
/** @param {string} day */
|
||||
function previousDate(day) {
|
||||
const date = new Date(day + 'T12:00:00Z');
|
||||
date.setUTCDate(date.getUTCDate() - 1);
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
/** @type {Record<string,string>} */
|
||||
const prefixes = { owner: '麦麦', assistant: '助理', assistant2: '助理2' };
|
||||
/** @param {string} member */
|
||||
const memberAccountPrefix = member => prefixes[member] || member;
|
||||
/** @param {readonly string[]} members @param {unknown} value */
|
||||
function accountIdentity(members, value) {
|
||||
const text = String(value ?? '');
|
||||
for (const member of members) {
|
||||
const names = member === 'assistant' ? ['助理', '助理1'] : [memberAccountPrefix(member)];
|
||||
for (const prefix of names) {
|
||||
if (text === prefix) return { member, prefix, channel: '' };
|
||||
const channel = text.slice(prefix.length);
|
||||
if (text.startsWith(prefix) && ['微信', '支付宝', '现金', '信用卡'].includes(channel))
|
||||
return { member, prefix, channel };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @typedef {{member: string, label?: string, enabled?: boolean}} Member */
|
||||
/** @typedef {{members?: Member[], shopSettings?: {members?: Member[]}, user?: {member?: string}}} MemberState */
|
||||
const legacyMembers = [
|
||||
{ member: 'owner', label: '麦麦' },
|
||||
{ member: 'assistant', label: '娜娜' },
|
||||
{ member: 'assistant2', label: '小昊' },
|
||||
];
|
||||
/** @param {MemberState | null | undefined} state @returns {Member[]} */
|
||||
function memberCatalog(state) {
|
||||
const rows = state?.members?.length
|
||||
? state.members
|
||||
: state?.shopSettings?.members?.length
|
||||
? state.shopSettings.members
|
||||
: legacyMembers;
|
||||
return rows.filter(row => row && typeof row.member === 'string');
|
||||
}
|
||||
/** @param {MemberState | null | undefined} state */
|
||||
const memberKeys = state => memberCatalog(state).map(row => row.member);
|
||||
/** @param {MemberState | null | undefined} state @param {string} key */
|
||||
const memberEnabled = (state, key) => {
|
||||
const row = memberCatalog(state).find(row => row.member === key);
|
||||
return !!row && row.enabled !== false;
|
||||
};
|
||||
|
||||
const api = {
|
||||
memberCatalog,
|
||||
memberKeys,
|
||||
memberEnabled,
|
||||
yuan,
|
||||
grams,
|
||||
positiveMg,
|
||||
validDate,
|
||||
previousDate,
|
||||
memberAccountPrefix,
|
||||
accountIdentity,
|
||||
};
|
||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||
else Object.assign(root, { LedgerValues: api });
|
||||
})(typeof globalThis === 'object' ? globalThis : this);
|
||||
+291
-265
@@ -7,281 +7,307 @@
|
||||
);
|
||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||
else root.OrderCopy = api;
|
||||
})(typeof globalThis === 'object' ? globalThis : this, function (Fees, Cards) {
|
||||
const money = value => (value == null ? '' : (value / 100).toFixed(2));
|
||||
const nonblank = value => value != null && String(value).trim() !== '';
|
||||
const normalizeAccount = account =>
|
||||
Cards?.normalizeAccount
|
||||
? Cards.normalizeAccount(account)
|
||||
: ['助理信用卡', '助理1信用卡', '助理2信用卡', '麦麦信用卡'].includes(account)
|
||||
? '麦麦信用卡'
|
||||
: account;
|
||||
const cardFee = item => item?.system === 'credit_card' || String(item?.key || '').startsWith('card_fee:');
|
||||
function inputs(order) {
|
||||
return {
|
||||
...order,
|
||||
rounding_mode: order.rounding_mode || 'cent',
|
||||
discount: money(order.discount),
|
||||
fee_items: (order.fee_items || []).map(item => ({ ...item, amount: money(item.amount) })),
|
||||
lines: order.lines.map(line => ({
|
||||
...line,
|
||||
quantity: line.unit === 'g' ? (line.quantity / 1000).toFixed(3) : line.quantity,
|
||||
sale: money(line.sale),
|
||||
baseSale: money(line.baseSale ?? line.sale),
|
||||
cost: money(line.cost),
|
||||
costMaterial:
|
||||
line.costMaterial?.mode === 'pool'
|
||||
? { ...line.costMaterial }
|
||||
: {
|
||||
mode:
|
||||
line.costMaterial?.mode ||
|
||||
((line.unit || 'g') === 'g' && line.costParts?.material == null ? 'gram' : 'total'),
|
||||
...(line.costMaterial?.mode === 'gram' ? { rate: money(line.costMaterial.rate) } : {}),
|
||||
},
|
||||
costLabor: { mode: line.costLabor?.mode || 'total', rate: money(line.costLabor?.rate) },
|
||||
charges: (line.charges || []).map(charge => ({ ...charge, amount: money(charge.amount) })),
|
||||
...(line.pricingMode === 'auto' ? { goldPrice: money(line.goldPrice), laborRate: money(line.laborRate) } : {}),
|
||||
...(line.costParts
|
||||
? { costParts: Object.fromEntries(Object.entries(line.costParts).map(([key, value]) => [key, money(value)])) }
|
||||
: {}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
function copyFees(order, lines, chargeIds, newId) {
|
||||
const corrected = new Set((order.corrections || []).filter(row => row.type === 'expense').map(row => row.target));
|
||||
const cardExpenseIds = new Set(
|
||||
order.fee_items
|
||||
.filter(cardFee)
|
||||
.map(fee => fee.expense_id)
|
||||
.filter(Boolean),
|
||||
);
|
||||
const positives = order.expenses.filter(
|
||||
row =>
|
||||
row.amount > 0 &&
|
||||
!String(row.note || '').startsWith('更正冲回:') &&
|
||||
!cardFee(row) &&
|
||||
!cardExpenseIds.has(row.id),
|
||||
);
|
||||
const active = positives.filter(row => !corrected.has(row.id)),
|
||||
matched = new Set(),
|
||||
used = new Set(),
|
||||
items = [];
|
||||
const pending = new Set((order.pendingFees || []).map(item => item.key));
|
||||
const same = (expense, fee) =>
|
||||
expense.amount === fee.amount &&
|
||||
expense.payer === fee.payer &&
|
||||
Fees.normalize(expense.note) === Fees.normalize(fee.note);
|
||||
for (const fee of order.fee_items) {
|
||||
if (cardFee(fee) || (fee.expense_id && cardExpenseIds.has(fee.expense_id))) continue;
|
||||
const linked = chargeIds.get(String(fee.key).replace(/^charge:/, ''));
|
||||
const key = linked ? 'charge:' + linked : fee.key === 'shipping' ? 'shipping' : 'manual:' + newId();
|
||||
let amount = fee.amount,
|
||||
payer = fee.payer;
|
||||
// 已入账模板仍保留旧金额;实际流水和更正结果才是当前支出的依据。
|
||||
if (fee.status !== 'estimated' && !pending.has(fee.key)) {
|
||||
const source = positives.find(expense => !matched.has(expense.id) && same(expense, fee));
|
||||
if (source) {
|
||||
matched.add(source.id);
|
||||
if (corrected.has(source.id)) amount = 0;
|
||||
else used.add(source.id);
|
||||
} else amount = 0;
|
||||
})(
|
||||
typeof globalThis === 'object' ? globalThis : /** @type {typeof globalThis} */ (/** @type {unknown} */ (this)),
|
||||
/** @param {typeof import('./fee-estimates')} Fees @param {typeof import('./credit-card-fees')} Cards */ function (
|
||||
Fees,
|
||||
Cards,
|
||||
) {
|
||||
/** @param {number|null|undefined} value */
|
||||
const money = value => (value == null ? '' : (value / 100).toFixed(2));
|
||||
/** @param {unknown} value */
|
||||
const nonblank = value => value != null && String(value).trim() !== '';
|
||||
/** @param {string} account */
|
||||
const normalizeAccount = account =>
|
||||
Cards?.normalizeAccount
|
||||
? Cards.normalizeAccount(account)
|
||||
: ['助理信用卡', '助理1信用卡', '助理2信用卡', '麦麦信用卡'].includes(account)
|
||||
? '麦麦信用卡'
|
||||
: account;
|
||||
/** @param {{system?:string;key?:string}} item */
|
||||
const cardFee = item => item?.system === 'credit_card' || String(item?.key || '').startsWith('card_fee:');
|
||||
/** @param {import('../web/src/shared/orderPresets').CopySource} order */
|
||||
function inputs(order) {
|
||||
return {
|
||||
...order,
|
||||
rounding_mode: order.rounding_mode || 'cent',
|
||||
discount: money(order.discount),
|
||||
fee_items: (order.fee_items || []).map(item => ({ ...item, amount: money(item.amount) })),
|
||||
lines: order.lines.map(line => ({
|
||||
...line,
|
||||
quantity: line.unit === 'g' ? (line.quantity / 1000).toFixed(3) : line.quantity,
|
||||
sale: money(line.sale),
|
||||
baseSale: money(line.baseSale ?? line.sale),
|
||||
cost: money(line.cost),
|
||||
costMaterial:
|
||||
line.costMaterial?.mode === 'pool'
|
||||
? { ...line.costMaterial }
|
||||
: {
|
||||
mode:
|
||||
line.costMaterial?.mode ||
|
||||
((line.unit || 'g') === 'g' && line.costParts?.material == null ? 'gram' : 'total'),
|
||||
...(line.costMaterial?.mode === 'gram' ? { rate: money(line.costMaterial.rate) } : {}),
|
||||
},
|
||||
costLabor: { mode: line.costLabor?.mode || 'total', rate: money(line.costLabor?.rate) },
|
||||
charges: (line.charges || []).map(charge => ({ ...charge, amount: money(charge.amount) })),
|
||||
...(line.pricingMode === 'auto'
|
||||
? { goldPrice: money(line.goldPrice), laborRate: money(line.laborRate) }
|
||||
: {}),
|
||||
...(line.costParts
|
||||
? {
|
||||
costParts: Object.fromEntries(
|
||||
Object.entries(line.costParts).map(([key, value]) => [key, money(value)]),
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
/** @param {import('../web/src/shared/orderPresets').CopySource} order @param {import('../web/src/shared/orderPresets').DraftProduct[]} lines @param {Map<string,string>} chargeIds @param {()=>string} newId */
|
||||
function copyFees(order, lines, chargeIds, newId) {
|
||||
const corrected = new Set((order.corrections || []).filter(row => row.type === 'expense').map(row => row.target));
|
||||
const cardExpenseIds = new Set(
|
||||
order.fee_items
|
||||
.filter(cardFee)
|
||||
.map(fee => fee.expense_id)
|
||||
.filter(Boolean),
|
||||
);
|
||||
const positives = order.expenses.filter(
|
||||
row =>
|
||||
row.amount > 0 &&
|
||||
!String(row.note || '').startsWith('更正冲回:') &&
|
||||
!cardFee(row) &&
|
||||
!cardExpenseIds.has(row.id),
|
||||
);
|
||||
const active = positives.filter(row => !corrected.has(row.id)),
|
||||
matched = new Set(),
|
||||
used = new Set(),
|
||||
items = /** @type {import('../web/src/shared/orderPresets').TemplateFee[]} */ ([]);
|
||||
const pending = new Set((order.pendingFees || []).map(item => item.key));
|
||||
/** @param {import('../web/src/shared/orderPresets').Expense} expense @param {import('../web/src/shared/orderPresets').SavedFee} fee */
|
||||
const same = (expense, fee) =>
|
||||
expense.amount === fee.amount &&
|
||||
expense.payer === fee.payer &&
|
||||
Fees.normalize(expense.note) === Fees.normalize(fee.note);
|
||||
for (const fee of order.fee_items) {
|
||||
if (cardFee(fee) || (fee.expense_id && cardExpenseIds.has(fee.expense_id))) continue;
|
||||
const linked = chargeIds.get(String(fee.key).replace(/^charge:/, ''));
|
||||
const key = linked ? 'charge:' + linked : fee.key === 'shipping' ? 'shipping' : 'manual:' + newId();
|
||||
let amount = fee.amount,
|
||||
payer = fee.payer;
|
||||
// 已入账模板仍保留旧金额;实际流水和更正结果才是当前支出的依据。
|
||||
if (fee.status !== 'estimated' && !pending.has(fee.key)) {
|
||||
const source = positives.find(expense => !matched.has(expense.id) && same(expense, fee));
|
||||
if (source) {
|
||||
matched.add(source.id);
|
||||
if (corrected.has(source.id)) amount = 0;
|
||||
else used.add(source.id);
|
||||
} else amount = 0;
|
||||
}
|
||||
items.push({
|
||||
key,
|
||||
note: fee.note,
|
||||
amount: money(amount),
|
||||
payer,
|
||||
status: 'estimated',
|
||||
edited: true,
|
||||
...(linked ? { sourceName: fee.sourceName || fee.note } : {}),
|
||||
});
|
||||
}
|
||||
items.push({
|
||||
key,
|
||||
note: fee.note,
|
||||
amount: money(amount),
|
||||
payer,
|
||||
status: 'estimated',
|
||||
edited: true,
|
||||
...(linked ? { sourceName: fee.sourceName || fee.note } : {}),
|
||||
});
|
||||
}
|
||||
for (const expense of active) {
|
||||
if (used.has(expense.id)) continue;
|
||||
const key =
|
||||
Fees.normalize(expense.note) === '快递' && !items.some(item => item.key === 'shipping')
|
||||
? 'shipping'
|
||||
: 'manual:' + newId();
|
||||
items.push({
|
||||
key,
|
||||
note: expense.note,
|
||||
amount: money(expense.amount),
|
||||
payer: expense.payer,
|
||||
status: 'estimated',
|
||||
edited: true,
|
||||
});
|
||||
}
|
||||
const completed = ['delivered', 'returned', 'cancelled'].includes(order.status);
|
||||
for (const [index, line] of lines.entries())
|
||||
for (const charge of line.charges) {
|
||||
if (charge.costRemoved === true) continue;
|
||||
const shipping = Fees.normalize(charge.name) === '快递',
|
||||
key = shipping ? 'shipping' : 'charge:' + charge.id;
|
||||
if (items.some(item => item.key === key)) continue;
|
||||
const found = items.find(
|
||||
item => item.key.startsWith('manual:') && Fees.normalize(item.note) === Fees.normalize(charge.name),
|
||||
);
|
||||
if (found) found.key = key;
|
||||
else
|
||||
items.push({
|
||||
for (const expense of active) {
|
||||
if (used.has(expense.id)) continue;
|
||||
/** @type {string} */
|
||||
const key =
|
||||
Fees.normalize(expense.note) === '快递' && !items.some(item => item.key === 'shipping')
|
||||
? 'shipping'
|
||||
: 'manual:' + newId();
|
||||
items.push({
|
||||
key,
|
||||
note: expense.note,
|
||||
amount: money(expense.amount),
|
||||
payer: expense.payer,
|
||||
status: 'estimated',
|
||||
edited: true,
|
||||
});
|
||||
}
|
||||
const completed = ['delivered', 'returned', 'cancelled'].includes(order.status);
|
||||
for (const [index, line] of lines.entries())
|
||||
for (const charge of line.charges || []) {
|
||||
if (charge.costRemoved === true) continue;
|
||||
const shipping = Fees.normalize(charge.name) === '快递',
|
||||
key = shipping ? 'shipping' : 'charge:' + charge.id;
|
||||
if (items.some(item => item.key === key)) continue;
|
||||
const found = items.find(
|
||||
item => item.key.startsWith('manual:') && Fees.normalize(item.note) === Fees.normalize(charge.name),
|
||||
);
|
||||
const item = found || {
|
||||
key,
|
||||
note: shipping ? '快递费' : charge.name,
|
||||
amount: completed ? '0.00' : '',
|
||||
payer: Fees.normalize(charge.name) === '包装' ? 'owner' : 'assistant',
|
||||
status: 'estimated',
|
||||
edited: true,
|
||||
});
|
||||
if (!shipping)
|
||||
Object.assign(
|
||||
items.find(item => item.key === key),
|
||||
{ sourceName: charge.name, lineNumber: index + 1 },
|
||||
);
|
||||
}
|
||||
// 所有项都标记手填,后续同步项目名称时不重新套用默认成本。
|
||||
return Fees.sync(items, lines);
|
||||
}
|
||||
function fromOrder(order, { today, newId = () => globalThis.crypto.randomUUID() } = {}) {
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(today || '')) throw new Error('未取得系统日期,请刷新后再复制。');
|
||||
if (!order || !Array.isArray(order.lines) || !Array.isArray(order.fee_items) || !Array.isArray(order.expenses))
|
||||
throw new Error('订单详情未完整返回,请重新读取后再复制。');
|
||||
const source = inputs(order),
|
||||
chargeIds = new Map(),
|
||||
locked = !!order.price_lock_id || order.lines.some(line => line.materialAllocations?.length);
|
||||
const lines = source.lines.map(line => {
|
||||
const result = Object.fromEntries(
|
||||
[
|
||||
'name',
|
||||
'nameType',
|
||||
'customName',
|
||||
'unit',
|
||||
'quantity',
|
||||
'pocket',
|
||||
'stockCount',
|
||||
'payer',
|
||||
'pricingMode',
|
||||
'goldPrice',
|
||||
'laborMode',
|
||||
'laborRate',
|
||||
'pieces',
|
||||
'priceNote',
|
||||
'sale',
|
||||
'baseSale',
|
||||
]
|
||||
.filter(key => Object.hasOwn(line, key))
|
||||
.map(key => [key, line[key]]),
|
||||
);
|
||||
result.charges = line.charges.map(charge => {
|
||||
const id = newId();
|
||||
if (charge.id) chargeIds.set(charge.id, id);
|
||||
return {
|
||||
id,
|
||||
name: charge.name,
|
||||
amount: charge.amount,
|
||||
...(charge.costRemoved === true ? { costRemoved: true } : {}),
|
||||
};
|
||||
});
|
||||
if (line.costParts) {
|
||||
result.costParts = { ...line.costParts };
|
||||
result.costMaterial = { ...line.costMaterial };
|
||||
result.costLabor = { ...line.costLabor };
|
||||
result.costPayers = {
|
||||
material: line.costPayers?.material ?? line.payer ?? 'owner',
|
||||
labor: line.costPayers?.labor ?? line.payer ?? 'owner',
|
||||
};
|
||||
if (line.costMaterial?.mode === 'pool') {
|
||||
// 同日池随新业务日期走;已经跨日选用的旧池保留选择,耗用快照必须重读。
|
||||
const defaultDate = line.costMaterial.poolId === order.date,
|
||||
poolId = defaultDate ? today : line.costMaterial.poolId;
|
||||
result.costMaterial = { mode: 'pool', poolId };
|
||||
result.costParts.material = '';
|
||||
result.materialPoolDraft = {
|
||||
poolId,
|
||||
defaultDate,
|
||||
manual: { mode: 'gram', rate: '', total: '', originalTotal: '', payer: result.costPayers.material },
|
||||
};
|
||||
item.key = key;
|
||||
if (!found) items.push(item);
|
||||
if (!shipping) Object.assign(item, { sourceName: charge.name, lineNumber: index + 1 });
|
||||
}
|
||||
if (locked) {
|
||||
result.costParts.material = '';
|
||||
result.costMaterial = { mode: 'total' };
|
||||
result.costPayers.material = '';
|
||||
delete result.materialPoolDraft;
|
||||
}
|
||||
} else result.cost = line.cost;
|
||||
return result;
|
||||
});
|
||||
return {
|
||||
date: today,
|
||||
fees_date: today,
|
||||
customer: '',
|
||||
salesperson: source.salesperson || '',
|
||||
payment_account: normalizeAccount(source.payment_account || '助理微信'),
|
||||
discount: source.discount,
|
||||
note: locked
|
||||
? String(source.note || '').replace(/;?锁价单 [^;]*;按原锁定金价 [^;]*元\/克结算$/, '')
|
||||
: source.note || '',
|
||||
rounding_mode: 'yuan',
|
||||
copy_kind: locked ? 'price-lock' : 'ordinary',
|
||||
fee_auto_initialized: true,
|
||||
lines,
|
||||
fee_items: copyFees(order, lines, chargeIds, newId),
|
||||
};
|
||||
}
|
||||
function hasDraftContent(draft, { today, salesperson } = {}) {
|
||||
if (!draft || typeof draft !== 'object' || !Array.isArray(draft.lines)) return !!draft;
|
||||
if (
|
||||
draft.id ||
|
||||
draft.copy_kind ||
|
||||
nonblank(draft.customer) ||
|
||||
nonblank(draft.note) ||
|
||||
nonblank(draft.internal_note) ||
|
||||
Number(draft.discount) ||
|
||||
(draft.date && today && draft.date !== today) ||
|
||||
(draft.salesperson && salesperson && draft.salesperson !== salesperson) ||
|
||||
(draft.payment_account && draft.payment_account !== '助理微信')
|
||||
)
|
||||
return true;
|
||||
if (
|
||||
(draft.fee_items || []).some(
|
||||
item =>
|
||||
item.key !== 'shipping' ||
|
||||
item.edited ||
|
||||
item.status !== 'estimated' ||
|
||||
Number(item.amount) !== 6 ||
|
||||
item.payer !== 'assistant',
|
||||
// 所有项都标记手填,后续同步项目名称时不重新套用默认成本。
|
||||
return Fees.sync(items, lines);
|
||||
}
|
||||
/** @param {import('../web/src/shared/orderPresets').CopySource} order @param {import('../web/src/shared/orderPresets').TemplateOptions} [options] */
|
||||
function fromOrder(order, { today, newId = () => globalThis.crypto.randomUUID() } = {}) {
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(today || '')) throw new Error('未取得系统日期,请刷新后再复制。');
|
||||
if (!order || !Array.isArray(order.lines) || !Array.isArray(order.fee_items) || !Array.isArray(order.expenses))
|
||||
throw new Error('订单详情未完整返回,请重新读取后再复制。');
|
||||
const source = inputs(order),
|
||||
chargeIds = new Map(),
|
||||
locked = !!order.price_lock_id || order.lines.some(line => line.materialAllocations?.length);
|
||||
const lines = source.lines.map(line => {
|
||||
/** @type {import('../web/src/shared/orderPresets').DraftProduct} */
|
||||
const result = Object.fromEntries(
|
||||
/** @type {const} */ ([
|
||||
'name',
|
||||
'nameType',
|
||||
'customName',
|
||||
'unit',
|
||||
'quantity',
|
||||
'pocket',
|
||||
'stockCount',
|
||||
'payer',
|
||||
'pricingMode',
|
||||
'goldPrice',
|
||||
'laborMode',
|
||||
'laborRate',
|
||||
'pieces',
|
||||
'priceNote',
|
||||
'sale',
|
||||
'baseSale',
|
||||
])
|
||||
.filter(key => Object.hasOwn(line, key))
|
||||
.map(key => [key, line[key]]),
|
||||
);
|
||||
result.charges = line.charges.map(charge => {
|
||||
const id = newId();
|
||||
if (charge.id) chargeIds.set(charge.id, id);
|
||||
return {
|
||||
id,
|
||||
name: charge.name,
|
||||
amount: charge.amount,
|
||||
...(charge.costRemoved === true ? { costRemoved: true } : {}),
|
||||
};
|
||||
});
|
||||
if (line.costParts) {
|
||||
result.costParts = { ...line.costParts };
|
||||
result.costMaterial = { ...line.costMaterial };
|
||||
result.costLabor = { ...line.costLabor };
|
||||
result.costPayers = {
|
||||
material: line.costPayers?.material ?? line.payer ?? 'owner',
|
||||
labor: line.costPayers?.labor ?? line.payer ?? 'owner',
|
||||
};
|
||||
if (line.costMaterial?.mode === 'pool') {
|
||||
// 同日池随新业务日期走;已经跨日选用的旧池保留选择,耗用快照必须重读。
|
||||
const defaultDate = result.costMaterial.poolId === order.date,
|
||||
poolId = defaultDate ? today : result.costMaterial.poolId;
|
||||
result.costMaterial = { mode: 'pool', poolId };
|
||||
result.costParts.material = '';
|
||||
result.materialPoolDraft = {
|
||||
poolId,
|
||||
defaultDate,
|
||||
manual: { mode: 'gram', rate: '', total: '', originalTotal: '', payer: result.costPayers.material },
|
||||
};
|
||||
}
|
||||
if (locked) {
|
||||
result.costParts.material = '';
|
||||
result.costMaterial = { mode: 'total' };
|
||||
result.costPayers.material = '';
|
||||
delete result.materialPoolDraft;
|
||||
}
|
||||
} else result.cost = line.cost;
|
||||
return result;
|
||||
});
|
||||
return {
|
||||
date: today,
|
||||
fees_date: today,
|
||||
customer: '',
|
||||
salesperson: source.salesperson || '',
|
||||
payment_account: normalizeAccount(source.payment_account || '助理微信'),
|
||||
discount: source.discount,
|
||||
note: locked
|
||||
? String(source.note || '').replace(/;?锁价单 [^;]*;按原锁定金价 [^;]*元\/克结算$/, '')
|
||||
: source.note || '',
|
||||
rounding_mode: 'yuan',
|
||||
copy_kind: locked ? 'price-lock' : 'ordinary',
|
||||
fee_auto_initialized: true,
|
||||
lines,
|
||||
fee_items: copyFees(order, lines, chargeIds, newId),
|
||||
};
|
||||
}
|
||||
/** @param {import('../web/src/shared/orderPresets').CopyDraft|null} draft @param {{today?:string;salesperson?:string}} [options] */
|
||||
function hasDraftContent(draft, { today, salesperson } = {}) {
|
||||
if (!draft || typeof draft !== 'object' || !Array.isArray(draft.lines)) return !!draft;
|
||||
if (
|
||||
draft.id ||
|
||||
draft.copy_kind ||
|
||||
nonblank(draft.customer) ||
|
||||
nonblank(draft.note) ||
|
||||
nonblank(draft.internal_note) ||
|
||||
Number(draft.discount) ||
|
||||
(draft.date && today && draft.date !== today) ||
|
||||
(draft.salesperson && salesperson && draft.salesperson !== salesperson) ||
|
||||
(draft.payment_account && draft.payment_account !== '助理微信')
|
||||
)
|
||||
)
|
||||
return true;
|
||||
return (
|
||||
draft.lines.length !== 1 ||
|
||||
draft.lines.some(line => {
|
||||
if (
|
||||
line.charges?.length ||
|
||||
(line.name && line.name !== '足金999') ||
|
||||
line.customName ||
|
||||
(line.unit && line.unit !== 'g') ||
|
||||
(line.pocket != null && line.pocket !== '现货') ||
|
||||
(line.payer && line.payer !== 'owner') ||
|
||||
line.costMaterial?.mode === 'pool'
|
||||
return true;
|
||||
if (
|
||||
(draft.fee_items || []).some(
|
||||
item =>
|
||||
item.key !== 'shipping' ||
|
||||
item.edited ||
|
||||
item.status !== 'estimated' ||
|
||||
Number(item.amount) !== 6 ||
|
||||
item.payer !== 'assistant',
|
||||
)
|
||||
return true;
|
||||
if (
|
||||
['quantity', 'stockCount', 'sale', 'baseSale', 'goldPrice', 'laborRate', 'priceNote', 'cost'].some(key =>
|
||||
nonblank(line[key]),
|
||||
)
|
||||
return true;
|
||||
return (
|
||||
draft.lines.length !== 1 ||
|
||||
draft.lines.some(line => {
|
||||
if (
|
||||
line.charges?.length ||
|
||||
(line.name && line.name !== '足金999') ||
|
||||
line.customName ||
|
||||
(line.unit && line.unit !== 'g') ||
|
||||
(line.pocket != null && line.pocket !== '现货') ||
|
||||
(line.payer && line.payer !== 'owner') ||
|
||||
line.costMaterial?.mode === 'pool'
|
||||
)
|
||||
)
|
||||
return true;
|
||||
if (
|
||||
['material', 'labor'].some(
|
||||
key =>
|
||||
nonblank(line.costParts?.[key]) ||
|
||||
nonblank(line[key === 'material' ? 'costMaterial' : 'costLabor']?.rate) ||
|
||||
(line.costPayers?.[key] && line.costPayers[key] !== 'owner'),
|
||||
return true;
|
||||
if (
|
||||
/** @type {const} */ ([
|
||||
'quantity',
|
||||
'stockCount',
|
||||
'sale',
|
||||
'baseSale',
|
||||
'goldPrice',
|
||||
'laborRate',
|
||||
'priceNote',
|
||||
'cost',
|
||||
]).some(key => nonblank(line[key]))
|
||||
)
|
||||
)
|
||||
return true;
|
||||
return ['accessories', 'other'].some(key => Number(line.costParts?.[key]));
|
||||
})
|
||||
);
|
||||
}
|
||||
return { inputs, fromOrder, hasDraftContent };
|
||||
});
|
||||
return true;
|
||||
if (
|
||||
['material', 'labor'].some(
|
||||
key =>
|
||||
nonblank(line.costParts?.[key]) ||
|
||||
nonblank(line[key === 'material' ? 'costMaterial' : 'costLabor']?.rate) ||
|
||||
(line.costPayers?.[key] && line.costPayers[key] !== 'owner'),
|
||||
)
|
||||
)
|
||||
return true;
|
||||
return ['accessories', 'other'].some(key => Number(line.costParts?.[key]));
|
||||
})
|
||||
);
|
||||
}
|
||||
return { inputs, fromOrder, hasDraftContent };
|
||||
},
|
||||
);
|
||||
+324
-159
File diff suppressed because it is too large.
Load diff
@@ -1,13 +1,16 @@
|
||||
'use strict';
|
||||
// 只接受约定的销售公式,不执行输入代码。金额复用开单的整数计算。
|
||||
(function (root) {
|
||||
/** @type {Pick<import('../web/src/shared/types').LedgerCalcApi, 'sale'|'cents'|'orderTotal'>} */
|
||||
const Calc = typeof module === 'object' && module.exports ? require('./calculations') : root.LedgerCalc;
|
||||
/** @param {string} value */
|
||||
const decimal = value => {
|
||||
const [whole, fraction = ''] = value.split('.');
|
||||
return (
|
||||
(whole.replace(/^0+(?=\d)/, '') || '0') + (fraction.replace(/0+$/, '') ? '.' + fraction.replace(/0+$/, '') : '')
|
||||
);
|
||||
};
|
||||
/** @param {string} input */
|
||||
const normalize = input =>
|
||||
input
|
||||
.normalize('NFKC')
|
||||
@@ -22,7 +25,9 @@
|
||||
weight = number + '(?:克|g)?\\*';
|
||||
const gramPattern = new RegExp('^' + weight + '\\(' + number + '\\+' + number + '\\)' + extras + ending, 'i');
|
||||
const piecePattern = new RegExp('^' + weight + number + '\\+' + number + extras + ending, 'i');
|
||||
/** @param {string} value */
|
||||
const money = value => Calc.cents(decimal(value), '公式金额');
|
||||
/** @param {string} input @param {{roundingMode?: 'cent'|'yuan'}} [options] */
|
||||
function parse(input, { roundingMode = 'yuan' } = {}) {
|
||||
if (typeof input !== 'string' || input.length > 300) throw new Error('每行请填写300字以内的销售公式');
|
||||
const formula = normalize(input),
|
||||
@@ -32,6 +37,7 @@
|
||||
const [, weight, gold, labor, extra, stated] = match;
|
||||
const quantities = extra ? extra.slice(1).split('+') : [];
|
||||
if (quantities.length > 100) throw new Error('每件商品最多100项附加费');
|
||||
/** @type {import('../web/src/shared/orderEntryTypes').FormulaLine} */
|
||||
const line = {
|
||||
unit: 'g',
|
||||
pricingMode: 'auto',
|
||||
@@ -56,6 +62,7 @@
|
||||
mismatch: statedTotal !== null && statedTotal !== total.total,
|
||||
};
|
||||
}
|
||||
/** @param {string} input @param {{roundingMode?: 'cent'|'yuan'}} [options] */
|
||||
function parseBatch(input, { roundingMode = 'yuan' } = {}) {
|
||||
if (typeof input !== 'string' || input.length > 18000) throw new Error('请填写18000字以内的公式,每件商品一行');
|
||||
const rows = input
|
||||
@@ -63,10 +70,11 @@
|
||||
.map(value => value.trim())
|
||||
.filter(Boolean);
|
||||
if (!rows.length || rows.length > 61) throw new Error('请填写1~60件商品公式,可在最后另写一行合计');
|
||||
/** @type {ReturnType<typeof parse>[]} */
|
||||
const items = [],
|
||||
warnings = [];
|
||||
let summary = null;
|
||||
rows.forEach((raw, index) => {
|
||||
for (const [index, raw] of rows.entries()) {
|
||||
const normalized = normalize(raw).replace(/^(?:合计|总价|总计|总金额):?/, '');
|
||||
const sumMatch = normalized.match(/^(\d+(?:\.\d+)?(?:\+\d+(?:\.\d+)?)+)(?:=(\d+(?:\.\d+)?))?$/);
|
||||
if (sumMatch) {
|
||||
@@ -87,10 +95,10 @@
|
||||
try {
|
||||
item = parse(raw, { roundingMode });
|
||||
} catch (err) {
|
||||
throw new Error('第' + (index + 1) + '行:' + err.message);
|
||||
throw new Error('第' + (index + 1) + '行:' + (err instanceof Error ? err.message : String(err)));
|
||||
}
|
||||
items.push(item);
|
||||
if (item.mismatch)
|
||||
if (item.mismatch && item.statedTotal !== null)
|
||||
warnings.push(
|
||||
'商品 ' +
|
||||
items.length +
|
||||
@@ -101,7 +109,7 @@
|
||||
'元。',
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
const total = Calc.orderTotal(
|
||||
items.map(item => item.subtotal),
|
||||
0,
|
||||
@@ -130,4 +138,4 @@
|
||||
const api = { parse, parseBatch };
|
||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||
else root.OrderFormula = api;
|
||||
})(typeof globalThis === 'object' ? globalThis : this);
|
||||
})(typeof globalThis === 'object' ? globalThis : /** @type {typeof globalThis} */ (/** @type {unknown} */ (this)));
|
||||
+314
-281
@@ -7,288 +7,321 @@
|
||||
);
|
||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||
else root.OrderTemplates = api;
|
||||
})(typeof globalThis === 'object' ? globalThis : this, function (Fees, Cards) {
|
||||
const products = ['足金999', '足银999', '纯银925'],
|
||||
charges = ['编绳', '证书', '包装', '快递', '附加费'];
|
||||
const pockets = ['', '现货', '金料', '找金', '回收旧料', '君宝汇'];
|
||||
const accounts = [
|
||||
'助理2微信',
|
||||
'助理2支付宝',
|
||||
'助理2现金',
|
||||
'助理2信用卡',
|
||||
'助理微信',
|
||||
'助理支付宝',
|
||||
'助理现金',
|
||||
'助理信用卡',
|
||||
'麦麦微信',
|
||||
'麦麦支付宝',
|
||||
'麦麦现金',
|
||||
'麦麦信用卡',
|
||||
];
|
||||
const normalizeAccount = account =>
|
||||
Cards?.normalizeAccount
|
||||
? Cards.normalizeAccount(account)
|
||||
: ['助理信用卡', '助理1信用卡', '助理2信用卡', '麦麦信用卡'].includes(account)
|
||||
? '麦麦信用卡'
|
||||
: account;
|
||||
const cardFee = item => item?.system === 'credit_card' || String(item?.key || '').startsWith('card_fee:');
|
||||
const uuid = /^[a-f0-9-]{36}$/;
|
||||
function object(value, name) {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(name + '格式无效');
|
||||
return value;
|
||||
}
|
||||
function string(value, name, max = 100) {
|
||||
if (value != null && !['string', 'number'].includes(typeof value)) throw new Error(name + '格式无效');
|
||||
const result = String(value ?? '').trim();
|
||||
if (result.length > max) throw new Error(name + '最多填写' + max + '字');
|
||||
return result;
|
||||
}
|
||||
function pick(value, values, name, fallback) {
|
||||
const result = value ?? fallback;
|
||||
if (!values.includes(result)) throw new Error(name + '无效');
|
||||
return result;
|
||||
}
|
||||
function numeric(value, name, places = 2) {
|
||||
const result = string(value, name, 24);
|
||||
if (!result) return '';
|
||||
if (!new RegExp('^\\d+(?:\\.\\d{1,' + places + '})?$').test(result))
|
||||
throw new Error(name + '须为非负数字,最多' + places + '位小数');
|
||||
const [whole, fraction = ''] = result.split('.');
|
||||
if (BigInt(whole) * 10n ** BigInt(places) + BigInt(fraction.padEnd(places, '0')) > 100000000000n)
|
||||
throw new Error(name + '超出支持范围');
|
||||
return result;
|
||||
}
|
||||
function count(value, name) {
|
||||
const result = string(value, name, 12);
|
||||
if (result && !/^\d+$/.test(result)) throw new Error(name + '须为非负整数');
|
||||
if (Number(result) > 1000000000) throw new Error(name + '超出支持范围');
|
||||
return result;
|
||||
}
|
||||
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 payer(value, fallback = 'owner') {
|
||||
const result = value ?? fallback;
|
||||
if (result !== '' && !validMember(result)) throw new Error('成本付款人无效');
|
||||
return result;
|
||||
}
|
||||
function paymentAccount(value) {
|
||||
const result = normalizeAccount(value ?? '助理微信');
|
||||
if (
|
||||
!accounts.includes(result) &&
|
||||
!/^staff_[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}(微信|支付宝|现金)$/.test(result)
|
||||
)
|
||||
throw new Error('收款账户无效');
|
||||
return result;
|
||||
}
|
||||
function manualMaterial(value = {}, fallback = {}) {
|
||||
object(value, '备用料费');
|
||||
return {
|
||||
mode: pick(value.mode, ['gram', 'total'], '备用料费方式', fallback.mode || 'gram'),
|
||||
rate: numeric(value.rate ?? fallback.rate, '备用进货料价'),
|
||||
total: numeric(value.total ?? fallback.total, '备用料费合计'),
|
||||
originalTotal: '',
|
||||
payer: payer(value.payer, fallback.payer ?? 'owner'),
|
||||
};
|
||||
}
|
||||
function fromDraft(draft, { newId = () => globalThis.crypto.randomUUID(), pocketKeys = pockets } = {}) {
|
||||
object(draft, '开单预设');
|
||||
if (!Array.isArray(draft.lines) || !draft.lines.length || draft.lines.length > 60)
|
||||
throw new Error('模板需要1~60行商品');
|
||||
const ids = new Map(),
|
||||
seen = new Set();
|
||||
const lines = draft.lines.map(raw => {
|
||||
const line = object(raw, '模板商品'),
|
||||
unit = pick(line.unit, ['g', '件'], '商品单位', 'g');
|
||||
const name = string(line.name, '商品名称', 60),
|
||||
nameType = pick(
|
||||
line.nameType,
|
||||
[...products, '其他'],
|
||||
'商品名称',
|
||||
products.includes(name) ? name : name ? '其他' : '足金999',
|
||||
);
|
||||
const result = {
|
||||
nameType,
|
||||
customName: string(line.customName ?? (nameType === '其他' ? name : ''), '其他商品名称', 60),
|
||||
unit,
|
||||
quantity: unit === 'g' ? numeric(line.quantity, '商品克重', 3) : count(line.quantity, '商品件数'),
|
||||
pocket:
|
||||
unit === '件' || ['足银999', '纯银925'].includes(nameType)
|
||||
? ''
|
||||
: pick(line.pocket, ['', ...pocketKeys], '出库货盘', nameType === '足金999' ? '现货' : ''),
|
||||
payer: payer(line.payer, 'owner'),
|
||||
pricingMode:
|
||||
unit === '件'
|
||||
? 'manual'
|
||||
: pick(line.pricingMode, ['auto', 'manual'], '计价方式', line.sale != null ? 'manual' : 'auto'),
|
||||
goldPrice: numeric(line.goldPrice, '销售金价'),
|
||||
laborMode: pick(line.laborMode, ['gram', 'piece'], '销售工费方式', 'gram'),
|
||||
laborRate: numeric(line.laborRate, '销售工费'),
|
||||
pieces: count(line.pieces ?? '1', '计工费件数'),
|
||||
priceNote: string(line.priceNote, '销售单价说明', 100),
|
||||
sale: numeric(line.sale, '本行销售额'),
|
||||
baseSale: numeric(line.baseSale ?? line.sale, '商品基础金额'),
|
||||
};
|
||||
result.name = nameType === '其他' ? result.customName : nameType;
|
||||
if (line.stockCount != null && String(line.stockCount).trim() !== '') {
|
||||
result.stockCount = count(line.stockCount, '出库数量(对)');
|
||||
if (Number(result.stockCount) < 1) throw new Error('出库数量(对)须为正整数,一对填1');
|
||||
}
|
||||
const rawCharges = line.charges ?? [];
|
||||
if (!Array.isArray(rawCharges) || rawCharges.length > 100) throw new Error('每行最多填写100项附加项目');
|
||||
result.charges = rawCharges.map(rawCharge => {
|
||||
const c = object(rawCharge, '附加项目'),
|
||||
old = string(c.id, '附加项目标识', 36);
|
||||
if (old && (!uuid.test(old) || seen.has(old))) throw new Error('附加项目标识无效或重复');
|
||||
if (old) seen.add(old);
|
||||
const name = string(c.name, '附加项目名称', 40),
|
||||
nameType = pick(
|
||||
c.nameType,
|
||||
[...charges, '其他'],
|
||||
'附加项目',
|
||||
charges.includes(name) ? name : name ? '其他' : '编绳',
|
||||
);
|
||||
if (c.costRemoved !== undefined && typeof c.costRemoved !== 'boolean') throw new Error('内部成本移除标记无效');
|
||||
const id = newId();
|
||||
if (old) ids.set(old, id);
|
||||
const customName = string(c.customName ?? (nameType === '其他' ? name : ''), '附加项目名称', 40),
|
||||
amount = numeric(c.amount, '附加金额');
|
||||
const prices = {};
|
||||
if (c.chargePrices != null) {
|
||||
object(c.chargePrices, '附加项目预设报价');
|
||||
for (const key of [...charges, '其他'])
|
||||
if (Object.hasOwn(c.chargePrices, key)) prices[key] = numeric(c.chargePrices[key], '附加项目报价');
|
||||
}
|
||||
return {
|
||||
id,
|
||||
nameType,
|
||||
customName,
|
||||
name: nameType === '其他' ? customName : nameType,
|
||||
amount,
|
||||
chargePrices: { ...prices, [nameType]: amount },
|
||||
...(c.costRemoved === true ? { costRemoved: true } : {}),
|
||||
};
|
||||
});
|
||||
if (line.costParts != null) {
|
||||
object(line.costParts, '分项成本');
|
||||
const parts = Object.fromEntries(
|
||||
['material', 'labor', 'accessories', 'other'].map(key => [key, numeric(line.costParts[key], '货品成本')]),
|
||||
);
|
||||
const material = object(line.costMaterial ?? {}, '料费方式'),
|
||||
labor = object(line.costLabor ?? {}, '进货工费方式');
|
||||
const mode = pick(
|
||||
material.mode,
|
||||
['gram', 'total', 'pool'],
|
||||
'进货料费方式',
|
||||
unit === 'g' && parts.material === '' ? 'gram' : 'total',
|
||||
);
|
||||
result.costParts = parts;
|
||||
result.costPayers = {
|
||||
material: payer(line.costPayers?.material, result.payer),
|
||||
labor: payer(line.costPayers?.labor, result.payer),
|
||||
};
|
||||
result.costMaterial = {
|
||||
mode: unit === '件' ? 'total' : mode,
|
||||
...(mode === 'gram' ? { rate: numeric(material.rate, '进货料价') } : {}),
|
||||
};
|
||||
result.costLabor = {
|
||||
mode: unit === '件' ? 'total' : pick(labor.mode, ['gram', 'total'], '进货工费方式', 'total'),
|
||||
rate: numeric(labor.rate, '进货克工费'),
|
||||
};
|
||||
if (result.costMaterial.mode === 'pool') {
|
||||
if (['足银999', '纯银925'].includes(nameType)) throw new Error('银饰模板请手动填写料费');
|
||||
parts.material = '';
|
||||
result.materialPoolDraft = { defaultDate: true, manual: manualMaterial(line.materialPoolDraft?.manual) };
|
||||
} else if (line.costMaterialDraft) {
|
||||
const remembered = manualMaterial(line.costMaterialDraft, {
|
||||
mode: result.costMaterial.mode,
|
||||
rate: material.rate,
|
||||
total: parts.material,
|
||||
payer: result.costPayers.material,
|
||||
});
|
||||
result.costMaterialDraft = {
|
||||
mode: remembered.mode,
|
||||
rate: remembered.rate,
|
||||
total: remembered.total,
|
||||
originalTotal: '',
|
||||
};
|
||||
}
|
||||
} else if (Object.hasOwn(line, 'cost')) result.cost = numeric(line.cost, '货品成本');
|
||||
})(
|
||||
typeof globalThis === 'object' ? globalThis : /** @type {typeof globalThis} */ (/** @type {unknown} */ (this)),
|
||||
/** @param {typeof import('./fee-estimates')} Fees @param {typeof import('./credit-card-fees')} Cards */ function (
|
||||
Fees,
|
||||
Cards,
|
||||
) {
|
||||
const products = ['足金999', '足银999', '纯银925'],
|
||||
charges = ['编绳', '证书', '包装', '快递', '附加费'];
|
||||
const pockets = ['', '现货', '金料', '找金', '回收旧料', '君宝汇'];
|
||||
const accounts = [
|
||||
'助理2微信',
|
||||
'助理2支付宝',
|
||||
'助理2现金',
|
||||
'助理2信用卡',
|
||||
'助理微信',
|
||||
'助理支付宝',
|
||||
'助理现金',
|
||||
'助理信用卡',
|
||||
'麦麦微信',
|
||||
'麦麦支付宝',
|
||||
'麦麦现金',
|
||||
'麦麦信用卡',
|
||||
];
|
||||
/** @param {string} account */
|
||||
const normalizeAccount = account =>
|
||||
Cards?.normalizeAccount
|
||||
? Cards.normalizeAccount(account)
|
||||
: ['助理信用卡', '助理1信用卡', '助理2信用卡', '麦麦信用卡'].includes(account)
|
||||
? '麦麦信用卡'
|
||||
: account;
|
||||
/** @param {{system?:unknown;key?:unknown}} item */
|
||||
const cardFee = item => item?.system === 'credit_card' || String(item?.key || '').startsWith('card_fee:');
|
||||
/** @param {unknown} value */
|
||||
const properties = value =>
|
||||
value && typeof value === 'object' ? /** @type {Record<string,unknown>} */ (value) : {};
|
||||
const uuid = /^[a-f0-9-]{36}$/;
|
||||
/** @param {unknown} value @param {string} name */
|
||||
function object(value, name) {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(name + '格式无效');
|
||||
return /** @type {Record<string,unknown>} */ (value);
|
||||
}
|
||||
/** @param {unknown} value @param {string} name */
|
||||
function string(value, name, max = 100) {
|
||||
if (value != null && !['string', 'number'].includes(typeof value)) throw new Error(name + '格式无效');
|
||||
const result = String(value ?? '').trim();
|
||||
if (result.length > max) throw new Error(name + '最多填写' + max + '字');
|
||||
return result;
|
||||
});
|
||||
const fees = draft.fee_items ?? [];
|
||||
if (!Array.isArray(fees) || fees.length > 6100) throw new Error('模板费用项目过多');
|
||||
const cardExpenseIds = new Set(
|
||||
fees
|
||||
.filter(cardFee)
|
||||
.map(fee => fee.expense_id)
|
||||
.filter(Boolean),
|
||||
);
|
||||
const keys = new Set(),
|
||||
items = fees
|
||||
.map(raw => {
|
||||
const fee = object(raw, '模板费用');
|
||||
if (cardFee(fee) || (fee.expense_id && cardExpenseIds.has(fee.expense_id))) return null;
|
||||
if (Fees.presetKind(fee) === 'box') {
|
||||
Fees.boxCount(fee.note.match(/(([^)]*)个 ×/)[1]);
|
||||
if (fee.amount === '') throw new Error('请先填写正整数的盒子数量');
|
||||
}
|
||||
/** @param {unknown} value @param {readonly string[]} values @param {string} name @param {unknown} fallback */
|
||||
function pick(value, values, name, fallback) {
|
||||
const result = value ?? fallback;
|
||||
if (typeof result !== 'string' || !values.includes(result)) throw new Error(name + '无效');
|
||||
return result;
|
||||
}
|
||||
/** @param {unknown} value @param {string} name */
|
||||
function numeric(value, name, places = 2) {
|
||||
const result = string(value, name, 24);
|
||||
if (!result) return '';
|
||||
if (!new RegExp('^\\d+(?:\\.\\d{1,' + places + '})?$').test(result))
|
||||
throw new Error(name + '须为非负数字,最多' + places + '位小数');
|
||||
const [whole, fraction = ''] = result.split('.');
|
||||
if (BigInt(whole) * 10n ** BigInt(places) + BigInt(fraction.padEnd(places, '0')) > 100000000000n)
|
||||
throw new Error(name + '超出支持范围');
|
||||
return result;
|
||||
}
|
||||
/** @param {unknown} value @param {string} name */
|
||||
function count(value, name) {
|
||||
const result = string(value, name, 12);
|
||||
if (result && !/^\d+$/.test(result)) throw new Error(name + '须为非负整数');
|
||||
if (Number(result) > 1000000000) throw new Error(name + '超出支持范围');
|
||||
return result;
|
||||
}
|
||||
/** @param {string} value */
|
||||
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);
|
||||
/** @param {unknown} value @param {unknown} [fallback] */
|
||||
function payer(value, fallback = 'owner') {
|
||||
const result = value ?? fallback;
|
||||
if (typeof result !== 'string' || (result !== '' && !validMember(result))) throw new Error('成本付款人无效');
|
||||
return result;
|
||||
}
|
||||
/** @param {unknown} value */
|
||||
function paymentAccount(value) {
|
||||
if (value != null && typeof value !== 'string') throw new Error('收款账户无效');
|
||||
const result = normalizeAccount(value ?? '助理微信');
|
||||
if (
|
||||
!accounts.includes(result) &&
|
||||
!/^staff_[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}(微信|支付宝|现金)$/.test(result)
|
||||
)
|
||||
throw new Error('收款账户无效');
|
||||
return result;
|
||||
}
|
||||
/** @param {unknown} [input] @param {Record<string,unknown>} [fallback] */
|
||||
function manualMaterial(input = {}, fallback = {}) {
|
||||
const value = object(input, '备用料费');
|
||||
return {
|
||||
mode: pick(value.mode, ['gram', 'total'], '备用料费方式', fallback.mode || 'gram'),
|
||||
rate: numeric(value.rate ?? fallback.rate, '备用进货料价'),
|
||||
total: numeric(value.total ?? fallback.total, '备用料费合计'),
|
||||
originalTotal: '',
|
||||
payer: payer(value.payer, fallback.payer ?? 'owner'),
|
||||
};
|
||||
}
|
||||
/** @param {Record<string,unknown>} draft @param {import('../web/src/shared/orderPresets').TemplateOptions} [options] */
|
||||
function fromDraft(draft, { newId = () => globalThis.crypto.randomUUID(), pocketKeys = pockets } = {}) {
|
||||
object(draft, '开单预设');
|
||||
if (!Array.isArray(draft.lines) || !draft.lines.length || draft.lines.length > 60)
|
||||
throw new Error('模板需要1~60行商品');
|
||||
const ids = new Map(),
|
||||
seen = new Set();
|
||||
const lines = draft.lines.map(raw => {
|
||||
const line = object(raw, '模板商品'),
|
||||
unit = pick(line.unit, ['g', '件'], '商品单位', 'g');
|
||||
const name = string(line.name, '商品名称', 60),
|
||||
nameType = pick(
|
||||
line.nameType,
|
||||
[...products, '其他'],
|
||||
'商品名称',
|
||||
products.includes(name) ? name : name ? '其他' : '足金999',
|
||||
);
|
||||
/** @type {import('../web/src/shared/orderPresets').TemplateProduct} */
|
||||
const result = {
|
||||
charges: [],
|
||||
nameType,
|
||||
customName: string(line.customName ?? (nameType === '其他' ? name : ''), '其他商品名称', 60),
|
||||
unit,
|
||||
quantity: unit === 'g' ? numeric(line.quantity, '商品克重', 3) : count(line.quantity, '商品件数'),
|
||||
pocket:
|
||||
unit === '件' || ['足银999', '纯银925'].includes(nameType)
|
||||
? ''
|
||||
: pick(line.pocket, ['', ...pocketKeys], '出库货盘', nameType === '足金999' ? '现货' : ''),
|
||||
payer: payer(line.payer, 'owner'),
|
||||
pricingMode:
|
||||
unit === '件'
|
||||
? 'manual'
|
||||
: pick(line.pricingMode, ['auto', 'manual'], '计价方式', line.sale != null ? 'manual' : 'auto'),
|
||||
goldPrice: numeric(line.goldPrice, '销售金价'),
|
||||
laborMode: pick(line.laborMode, ['gram', 'piece'], '销售工费方式', 'gram'),
|
||||
laborRate: numeric(line.laborRate, '销售工费'),
|
||||
pieces: count(line.pieces ?? '1', '计工费件数'),
|
||||
priceNote: string(line.priceNote, '销售单价说明', 100),
|
||||
sale: numeric(line.sale, '本行销售额'),
|
||||
baseSale: numeric(line.baseSale ?? line.sale, '商品基础金额'),
|
||||
};
|
||||
result.name = nameType === '其他' ? result.customName : nameType;
|
||||
if (line.stockCount != null && String(line.stockCount).trim() !== '') {
|
||||
result.stockCount = count(line.stockCount, '出库数量(对)');
|
||||
if (Number(result.stockCount) < 1) throw new Error('出库数量(对)须为正整数,一对填1');
|
||||
}
|
||||
const rawCharges = line.charges ?? [];
|
||||
if (!Array.isArray(rawCharges) || rawCharges.length > 100) throw new Error('每行最多填写100项附加项目');
|
||||
result.charges = rawCharges.map(rawCharge => {
|
||||
const c = object(rawCharge, '附加项目'),
|
||||
old = string(c.id, '附加项目标识', 36);
|
||||
if (old && (!uuid.test(old) || seen.has(old))) throw new Error('附加项目标识无效或重复');
|
||||
if (old) seen.add(old);
|
||||
const name = string(c.name, '附加项目名称', 40),
|
||||
nameType = pick(
|
||||
c.nameType,
|
||||
[...charges, '其他'],
|
||||
'附加项目',
|
||||
charges.includes(name) ? name : name ? '其他' : '编绳',
|
||||
);
|
||||
if (c.costRemoved !== undefined && typeof c.costRemoved !== 'boolean')
|
||||
throw new Error('内部成本移除标记无效');
|
||||
const id = newId();
|
||||
if (old) ids.set(old, id);
|
||||
const customName = string(c.customName ?? (nameType === '其他' ? name : ''), '附加项目名称', 40),
|
||||
amount = numeric(c.amount, '附加金额');
|
||||
/** @type {Record<string,string>} */
|
||||
const prices = {};
|
||||
if (c.chargePrices != null) {
|
||||
const values = object(c.chargePrices, '附加项目预设报价');
|
||||
for (const key of [...charges, '其他'])
|
||||
if (Object.hasOwn(values, key)) prices[key] = numeric(values[key], '附加项目报价');
|
||||
}
|
||||
const old = string(fee.key, '费用标识', 80);
|
||||
if (
|
||||
!['shipping', 'box', 'certificate', 'braiding', 'sticker', 'other'].includes(old) &&
|
||||
!/^(charge|manual):[a-f0-9-]{36}$/.test(old)
|
||||
)
|
||||
throw new Error('模板费用项目无效');
|
||||
if (keys.has(old)) throw new Error('模板费用项目不能重复');
|
||||
keys.add(old);
|
||||
const linked = old.startsWith('charge:') ? ids.get(old.slice(7)) : null;
|
||||
if (old.startsWith('charge:') && !linked) return null;
|
||||
return {
|
||||
key: linked ? 'charge:' + linked : old === 'shipping' || Fees.presetKind(fee) ? old : 'manual:' + newId(),
|
||||
note: string(fee.note, '费用名称', 150),
|
||||
amount: numeric(fee.amount, '实际费用'),
|
||||
payer: payer(fee.payer, 'assistant'),
|
||||
status: 'estimated',
|
||||
edited: fee.edited !== false,
|
||||
...(linked ? { sourceName: string(fee.sourceName || fee.note, '附加项目名称', 40) } : {}),
|
||||
id,
|
||||
nameType,
|
||||
customName,
|
||||
name: nameType === '其他' ? customName : nameType,
|
||||
amount,
|
||||
chargePrices: { ...prices, [nameType]: amount },
|
||||
...(c.costRemoved === true ? { costRemoved: true } : {}),
|
||||
};
|
||||
})
|
||||
.filter(Boolean);
|
||||
const preset = {
|
||||
salesperson: string(draft.salesperson, '开单人', 30),
|
||||
payment_account: paymentAccount(draft.payment_account),
|
||||
credit_card_fee_payer: payer(draft.credit_card_fee_payer, 'owner'),
|
||||
discount: numeric(draft.discount ?? '0', '整单优惠'),
|
||||
note: string(draft.note, '客户单备注', 240),
|
||||
fee_auto_initialized: true,
|
||||
...(draft.fee_cost_mode === 'checkboxes' ? { fee_cost_mode: 'checkboxes' } : {}),
|
||||
lines,
|
||||
fee_items: Fees.sync(items, lines, { checkboxCosts: draft.fee_cost_mode === 'checkboxes' }),
|
||||
};
|
||||
if (JSON.stringify(preset).length > 240000) throw new Error('模板内容过大,请减少商品或附加项目');
|
||||
return preset;
|
||||
}
|
||||
function apply(preset, { today, salesperson = '', newId, pocketKeys } = {}) {
|
||||
if (
|
||||
!/^\d{4}-\d{2}-\d{2}$/.test(today || '') ||
|
||||
!Number.isFinite(Date.parse(today + 'T00:00:00Z')) ||
|
||||
new Date(today + 'T00:00:00Z').toISOString().slice(0, 10) !== today
|
||||
)
|
||||
throw new Error('未取得有效系统日期,请刷新后再套用模板。');
|
||||
const draft = fromDraft({ ...preset, fee_cost_mode: 'checkboxes' }, { newId, pocketKeys });
|
||||
for (const line of draft.lines)
|
||||
if (line.costMaterial?.mode === 'pool') {
|
||||
line.costMaterial = { mode: 'pool', poolId: today };
|
||||
line.materialPoolDraft = { ...line.materialPoolDraft, poolId: today, defaultDate: true };
|
||||
}
|
||||
return {
|
||||
...draft,
|
||||
date: today,
|
||||
fees_date: today,
|
||||
customer: '',
|
||||
salesperson: draft.salesperson || salesperson,
|
||||
rounding_mode: 'yuan',
|
||||
};
|
||||
}
|
||||
return { fromDraft, apply };
|
||||
});
|
||||
});
|
||||
if (line.costParts != null) {
|
||||
const costs = object(line.costParts, '分项成本');
|
||||
const parts = Object.fromEntries(
|
||||
['material', 'labor', 'accessories', 'other'].map(key => [key, numeric(costs[key], '货品成本')]),
|
||||
);
|
||||
const material = object(line.costMaterial ?? {}, '料费方式'),
|
||||
labor = object(line.costLabor ?? {}, '进货工费方式');
|
||||
const mode = pick(
|
||||
material.mode,
|
||||
['gram', 'total', 'pool'],
|
||||
'进货料费方式',
|
||||
unit === 'g' && parts.material === '' ? 'gram' : 'total',
|
||||
);
|
||||
result.costParts = parts;
|
||||
result.costPayers = {
|
||||
material: payer(properties(line.costPayers).material, result.payer),
|
||||
labor: payer(properties(line.costPayers).labor, result.payer),
|
||||
};
|
||||
result.costMaterial = {
|
||||
mode: unit === '件' ? 'total' : mode,
|
||||
...(mode === 'gram' ? { rate: numeric(material.rate, '进货料价') } : {}),
|
||||
};
|
||||
result.costLabor = {
|
||||
mode: unit === '件' ? 'total' : pick(labor.mode, ['gram', 'total'], '进货工费方式', 'total'),
|
||||
rate: numeric(labor.rate, '进货克工费'),
|
||||
};
|
||||
if (result.costMaterial.mode === 'pool') {
|
||||
if (['足银999', '纯银925'].includes(nameType)) throw new Error('银饰模板请手动填写料费');
|
||||
parts.material = '';
|
||||
result.materialPoolDraft = {
|
||||
defaultDate: true,
|
||||
manual: manualMaterial(properties(line.materialPoolDraft).manual),
|
||||
};
|
||||
} else if (line.costMaterialDraft) {
|
||||
const remembered = manualMaterial(line.costMaterialDraft, {
|
||||
mode: result.costMaterial.mode,
|
||||
rate: material.rate,
|
||||
total: parts.material,
|
||||
payer: result.costPayers.material,
|
||||
});
|
||||
result.costMaterialDraft = {
|
||||
mode: remembered.mode,
|
||||
rate: remembered.rate,
|
||||
total: remembered.total,
|
||||
originalTotal: '',
|
||||
};
|
||||
}
|
||||
} else if (Object.hasOwn(line, 'cost')) result.cost = numeric(line.cost, '货品成本');
|
||||
return result;
|
||||
});
|
||||
const fees = draft.fee_items ?? [];
|
||||
if (!Array.isArray(fees) || fees.length > 6100) throw new Error('模板费用项目过多');
|
||||
const cardExpenseIds = new Set(
|
||||
fees
|
||||
.filter(cardFee)
|
||||
.map(fee => fee.expense_id)
|
||||
.filter(Boolean),
|
||||
);
|
||||
const keys = new Set(),
|
||||
items = fees
|
||||
.map(raw => {
|
||||
const fee = object(raw, '模板费用');
|
||||
if (cardFee(fee) || (fee.expense_id && cardExpenseIds.has(fee.expense_id))) return null;
|
||||
const kind = !fee.expense_id && !fee.funding && typeof fee.key === 'string' &&
|
||||
typeof fee.note === 'string' && typeof fee.payer === 'string' && (typeof fee.amount === 'string' || typeof fee.amount === 'number')
|
||||
? Fees.presetKind({key:fee.key, note:fee.note, amount:fee.amount, payer:fee.payer}) : '';
|
||||
if (kind === 'box') {
|
||||
Fees.boxCount(String(fee.note).match(/(([^)]*)个 ×/)?.[1]);
|
||||
if (fee.amount === '') throw new Error('请先填写正整数的盒子数量');
|
||||
}
|
||||
const old = string(fee.key, '费用标识', 80);
|
||||
if (
|
||||
!['shipping', 'box', 'certificate', 'braiding', 'sticker', 'other'].includes(old) &&
|
||||
!/^(charge|manual):[a-f0-9-]{36}$/.test(old)
|
||||
)
|
||||
throw new Error('模板费用项目无效');
|
||||
if (keys.has(old)) throw new Error('模板费用项目不能重复');
|
||||
keys.add(old);
|
||||
const linked = old.startsWith('charge:') ? ids.get(old.slice(7)) : null;
|
||||
if (old.startsWith('charge:') && !linked) return null;
|
||||
return {
|
||||
key: linked ? 'charge:' + linked : old === 'shipping' || kind ? old : 'manual:' + newId(),
|
||||
note: string(fee.note, '费用名称', 150),
|
||||
amount: numeric(fee.amount, '实际费用'),
|
||||
payer: payer(fee.payer, 'assistant'),
|
||||
status: 'estimated',
|
||||
edited: fee.edited !== false,
|
||||
...(linked ? { sourceName: string(fee.sourceName || fee.note, '附加项目名称', 40) } : {}),
|
||||
};
|
||||
})
|
||||
.filter(row=>row!==null);
|
||||
const preset = {
|
||||
salesperson: string(draft.salesperson, '开单人', 30),
|
||||
payment_account: paymentAccount(draft.payment_account),
|
||||
credit_card_fee_payer: payer(draft.credit_card_fee_payer, 'owner'),
|
||||
discount: numeric(draft.discount ?? '0', '整单优惠'),
|
||||
note: string(draft.note, '客户单备注', 240),
|
||||
fee_auto_initialized: true,
|
||||
...(draft.fee_cost_mode === 'checkboxes' ? { fee_cost_mode: 'checkboxes' } : {}),
|
||||
lines,
|
||||
fee_items: Fees.sync(items, lines, { checkboxCosts: draft.fee_cost_mode === 'checkboxes' }),
|
||||
};
|
||||
if (JSON.stringify(preset).length > 240000) throw new Error('模板内容过大,请减少商品或附加项目');
|
||||
return preset;
|
||||
}
|
||||
/** @param {Record<string,unknown>} preset @param {import('../web/src/shared/orderPresets').TemplateOptions} [options] */
|
||||
function apply(preset, { today, salesperson = '', newId, pocketKeys } = {}) {
|
||||
if (
|
||||
!/^\d{4}-\d{2}-\d{2}$/.test(today || '') ||
|
||||
!Number.isFinite(Date.parse(today + 'T00:00:00Z')) ||
|
||||
new Date(today + 'T00:00:00Z').toISOString().slice(0, 10) !== today
|
||||
)
|
||||
throw new Error('未取得有效系统日期,请刷新后再套用模板。');
|
||||
const draft = fromDraft({ ...preset, fee_cost_mode: 'checkboxes' }, { newId, pocketKeys });
|
||||
for (const line of draft.lines)
|
||||
if (line.costMaterial?.mode === 'pool') {
|
||||
line.costMaterial = { mode: 'pool', poolId: today };
|
||||
line.materialPoolDraft = { ...line.materialPoolDraft, poolId: today, defaultDate: true };
|
||||
}
|
||||
return {
|
||||
...draft,
|
||||
date: today,
|
||||
fees_date: today,
|
||||
customer: '',
|
||||
salesperson: draft.salesperson || salesperson,
|
||||
rounding_mode: 'yuan',
|
||||
};
|
||||
}
|
||||
return { fromDraft, apply };
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,876 @@
|
||||
// @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 = /** @type {const} */ ([
|
||||
'new_name',
|
||||
'new_quantity',
|
||||
'pocket',
|
||||
'stockCount',
|
||||
'labor_mode',
|
||||
'labor_rate',
|
||||
'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 + '})?$');
|
||||
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);
|
||||
}
|
||||
|
||||
/** @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,
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
/** @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 })),
|
||||
0,
|
||||
);
|
||||
}
|
||||
|
||||
/** @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(
|
||||
({
|
||||
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,
|
||||
shared_old_notice: draft.extra_products?.length ? '已恢复为一份来料,沿用上方第一份来料;请核对实际总克重。' : '',
|
||||
};
|
||||
}
|
||||
|
||||
/** @param {Input} input @returns {Calculation} */
|
||||
function recoveryCalculate(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 }),
|
||||
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') {
|
||||
/** @type {Partial<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),
|
||||
};
|
||||
}
|
||||
|
||||
/** @param {Input} input @param {Exchange} exchange @param {ItemInput[]} items @returns {Calculation} */
|
||||
function recoveryItemsCalculate(input, exchange, items) {
|
||||
const parts = 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,
|
||||
}),
|
||||
);
|
||||
/** @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),
|
||||
);
|
||||
const discount = recoveryUnits(exchange.discount || '0', 2, '整单优惠');
|
||||
const before =
|
||||
recoveryLimit(sums.goldAmount + sums.laborAmount + sums.depreciationAmount + chargesAmount) - discount;
|
||||
if (before < 0) throw new Error('优惠金额不能大于置换费用');
|
||||
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' },
|
||||
];
|
||||
}
|
||||
|
||||
// 页面的成员、货盘和账户策略由调用方提供。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,
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
/** @param {import('../web/src/pages/Recoveries/types').Mode} [mode] @returns {Draft} */
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
/** @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,
|
||||
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') {
|
||||
/** @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 }
|
||||
: 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;
|
||||
}
|
||||
|
||||
/** @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,
|
||||
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)
|
||||
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?.[itemIndex],
|
||||
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' && input.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 (!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 (input.verified !== true) throw new Error('请核实重量、结算金额和实际收付款后,勾选确认再保存。');
|
||||
return input;
|
||||
}
|
||||
|
||||
/** @param {Draft} draft @returns {Input} */
|
||||
function recoveryItemsInput(draft, { quote = false } = {}) {
|
||||
const common = {
|
||||
mode: /** @type {const} */ ('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,
|
||||
mode: 'exchange',
|
||||
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;
|
||||
}
|
||||
|
||||
/** @param {Input|null} 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 &&
|
||||
/** @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 ||
|
||||
data.id !== id ||
|
||||
data.record?.id !== id ||
|
||||
!Number.isSafeInteger(data.revision) ||
|
||||
data.revision < 1 ||
|
||||
!['active', 'cancelled'].includes(data.status) ||
|
||||
!recoveryInputShape(data.inputs) ||
|
||||
!data.permissions ||
|
||||
!/** @type {const} */ (['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;
|
||||
}
|
||||
|
||||
/** @param {ChangeRequest} request @returns {ChangeRequest} */
|
||||
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;
|
||||
}
|
||||
|
||||
/** @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 })),
|
||||
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,
|
||||
};
|
||||
}
|
||||
/** @type {Partial<Exchange>} */
|
||||
const x = input.exchange || {};
|
||||
const first = input.old_lines[0],
|
||||
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 /** @type {{RecoveryRules?:object}} */ (root).RecoveryRules = api;
|
||||
})(typeof globalThis === 'object' ? globalThis : this);
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user