第4项:对页面、表单及两版共享规则启用严格类型检查
This commit is contained in:
1 parent
389952f31c
commit
f570929cfe
77 files changed
+7629
-2981
No files matched your search
+130
-47
@@ -1,9 +1,54 @@
|
||||
'use strict';
|
||||
// 浏览器预览和服务器记账共用整数算法;每行销售额最后统一四舍五入到分。
|
||||
/**
|
||||
* @typedef {{id?: string, name?: string, amount?: string|number|null, costRemoved?: boolean}} ChargeInput
|
||||
* @typedef {{mode?: string, rate?: string|number|null, poolId?: string}} CostEntry
|
||||
* @typedef {{
|
||||
* unit?: string, name?: string, quantity?: string|number, pricingMode?: string,
|
||||
* baseSale?: string|number, sale?: string|number, charges?: ChargeInput[], goldPrice?: string|number,
|
||||
* laborRate?: string|number, laborMode?: string, pieces?: string|number,
|
||||
* costParts?: Record<string,string|number|null>, costMaterial?: CostEntry, costLabor?: CostEntry,
|
||||
* materialPool?: {amount?: number|null}
|
||||
* }} SaleInput
|
||||
* @typedef {{mg: number, active?: boolean, order_id?: string, line_index?: number,
|
||||
* created?: string, fifo_sequence?: number}} PoolUsage
|
||||
* @typedef {{appended: true, previewIndex: number, mg: number}} NewUsage
|
||||
* @typedef {PoolUsage & {appended?: false, previewIndex?: number}} ExistingUsage
|
||||
* @typedef {ExistingUsage | NewUsage} PreviewUsage
|
||||
* @typedef {(ExistingUsage & {created: string, fifo_sequence: number}) | NewUsage} SortedUsage
|
||||
* @typedef {{totalMg: number, totalAmount: number|null, usages: PoolUsage[]}} PreviewPool
|
||||
* @typedef {{key: string, note: string, payer: string, amount: number|null, status?: string}} RecordedFee
|
||||
* @typedef {{rate?: number|null, mode?: string, poolId?: string}} RecordedCostMode
|
||||
* @typedef {{poolId: string, amount: number|null}} LockPool
|
||||
* @typedef {{payer: string, amount: number}} Allocation
|
||||
* @typedef {{
|
||||
* name: string, payer: string, quantity: number, cost?: number|null, costParts?: Record<string,number|null>,
|
||||
* costPayers?: Record<string,string>, priceLockPool?: LockPool, priceLockExtraPool?: LockPool,
|
||||
* costMaterial?: RecordedCostMode, costLabor?: RecordedCostMode,
|
||||
* materialPool?: {allocations: Allocation[], averageRate: number|null, quantity?: number, revision?: string|number},
|
||||
* materialAllocations?: (Allocation & {source: string, quantity: number, rate: number, weighted?: boolean, poolId?: string})[],
|
||||
* returnedStock?: boolean, returnedStockId?: string, recovery_id?: string, recoveryMaterialMg?: number,
|
||||
* charges?: {id:string}[]
|
||||
* }} RecordedLine
|
||||
* @typedef {{status: string, lines: RecordedLine[], corrections?: {type:string,target:string}[],
|
||||
* expenses?: {id:string,note:string,date:string,amount:number,payer:string}[],
|
||||
* pendingFees?: RecordedFee[], fee_items?: RecordedFee[]}} RecordedOrder
|
||||
* @typedef {({kind: 'paid'|'zero', amount: number} | {kind: 'goods'|'pending', amount: number|null}) & {
|
||||
* payer: string, name: string, source: string, excluded?: boolean, component?: string,
|
||||
* materialPoolId?: string, materialPoolRevision?: string|number, poolPending?: boolean,
|
||||
* calculation?: {rate?: number|null, quantity?: number, weighted?: boolean}|null,
|
||||
* priceLockSource?: string, inheritedStockCost?: boolean, returnedStockId?: string
|
||||
* }} CostRow
|
||||
*/
|
||||
(function (root) {
|
||||
const validMember = value =>
|
||||
const validMember = (/** @type {string} */ value) =>
|
||||
['owner', 'assistant', 'assistant2'].includes(value) ||
|
||||
/^staff_[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value);
|
||||
/**
|
||||
* @param {unknown} value
|
||||
* @param {number} places
|
||||
* @param {string} name
|
||||
*/
|
||||
function fixed(value, places, name) {
|
||||
const s = String(value ?? '').trim();
|
||||
if (!new RegExp('^\\d+(?:\\.\\d{1,' + places + '})?$').test(s))
|
||||
@@ -13,10 +58,12 @@
|
||||
if (n > 100000000000n) throw new Error(name + '超出支持范围');
|
||||
return n;
|
||||
}
|
||||
/** @param {unknown} v */
|
||||
function cents(v, name = '金额') {
|
||||
return Number(fixed(v, 2, name));
|
||||
}
|
||||
const isSilver = name => ['足银999', '纯银925'].includes(name);
|
||||
const isSilver = (/** @type {string|undefined} */ name) => name === '足银999' || name === '纯银925';
|
||||
/** @param {ChargeInput[]} [raw] */
|
||||
function charges(raw = []) {
|
||||
if (!Array.isArray(raw) || raw.length > 100) throw new Error('每行最多填写100项附加项目');
|
||||
const items = [];
|
||||
@@ -38,6 +85,7 @@
|
||||
if (total > 100000000000) throw new Error('附加项目合计超出支持范围');
|
||||
return { items, total };
|
||||
}
|
||||
/** @param {SaleInput} line */
|
||||
function sale(line) {
|
||||
const pricing = line.pricingMode === 'auto' ? calculate(line) : null;
|
||||
const baseSale = pricing ? pricing.sale : cents(line.baseSale ?? line.sale, '商品基础金额');
|
||||
@@ -46,6 +94,7 @@
|
||||
if (total > 100000000000) throw new Error('本行销售额超出支持范围');
|
||||
return { ...(pricing || {}), baseSale, charges: extra.items, chargesTotal: extra.total, sale: total };
|
||||
}
|
||||
/** @param {number[]} lineAmounts */
|
||||
function orderTotal(lineAmounts, discount = 0, roundingMode = 'yuan') {
|
||||
const limit = 100000000000n;
|
||||
if (!Array.isArray(lineAmounts) || lineAmounts.length < 1 || lineAmounts.length > 60)
|
||||
@@ -75,13 +124,14 @@
|
||||
rounding_adjustment: Number(total - unroundedTotal),
|
||||
};
|
||||
}
|
||||
/** @param {SaleInput} line */
|
||||
function calculate(line) {
|
||||
if (line.unit !== 'g') throw new Error('按金价计算需要填写克重;按件报价请选择直接填金额');
|
||||
const mg = fixed(line.quantity, 3, '克重');
|
||||
if (mg <= 0n) throw new Error('克重必须大于0');
|
||||
const gold = fixed(line.goldPrice, 2, '金价'),
|
||||
labor = fixed(line.laborRate, 2, '销售工费');
|
||||
if (!['gram', 'piece'].includes(line.laborMode)) throw new Error('请选择克工费或件工费');
|
||||
if (line.laborMode !== 'gram' && line.laborMode !== 'piece') throw new Error('请选择克工费或件工费');
|
||||
let pieces = 1n;
|
||||
if (line.laborMode === 'piece') {
|
||||
if (!/^\d+$/.test(String(line.pieces ?? '1'))) throw new Error('件数须为正整数');
|
||||
@@ -99,7 +149,10 @@
|
||||
pieces: Number(pieces),
|
||||
};
|
||||
}
|
||||
/** @type {Record<string,string>} */
|
||||
const costLabels = { material: '料费成本', labor: '进货工费', accessories: '配件成本', other: '其他货品成本' };
|
||||
/** @param {Record<string,string> | undefined} raw
|
||||
* @returns {{material:string,labor:string,[key:string]:string|undefined} | undefined} */
|
||||
function costPayers(raw) {
|
||||
// 旧行不补写分项付款人;显式传入时必须完整、有效,不能把无效值当作缺省。
|
||||
if (raw === undefined) return undefined;
|
||||
@@ -114,7 +167,9 @@
|
||||
if (!Object.hasOwn(raw, key) || !validMember(raw[key])) throw new Error(costLabels[key] + '付款人无效');
|
||||
return { material: raw.material, labor: raw.labor };
|
||||
}
|
||||
/** @param {Record<string,string|number|null>|undefined} raw */
|
||||
function costs(raw) {
|
||||
/** @type {Record<string,number|null>} */
|
||||
const parts = {};
|
||||
let total = 0,
|
||||
missing = false;
|
||||
@@ -126,12 +181,20 @@
|
||||
if (total > 100000000000) throw new Error('货品成本超出支持范围');
|
||||
return { parts, total: missing ? null : total };
|
||||
}
|
||||
/** @param {SaleInput} line */
|
||||
function purchaseCosts(line) {
|
||||
const parts = { ...line.costParts };
|
||||
/** @param {string} key
|
||||
* @param {CostEntry|undefined} metadata
|
||||
* @param {string} rateLabel
|
||||
* @param {string} totalLabel
|
||||
* @param {string} modeError
|
||||
* @param {string} unitError */
|
||||
const perGram = (key, metadata, rateLabel, totalLabel, modeError, unitError) => {
|
||||
// 旧单没有计价元数据时,原分项金额始终是总额,不能再乘克重。
|
||||
const mode = metadata?.mode || 'total';
|
||||
if (!['gram', 'total'].includes(mode)) throw new Error(modeError);
|
||||
/** @type {{mode:string,rate?:number|null}} */
|
||||
const result = { mode };
|
||||
if (mode === 'gram') {
|
||||
if (line.unit !== 'g') throw new Error(unitError);
|
||||
@@ -157,7 +220,9 @@
|
||||
costMaterial = { mode: 'pool', poolId };
|
||||
const previewAmount = line.materialPool?.amount;
|
||||
parts.material =
|
||||
Number.isSafeInteger(previewAmount) && previewAmount >= 0 ? (previewAmount / 100).toFixed(2) : '';
|
||||
typeof previewAmount === 'number' && Number.isSafeInteger(previewAmount) && previewAmount >= 0
|
||||
? (previewAmount / 100).toFixed(2)
|
||||
: '';
|
||||
} else
|
||||
costMaterial = perGram(
|
||||
'material',
|
||||
@@ -178,6 +243,11 @@
|
||||
return { ...costs(parts), costMaterial, costLabor };
|
||||
}
|
||||
// 先用实际总金额与总毫克计算,展示用均价不可参与成本分摊。
|
||||
/**
|
||||
* @param {number} totalAmount
|
||||
* @param {number} totalMg
|
||||
* @param {number} quantityMg
|
||||
*/
|
||||
function poolMaterialAmount(totalAmount, totalMg, quantityMg) {
|
||||
for (const value of [totalAmount, totalMg, quantityMg])
|
||||
if (!Number.isSafeInteger(value) || value < 0 || value > 100000000000) throw new Error('日购料金额或克重无效');
|
||||
@@ -187,8 +257,14 @@
|
||||
return Number(amount);
|
||||
}
|
||||
// 同池先按完整耗用顺序累计取整,再取相邻差额;编辑沿用原行身份,新增行追加。
|
||||
/**
|
||||
* @param {PreviewPool} pool
|
||||
* @param {{lineIndex:number,mg:number}[]} entries
|
||||
* @param {{orderId?:string|null,allUsages?:PoolUsage[]}} [options]
|
||||
*/
|
||||
function poolMaterialPreview(pool, entries, { orderId = null, allUsages = pool.usages || [] } = {}) {
|
||||
const valid = value => Number.isSafeInteger(value) && value >= 0 && value <= 100000000000;
|
||||
/** @param {number|null} value @returns {value is number} */
|
||||
const valid = value => value !== null && Number.isSafeInteger(value) && value >= 0 && value <= 100000000000;
|
||||
if (
|
||||
!valid(pool.totalAmount) ||
|
||||
!valid(pool.totalMg) ||
|
||||
@@ -197,7 +273,7 @@
|
||||
!Array.isArray(allUsages)
|
||||
)
|
||||
throw new Error('日购料预估记录无效,请刷新料价');
|
||||
const indices = new Set();
|
||||
const indices = /** @type {Set<number>} */ (new Set());
|
||||
for (const entry of entries) {
|
||||
if (
|
||||
!Number.isSafeInteger(entry.lineIndex) ||
|
||||
@@ -210,40 +286,40 @@
|
||||
indices.add(entry.lineIndex);
|
||||
}
|
||||
const originals = orderId ? allUsages.filter(usage => usage.order_id === orderId) : [];
|
||||
/** @type {PreviewUsage[]} */
|
||||
const usages = pool.usages
|
||||
.filter(usage => usage.active && (!orderId || usage.order_id !== orderId))
|
||||
.map(usage => ({ ...usage }));
|
||||
const usedMg = usages.reduce((total, usage) => total + usage.mg, 0),
|
||||
wantedMg = entries.reduce((total, entry) => total + entry.mg, 0);
|
||||
const covered = pool.totalMg > 0 && usedMg + wantedMg <= pool.totalMg,
|
||||
amounts = Object.fromEntries(entries.map(entry => [entry.lineIndex, null]));
|
||||
amounts = /** @type {Record<number,number|null>} */ (
|
||||
Object.fromEntries(entries.map(entry => [entry.lineIndex, null]))
|
||||
);
|
||||
for (const entry of entries) {
|
||||
const original = originals.find(usage => usage.line_index === entry.lineIndex);
|
||||
usages.push({ ...original, mg: entry.mg, previewIndex: entry.lineIndex, appended: !original });
|
||||
usages.push(
|
||||
original
|
||||
? { ...original, mg: entry.mg, previewIndex: entry.lineIndex, appended: false }
|
||||
: { mg: entry.mg, previewIndex: entry.lineIndex, appended: true },
|
||||
);
|
||||
}
|
||||
for (const usage of usages) {
|
||||
if (
|
||||
!valid(usage.mg) ||
|
||||
!usage.mg ||
|
||||
(!usage.appended &&
|
||||
(!Number.isSafeInteger(usage.fifo_sequence) ||
|
||||
usage.fifo_sequence < 1 ||
|
||||
typeof usage.created !== 'string' ||
|
||||
!usage.created))
|
||||
)
|
||||
throw new Error('日购料耗用顺序尚未读到,请刷新料价');
|
||||
}
|
||||
usages.sort(
|
||||
(a, b) =>
|
||||
Number(!!a.appended) - Number(!!b.appended) ||
|
||||
(a.appended
|
||||
? a.previewIndex - b.previewIndex
|
||||
: a.created < b.created
|
||||
? -1
|
||||
: a.created > b.created
|
||||
? 1
|
||||
: a.fifo_sequence - b.fifo_sequence),
|
||||
);
|
||||
/** @param {PreviewUsage} usage @returns {usage is SortedUsage} */
|
||||
const sortable = usage =>
|
||||
valid(usage.mg) &&
|
||||
usage.mg > 0 &&
|
||||
(usage.appended === true ||
|
||||
(typeof usage.fifo_sequence === 'number' &&
|
||||
Number.isSafeInteger(usage.fifo_sequence) &&
|
||||
usage.fifo_sequence >= 1 &&
|
||||
typeof usage.created === 'string' &&
|
||||
usage.created.length > 0));
|
||||
if (!usages.every(sortable)) throw new Error('日购料耗用顺序尚未读到,请刷新料价');
|
||||
usages.sort((a, b) => {
|
||||
if (a.appended) return b.appended ? a.previewIndex - b.previewIndex : 1;
|
||||
if (b.appended) return -1;
|
||||
return a.created < b.created ? -1 : a.created > b.created ? 1 : a.fifo_sequence - b.fifo_sequence;
|
||||
});
|
||||
if (covered) {
|
||||
let cumulativeMg = 0,
|
||||
previousAmount = 0;
|
||||
@@ -256,6 +332,7 @@
|
||||
}
|
||||
return { amounts, usedMg, wantedMg, covered };
|
||||
}
|
||||
/** @param {{lockedQuantity:unknown,quantity:unknown,buyRate:unknown,extraBuyRate?:unknown}} input */
|
||||
function priceLockCost(input) {
|
||||
const locked = fixed(input.lockedQuantity, 3, '锁定克重'),
|
||||
actual = fixed(input.quantity, 3, '实际克重');
|
||||
@@ -266,7 +343,7 @@
|
||||
extra = actual > locked ? actual - locked : 0n;
|
||||
const extraRate = extra ? fixed(input.extraBuyRate, 2, '补重进货料价') : 0n;
|
||||
if (extra && extraRate <= 0n) throw new Error('补重进货料价必须大于0');
|
||||
const amount = (quantity, rate) => (quantity * rate + 500n) / 1000n;
|
||||
const amount = (/** @type {bigint} */ quantity, /** @type {bigint} */ rate) => (quantity * rate + 500n) / 1000n;
|
||||
const originalPurchase = amount(locked, originalRate),
|
||||
originalUsedCost = amount(used, originalRate),
|
||||
extraCost = amount(extra, extraRate);
|
||||
@@ -286,6 +363,7 @@
|
||||
};
|
||||
}
|
||||
// 订单内部对账用,输入为账本已保存的整数分;预估费用与实际支出分开。
|
||||
/** @param {RecordedOrder} order */
|
||||
function orderCosts(order) {
|
||||
const empty = () => ({
|
||||
goods: 0,
|
||||
@@ -296,10 +374,14 @@
|
||||
total: 0,
|
||||
missing: 0,
|
||||
});
|
||||
const byPayer = { owner: empty(), assistant: empty(), assistant2: empty() },
|
||||
rows = [];
|
||||
const byPayer = /** @type {Record<string, ReturnType<typeof empty>>} */ ({
|
||||
owner: empty(),
|
||||
assistant: empty(),
|
||||
assistant2: empty(),
|
||||
}),
|
||||
rows = /** @type {CostRow[]} */ ([]);
|
||||
const goodsExcluded = ['returned', 'cancelled'].includes(order.status);
|
||||
const add = row => {
|
||||
const add = (/** @type {CostRow} */ row) => {
|
||||
rows.push(row);
|
||||
if (row.excluded) return;
|
||||
if (!validMember(row.payer)) throw new Error('成本付款人无效');
|
||||
@@ -317,10 +399,14 @@
|
||||
for (const [i, line] of order.lines.entries()) {
|
||||
const payers = costPayers(line.costPayers);
|
||||
const parts = line.costParts
|
||||
? Object.entries(costLabels).map(([key, name]) => ({ key, name, amount: line.costParts[key] ?? null }))
|
||||
? Object.entries(costLabels).map(([key, name]) => ({ key, name, amount: line.costParts?.[key] ?? null }))
|
||||
: [{ key: 'total', name: '货品成本(原单未分项)', amount: line.cost ?? null }];
|
||||
const lockPool =
|
||||
line.priceLockExtraPool?.amount === null
|
||||
? line.priceLockExtraPool
|
||||
: line.priceLockPool || line.priceLockExtraPool;
|
||||
for (const part of parts) {
|
||||
if (part.key === 'material' && (line.priceLockPool || line.priceLockExtraPool) && part.amount === null) {
|
||||
if (part.key === 'material' && lockPool && part.amount === null) {
|
||||
add({
|
||||
kind: 'goods',
|
||||
component: 'material',
|
||||
@@ -329,17 +415,13 @@
|
||||
amount: null,
|
||||
payer: payers?.material ?? line.payer,
|
||||
excluded: goodsExcluded,
|
||||
materialPoolId: (line.priceLockExtraPool?.amount === null
|
||||
? line.priceLockExtraPool
|
||||
: line.priceLockPool || line.priceLockExtraPool
|
||||
).poolId,
|
||||
materialPoolId: lockPool.poolId,
|
||||
poolPending: true,
|
||||
calculation: null,
|
||||
});
|
||||
} else if (part.key === 'material' && line.costMaterial?.mode === 'pool') {
|
||||
const pool = line.materialPool,
|
||||
allocations = pool?.allocations;
|
||||
if (part.amount === null || !allocations?.length) {
|
||||
const pool = line.materialPool;
|
||||
if (part.amount === null || !pool?.allocations?.length) {
|
||||
add({
|
||||
kind: 'goods',
|
||||
component: 'material',
|
||||
@@ -354,6 +436,7 @@
|
||||
calculation: null,
|
||||
});
|
||||
} else {
|
||||
const allocations = pool.allocations;
|
||||
if (
|
||||
!Array.isArray(allocations) ||
|
||||
allocations.some(
|
||||
@@ -437,7 +520,7 @@
|
||||
for (const fee of order.expenses || [])
|
||||
if (fee.amount > 0 && !corrected.has(fee.id))
|
||||
add({ kind: 'paid', name: fee.note, source: fee.date, amount: fee.amount, payer: fee.payer });
|
||||
const sourceFor = fee => {
|
||||
const sourceFor = (/** @type {RecordedFee} */ fee) => {
|
||||
const index = order.lines.findIndex(l => (l.charges || []).some(c => 'charge:' + c.id === fee.key));
|
||||
return index < 0 ? '整单费用' : `商品 ${index + 1} · ${order.lines[index].name}`;
|
||||
};
|
||||
@@ -451,7 +534,7 @@
|
||||
for (const s of Object.values(byPayer)) {
|
||||
s.total = s.goods + s.paidFees + s.pendingFees;
|
||||
s.missing = s.goodsMissing + s.pendingMissing;
|
||||
for (const key of Object.keys(total)) total[key] += s[key];
|
||||
for (const key of /** @type {(keyof typeof total)[]} */ (Object.keys(total))) total[key] += s[key];
|
||||
}
|
||||
return { byPayer, total, rows, goodsExcluded, pendingCount: (order.pendingFees || []).length };
|
||||
}
|
||||
@@ -473,5 +556,5 @@
|
||||
orderCosts,
|
||||
};
|
||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||
else root.LedgerCalc = api;
|
||||
else Object.assign(root, { LedgerCalc: api });
|
||||
})(typeof globalThis === 'object' ? globalThis : this);
|
||||
@@ -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,32 @@
|
||||
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)
|
||||
typeof shopDefaults.packagingPayer === 'string' &&
|
||||
(['owner', 'assistant', 'assistant2'].includes(shopDefaults.packagingPayer) ||
|
||||
/^staff_[a-f0-9-]{36}$/.test(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 +340,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);
|
||||
@@ -86,5 +86,5 @@
|
||||
accountIdentity,
|
||||
};
|
||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||
else root.LedgerValues = 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 };
|
||||
},
|
||||
);
|
||||
+308
-113
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)));
|
||||
+321
-281
@@ -7,288 +7,328 @@
|
||||
);
|
||||
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 {Omit<import('../web/src/shared/orderPresets').TemplateProduct, 'charges'>} */
|
||||
const product = {
|
||||
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, '商品基础金额'),
|
||||
};
|
||||
product.name = nameType === '其他' ? product.customName : nameType;
|
||||
if (line.stockCount != null && String(line.stockCount).trim() !== '') {
|
||||
product.stockCount = count(line.stockCount, '出库数量(对)');
|
||||
if (Number(product.stockCount) < 1) throw new Error('出库数量(对)须为正整数,一对填1');
|
||||
}
|
||||
const rawCharges = line.charges ?? [];
|
||||
if (!Array.isArray(rawCharges) || rawCharges.length > 100) throw new Error('每行最多填写100项附加项目');
|
||||
/** @type {import('../web/src/shared/orderPresets').TemplateProduct['charges']} */
|
||||
const normalizedCharges = 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 };
|
||||
});
|
||||
});
|
||||
const result = {...product, charges:normalizedCharges};
|
||||
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 };
|
||||
},
|
||||
);
|
||||
+148
-59
@@ -1,9 +1,24 @@
|
||||
// @ts-check
|
||||
'use strict';
|
||||
/** @typedef {import('../web/src/pages/Recoveries/types').Draft} Draft */
|
||||
/** @typedef {import('../web/src/pages/Recoveries/types').OldLine} OldLine */
|
||||
/** @typedef {import('../web/src/pages/Recoveries/types').Input} Input */
|
||||
/** @typedef {import('../web/src/pages/Recoveries/types').Product} Product */
|
||||
/** @typedef {import('../web/src/pages/Recoveries/types').Calculation} Calculation */
|
||||
/** @typedef {import('../web/src/pages/Recoveries/types').EditDetail} EditDetail */
|
||||
/** @typedef {import('../web/src/pages/Recoveries/types').ChangeRequest} ChangeRequest */
|
||||
/** @typedef {import('../web/src/pages/Recoveries/types').ItemInput} ItemInput */
|
||||
/** @typedef {import('../web/src/pages/Recoveries/types').Exchange} Exchange */
|
||||
/** @typedef {import('../web/src/pages/Recoveries/types').Material} Material */
|
||||
/** @typedef {import('../web/src/pages/Recoveries/types').RecoveryContext} RecoveryContext */
|
||||
/** @typedef {import('../web/src/pages/Recoveries/types').RecoveryModel} RecoveryModel */
|
||||
/** @typedef {import('../web/src/pages/Recoveries/types').Totals} Totals */
|
||||
// 两种前端共用的回收规则。金额为分、重量为毫克,新版与历史两种多件置换格式分别结算。
|
||||
(function (root) {
|
||||
const recoveryModeNames = { direct: '直接回收', exchange: '置换' };
|
||||
/** @param {unknown} value */
|
||||
const recoveryText = value => String(value ?? '').trim();
|
||||
const recoveryProductFields = [
|
||||
const recoveryProductFields = /** @type {const} */ ([
|
||||
'new_name',
|
||||
'new_quantity',
|
||||
'pocket',
|
||||
@@ -13,8 +28,9 @@
|
||||
'cost_labor_mode',
|
||||
'cost_labor_value',
|
||||
'labor_payer',
|
||||
];
|
||||
]);
|
||||
|
||||
/** @param {unknown} value @param {number} places @param {string} title @returns {number} */
|
||||
function recoveryUnits(value, places, title, { zero = true } = {}) {
|
||||
const raw = recoveryText(value),
|
||||
pattern = new RegExp('^\\d+(?:\\.\\d{1,' + places + '})?$');
|
||||
@@ -26,16 +42,19 @@
|
||||
return Number(units);
|
||||
}
|
||||
|
||||
/** @param {number} value @returns {number} */
|
||||
function recoveryLimit(value, title = '回收/置换合计') {
|
||||
if (!Number.isSafeInteger(value) || Math.abs(value) > 100000000000)
|
||||
throw new Error(title + '超出支持范围,请核对。');
|
||||
return value;
|
||||
}
|
||||
|
||||
/** @param {number} weight @param {number} rate @returns {number} */
|
||||
function recoveryMul(weight, rate) {
|
||||
return recoveryLimit(Number((BigInt(weight) * BigInt(rate) + 500n) / 1000n));
|
||||
}
|
||||
|
||||
/** @param {Product} row */
|
||||
function recoveryProductDraft(row) {
|
||||
return {
|
||||
new_name: row.name,
|
||||
@@ -50,6 +69,7 @@
|
||||
};
|
||||
}
|
||||
|
||||
/** @param {Draft} draft @returns {number} */
|
||||
function recoveryNewWeight(draft) {
|
||||
return [draft, ...(draft.extra_products || [])].reduce(
|
||||
(n, row) => recoveryLimit(n + recoveryUnits(row.new_quantity, 3, '新货克重', { zero: false })),
|
||||
@@ -57,13 +77,34 @@
|
||||
);
|
||||
}
|
||||
|
||||
/** @param {Draft} draft @returns {Draft} */
|
||||
function recoverySharedOldDraft(draft) {
|
||||
if (!draft.independent_products) return draft;
|
||||
return {
|
||||
...draft,
|
||||
independent_products: false,
|
||||
extra_products: (draft.extra_products || []).map(row =>
|
||||
Object.fromEntries(recoveryProductFields.map(k => [k, row[k]])),
|
||||
extra_products: (draft.extra_products || []).map(
|
||||
({
|
||||
new_name,
|
||||
new_quantity,
|
||||
pocket,
|
||||
stockCount,
|
||||
labor_mode,
|
||||
labor_rate,
|
||||
cost_labor_mode,
|
||||
cost_labor_value,
|
||||
labor_payer,
|
||||
}) => ({
|
||||
new_name,
|
||||
new_quantity,
|
||||
pocket,
|
||||
stockCount,
|
||||
labor_mode,
|
||||
labor_rate,
|
||||
cost_labor_mode,
|
||||
cost_labor_value,
|
||||
labor_payer,
|
||||
}),
|
||||
),
|
||||
...(draft.extra_products?.length ? { buy_total_manual: false, buy_total: '', depreciation_manual: false } : {}),
|
||||
verified: false,
|
||||
@@ -71,8 +112,10 @@
|
||||
};
|
||||
}
|
||||
|
||||
/** @param {Input} input @returns {Calculation} */
|
||||
function recoveryCalculate(input) {
|
||||
if (input.mode === 'exchange' && input.exchange?.items) return recoveryItemsCalculate(input);
|
||||
if (input.mode === 'exchange' && input.exchange?.items)
|
||||
return recoveryItemsCalculate(input, input.exchange, input.exchange.items);
|
||||
if (!Object.hasOwn(recoveryModeNames, input.mode)) throw new Error('请选择直接回收或置换。');
|
||||
const oldLines = (input.old_lines || []).map(line => {
|
||||
const incomingMg = recoveryUnits(line.incoming_weight, 3, '来料重量', { zero: false }),
|
||||
@@ -103,6 +146,7 @@
|
||||
receivable = 0,
|
||||
roundingAdjustment = 0;
|
||||
if (input.mode === 'exchange') {
|
||||
/** @type {Partial<Exchange>} */
|
||||
const x = input.exchange || {};
|
||||
newMg = x.products
|
||||
? recoveryLimit(
|
||||
@@ -179,8 +223,9 @@
|
||||
};
|
||||
}
|
||||
|
||||
function recoveryItemsCalculate(input) {
|
||||
const parts = input.exchange.items.map(row =>
|
||||
/** @param {Input} input @param {Exchange} exchange @param {ItemInput[]} items @returns {Calculation} */
|
||||
function recoveryItemsCalculate(input, exchange, items) {
|
||||
const parts = items.map(row =>
|
||||
recoveryCalculate({
|
||||
...input,
|
||||
...row,
|
||||
@@ -192,37 +237,48 @@
|
||||
exchange: row.exchange,
|
||||
}),
|
||||
);
|
||||
const q = { mode: 'exchange', old_lines: parts.flatMap(p => p.old_lines), exchangeItems: parts };
|
||||
for (const key of [
|
||||
'oldMg',
|
||||
'newMg',
|
||||
'matchedMg',
|
||||
'differenceMg',
|
||||
'surplusMg',
|
||||
'depositMg',
|
||||
'purchaseMg',
|
||||
'goldAmount',
|
||||
'laborAmount',
|
||||
'depreciationMg',
|
||||
'depreciationAmount',
|
||||
'purchaseAmount',
|
||||
'defaultPurchaseAmount',
|
||||
])
|
||||
q[key] = recoveryLimit(parts.reduce((n, p) => n + p[key], 0));
|
||||
q.chargesAmount = recoveryLimit(
|
||||
(input.exchange.charges || []).reduce((n, r) => n + recoveryUnits(r.amount, 2, '其他收费'), 0),
|
||||
/** @param {keyof Pick<Calculation,'oldMg'|'newMg'|'matchedMg'|'differenceMg'|'surplusMg'|'depositMg'|'purchaseMg'|'goldAmount'|'laborAmount'|'depreciationMg'|'depreciationAmount'|'purchaseAmount'|'defaultPurchaseAmount'>} key */
|
||||
const sum = key => recoveryLimit(parts.reduce((n, p) => n + p[key], 0));
|
||||
const sums = {
|
||||
oldMg: sum('oldMg'),
|
||||
newMg: sum('newMg'),
|
||||
matchedMg: sum('matchedMg'),
|
||||
differenceMg: sum('differenceMg'),
|
||||
surplusMg: sum('surplusMg'),
|
||||
depositMg: sum('depositMg'),
|
||||
purchaseMg: sum('purchaseMg'),
|
||||
goldAmount: sum('goldAmount'),
|
||||
laborAmount: sum('laborAmount'),
|
||||
depreciationMg: sum('depreciationMg'),
|
||||
depreciationAmount: sum('depreciationAmount'),
|
||||
purchaseAmount: sum('purchaseAmount'),
|
||||
defaultPurchaseAmount: sum('defaultPurchaseAmount'),
|
||||
};
|
||||
const chargesAmount = recoveryLimit(
|
||||
(exchange.charges || []).reduce((n, r) => n + recoveryUnits(r.amount, 2, '其他收费'), 0),
|
||||
);
|
||||
q.discount = recoveryUnits(input.exchange.discount || '0', 2, '整单优惠');
|
||||
const before = recoveryLimit(q.goldAmount + q.laborAmount + q.depreciationAmount + q.chargesAmount) - q.discount;
|
||||
const discount = recoveryUnits(exchange.discount || '0', 2, '整单优惠');
|
||||
const before =
|
||||
recoveryLimit(sums.goldAmount + sums.laborAmount + sums.depreciationAmount + chargesAmount) - discount;
|
||||
if (before < 0) throw new Error('优惠金额不能大于置换费用');
|
||||
q.receivable = input.exchange.rounding_mode === 'yuan' ? Math.floor((before + 50) / 100) * 100 : before;
|
||||
q.roundingAdjustment = q.receivable - before;
|
||||
q.netSettlement = q.receivable - q.purchaseAmount;
|
||||
q.cashReceipt = Math.max(0, q.netSettlement);
|
||||
q.cashPayment = Math.max(0, -q.netSettlement);
|
||||
return q;
|
||||
const receivable = exchange.rounding_mode === 'yuan' ? Math.floor((before + 50) / 100) * 100 : before;
|
||||
const netSettlement = receivable - sums.purchaseAmount;
|
||||
return {
|
||||
mode: 'exchange',
|
||||
old_lines: parts.flatMap(p => p.old_lines),
|
||||
exchangeItems: parts,
|
||||
...sums,
|
||||
chargesAmount,
|
||||
discount,
|
||||
receivable,
|
||||
roundingAdjustment: receivable - before,
|
||||
netSettlement,
|
||||
cashReceipt: Math.max(0, netSettlement),
|
||||
cashPayment: Math.max(0, -netSettlement),
|
||||
};
|
||||
}
|
||||
|
||||
/** @param {Draft} draft @returns {OldLine[]} */
|
||||
function customerMaterialOldLines(draft) {
|
||||
return [
|
||||
{ name: '客户寄存料', incoming_weight: draft.deposit_weight, melted_weight: draft.deposit_weight, purity: '100' },
|
||||
@@ -230,7 +286,12 @@
|
||||
}
|
||||
|
||||
// 页面的成员、货盘和账户策略由调用方提供。originalInput 只在编辑既有单据时参与历史值校验。
|
||||
/**
|
||||
* @param {import('../web/src/pages/Recoveries/types').RecoveryContext} context
|
||||
* @returns {import('../web/src/pages/Recoveries/types').RecoveryModel}
|
||||
*/
|
||||
function createModel(context) {
|
||||
/** @param {import('../web/src/pages/Recoveries/types').ProductDraft} draft @returns {Product} */
|
||||
function recoveryProductInput(draft) {
|
||||
return {
|
||||
name: draft.new_name,
|
||||
@@ -251,6 +312,7 @@
|
||||
};
|
||||
}
|
||||
|
||||
/** @param {import('../web/src/pages/Recoveries/types').Mode} [mode] @returns {Draft} */
|
||||
function recoveryDefaults(mode = 'direct') {
|
||||
const member = context.currentMember();
|
||||
return {
|
||||
@@ -307,11 +369,15 @@
|
||||
};
|
||||
}
|
||||
|
||||
/** @overload @param {Draft & {mode:'exchange'}} draft @param {{quote?:boolean}} [options] @returns {Input & {exchange:Exchange}} */
|
||||
/** @overload @param {Draft} draft @param {{quote?:boolean}} [options] @returns {Input} */
|
||||
/** @param {Draft} draft @returns {Input} */
|
||||
function recoveryInput(draft, { quote = false } = {}) {
|
||||
if (draft.mode === 'exchange' && draft.independent_products) return recoveryItemsInput(draft, { quote });
|
||||
if (draft.mode === 'exchange' && draft.old_source === 'deposit')
|
||||
draft = { ...draft, old_lines: customerMaterialOldLines(draft) };
|
||||
const member = context.state.user.role === 'owner' ? draft.member : context.currentMember();
|
||||
/** @type {Input} */
|
||||
const input = {
|
||||
mode: draft.mode,
|
||||
date: draft.date,
|
||||
@@ -354,12 +420,14 @@
|
||||
buy_total: '0',
|
||||
});
|
||||
if (draft.mode === 'exchange') {
|
||||
/** @type {import('../web/src/pages/Recoveries/types').Labor|undefined} */
|
||||
const costLabor =
|
||||
draft.cost_labor_value === ''
|
||||
? undefined
|
||||
: draft.cost_labor_mode === 'total'
|
||||
? { mode: 'total', amount: draft.cost_labor_value }
|
||||
: { mode: 'gram', rate: draft.cost_labor_value };
|
||||
/** @type {Material|undefined} */
|
||||
const costMaterial =
|
||||
draft.material_source === 'pool'
|
||||
? { mode: 'pool', poolId: draft.material_pool_id || draft.date }
|
||||
@@ -428,19 +496,22 @@
|
||||
return input;
|
||||
}
|
||||
|
||||
function validateRecoveryInput(input) {
|
||||
/** @param {Input} input @returns {Input} */
|
||||
function validateRecoveryInput(input, itemIndex = -1) {
|
||||
if (input.exchange?.items) {
|
||||
for (const [index, row] of input.exchange.items.entries())
|
||||
validateRecoveryInput({
|
||||
...input,
|
||||
...row,
|
||||
_recoveryItemIndex: index,
|
||||
buy_total: row.buy_total,
|
||||
buy_rate: row.buy_rate,
|
||||
exchange: row.exchange,
|
||||
payment_account: context.memberAccountPrefix(input.payer) + '微信',
|
||||
});
|
||||
if (!context.state.accounts.includes(input.payment_account)) throw new Error('请选择有效收付款账户');
|
||||
validateRecoveryInput(
|
||||
{
|
||||
...input,
|
||||
...row,
|
||||
buy_total: row.buy_total,
|
||||
buy_rate: row.buy_rate,
|
||||
exchange: row.exchange,
|
||||
payment_account: context.memberAccountPrefix(input.payer) + '微信',
|
||||
},
|
||||
index,
|
||||
);
|
||||
if (!context.state.accounts?.includes(input.payment_account)) throw new Error('请选择有效收付款账户');
|
||||
return input;
|
||||
}
|
||||
if (!context.validOrderDate(input.date) || input.date > context.state.today)
|
||||
@@ -452,7 +523,7 @@
|
||||
throw new Error('请选择归属成员和实际付款人。');
|
||||
const calculation = recoveryCalculate(input);
|
||||
const source = context.originalInput,
|
||||
item = source?.exchange?.items?.[input._recoveryItemIndex],
|
||||
item = source?.exchange?.items?.[itemIndex],
|
||||
oldOriginal = item ? { ...source, ...item } : source;
|
||||
const oldPocket = input.old_pocket ?? '回收旧料';
|
||||
if (
|
||||
@@ -477,10 +548,10 @@
|
||||
if (recoveryUnits(input.deposit_weight, 3, '使用寄存克重', { zero: false }) > calculation.newMg)
|
||||
throw new Error('本次寄存用量不能超过新货克重,剩余继续寄存');
|
||||
}
|
||||
if (input.mode === 'exchange') {
|
||||
if (input.mode === 'exchange' && input.exchange) {
|
||||
const x = input.exchange,
|
||||
original = oldOriginal?.exchange;
|
||||
if (context.pocketCountsEnabled(x.pocket))
|
||||
if (context.pocketCountsEnabled(x.pocket ?? ''))
|
||||
context.stockCountValue(x.stockCount, {
|
||||
optional:
|
||||
!!original &&
|
||||
@@ -492,7 +563,7 @@
|
||||
if (!x.name || x.name.length > 60) throw new Error('请填写1~60字的新货商品名称。');
|
||||
if (
|
||||
x.pocket !== '' &&
|
||||
!context.activePocketKeys().includes(x.pocket) &&
|
||||
!context.activePocketKeys().includes(x.pocket ?? '') &&
|
||||
!(source && original?.pocket === x.pocket)
|
||||
)
|
||||
throw new Error('请选择新货实际出库的已启用货盘。');
|
||||
@@ -524,18 +595,19 @@
|
||||
throw new Error('料池日期不能晚于业务日期。');
|
||||
}
|
||||
for (const payer of [x.cost_material_payer, x.cost_labor_payer, ...x.fee_items.map(row => row.payer)])
|
||||
if (!context.teamMemberKeys().includes(payer)) throw new Error('请选择内部成本的实际付款人。');
|
||||
if (!payer || !context.teamMemberKeys().includes(payer)) throw new Error('请选择内部成本的实际付款人。');
|
||||
}
|
||||
if (calculation.netSettlement < 0 && context.isCreditCardAccount(input.payment_account))
|
||||
throw new Error('向客户付款不能使用信用卡收款账户。');
|
||||
if (!context.state.accounts.includes(input.payment_account)) throw new Error('请选择有效的收付款方式。');
|
||||
if (!context.state.accounts?.includes(input.payment_account)) throw new Error('请选择有效的收付款方式。');
|
||||
if (input.verified !== true) throw new Error('请核实重量、结算金额和实际收付款后,勾选确认再保存。');
|
||||
return input;
|
||||
}
|
||||
|
||||
/** @param {Draft} draft @returns {Input} */
|
||||
function recoveryItemsInput(draft, { quote = false } = {}) {
|
||||
const common = {
|
||||
mode: 'exchange',
|
||||
mode: /** @type {const} */ ('exchange'),
|
||||
date: draft.date,
|
||||
customer: draft.customer,
|
||||
customer_type: draft.customer_type,
|
||||
@@ -579,7 +651,14 @@
|
||||
};
|
||||
});
|
||||
const first = recoveryInput(
|
||||
{ ...draft, independent_products: false, extra_products: [], discount: '0', rounding_mode: 'cent' },
|
||||
{
|
||||
...draft,
|
||||
mode: 'exchange',
|
||||
independent_products: false,
|
||||
extra_products: [],
|
||||
discount: '0',
|
||||
rounding_mode: 'cent',
|
||||
},
|
||||
{ quote: true },
|
||||
),
|
||||
input = {
|
||||
@@ -609,6 +688,7 @@
|
||||
return input;
|
||||
}
|
||||
|
||||
/** @param {Input|null} input */
|
||||
function recoveryInputShape(input) {
|
||||
return (
|
||||
input &&
|
||||
@@ -621,13 +701,17 @@
|
||||
input.old_lines.length > 0 &&
|
||||
input.old_lines.every(
|
||||
row =>
|
||||
row && ['name', 'incoming_weight', 'melted_weight', 'purity'].every(key => typeof row[key] === 'string'),
|
||||
row &&
|
||||
/** @type {const} */ (['name', 'incoming_weight', 'melted_weight', 'purity']).every(
|
||||
key => typeof row[key] === 'string',
|
||||
),
|
||||
) &&
|
||||
(input.mode === 'direct' ||
|
||||
(input.exchange && Array.isArray(input.exchange.charges) && Array.isArray(input.exchange.fee_items)))
|
||||
);
|
||||
}
|
||||
|
||||
/** @param {EditDetail} data @param {string} id @returns {EditDetail} */
|
||||
function validateRecoveryEditDetail(data, id) {
|
||||
if (
|
||||
!data ||
|
||||
@@ -638,8 +722,10 @@
|
||||
!['active', 'cancelled'].includes(data.status) ||
|
||||
!recoveryInputShape(data.inputs) ||
|
||||
!data.permissions ||
|
||||
!['canEdit', 'canCancel', 'canDirect', 'requiresApproval'].every(
|
||||
key => typeof data.permissions[key] === 'boolean',
|
||||
!(
|
||||
/** @type {const} */ (['canEdit', 'canCancel', 'canDirect', 'requiresApproval']).every(
|
||||
key => typeof data.permissions[key] === 'boolean',
|
||||
)
|
||||
) ||
|
||||
!Array.isArray(data.blockedUsages) ||
|
||||
!Array.isArray(data.history) ||
|
||||
@@ -655,6 +741,7 @@
|
||||
return data;
|
||||
}
|
||||
|
||||
/** @param {ChangeRequest} request @returns {ChangeRequest} */
|
||||
function validateRecoveryChangeRequest(request) {
|
||||
if (
|
||||
!request ||
|
||||
@@ -680,6 +767,7 @@
|
||||
return request;
|
||||
}
|
||||
|
||||
/** @param {Input} input @returns {Draft} */
|
||||
function recoveryEditDraft(input) {
|
||||
if (input.exchange?.items) {
|
||||
const rows = input.exchange.items.map(row => recoveryEditDraft({ ...input, ...row, exchange: row.exchange })),
|
||||
@@ -700,8 +788,9 @@
|
||||
rounding_mode: x.rounding_mode,
|
||||
};
|
||||
}
|
||||
/** @type {Partial<Exchange>} */
|
||||
const x = input.exchange || {};
|
||||
const first = input.old_lines[0],
|
||||
x = input.exchange || {},
|
||||
charge = x.charges?.[0],
|
||||
fee = x.fee_items?.[0],
|
||||
account = input.payment_account || '',
|
||||
@@ -739,7 +828,7 @@
|
||||
payout_method: method === '信用卡' ? '微信' : method,
|
||||
new_name: x.name || '足金999',
|
||||
new_quantity: x.quantity || '',
|
||||
pocket: x.pocket ?? context.state.pockets[0] ?? '',
|
||||
pocket: x.pocket ?? context.state.pockets?.[0] ?? '',
|
||||
stockCount: x.stockCount ?? '',
|
||||
gold_price: x.gold_price || '0',
|
||||
labor_mode: x.labor_mode || 'gram',
|
||||
@@ -785,5 +874,5 @@
|
||||
}
|
||||
const api = { createModel, recoveryModeNames, recoveryProductFields, customerMaterialOldLines };
|
||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||
else root.RecoveryRules = api;
|
||||
else /** @type {{RecoveryRules?:object}} */ (root).RecoveryRules = api;
|
||||
})(typeof globalThis === 'object' ? globalThis : this);
|
||||
+220
-99
@@ -1,14 +1,40 @@
|
||||
'use strict';
|
||||
// 两版对账共用的校验和归集规则。成员、当前查询以及日期校验由调用方提供。
|
||||
/** @typedef {import('../web/src/pages/Report/contracts').Business} Business */
|
||||
/** @typedef {import('../web/src/pages/Report/contracts').DailyFunds} DailyFunds */
|
||||
/** @typedef {import('../web/src/pages/Report/contracts').OwnershipReceipts} OwnershipReceipts */
|
||||
/** @typedef {import('../web/src/pages/Report/contracts').PayerCosts} PayerCosts */
|
||||
/** @typedef {import('../web/src/pages/Report/contracts').Range} Range */
|
||||
/** @typedef {import('../web/src/pages/Report/contracts').RecoveryCosts} RecoveryCosts */
|
||||
/** @typedef {import('../web/src/pages/Report/contracts').Reimbursement} Reimbursement */
|
||||
/** @typedef {import('../web/src/pages/Report/contracts').ReimbursementList} ReimbursementList */
|
||||
/** @typedef {import('../web/src/pages/Report/contracts').Report} Report */
|
||||
/** @typedef {import('../web/src/pages/Report/contracts').Row} Row */
|
||||
/** @typedef {import('../web/src/pages/Report/contracts').RuleContext} RuleContext */
|
||||
/** @typedef {import('../web/src/pages/Report/contracts').Team} Team */
|
||||
/** @typedef {import('../web/src/pages/Report/contracts').CostItem} CostItem */
|
||||
/** @typedef {import('../web/src/pages/Report/contracts').ReceiptItem} ReceiptItem */
|
||||
/** @typedef {import('../web/src/pages/Report/contracts').Profit} Profit */
|
||||
/** @typedef {import('../web/src/pages/Report/contracts').MaterialValue} MaterialValue */
|
||||
/** @typedef {import('../web/src/pages/Report/contracts').AdvanceItem} AdvanceItem */
|
||||
(function (root) {
|
||||
function reportAfterSaleAmount(cost) {
|
||||
return cost.items.filter(item => item.kind === 'afterSale').reduce((sum, item) => sum + item.amount, 0);
|
||||
/** @param {unknown} value
|
||||
* @returns {value is number} */
|
||||
function integer(value) {
|
||||
return Number.isSafeInteger(value);
|
||||
}
|
||||
|
||||
/** @param {PayerCosts} cost */
|
||||
function reportAfterSaleAmount(cost) {
|
||||
return cost.items.filter(item => item.kind === 'afterSale').reduce((sum, item) => sum + (item.amount ?? 0), 0);
|
||||
}
|
||||
|
||||
/** @param {PayerCosts} cost */
|
||||
function reportCostItems(cost) {
|
||||
return cost.items.filter(item => item.kind !== 'goods' || item.amount !== 0);
|
||||
}
|
||||
|
||||
/** @param {Row} row */
|
||||
function reportRowCost(row) {
|
||||
const goods = (row.costItems || []).filter(item => item.kind === 'goods');
|
||||
return {
|
||||
@@ -16,10 +42,11 @@
|
||||
missing: goods.filter(item => item.amount == null).length,
|
||||
paidFees: (row.costItems || [])
|
||||
.filter(item => ['paid', 'afterSale'].includes(item.kind))
|
||||
.reduce((sum, item) => sum + item.amount, 0),
|
||||
.reduce((sum, item) => sum + (item.amount ?? 0), 0),
|
||||
};
|
||||
}
|
||||
|
||||
/** @param {Business} business */
|
||||
function reportCurrentAccountDays(business) {
|
||||
const account = business.currentAccount;
|
||||
return account.days.length
|
||||
@@ -42,6 +69,10 @@
|
||||
: [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{amount:string}[]} items
|
||||
* @param {(value: string) => number} cents
|
||||
*/
|
||||
function reimbursementAmounts(items, cents) {
|
||||
let total = 0,
|
||||
complete = true;
|
||||
@@ -63,6 +94,7 @@
|
||||
};
|
||||
}
|
||||
|
||||
/** @param {RuleContext} context */
|
||||
function forContext({
|
||||
teamDataKeys,
|
||||
validOrderDate,
|
||||
@@ -73,7 +105,13 @@
|
||||
state,
|
||||
reportMember,
|
||||
}) {
|
||||
function validateReport(r, range) {
|
||||
/**
|
||||
* @param {unknown} input
|
||||
* @param {Range} range
|
||||
* @returns {asserts input is Report}
|
||||
*/
|
||||
function validateReport(input, range) {
|
||||
const r = /** @type {Report} */ (input);
|
||||
if (r.basis !== 'orderDate' || r.date !== range.date || r.from !== range.from)
|
||||
throw new Error('返回口径或日期与当前选择不一致,请重新读取。');
|
||||
if (
|
||||
@@ -87,7 +125,9 @@
|
||||
return (
|
||||
c &&
|
||||
Array.isArray(c.items) &&
|
||||
['goods', 'paidFees', 'total', 'missingCount', 'pendingCount'].every(name => Number.isSafeInteger(c[name]))
|
||||
/** @type {const} */ (['goods', 'paidFees', 'total', 'missingCount', 'pendingCount']).every(name =>
|
||||
Number.isSafeInteger(c[name]),
|
||||
)
|
||||
);
|
||||
})
|
||||
)
|
||||
@@ -103,7 +143,7 @@
|
||||
typeof person.name === 'string' &&
|
||||
person.name &&
|
||||
Array.isArray(person.items) &&
|
||||
['receipt', 'refund', 'net'].every(key => Number.isSafeInteger(person[key])) &&
|
||||
/** @type {const} */ (['receipt', 'refund', 'net']).every(key => Number.isSafeInteger(person[key])) &&
|
||||
person.items.every(
|
||||
item =>
|
||||
item &&
|
||||
@@ -113,14 +153,16 @@
|
||||
validOrderDate(item.date),
|
||||
) &&
|
||||
person.net === person.receipt - person.refund &&
|
||||
['receipt', 'refund'].every(
|
||||
/** @type {const} */ (['receipt', 'refund']).every(
|
||||
kind =>
|
||||
person.items.filter(item => item.kind === kind).reduce((sum, item) => sum + item.amount, 0) ===
|
||||
person.items.filter(item => item.kind === kind).reduce((sum, item) => sum + (item.amount ?? 0), 0) ===
|
||||
person[kind],
|
||||
),
|
||||
) ||
|
||||
!['receipt', 'refund', 'net'].every(
|
||||
key => recipients.reduce((sum, person) => sum + person[key], 0) === r.receiptsByOrderDate[key],
|
||||
!(
|
||||
/** @type {const} */ (['receipt', 'refund', 'net']).every(
|
||||
key => recipients.reduce((sum, person) => sum + person[key], 0) === r.receiptsByOrderDate[key],
|
||||
)
|
||||
)
|
||||
)
|
||||
throw new Error('收款人汇总与明细未完整返回或金额不一致,请重新读取。');
|
||||
@@ -129,7 +171,12 @@
|
||||
validateDailyProfits(r);
|
||||
}
|
||||
|
||||
function validateDailyFunds(data, range) {
|
||||
/**
|
||||
* @param {unknown} input
|
||||
* @param {Range} range
|
||||
*/
|
||||
function validateDailyFunds(input, range) {
|
||||
const data = /** @type {DailyFunds} */ (input);
|
||||
if (data?.team) {
|
||||
if (data.date !== range.date || data.from !== range.from || !Array.isArray(data.reimbursements))
|
||||
throw new Error('团队日期或报销资料未完整返回,请重新读取。');
|
||||
@@ -137,15 +184,15 @@
|
||||
data.reimbursements.forEach(validateReimbursement);
|
||||
return data;
|
||||
}
|
||||
const money = value => Number.isSafeInteger(value),
|
||||
nullable = value => value === null || money(value);
|
||||
const money = integer,
|
||||
nullable = (/** @type {unknown} */ value) => value === null || money(value);
|
||||
if (
|
||||
!data ||
|
||||
data.date !== range.date ||
|
||||
data.from !== range.from ||
|
||||
typeof data.readOnly !== 'boolean' ||
|
||||
typeof data.ready !== 'boolean' ||
|
||||
!['receipt', 'refund', 'net'].every(key => money(data.ownerReceipts?.[key])) ||
|
||||
!(/** @type {const} */ (['receipt', 'refund', 'net']).every(key => money(data.ownerReceipts?.[key]))) ||
|
||||
data.ownerReceipts.net !== data.ownerReceipts.receipt - data.ownerReceipts.refund ||
|
||||
!money(data.approvedReimbursements) ||
|
||||
!nullable(data.actualOutlay) ||
|
||||
@@ -169,7 +216,7 @@
|
||||
item.payer === 'owner' &&
|
||||
typeof item.name === 'string',
|
||||
) ||
|
||||
data.sources.items.reduce((sum, item) => sum + item.amount, 0) !== data.sources.total
|
||||
data.sources.items.reduce((sum, item) => sum + (item.amount ?? 0), 0) !== data.sources.total
|
||||
)
|
||||
throw new Error('转账核对资料未完整返回,请重新读取。');
|
||||
data.reimbursements.forEach(validateReimbursement);
|
||||
@@ -194,7 +241,9 @@
|
||||
return data;
|
||||
}
|
||||
|
||||
function validateDailyReimbursements(data) {
|
||||
/** @param {unknown} input */
|
||||
function validateDailyReimbursements(input) {
|
||||
const data = /** @type {ReimbursementList} */ (input);
|
||||
if (
|
||||
!data ||
|
||||
!Array.isArray(data.requests) ||
|
||||
@@ -202,13 +251,18 @@
|
||||
!Number.isSafeInteger(data.offset) ||
|
||||
!Number.isSafeInteger(data.limit) ||
|
||||
typeof data.hasMore !== 'boolean' ||
|
||||
!['pending', 'approved', 'rejected'].every(key => Number.isSafeInteger(data.counts?.[key]))
|
||||
!(
|
||||
/** @type {const} */ (['pending', 'approved', 'rejected']).every(key =>
|
||||
Number.isSafeInteger(data.counts?.[key]),
|
||||
)
|
||||
)
|
||||
)
|
||||
throw new Error('全日期报销列表未完整返回,请重新读取。');
|
||||
data.requests.forEach(validateReimbursement);
|
||||
return data;
|
||||
}
|
||||
|
||||
/** @param {Report} r */
|
||||
function validateOwnershipReceipts(r) {
|
||||
const fail = () => {
|
||||
throw new Error('所属订单净收入与账户明细未完整返回或金额不一致,请重新读取。');
|
||||
@@ -225,9 +279,10 @@
|
||||
!expected.every(key => keys.includes(key))
|
||||
)
|
||||
fail();
|
||||
const receipts = [],
|
||||
const receipts = /** @type {OwnershipReceipts[]} */ ([]),
|
||||
owned = [],
|
||||
sum = (items, kind) => items.filter(item => item.kind === kind).reduce((total, item) => total + item.amount, 0);
|
||||
sum = (/** @type {ReceiptItem[]} */ items, /** @type {string} */ kind) =>
|
||||
items.filter(item => item.kind === kind).reduce((total, item) => total + (item.amount ?? 0), 0);
|
||||
for (const key of keys) {
|
||||
const person = r.ownershipReceipts[key];
|
||||
if (
|
||||
@@ -237,7 +292,7 @@
|
||||
!person.name ||
|
||||
!Array.isArray(person.accounts) ||
|
||||
!Array.isArray(person.items) ||
|
||||
!['receipt', 'refund', 'net'].every(name => Number.isSafeInteger(person[name])) ||
|
||||
!(/** @type {const} */ (['receipt', 'refund', 'net']).every(name => Number.isSafeInteger(person[name]))) ||
|
||||
person.net !== person.receipt - person.refund
|
||||
)
|
||||
fail();
|
||||
@@ -250,10 +305,10 @@
|
||||
typeof item.account === 'string' &&
|
||||
validOrderDate(item.date),
|
||||
) ||
|
||||
!['receipt', 'refund'].every(kind => sum(person.items, kind) === person[kind])
|
||||
!(/** @type {const} */ (['receipt', 'refund']).every(kind => sum(person.items, kind) === person[kind]))
|
||||
)
|
||||
fail();
|
||||
const accounts = new Set();
|
||||
const accounts = /** @type {Set<string>} */ (new Set());
|
||||
for (const account of person.accounts) {
|
||||
if (
|
||||
!account ||
|
||||
@@ -262,7 +317,11 @@
|
||||
accounts.has(account.account) ||
|
||||
!teamMemberKeys().includes(account.recipient) ||
|
||||
!['wechat', 'alipay', 'cash', 'credit_card'].includes(account.channel) ||
|
||||
!['receipt', 'refund', 'net', 'entryCount'].every(name => Number.isSafeInteger(account[name])) ||
|
||||
!(
|
||||
/** @type {const} */ (['receipt', 'refund', 'net', 'entryCount']).every(name =>
|
||||
Number.isSafeInteger(account[name]),
|
||||
)
|
||||
) ||
|
||||
account.entryCount < 1 ||
|
||||
account.net !== account.receipt - account.refund
|
||||
)
|
||||
@@ -270,15 +329,17 @@
|
||||
const items = person.items.filter(item => item.account === account.account);
|
||||
if (
|
||||
items.length !== account.entryCount ||
|
||||
!['receipt', 'refund'].every(kind => sum(items, kind) === account[kind])
|
||||
!(/** @type {const} */ (['receipt', 'refund']).every(kind => sum(items, kind) === account[kind]))
|
||||
)
|
||||
fail();
|
||||
accounts.add(account.account);
|
||||
}
|
||||
if (
|
||||
person.items.some(item => !accounts.has(item.account)) ||
|
||||
!['receipt', 'refund', 'net'].every(
|
||||
name => person.accounts.reduce((total, account) => total + account[name], 0) === person[name],
|
||||
!(
|
||||
/** @type {const} */ (['receipt', 'refund', 'net']).every(
|
||||
name => person.accounts.reduce((total, account) => total + account[name], 0) === person[name],
|
||||
)
|
||||
)
|
||||
)
|
||||
fail();
|
||||
@@ -286,12 +347,14 @@
|
||||
owned.push(...person.items);
|
||||
}
|
||||
if (
|
||||
!['receipt', 'refund', 'net'].every(
|
||||
name => receipts.reduce((total, person) => total + person[name], 0) === r.receiptsByOrderDate[name],
|
||||
!(
|
||||
/** @type {const} */ (['receipt', 'refund', 'net']).every(
|
||||
name => receipts.reduce((total, person) => total + person[name], 0) === r.receiptsByOrderDate[name],
|
||||
)
|
||||
)
|
||||
)
|
||||
fail();
|
||||
const identity = item =>
|
||||
const identity = (/** @type {ReceiptItem} */ item) =>
|
||||
JSON.stringify([item.id, item.kind, item.amount, item.account, item.date, item.order_id, item.price_lock_id]),
|
||||
actual = teamDataKeys(r.recipientReceipts)
|
||||
.flatMap(key => r.recipientReceipts[key].items)
|
||||
@@ -301,13 +364,14 @@
|
||||
if (actual.length !== copies.length || actual.some((value, index) => value !== copies[index])) fail();
|
||||
}
|
||||
|
||||
/** @param {Report} r */
|
||||
function validateOwnershipBusiness(r) {
|
||||
const fail = () => {
|
||||
throw new Error('所属订单成本、利润或待转资料未完整返回,请重新读取。');
|
||||
},
|
||||
money = value => Number.isSafeInteger(value),
|
||||
nullable = value => value === null || money(value),
|
||||
count = value => money(value) && value >= 0,
|
||||
money = integer,
|
||||
nullable = (/** @type {unknown} */ value) => value === null || money(value),
|
||||
count = (/** @type {unknown} */ value) => money(value) && value >= 0,
|
||||
keys = teamDataKeys(r.ownershipReceipts);
|
||||
if (
|
||||
!r.ownershipBusiness ||
|
||||
@@ -328,19 +392,28 @@
|
||||
b.from !== r.from ||
|
||||
b.date !== r.date ||
|
||||
b.netReceipts !== r.ownershipReceipts[member].net ||
|
||||
!['sales', 'netReceipts', 'knownTotalCost', 'knownSelfCost', 'knownOtherCost', 'knownProfit'].every(key =>
|
||||
money(b[key]),
|
||||
!(
|
||||
/** @type {const} */ ([
|
||||
'sales',
|
||||
'netReceipts',
|
||||
'knownTotalCost',
|
||||
'knownSelfCost',
|
||||
'knownOtherCost',
|
||||
'knownProfit',
|
||||
]).every(key => money(b[key]))
|
||||
) ||
|
||||
!(/** @type {const} */ (['totalCost', 'selfCost', 'otherCost', 'profit']).every(key => nullable(b[key]))) ||
|
||||
!(
|
||||
/** @type {const} */ ([
|
||||
'missingCostCount',
|
||||
'pendingCostCount',
|
||||
'unknownProfitCount',
|
||||
'draftCount',
|
||||
'recordCount',
|
||||
'orderCount',
|
||||
'afterSaleCount',
|
||||
]).every(key => count(b[key]))
|
||||
) ||
|
||||
!['totalCost', 'selfCost', 'otherCost', 'profit'].every(key => nullable(b[key])) ||
|
||||
![
|
||||
'missingCostCount',
|
||||
'pendingCostCount',
|
||||
'unknownProfitCount',
|
||||
'draftCount',
|
||||
'recordCount',
|
||||
'orderCount',
|
||||
'afterSaleCount',
|
||||
].every(key => count(b[key])) ||
|
||||
typeof b.incomplete !== 'boolean' ||
|
||||
typeof b.hasActivity !== 'boolean'
|
||||
)
|
||||
@@ -424,7 +497,7 @@
|
||||
: settlement.dueOut !== null || settlement.dueIn !== null
|
||||
)
|
||||
fail();
|
||||
const seen = new Set();
|
||||
const seen = /** @type {Set<string>} */ (new Set());
|
||||
for (const row of settlement.counterparts) {
|
||||
if (
|
||||
!row ||
|
||||
@@ -433,8 +506,12 @@
|
||||
seen.has(row.member) ||
|
||||
typeof row.name !== 'string' ||
|
||||
!row.name ||
|
||||
!['dueOut', 'dueIn', 'offset'].every(key => count(row[key])) ||
|
||||
!['openingDue', 'periodNew', 'periodTransferred', 'closingDue'].every(key => money(row[key])) ||
|
||||
!(/** @type {const} */ (['dueOut', 'dueIn', 'offset']).every(key => count(row[key]))) ||
|
||||
!(
|
||||
/** @type {const} */ (['openingDue', 'periodNew', 'periodTransferred', 'closingDue']).every(key =>
|
||||
money(row[key]),
|
||||
)
|
||||
) ||
|
||||
row.openingDue + row.periodNew - row.periodTransferred !== row.closingDue ||
|
||||
row.dueOut !== Math.max(0, row.closingDue) ||
|
||||
row.dueIn !== Math.max(0, -row.closingDue) ||
|
||||
@@ -450,7 +527,7 @@
|
||||
}
|
||||
if (
|
||||
settlement.available &&
|
||||
['dueOut', 'dueIn'].some(
|
||||
/** @type {const} */ (['dueOut', 'dueIn']).some(
|
||||
key => settlement.counterparts.reduce((total, row) => total + row[key], 0) !== settlement[key],
|
||||
)
|
||||
)
|
||||
@@ -458,25 +535,26 @@
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {Report} r */
|
||||
function validateDailyProfits(r) {
|
||||
const fail = () => {
|
||||
throw new Error('每日利润表未完整返回或与当前对账金额不一致,请重新读取。');
|
||||
},
|
||||
table = r.dailyProfits,
|
||||
money = Number.isSafeInteger,
|
||||
count = value => money(value) && value >= 0,
|
||||
nullable = value => value === null || money(value),
|
||||
money = integer,
|
||||
count = (/** @type {unknown} */ value) => money(value) && value >= 0,
|
||||
nullable = (/** @type {unknown} */ value) => value === null || money(value),
|
||||
members = teamDataKeys(r.ownershipReceipts);
|
||||
const amounts = ['sales', 'knownTotalCost', 'knownProfit'],
|
||||
counts = [
|
||||
const amounts = /** @type {const} */ (['sales', 'knownTotalCost', 'knownProfit']),
|
||||
counts = /** @type {const} */ ([
|
||||
'recordCount',
|
||||
'orderCount',
|
||||
'afterSaleCount',
|
||||
'draftCount',
|
||||
'unknownCostCount',
|
||||
'unknownProfitCount',
|
||||
];
|
||||
const valid = row =>
|
||||
]);
|
||||
const valid = (/** @type {Profit} */ row) =>
|
||||
row &&
|
||||
amounts.every(key => money(row[key])) &&
|
||||
counts.every(key => count(row[key])) &&
|
||||
@@ -534,8 +612,9 @@
|
||||
fail();
|
||||
}
|
||||
|
||||
/** @param {Team} report */
|
||||
function validateTeamFunds(report) {
|
||||
const money = value => Number.isSafeInteger(value);
|
||||
const money = integer;
|
||||
if (
|
||||
!report ||
|
||||
!Array.isArray(report.pairs) ||
|
||||
@@ -553,7 +632,7 @@
|
||||
pair.members.length !== 2 ||
|
||||
pair.members[0] === pair.members[1] ||
|
||||
!pair.members.every(member => teamMemberKeys().includes(member)) ||
|
||||
!['net', 'obligationNet', 'transferred', 'due'].every(key => money(pair[key])) ||
|
||||
!(/** @type {const} */ (['net', 'obligationNet', 'transferred', 'due']).every(key => money(pair[key]))) ||
|
||||
pair.due < 0 ||
|
||||
Math.abs(pair.net) !== pair.due ||
|
||||
!Array.isArray(pair.entries)
|
||||
@@ -565,6 +644,7 @@
|
||||
return report;
|
||||
}
|
||||
|
||||
/** @param {Reimbursement} row */
|
||||
function validateReimbursement(row) {
|
||||
if (
|
||||
!row ||
|
||||
@@ -583,18 +663,24 @@
|
||||
item => typeof item.name === 'string' && item.name && Number.isSafeInteger(item.amount) && item.amount > 0,
|
||||
) ||
|
||||
!Number.isSafeInteger(row.total) ||
|
||||
row.items.reduce((sum, item) => sum + item.amount, 0) !== row.total
|
||||
row.items.reduce((sum, item) => sum + (item.amount ?? 0), 0) !== row.total
|
||||
)
|
||||
throw new Error('报销单未完整返回,请重新读取。');
|
||||
return row;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Report} r
|
||||
* @param {Business} b
|
||||
* @param {() => never} fail
|
||||
* @returns {RecoveryCosts}
|
||||
*/
|
||||
function reportAfterSaleRecoveryCosts(r, b, fail) {
|
||||
const money = Number.isSafeInteger,
|
||||
count = value => money(value) && value >= 0,
|
||||
const money = integer,
|
||||
count = (/** @type {unknown} */ value) => money(value) && value >= 0,
|
||||
items = [],
|
||||
byPayer = Object.fromEntries(teamMemberKeys().map(key => [key, 0]));
|
||||
const identity = item =>
|
||||
const identity = (/** @type {Pick<CostItem,'component'|'payer'|'amount'|'source'|'materialPoolId'>} */ item) =>
|
||||
JSON.stringify([item.component, item.payer, item.amount, item.source, item.materialPoolId ?? null]);
|
||||
for (const row of r.orderRows.filter(
|
||||
row => row.kind === 'orderAfterSale' && (row.member ?? (teamMode() ? null : 'assistant')) === b.member,
|
||||
@@ -620,10 +706,10 @@
|
||||
fail();
|
||||
for (const line of summary.lines) {
|
||||
if (!line || !count(line.lineIndex) || typeof line.name !== 'string') fail();
|
||||
for (const [component, key, totalKey] of [
|
||||
for (const [component, key, totalKey] of /** @type {const} */ ([
|
||||
['material', 'materialAllocations', 'materialReturnedCost'],
|
||||
['labor', 'restockedLaborAllocations', 'laborRestockedCost'],
|
||||
]) {
|
||||
])) {
|
||||
const parts = line[key];
|
||||
if (
|
||||
!Array.isArray(parts) ||
|
||||
@@ -644,7 +730,7 @@
|
||||
}
|
||||
}
|
||||
if (
|
||||
['materialReturnedCost', 'laborRestockedCost'].some(
|
||||
/** @type {const} */ (['materialReturnedCost', 'laborRestockedCost']).some(
|
||||
key => summary.lines.reduce((sum, line) => sum + line[key], 0) !== summary[key],
|
||||
)
|
||||
)
|
||||
@@ -667,7 +753,7 @@
|
||||
item.afterSaleExpense !== true ||
|
||||
item.amount < 0),
|
||||
) ||
|
||||
row.costItems.reduce((sum, item) => sum + item.amount, 0) !== row.known?.totalCost ||
|
||||
row.costItems.reduce((sum, item) => sum + (item.amount ?? 0), 0) !== row.known?.totalCost ||
|
||||
row.totalCost !== row.known.totalCost ||
|
||||
!money(original?.total) ||
|
||||
!money(summary.retainedAmount) ||
|
||||
@@ -678,7 +764,7 @@
|
||||
)
|
||||
fail();
|
||||
for (const item of recovered) {
|
||||
byPayer[item.payer] += item.amount;
|
||||
byPayer[item.payer] += item.amount ?? 0;
|
||||
items.push({
|
||||
...item,
|
||||
id: row.id,
|
||||
@@ -692,14 +778,21 @@
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Business} b
|
||||
* @param {RecoveryCosts} recoveries
|
||||
* @param {() => never} fail
|
||||
*/
|
||||
function validatePoolMaterialCosts(b, recoveries, fail) {
|
||||
const money = Number.isSafeInteger,
|
||||
count = value => money(value) && value >= 0,
|
||||
nullable = value => value === null || count(value),
|
||||
const money = integer,
|
||||
count = (/** @type {unknown} */ value) => money(value) && value >= 0,
|
||||
nullable = (/** @type {unknown} */ value) => value === null || count(value),
|
||||
pool = b.poolMaterial;
|
||||
const valid = value =>
|
||||
const valid = (
|
||||
/** @type {Pick<import('../web/src/pages/Report/contracts').PoolMaterial,'mg'|'amount'|'knownAmount'|'missingCount'|'byPayer'>} */ value,
|
||||
) =>
|
||||
value &&
|
||||
['mg', 'knownAmount', 'missingCount'].every(key => count(value[key])) &&
|
||||
/** @type {const} */ (['mg', 'knownAmount', 'missingCount']).every(key => count(value[key])) &&
|
||||
nullable(value.amount) &&
|
||||
value.amount === (value.missingCount ? null : value.knownAmount) &&
|
||||
value.byPayer &&
|
||||
@@ -725,7 +818,7 @@
|
||||
(pool.otherCosts.amount !== null && pool.otherCosts.amount !== pool.otherCosts.knownAmount)
|
||||
)
|
||||
fail();
|
||||
const seen = new Set();
|
||||
const seen = /** @type {Set<string>} */ (new Set());
|
||||
for (const day of pool.days) {
|
||||
if (
|
||||
!valid(day) ||
|
||||
@@ -769,7 +862,7 @@
|
||||
seen.add(key);
|
||||
}
|
||||
if (
|
||||
['mg', 'knownAmount', 'missingCount'].some(
|
||||
/** @type {const} */ (['mg', 'knownAmount', 'missingCount']).some(
|
||||
key => pool.days.reduce((sum, day) => sum + day[key], 0) !== pool[key],
|
||||
) ||
|
||||
teamMemberKeys().some(
|
||||
@@ -787,12 +880,19 @@
|
||||
fail();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Business} b
|
||||
* @param {RecoveryCosts} recoveries
|
||||
* @param {() => never} fail
|
||||
*/
|
||||
function validateOwnerAdvances(b, recoveries, fail) {
|
||||
const money = Number.isSafeInteger,
|
||||
count = value => money(value) && value >= 0,
|
||||
nullable = value => value === null || money(value),
|
||||
const money = integer,
|
||||
count = (/** @type {unknown} */ value) => money(value) && value >= 0,
|
||||
nullable = (/** @type {unknown} */ value) => value === null || money(value),
|
||||
advances = b.ownerAdvances;
|
||||
const identity = item =>
|
||||
const identity = (
|
||||
/** @type {{id:string; date:string; source:string; component:string; amount:number|null;poolId?:string|null;materialPoolId?:string|null}} */ item,
|
||||
) =>
|
||||
JSON.stringify([
|
||||
item.id,
|
||||
item.date,
|
||||
@@ -822,9 +922,11 @@
|
||||
!/^\d{4}-\d{2}-\d{2}$/.test(day.date) ||
|
||||
!Array.isArray(day.items) ||
|
||||
!day.items.length ||
|
||||
!['knownAmount', 'knownPoolAmount', 'knownOtherAmount'].every(key => money(day[key])) ||
|
||||
!['missingCount', 'pendingCount'].every(key => count(day[key])) ||
|
||||
!['amount', 'poolAmount', 'otherAmount'].every(key => nullable(day[key]))
|
||||
!(
|
||||
/** @type {const} */ (['knownAmount', 'knownPoolAmount', 'knownOtherAmount']).every(key => money(day[key]))
|
||||
) ||
|
||||
!(/** @type {const} */ (['missingCount', 'pendingCount']).every(key => count(day[key]))) ||
|
||||
!(/** @type {const} */ (['amount', 'poolAmount', 'otherAmount']).every(key => nullable(day[key])))
|
||||
)
|
||||
fail();
|
||||
for (const item of day.items) {
|
||||
@@ -832,8 +934,10 @@
|
||||
!item ||
|
||||
item.date !== day.date ||
|
||||
!['order', 'afterSale'].includes(item.kind) ||
|
||||
!['id', 'number', 'paperNumber', 'customer', 'name', 'source', 'component'].every(
|
||||
key => typeof item[key] === 'string',
|
||||
!(
|
||||
/** @type {const} */ (['id', 'number', 'paperNumber', 'customer', 'name', 'source', 'component']).every(
|
||||
key => typeof item[key] === 'string',
|
||||
)
|
||||
) ||
|
||||
!item.id ||
|
||||
!item.name ||
|
||||
@@ -856,13 +960,13 @@
|
||||
(item.allocationPending && (!item.poolMaterial || item.status !== 'missing')))
|
||||
)
|
||||
fail();
|
||||
if (item.amount < 0 || item.nonCash === true) {
|
||||
if ((item.amount ?? 0) < 0 || item.nonCash === true) {
|
||||
const index = remaining.indexOf(identity(item));
|
||||
if (
|
||||
item.kind !== 'order' ||
|
||||
item.status !== 'recorded' ||
|
||||
item.nonCash !== true ||
|
||||
item.amount >= 0 ||
|
||||
(item.amount ?? 0) >= 0 ||
|
||||
index < 0
|
||||
)
|
||||
fail();
|
||||
@@ -871,7 +975,7 @@
|
||||
}
|
||||
const recorded = day.items.filter(item => item.status === 'recorded'),
|
||||
missing = day.items.filter(item => item.status === 'missing'),
|
||||
total = rows => rows.reduce((sum, item) => sum + item.amount, 0),
|
||||
total = (/** @type {AdvanceItem[]} */ rows) => rows.reduce((sum, item) => sum + (item.amount ?? 0), 0),
|
||||
poolMissing = missing.some(item => item.poolMaterial),
|
||||
otherMissing = missing.some(item => !item.poolMaterial);
|
||||
if (
|
||||
@@ -891,11 +995,16 @@
|
||||
if (remaining.length || knownTotal > b.costByPayer.owner.knownTotalCost) fail();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Business} b
|
||||
* @param {OwnershipReceipts} income
|
||||
* @param {() => never} fail
|
||||
*/
|
||||
function validateCurrentAccount(b, income, fail) {
|
||||
const account = b.currentAccount,
|
||||
money = Number.isSafeInteger,
|
||||
count = value => money(value) && value >= 0,
|
||||
nullable = value => value === null || money(value);
|
||||
money = integer,
|
||||
count = (/** @type {unknown} */ value) => money(value) && value >= 0,
|
||||
nullable = (/** @type {unknown} */ value) => value === null || money(value);
|
||||
if (
|
||||
!account ||
|
||||
account.basis !== 'orderDate' ||
|
||||
@@ -905,14 +1014,14 @@
|
||||
)
|
||||
fail();
|
||||
const ownerAccounts = new Set(income.accounts.filter(row => row.recipient === 'owner').map(row => row.account)),
|
||||
received = new Map();
|
||||
received = /** @type {Map<string,number>} */ (new Map());
|
||||
for (const item of income.items) {
|
||||
const date = item.price_lock_id || item.order_after_sale ? item.date : item.order_date;
|
||||
if (!date || date < b.from || date > b.date) continue;
|
||||
if (ownerAccounts.has(item.account))
|
||||
received.set(date, (received.get(date) || 0) + (item.kind === 'receipt' ? item.amount : -item.amount));
|
||||
}
|
||||
const seen = new Set();
|
||||
const seen = /** @type {Set<string>} */ (new Set());
|
||||
let previous = '';
|
||||
for (const day of account.days) {
|
||||
if (
|
||||
@@ -921,13 +1030,23 @@
|
||||
day.date < b.from ||
|
||||
day.date > b.date ||
|
||||
day.date <= previous ||
|
||||
!['recordCount', 'missingCostCount', 'pendingCostCount', 'unknownProfitCount'].every(key =>
|
||||
count(day[key]),
|
||||
!(
|
||||
/** @type {const} */ (['recordCount', 'missingCostCount', 'pendingCostCount', 'unknownProfitCount']).every(
|
||||
key => count(day[key]),
|
||||
)
|
||||
) ||
|
||||
!['knownMaterialCost', 'knownOtherCost', 'knownProfit', 'ownerNetReceipts', 'knownAmount'].every(key =>
|
||||
money(day[key]),
|
||||
!(
|
||||
/** @type {const} */ ([
|
||||
'knownMaterialCost',
|
||||
'knownOtherCost',
|
||||
'knownProfit',
|
||||
'ownerNetReceipts',
|
||||
'knownAmount',
|
||||
]).every(key => money(day[key]))
|
||||
) ||
|
||||
!(
|
||||
/** @type {const} */ (['materialCost', 'otherCost', 'profit', 'amount']).every(key => nullable(day[key]))
|
||||
) ||
|
||||
!['materialCost', 'otherCost', 'profit', 'amount'].every(key => nullable(day[key])) ||
|
||||
typeof day.incomplete !== 'boolean'
|
||||
)
|
||||
fail();
|
||||
@@ -944,9 +1063,9 @@
|
||||
const advance = b.ownerAdvances.days.find(row => row.date === day.date),
|
||||
items = advance?.items || [],
|
||||
recorded = items.filter(item => item.status === 'recorded');
|
||||
const material = rows => rows.filter(item => item.component === 'material'),
|
||||
other = rows => rows.filter(item => item.component !== 'material'),
|
||||
sum = rows => rows.reduce((total, item) => total + item.amount, 0),
|
||||
const material = (/** @type {AdvanceItem[]} */ rows) => rows.filter(item => item.component === 'material'),
|
||||
other = (/** @type {AdvanceItem[]} */ rows) => rows.filter(item => item.component !== 'material'),
|
||||
sum = (/** @type {AdvanceItem[]} */ rows) => rows.reduce((total, item) => total + (item.amount ?? 0), 0),
|
||||
missing = items.filter(item => item.status === 'missing');
|
||||
if (
|
||||
day.knownMaterialCost !== sum(material(recorded)) ||
|
||||
@@ -969,6 +1088,7 @@
|
||||
)
|
||||
fail();
|
||||
}
|
||||
/** @param {Report} r */
|
||||
function reportActiveAccounts(r) {
|
||||
const recorded = new Set(
|
||||
teamDataKeys(r.recipientReceipts).flatMap(key => r.recipientReceipts[key].items.map(item => item.account)),
|
||||
@@ -983,6 +1103,7 @@
|
||||
);
|
||||
}
|
||||
|
||||
/** @param {Report} r */
|
||||
function reportOwnershipKeys(r) {
|
||||
const keys = teamDataKeys(r.ownershipReceipts);
|
||||
return state.user.role === 'owner' && !reportMember
|
||||
@@ -1018,5 +1139,5 @@
|
||||
reimbursementAmounts,
|
||||
};
|
||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||
else root.ReportRules = api;
|
||||
else Object.assign(root, { ReportRules: api });
|
||||
})(typeof globalThis === 'object' ? globalThis : this);
|
||||
Reference in new issue
Block a user