1848 lines
83 KiB
JavaScript
1848 lines
83 KiB
JavaScript
// @ts-check
|
||
'use strict';
|
||
/** @typedef {import('../web/src/shared/types').LedgerState} LedgerState */
|
||
/** @typedef {import('../web/src/shared/types').SessionInfo} SessionInfo */
|
||
/** @typedef {import('../web/src/shared/types').OrderForm} OrderForm */
|
||
/** @typedef {import('../web/src/shared/types').ChargeState} ChargeState */
|
||
/** @typedef {import('../web/src/shared/types').LineState} LineState */
|
||
/** @typedef {import('../web/src/shared/types').PoolState} PoolState */
|
||
/** @typedef {import('../web/src/shared/types').FeeRowState} FeeRowState */
|
||
/** @typedef {import('../web/src/shared/types').PresetState} PresetState */
|
||
/** @typedef {import('../web/src/shared/types').SyncContext} SyncContext */
|
||
/** @typedef {import('../web/src/shared/types').PaymentState} PaymentState */
|
||
/** @typedef {import('../web/src/shared/types').LedgerCalcApi} LedgerCalcApi */
|
||
/** @typedef {import('../web/src/shared/types').FormSummary} FormSummary */
|
||
/** @typedef {import('../web/src/shared/types').MaterialPools} MaterialPools */
|
||
/** @typedef {import('../web/src/shared/types').PresetCatalogItem} PresetCatalogItem */
|
||
/** @typedef {import('../web/src/shared/types').ReturnedStockLot} ReturnedStockLot */
|
||
/** @typedef {import('../web/src/shared/orderEntryTypes').Uuid} Uuid */
|
||
/** @typedef {import('../web/src/shared/orderEntryTypes').LineContext} LineContext */
|
||
/** @typedef {import('../web/src/shared/orderEntryTypes').ManualMaterial} ManualMaterial */
|
||
/** @typedef {import('../web/src/shared/orderEntryTypes').PoolChoice} PoolChoice */
|
||
/** @typedef {import('../web/src/shared/orderEntryTypes').PoolPreview} PoolPreview */
|
||
/** @typedef {import('../web/src/shared/orderEntryTypes').ChargeInput} ChargeInput */
|
||
/** @typedef {import('../web/src/shared/orderEntryTypes').FeeInput} FeeInput */
|
||
/** @typedef {import('../web/src/shared/orderEntryTypes').LineInput} LineInput */
|
||
/** @typedef {import('../web/src/shared/orderEntryTypes').EntryDraft} EntryDraft */
|
||
/** @typedef {import('../web/src/shared/orderEntryTypes').IssuedOrder} IssuedOrder */
|
||
/** @typedef {import('../web/src/shared/orderEntryTypes').FormLine} FormLine */
|
||
/** @typedef {import('../web/src/shared/orderEntryTypes').OrderInput} OrderInput */
|
||
/** @typedef {import('../web/src/shared/orderEntryTypes').EditableLine} EditableLine */
|
||
/** @typedef {import('../web/src/shared/orderEntryTypes').EditablePresetForm} EditablePresetForm */
|
||
/** @typedef {import('../web/src/pages/MaterialPools/model').Pool} Pool */
|
||
/** @typedef {import('../web/src/lib/materialQuote').QuoteEntry} QuoteEntry */
|
||
/** @typedef {import('../web/src/lib/materialQuote').QuoteRequest} QuoteRequest */
|
||
|
||
// 普通开单表单的纯数据模型:把旧界面(app.js、order-cost-presets-ui.js、material-pools-ui.js)里依附于 DOM 的
|
||
// 同步、收集与校验规则抽成不读写页面的函数,供新版界面(web/)使用。旧界面暂不加载本文件,行为不变。
|
||
// 表单状态按旧页面各输入框的取值建模(金额用元的字符串、克重用克的字符串),collectDraft 输出与旧页面
|
||
// collectDraft() 相同结构的草稿,即提交给 /api/orders/issue 的请求体。
|
||
(function (root) {
|
||
const node = typeof module === 'object' && Boolean(module.exports);
|
||
/** @type {typeof import('./calculations')} */
|
||
const Calc = node ? require('./calculations') : root.LedgerCalc;
|
||
/** @type {typeof import('./fee-estimates')} */
|
||
const Fees = node ? require('./fee-estimates') : root.FeeEstimates;
|
||
/** @type {typeof import('./credit-card-fees')} */
|
||
const Cards = node ? require('./credit-card-fees') : root.CreditCardFees;
|
||
/** @type {typeof import('./ledger-values')} */
|
||
const Values = node ? require('./ledger-values') : root.LedgerValues;
|
||
const productNames = ['足金999', '足银999', '纯银925'];
|
||
const chargeNames = ['编绳', '证书', '包装', '快递', '附加费'];
|
||
/** @type {Record<string,string>} */
|
||
const chargeSaleDefaults = { 编绳: '55', 证书: '10', 包装: '10', 快递: '8' };
|
||
/** @type {Record<string,string>} */
|
||
const feeLabels = {
|
||
shipping: '快递费',
|
||
box: '包装盒',
|
||
certificate: '证书',
|
||
braiding: '编绳',
|
||
sticker: '手机贴',
|
||
other: '其他直接费用',
|
||
};
|
||
const defaultPocketKeys = ['现货', '金料', '找金', '回收旧料', '君宝汇'];
|
||
/** @type {Record<string,string>} */
|
||
const orderCostCategories = { jd: 'shipping', yt: 'shipping', box: 'box', steel: 'braiding', silver: 'silverChain' };
|
||
/** @template T @param {T} value @returns {T} */
|
||
const clone = value => (value === undefined ? value : JSON.parse(JSON.stringify(value)));
|
||
/** @param {object} object @param {PropertyKey} key */
|
||
const own = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
|
||
|
||
// —— 金额与文字 ——
|
||
/** @param {number|null|undefined} n */
|
||
const yuan = n => (n == null ? '待补' : Values.yuan(n));
|
||
const grams = Values.grams;
|
||
/** @param {number|null|undefined} value @param {string} mode */
|
||
function orderAmount(value, mode) {
|
||
return value == null ? '待补' : '¥' + (mode === 'yuan' ? Values.yuan(value, 0) : yuan(value));
|
||
}
|
||
/** @param {ReturnType<LedgerCalcApi['orderTotal']>} total */
|
||
function orderRoundingHint(total) {
|
||
if (total.rounding_mode !== 'yuan') return '保留原单金额,精确到分。';
|
||
const adjustment = total.rounding_adjustment;
|
||
return (
|
||
'四舍五入到元' +
|
||
(adjustment
|
||
? ' · 优惠后 ¥' +
|
||
yuan(total.unroundedTotal) +
|
||
' → ' +
|
||
orderAmount(total.total, 'yuan') +
|
||
'(差额 ' +
|
||
(adjustment > 0 ? '+' : '-') +
|
||
yuan(Math.abs(adjustment)) +
|
||
'元)'
|
||
: '')
|
||
);
|
||
}
|
||
|
||
// —— 账号、成员与店铺配置(输入为 /api/state 结果,可附 session)——
|
||
const memberKeys = Values.memberKeys;
|
||
const memberEnabled = Values.memberEnabled;
|
||
/** @param {LedgerState} st */
|
||
const activeMemberKeys = st => memberKeys(st).filter(member => memberEnabled(st, member));
|
||
/** @param {LedgerState} st */
|
||
const teamMode = st => !!(st?.user?.member || st?.members?.some(member => member.member === 'assistant2'));
|
||
/** @param {LedgerState} st @param {SessionInfo|null} [session] */
|
||
const currentMember = (st, session) =>
|
||
st?.user?.member || session?.user?.member || (st?.user?.role === 'owner' ? 'owner' : 'assistant');
|
||
/** @param {LedgerState} st @param {string|null|undefined} member @param {SessionInfo|null} [session] */
|
||
function memberName(st, member, session) {
|
||
return (
|
||
st?.shopSettings?.members?.find(row => row.member === member)?.label ||
|
||
st?.members?.find(row => row.member === member)?.label ||
|
||
session?.loginOptions?.find(row => row.member === member)?.label ||
|
||
/** @type {Record<string,string>} */ ({ owner: '麦麦', assistant: '娜娜', assistant2: '小昊' })[member ?? ''] ||
|
||
'待确认'
|
||
);
|
||
}
|
||
/** @param {LedgerState} st @param {boolean} [assistantFirst] @param {{selected?:string}} [options] @returns {[string,string][]} */
|
||
function memberOptions(st, assistantFirst = false, { selected = '' } = {}) {
|
||
let keys = activeMemberKeys(st).filter(member => teamMode(st) || member !== 'assistant2');
|
||
if (assistantFirst)
|
||
keys = [...keys.filter(member => member !== 'owner'), ...keys.filter(member => member === 'owner')];
|
||
/** @type {[string,string][]} */
|
||
const options = keys.map(member => [member, memberName(st, member)]);
|
||
if (selected && memberKeys(st).includes(selected) && !keys.includes(selected))
|
||
options.push([selected, memberName(st, selected) + '(已停用 · 原记录)']);
|
||
return options;
|
||
}
|
||
/** @param {LedgerState} st @param {SessionInfo|null} [session] */
|
||
function defaultSalesperson(st, session) {
|
||
const user = st?.user || session?.user,
|
||
member = currentMember(st, session);
|
||
return (
|
||
st?.shopSettings?.members?.find(row => row.member === member)?.operatorName ||
|
||
user?.operatorName ||
|
||
st?.shopSettings?.members?.find(row => row.member === member)?.label ||
|
||
st?.members?.find(row => row.member === member)?.label ||
|
||
user?.label ||
|
||
user?.name ||
|
||
''
|
||
);
|
||
}
|
||
/** @param {LedgerState} st */
|
||
const shopFeeDefaults = st => ({
|
||
certificate: '4',
|
||
packaging: '3',
|
||
shipping: '6',
|
||
packagingPayer: 'owner',
|
||
...st?.shopSettings?.feeDefaults,
|
||
});
|
||
/** @param {LedgerState} st */
|
||
const costConfig = st => Fees.presets(st?.shopSettings?.costPresets);
|
||
/** @param {LedgerState} st */
|
||
const creditCardRate = st => st?.shopSettings?.creditCardRatePermille ?? 6;
|
||
/** @param {LedgerState} st */
|
||
const creditCardAvailable = st => !!st?.accounts?.includes('麦麦信用卡');
|
||
const memberAccountPrefix = Values.memberAccountPrefix;
|
||
/** @param {LedgerState} st @param {string} value */
|
||
const accountIdentity = (st, value) => Values.accountIdentity(memberKeys(st), value);
|
||
/** @param {LedgerState} st */
|
||
const activePocketKeys = st => (Array.isArray(st?.pockets) ? st.pockets : defaultPocketKeys);
|
||
/** @param {LedgerState} st @param {string} key */
|
||
const pocketLabel = (st, key) => st?.pocketCatalog?.find(row => row.key === key)?.name || String(key ?? '');
|
||
/** @param {LedgerState} st @param {string} key */
|
||
const pocketCountsEnabled = (st, key) =>
|
||
!!key && st?.pocketCatalog?.some(row => row.key === key && row.countUnit === 'pair') === true;
|
||
/** @param {LedgerState} st @param {string} [selected] @param {boolean} [historical] @returns {[string,string,boolean?][]} */
|
||
function pocketOptions(st, selected = '', historical = false) {
|
||
const keys = activePocketKeys(st);
|
||
/** @type {[string,string,boolean?][]} */
|
||
const options = keys.map(key => [key, pocketLabel(st, key)]);
|
||
if (selected && !keys.includes(selected))
|
||
options.push([
|
||
selected,
|
||
pocketLabel(st, selected) + (historical ? '(已停用 · 原货盘)' : '(已停用,请重新选择)'),
|
||
true,
|
||
]);
|
||
return [['', '外配/不扣黄金'], ...options];
|
||
}
|
||
/** @param {unknown} value */
|
||
function stockCountValue(value, { optional = false, title = '库存数量(对)' } = {}) {
|
||
const text = String(value ?? '').trim();
|
||
if (!text && optional) return null;
|
||
if (!/^\d+$/.test(text) || !Number.isSafeInteger(Number(text)) || Number(text) > 1000000000 || Number(text) < 1)
|
||
throw new Error(title + '请填写大于0的整数,一对填1。');
|
||
return Number(text);
|
||
}
|
||
/** @param {string} account */
|
||
const normalizeAccount = account => Cards.normalizeAccount(account);
|
||
|
||
// —— 附加项目 ——
|
||
/** @param {ChargeInput|undefined} c @param {Uuid} uuid @returns {ChargeState} */
|
||
function newCharge(c = {}, uuid) {
|
||
const type = c.nameType || (c.name && chargeNames.includes(c.name) ? c.name : c.name ? '其他' : '编绳');
|
||
// 只给新选择预填报价;旧金额、手填0和主动清空都原样保留。
|
||
const amount = own(c, 'amount') ? (c.amount ?? '') : (chargeSaleDefaults[type] ?? '');
|
||
return {
|
||
id: c.id || uuid(),
|
||
type,
|
||
customName: c.customName ?? (type === '其他' ? c.name : ''),
|
||
amount: String(amount),
|
||
prices: { ...c.chargePrices, [type]: String(amount) },
|
||
...(c.costRemoved === true ? { costRemoved: true } : {}),
|
||
};
|
||
}
|
||
/** @param {ChargeState} charge @param {string} type @returns {ChargeState} */
|
||
function changeChargeType(charge, type) {
|
||
if (type === charge.type) return charge;
|
||
const prices = { ...charge.prices, [charge.type]: charge.amount };
|
||
const amount = own(prices, type) ? prices[type] : (chargeSaleDefaults[type] ?? '');
|
||
return { ...charge, type, amount, prices: { ...prices, [type]: amount } };
|
||
}
|
||
/** @param {ChargeState} charge @param {string} amount @returns {ChargeState} */
|
||
const setChargeAmount = (charge, amount) => ({
|
||
...charge,
|
||
amount,
|
||
prices: { ...charge.prices, [charge.type]: amount },
|
||
});
|
||
/** @param {ChargeState} charge */
|
||
const chargeName = charge => (charge.type === '其他' ? charge.customName : charge.type);
|
||
/** @param {ChargeState} charge */
|
||
const collectCharge = charge => ({
|
||
id: charge.id,
|
||
nameType: charge.type,
|
||
customName: charge.customName,
|
||
name: chargeName(charge),
|
||
amount: charge.amount,
|
||
chargePrices: { ...charge.prices },
|
||
...(charge.costRemoved === true ? { costRemoved: true } : {}),
|
||
});
|
||
|
||
// —— 商品行 ——
|
||
/** @template {string|number} T
|
||
* @param {import('../web/src/shared/orderEntryTypes').LineInput<T>} line
|
||
* @returns {{mode:'gram'|'total',rate?:T|null}}
|
||
*/
|
||
function materialCostInput(line) {
|
||
if (line.costMaterial?.mode === 'gram' || line.costMaterial?.mode === 'total')
|
||
return { ...line.costMaterial, mode: line.costMaterial.mode };
|
||
const amount = line.costParts?.material,
|
||
hasTotal = amount != null && String(amount).trim() !== '';
|
||
return { mode: (line.unit || 'g') === 'g' && !hasTotal ? 'gram' : 'total' };
|
||
}
|
||
/** @param {LineInput} line @param {string} unit @returns {ManualMaterial} */
|
||
function materialPoolManualDraft(line, unit) {
|
||
const saved = line.materialPoolDraft?.manual;
|
||
if (line.costMaterial?.mode === 'pool')
|
||
return {
|
||
mode: saved?.mode || (unit === 'g' ? 'gram' : 'total'),
|
||
rate: saved?.rate ?? '',
|
||
total: saved?.total ?? '',
|
||
originalTotal: saved?.originalTotal ?? '',
|
||
payer: saved?.payer || 'owner',
|
||
};
|
||
const mode =
|
||
line.costMaterial?.mode === 'gram' || line.costMaterial?.mode === 'total'
|
||
? line.costMaterial.mode
|
||
: unit === 'g' && line.costParts?.material == null
|
||
? 'gram'
|
||
: 'total';
|
||
return {
|
||
mode: line.costMaterialDraft?.mode || mode,
|
||
rate: line.costMaterial?.rate ?? line.costMaterialDraft?.rate ?? '',
|
||
total: line.costMaterialDraft?.total ?? (mode === 'total' ? (line.costParts?.material ?? '') : ''),
|
||
originalTotal:
|
||
line.costMaterialDraft?.originalTotal ?? (mode === 'total' ? (line.costParts?.material ?? '') : ''),
|
||
payer: line.costPayers?.material ?? line.payer ?? 'owner',
|
||
};
|
||
}
|
||
/** @param {unknown} value @returns {string} */
|
||
const str = value => (value == null ? '' : String(value));
|
||
// 与旧页面 lineHTML(l, index, {materialPool:true}) 相同的初始取值。ctx: {st, member, historicalPocket, uuid}
|
||
/** @param {LineInput|undefined} input @param {LineContext} ctx @returns {LineState} */
|
||
function newLine(input = {}, ctx) {
|
||
const { st } = ctx;
|
||
let l = input;
|
||
if (!l.name && !l.quantity && !l.sale && !l.cost && !l.costParts && !l.pricingMode)
|
||
l = { ...l, cost: undefined, sale: undefined };
|
||
const nameType = l.nameType || (l.name && productNames.includes(l.name) ? l.name : l.name ? '其他' : '足金999');
|
||
const legacy = l.costParts == null && l.cost !== undefined;
|
||
const unit = l.unit || 'g';
|
||
const pocket = l.pocket ?? (nameType === '足金999' ? '现货' : '');
|
||
const formMember = ctx.member ?? currentMember(st);
|
||
/** @type {LineState} */
|
||
const line = {
|
||
legacy,
|
||
historicalPocket: !!ctx.historicalPocket,
|
||
...(l.returnedStockId ? { returnedStockId: l.returnedStockId, returnedStockCode: l.code || '' } : {}),
|
||
countOriginalPocket: ctx.historicalPocket ? l.pocket || '' : '',
|
||
countOriginalQuantity: ctx.historicalPocket ? str(l.quantity) : '',
|
||
countHistoricalUnknown: !!ctx.historicalPocket && l.stockCount == null,
|
||
nameType,
|
||
customName: str(l.customName ?? (nameType === '其他' ? l.name : '')),
|
||
pricingMode: l.pricingMode || (l.sale !== undefined ? 'manual' : 'auto'),
|
||
unit,
|
||
quantity: str(l.quantity),
|
||
goldPrice: str(l.goldPrice),
|
||
laborMode: l.laborMode || 'gram',
|
||
laborRate: str(l.laborRate),
|
||
pieces: str(l.pieces ?? '1'),
|
||
priceNote: l.priceNote || '',
|
||
baseSale: str(l.baseSale ?? l.sale),
|
||
sale: str(l.sale),
|
||
pocket,
|
||
stockCount: str(l.stockCount),
|
||
payer: legacy ? l.payer || 'owner' : (l.payer ?? 'owner'),
|
||
charges: (l.charges || []).map(c => newCharge(c, ctx.uuid)),
|
||
cost: legacy ? str(l.cost) : '',
|
||
purchase: null,
|
||
pool: null,
|
||
view: { calculation: '', materialFormula: '', laborFormula: '', materialOriginal: '', poolNote: '' },
|
||
};
|
||
if (legacy) return line;
|
||
// costFields(...),含 materialPoolFieldsSetup
|
||
let parts = l.costParts || { material: '', labor: '', accessories: '0', other: '0' };
|
||
let costMaterial = materialCostInput(l),
|
||
materialDraft = l.costMaterialDraft || {};
|
||
const fallbackPayer = teamMode(st) ? formMember : 'owner';
|
||
let payers = {
|
||
material: l.costPayers?.material ?? l.payer ?? fallbackPayer,
|
||
labor: l.costPayers?.labor ?? l.payer ?? fallbackPayer,
|
||
};
|
||
if (l.costMaterial?.mode === 'pool') {
|
||
const manual = materialPoolManualDraft(l, unit);
|
||
parts = { ...parts, material: manual.total };
|
||
costMaterial = { mode: manual.mode, rate: manual.rate };
|
||
materialDraft = {
|
||
mode: manual.mode,
|
||
rate: manual.rate,
|
||
total: manual.total,
|
||
originalTotal: manual.originalTotal,
|
||
};
|
||
payers = { ...payers, material: manual.payer };
|
||
}
|
||
const costLabor = l.costLabor || {};
|
||
const materialMode = unit === 'g' ? costMaterial.mode || 'total' : 'total';
|
||
const keys = memberKeys(st);
|
||
line.purchase = {
|
||
materialMode,
|
||
materialRate: str(costMaterial.rate ?? materialDraft.rate),
|
||
material: str(parts.material),
|
||
materialPayer: keys.includes(payers.material) ? payers.material : '',
|
||
laborMode: costLabor.mode || 'total',
|
||
laborRate: str(costLabor.rate),
|
||
labor: str(parts.labor),
|
||
laborPayer: keys.includes(payers.labor) ? payers.labor : '',
|
||
accessories: str(parts.accessories),
|
||
other: str(parts.other),
|
||
// .purchase-material 的 data-*:上一次方式、偏好方式、单位、记住的总额与原总额
|
||
dataMode: materialMode,
|
||
preferredMode: materialDraft.mode || costMaterial.mode || 'total',
|
||
dataUnit: unit,
|
||
total: str(materialDraft.total ?? (materialMode === 'total' ? (parts.material ?? '') : '')),
|
||
originalTotal: str(materialDraft.originalTotal ?? (materialMode === 'total' ? (parts.material ?? '') : '')),
|
||
...(l.costFundings ? { costFundings: clone(l.costFundings) } : {}),
|
||
};
|
||
const saved = l.materialPoolDraft || {},
|
||
poolId = l.costMaterial?.poolId || saved.poolId || '';
|
||
line.pool = {
|
||
source: l.costMaterial?.mode === 'pool' ? 'pool' : 'manual',
|
||
poolId,
|
||
dataPoolId: poolId,
|
||
dataSource: 'manual',
|
||
preferredSource: l.costMaterial?.mode === 'pool' ? 'pool' : 'manual',
|
||
defaultDate: !(saved.defaultDate === false || (poolId && !saved.defaultDate)),
|
||
manual: materialPoolManualDraft(l, unit),
|
||
allowed: true,
|
||
preview: null,
|
||
options: [],
|
||
};
|
||
return line;
|
||
}
|
||
// 旧页面 change 事件里的联动:选银饰清空货盘;改为按件即改为直接填金额并清空货盘。
|
||
/** @param {LineState} line @param {string} field @param {string} value @returns {LineState} */
|
||
function setLineField(line, field, value) {
|
||
const next = { ...line, [field]: value };
|
||
if (field === 'nameType' && ['足银999', '纯银925'].includes(value)) next.pocket = '';
|
||
if (field === 'unit' && value === '件') {
|
||
next.pricingMode = 'manual';
|
||
next.pocket = '';
|
||
}
|
||
return next;
|
||
}
|
||
/** @param {EditableLine} line @param {string} field @param {string} value @returns {LineState} */
|
||
function setPurchaseField(line, field, value) {
|
||
return { ...line, purchase: { ...line.purchase, [field]: value } };
|
||
}
|
||
/** @param {LineState&{pool:PoolState}} line @param {PoolState['source']} source @returns {LineState} */
|
||
function setPoolSource(line, source) {
|
||
return { ...line, pool: { ...line.pool, source } };
|
||
}
|
||
/** @param {EditableLine} line @returns {ManualMaterial} */
|
||
function captureManual(line) {
|
||
const p = line.purchase;
|
||
return {
|
||
mode: p.preferredMode || p.materialMode,
|
||
rate: p.materialRate,
|
||
total: p.materialMode === 'total' ? p.material : p.total,
|
||
originalTotal: p.originalTotal,
|
||
payer: p.materialPayer,
|
||
};
|
||
}
|
||
/** @param {LineState} line @returns {line is EditableLine} */
|
||
function hasPurchase(line) {
|
||
return !line.legacy;
|
||
}
|
||
/** @param {EditableLine} line */
|
||
function readPurchaseCost(line) {
|
||
const p = line.purchase,
|
||
mode = p.materialMode;
|
||
/** @type {Pick<LineInput,'costParts'|'costPayers'|'costMaterial'|'costLabor'|'materialPoolDraft'|'materialPool'|'costFundings'|'costMaterialDraft'> & {costPayers:{material:string,labor:string}}} */
|
||
const cost = {
|
||
costParts: { material: p.material, labor: p.labor, accessories: p.accessories, other: p.other },
|
||
costPayers: { material: p.materialPayer, labor: p.laborPayer },
|
||
costMaterial: { mode, ...(mode === 'gram' ? { rate: p.materialRate } : {}) },
|
||
costMaterialDraft: {
|
||
mode: p.preferredMode,
|
||
rate: p.materialRate,
|
||
total: mode === 'total' ? p.material : p.total,
|
||
originalTotal: p.originalTotal,
|
||
},
|
||
costLabor: { mode: p.laborMode, ...(p.laborMode === 'gram' ? { rate: p.laborRate } : {}) },
|
||
...(p.costFundings ? { costFundings: { labor: clone(p.costFundings.labor) } } : {}),
|
||
};
|
||
// readMaterialPoolCost
|
||
const pool = line.pool;
|
||
if (!pool) return cost;
|
||
const manual = pool.source === 'pool' || pool.dataSource === 'pool' ? pool.manual : captureManual(line);
|
||
const poolId = pool.poolId || pool.dataPoolId;
|
||
cost.materialPoolDraft = { poolId, defaultDate: pool.defaultDate, manual: { ...manual } };
|
||
if (pool.source === 'pool') {
|
||
cost.costMaterial = { mode: 'pool', poolId };
|
||
cost.costMaterialDraft = {
|
||
mode: manual.mode,
|
||
rate: manual.rate,
|
||
total: manual.total,
|
||
originalTotal: manual.originalTotal,
|
||
};
|
||
cost.costPayers.material = manual.payer;
|
||
cost.materialPool = clone(pool.preview) || { poolId, date: poolId, status: 'pending', amount: null };
|
||
}
|
||
return cost;
|
||
}
|
||
// 与旧页面 collectLine(row) 相同的结构(不含旧页面原样带出的 cost-* 输入框名,服务端不读取)。
|
||
/** @param {LineState} line @param {LedgerState} st @returns {FormLine} */
|
||
function collectLine(line, st) {
|
||
/** @type {FormLine} */
|
||
const values = {
|
||
nameType: line.nameType,
|
||
customName: line.customName,
|
||
pricingMode: line.pricingMode,
|
||
unit: line.unit,
|
||
quantity: line.quantity,
|
||
goldPrice: line.goldPrice,
|
||
laborMode: line.laborMode,
|
||
laborRate: line.laborRate,
|
||
pieces: line.pieces,
|
||
priceNote: line.priceNote,
|
||
baseSale: line.baseSale,
|
||
sale: line.sale,
|
||
pocket: line.pocket,
|
||
stockCount: line.stockCount,
|
||
payer: line.payer,
|
||
...(line.legacy ? { cost: line.cost } : {}),
|
||
charges: line.charges.map(collectCharge),
|
||
name: line.nameType === '其他' ? line.customName : line.nameType,
|
||
};
|
||
if (!pocketCountsEnabled(st, values.pocket) || values.unit !== 'g') delete values.stockCount;
|
||
else if (String(values.stockCount ?? '').trim() === '') values.stockCount = null;
|
||
if (hasPurchase(line)) Object.assign(values, readPurchaseCost(line));
|
||
if (line.returnedStockId) {
|
||
values.returnedStockId = line.returnedStockId;
|
||
values.code = line.returnedStockCode || '';
|
||
const lot = line.returnedStockLot;
|
||
if (lot) {
|
||
if (!line.pool) throw new Error('退回现货需要日购料资料,请重新读取。');
|
||
values.name = lot.name;
|
||
values.quantity = grams(lot.remainingMg);
|
||
values.unit = 'g';
|
||
values.pocket = lot.pocket;
|
||
if (pocketCountsEnabled(st, lot.pocket)) values.stockCount = lot.remainingCount ?? lot.stockCount;
|
||
else delete values.stockCount;
|
||
values.costParts = { ...values.costParts, labor: (lot.laborCost / 100).toFixed(2) };
|
||
values.costLabor = { mode: 'total' };
|
||
values.costPayers = { ...values.costPayers, labor: lot.laborPayer };
|
||
values.costMaterial = { mode: 'pool', poolId: line.pool.poolId };
|
||
delete values.costFundings;
|
||
}
|
||
}
|
||
return values;
|
||
}
|
||
|
||
// —— 日购料(旧 material-pools-ui.js 中与开单有关的部分)——
|
||
const materialPoolMg = Values.positiveMg;
|
||
/** @param {PoolChoice|Pool|null|undefined} pool */
|
||
const poolHasPersonal = pool => !!pool && own(pool, 'personalPools');
|
||
/** @param {MaterialPools|null|undefined} pools */
|
||
const rollingOf = pools => (pools?.rolling?.enabled === true ? pools.rolling : null);
|
||
/** @param {MaterialPools|null|undefined} pools */
|
||
function poolRows(pools) {
|
||
const rows = pools?.rows || [],
|
||
current = pools?.current;
|
||
return pools?.rolling?.enabled && current ? [current, ...rows.filter(pool => pool.id !== current.id)] : rows;
|
||
}
|
||
/** @param {MaterialPools} pools @param {string} orderDate @param {string} selected @param {{orderId?:string,member?:string}} [options] @returns {PoolChoice[]} */
|
||
function poolAvailableRows(pools, orderDate, selected, { orderId = '', member } = {}) {
|
||
const rows = poolRows(pools),
|
||
rolling = rollingOf(pools);
|
||
const available = rows.map(pool => {
|
||
if (!poolHasPersonal(pool))
|
||
return {
|
||
...pool,
|
||
availableMg: orderId
|
||
? Math.max(
|
||
0,
|
||
pool.totalMg -
|
||
(pool.usages || [])
|
||
.filter(usage => usage.active && usage.order_id !== orderId)
|
||
.reduce((sum, usage) => sum + usage.mg, 0),
|
||
)
|
||
: pool.remainingMg,
|
||
};
|
||
const restored = orderId
|
||
? (pool.usages || [])
|
||
.filter(usage => usage.active && usage.order_id === orderId)
|
||
.flatMap(usage => usage.materialSources || [{ kind: 'public', quantity: usage.mg }])
|
||
.filter(source => source.kind === 'public' || source.member === member)
|
||
.reduce((sum, source) => sum + source.quantity, 0)
|
||
: 0;
|
||
return {
|
||
...pool,
|
||
availableMg: pool.remainingMg + (pool.personalPools?.[member ?? '']?.remainingMg || 0) + restored,
|
||
};
|
||
});
|
||
/** @param {string} id @returns {PoolChoice} */
|
||
const blank = id => ({ id, date: id, totalMg: 0, usedMg: 0, remainingMg: 0, availableMg: 0, status: 'pending' });
|
||
if (rolling && orderDate >= rolling.cutover)
|
||
return [available.find(pool => pool.id === orderDate) || blank(orderDate)];
|
||
/** @type {Map<string,PoolChoice>} */
|
||
const byDate = new Map(
|
||
available
|
||
.filter(
|
||
pool =>
|
||
pool.date <= orderDate &&
|
||
(pool.availableMg > 0 ||
|
||
pool.id === selected ||
|
||
pool.date === orderDate ||
|
||
(orderId && pool.usages?.some(usage => usage.active && usage.order_id === orderId))),
|
||
)
|
||
.map(pool => [pool.id, pool]),
|
||
);
|
||
if (orderDate && !byDate.has(orderDate)) byDate.set(orderDate, blank(orderDate));
|
||
if (selected && selected <= orderDate && !byDate.has(selected)) byDate.set(selected, blank(selected));
|
||
return [...byDate.values()].sort((a, b) => b.date.localeCompare(a.date));
|
||
}
|
||
/** @param {PoolChoice} pool @param {boolean} unified */
|
||
function poolOptionLabel(pool, unified) {
|
||
return (
|
||
pool.date +
|
||
(unified ? ' · 统一料价' : '') +
|
||
' · ' +
|
||
(poolHasPersonal(pool)
|
||
? `可用 ${grams(pool.availableMg ?? pool.remainingMg)}g(个人回收料+公共)`
|
||
: pool.totalMg
|
||
? `余 ${grams(pool.availableMg ?? pool.remainingMg)}g`
|
||
: '待补采购') +
|
||
(pool.totalMg && pool.status === 'pending' ? ' · 待补采购' : '')
|
||
);
|
||
}
|
||
// 本单各行对日购料的取用(与 materialOrderQuoteInput 相同),用于个人回收料报价接口。
|
||
/** @param {OrderForm} form @param {SyncContext} ctx @returns {QuoteRequest} */
|
||
function poolQuoteInput(form, ctx) {
|
||
/** @type {QuoteEntry[]} */
|
||
const entries = [];
|
||
form.lines.forEach((line, lineIndex) => {
|
||
if (!line.pool) return;
|
||
const allowed = line.unit === 'g' && !Calc.isSilver(line.nameType);
|
||
if (!allowed || line.pool.source !== 'pool') return;
|
||
let poolId = line.pool.poolId || line.pool.dataPoolId;
|
||
const rolling = rollingOf(ctx.materialPools);
|
||
if ((rolling && form.date >= rolling.cutover) || line.pool.defaultDate || !poolId || poolId > form.date)
|
||
poolId = form.date;
|
||
const mg = materialPoolMg(line.quantity);
|
||
if (mg) entries.push({ lineIndex, poolId, mg });
|
||
});
|
||
return { date: form.date, member: formMember(form, ctx.st), ...(form.id ? { orderId: form.id } : {}), entries };
|
||
}
|
||
/** @param {OrderForm} form @param {number} lineIndex @param {Pool} pool @param {SyncContext} ctx @returns {PoolPreview} */
|
||
function poolPreview(form, lineIndex, pool, ctx) {
|
||
if (poolHasPersonal(pool)) {
|
||
const input = poolQuoteInput(form, ctx),
|
||
quote = ctx.quote && JSON.stringify(ctx.quote.input) === JSON.stringify(input) ? ctx.quote : null,
|
||
entry = quote?.result?.entries.find(row => row.lineIndex === lineIndex),
|
||
balance = quote?.result?.pools.find(row => row.poolId === pool.id);
|
||
return {
|
||
amount: entry?.amount ?? null,
|
||
materialSources: entry?.materialSources || [],
|
||
allocations: entry?.allocations || [],
|
||
balance,
|
||
quoteError: quote?.error || '',
|
||
quoteReady: !!quote?.result,
|
||
covered: entry?.amount != null,
|
||
wantedMg: input.entries.filter(row => row.poolId === pool.id).reduce((sum, row) => sum + row.mg, 0),
|
||
};
|
||
}
|
||
/** @type {{lineIndex:number,mg:number}[]} */
|
||
const entries = [];
|
||
form.lines.forEach((line, index) => {
|
||
if (!line.pool) return;
|
||
let selected = line.pool.poolId || line.pool.dataPoolId;
|
||
const rolling = rollingOf(ctx.materialPools);
|
||
if ((rolling && form.date >= rolling.cutover) || line.pool.defaultDate || !selected || selected > form.date)
|
||
selected = form.date;
|
||
const allowed = line.unit === 'g' && !Calc.isSilver(line.nameType);
|
||
const active =
|
||
line.pool.source === 'pool' || (allowed && line.pool.allowed === false && line.pool.preferredSource === 'pool');
|
||
if (!allowed || !active || selected !== pool.id) return;
|
||
const mg = materialPoolMg(line.quantity);
|
||
if (mg) entries.push({ lineIndex: index, mg });
|
||
});
|
||
const allUsages = poolRows(ctx.materialPools).flatMap(value => value.usages || []);
|
||
const preview = Calc.poolMaterialPreview(pool, entries, { orderId: form.id || null, allUsages });
|
||
return { ...preview, amount: preview.amounts[lineIndex] ?? null };
|
||
}
|
||
/** @param {EditableLine} line @param {OrderForm} form @param {number} lineIndex @param {SyncContext} ctx @returns {{line:EditableLine,pooled:boolean}} */
|
||
function syncPoolSelection(line, form, lineIndex, ctx) {
|
||
if (!line.pool) return { line, pooled: false };
|
||
const { st } = ctx,
|
||
pools = ctx.materialPools;
|
||
const pool = { ...line.pool },
|
||
purchase = { ...line.purchase },
|
||
view = { ...line.view };
|
||
const allowed = line.unit === 'g' && !Calc.isSilver(line.nameType);
|
||
if (!allowed && pool.source === 'pool') {
|
||
pool.preferredSource = 'pool';
|
||
pool.source = 'manual';
|
||
} else if (allowed && pool.allowed === false && pool.preferredSource === 'pool') pool.source = 'pool';
|
||
pool.allowed = allowed;
|
||
let selected = pool.poolId || pool.dataPoolId;
|
||
const rolling = rollingOf(pools),
|
||
unified = !!rolling && form.date >= rolling.cutover;
|
||
if (unified || pool.defaultDate || !selected || selected > form.date) selected = form.date;
|
||
const member = formMember(form, st);
|
||
const available = pools ? poolAvailableRows(pools, form.date, selected, { orderId: form.id || '', member }) : [];
|
||
pool.options = available.map(row => ({ value: row.id, label: poolOptionLabel(row, unified) }));
|
||
if (!pools && selected) pool.options = [{ value: selected, label: selected }];
|
||
pool.poolId = selected;
|
||
pool.dataPoolId = selected;
|
||
pool.unified = unified;
|
||
const active = pool.source === 'pool',
|
||
previous = pool.dataSource;
|
||
let next = { ...line, pool, purchase, view };
|
||
if (active && previous !== 'pool') pool.manual = captureManual(next);
|
||
if (!active && previous === 'pool') {
|
||
const manual = pool.manual;
|
||
Object.assign(purchase, {
|
||
materialMode: manual.mode,
|
||
materialRate: manual.rate,
|
||
material: manual.total,
|
||
materialPayer: manual.payer,
|
||
dataMode: manual.mode,
|
||
preferredMode: manual.mode,
|
||
total: manual.total,
|
||
originalTotal: manual.originalTotal,
|
||
dataUnit: line.unit,
|
||
});
|
||
}
|
||
pool.dataSource = pool.source;
|
||
pool.help = allowed
|
||
? unified
|
||
? '昨日余料、今日购料及退货回料合并加权;今日加料只更新今日订单。进货工费按实际填写。'
|
||
: '料价按当天加权;垫付款按购料录入顺序扣减。进货工费仍按实际填写。'
|
||
: '按件商品和银饰请手动填写料费成本。';
|
||
if (!active) {
|
||
pool.preview = null;
|
||
view.poolNote = '';
|
||
return { line: next, pooled: false };
|
||
}
|
||
const row = pools ? poolRows(pools).find(value => value.id === selected) : null,
|
||
mg = materialPoolMg(line.quantity),
|
||
personal = poolHasPersonal(row);
|
||
let preview = null,
|
||
previewError = '';
|
||
if (row)
|
||
try {
|
||
if (!personal && row.totalAmount === null) previewError = '材料成本尚未补齐,请先由店主核对历史材料记录。';
|
||
else preview = poolPreview(form, lineIndex, row, ctx);
|
||
} catch (err) {
|
||
previewError = err instanceof Error ? err.message : String(err);
|
||
}
|
||
if (personal) previewError = previewError || preview?.quoteError || '';
|
||
const wanted = preview?.wantedMg ?? 0,
|
||
used = preview?.usedMg ?? row?.usedMg ?? 0,
|
||
covered = preview?.covered === true,
|
||
amount = mg ? (preview?.amount ?? null) : null;
|
||
purchase.materialMode = 'total';
|
||
purchase.materialRate = personal || row?.averageRate == null ? '' : (row.averageRate / 100).toFixed(2);
|
||
purchase.material = amount == null ? '' : (amount / 100).toFixed(2);
|
||
/** @param {{payer:string}[]} parts */
|
||
const payerNames = parts => [...new Set(parts.map(part => memberName(st, part.payer)))].join('、');
|
||
pool.payerText = personal
|
||
? preview?.allocations?.length
|
||
? payerNames(preview.allocations)
|
||
: '按本单来源核对'
|
||
: memberKeys(st)
|
||
.filter(payer => (row?.byPayer?.[payer]?.purchased ?? 0) > 0)
|
||
.map(payer => memberName(st, payer))
|
||
.join('、') || '待补采购';
|
||
pool.personal = personal;
|
||
view.materialFormula = personal
|
||
? preview?.materialSources?.length
|
||
? preview.materialSources
|
||
.map(
|
||
source =>
|
||
`${source.kind === 'personal_recovery' ? memberName(st, source.member) + '个人回收料' : '公共料'} ${grams(source.quantity)}g · ${source.amount == null ? '料费待补' : '¥' + yuan(source.amount)}`,
|
||
)
|
||
.join(';') + ';各来源独立加权,已计分币尾差。'
|
||
: previewError || '正在按' + memberName(st, member) + '的归属核对个人回收料与公共补足。'
|
||
: amount == null
|
||
? '料费尚未确定;登记足额购料后自动补齐,销售金额保持原单。'
|
||
: `${line.quantity}g 按当天加权料价计费,本行 ${yuan(amount)}元(已分配分币尾差);垫付款按购料录入顺序扣减,保存后可查看本单归属。`;
|
||
view.materialOriginal = '';
|
||
view.poolNote = !pools
|
||
? '正在读取每日料价;可保留选择,读取完成后显示当前料费。'
|
||
: previewError
|
||
? previewError
|
||
: !row || !row.totalMg
|
||
? `${selected} 尚无可用材料。可以先开单,稍后补足购料后自动核算成本与利润。`
|
||
: !covered
|
||
? `${selected} ${unified ? '统一材料' : '已购'} ${grams(row.totalMg)}g,已用 ${grams(used)}g,本次共用 ${grams(wanted)}g;还需补采购 ${grams(Math.max(0, used + wanted - row.totalMg))}g。可先开单,料费与利润暂待补。`
|
||
: `${selected} ${unified ? '统一材料' : '已购'} ${grams(row.totalMg)}g,已用 ${grams(used)}g,余 ${grams(Math.max(0, row.totalMg - used))}g;本次共用 ${grams(wanted)}g。`;
|
||
pool.preview = {
|
||
poolId: selected,
|
||
date: selected,
|
||
status: amount == null ? 'pending' : 'preview',
|
||
amount,
|
||
quantity: mg,
|
||
averageRate: personal ? null : (row?.averageRate ?? null),
|
||
revision: preview?.balance?.revision ?? row?.revision ?? 0,
|
||
allocations: preview?.allocations || [],
|
||
...(personal ? { materialSources: preview?.materialSources || [] } : {}),
|
||
};
|
||
return { line: next, pooled: true };
|
||
}
|
||
// syncPurchaseCost:按克与总额分别记住,切换单位或方式时不把每克料价当作总额。
|
||
/** @param {EditableLine} line @param {boolean} pooled @returns {EditableLine} */
|
||
function syncPurchase(line, pooled) {
|
||
const p = { ...line.purchase },
|
||
view = { ...line.view },
|
||
unit = line.unit,
|
||
quantity = line.quantity;
|
||
const previousMode = p.dataMode,
|
||
changedUnit = p.dataUnit !== unit;
|
||
if (!pooled && previousMode === 'total') p.total = p.material;
|
||
if (!pooled && changedUnit) {
|
||
if (unit !== 'g' && previousMode === 'gram') {
|
||
p.preferredMode = 'gram';
|
||
p.materialMode = 'total';
|
||
p.material = p.total;
|
||
} else if (unit === 'g' && p.preferredMode === 'gram') p.materialMode = 'gram';
|
||
} else if (!pooled && p.materialMode !== previousMode) {
|
||
p.preferredMode = p.materialMode;
|
||
if (p.materialMode === 'total') {
|
||
if (p.total === '') p.total = p.material;
|
||
p.material = p.total;
|
||
}
|
||
}
|
||
if (unit !== 'g') p.materialMode = 'total';
|
||
p.dataMode = p.materialMode;
|
||
p.dataUnit = unit;
|
||
view.materialOriginal =
|
||
pooled || p.originalTotal === ''
|
||
? ''
|
||
: `已保留原料费合计 ${p.originalTotal}元。原金额不会当成每克料价;切换按克后请填写实际进货料价。`;
|
||
for (const [key, metaKey, modeKey, rateKey, noteKey] of /** @type {const} */ ([
|
||
['material', 'costMaterial', 'materialMode', 'materialRate', 'materialFormula'],
|
||
['labor', 'costLabor', 'laborMode', 'laborRate', 'laborFormula'],
|
||
])) {
|
||
if (key === 'material' && pooled) continue;
|
||
if (unit !== 'g' && p[modeKey] === 'gram') p[modeKey] = 'total';
|
||
if (p[modeKey] !== 'gram') {
|
||
view[noteKey] =
|
||
key === 'material'
|
||
? unit === 'g'
|
||
? '直接填写本行料费合计,不再乘以克重。'
|
||
: `按件商品请填写本行料费合计${p.materialRate !== '' ? ';每克料价已保留,切回g可恢复' : ''}。`
|
||
: '直接填写本行总工费。';
|
||
continue;
|
||
}
|
||
try {
|
||
const result = Calc.purchaseCosts({
|
||
unit,
|
||
quantity,
|
||
costParts: { material: '0', labor: '0', accessories: '0', other: '0' },
|
||
costMaterial: { mode: 'total' },
|
||
costLabor: { mode: 'total' },
|
||
[metaKey]: { mode: 'gram', rate: p[rateKey] },
|
||
}),
|
||
value = result.parts[key];
|
||
p[key] = value === null ? '' : (value / 100).toFixed(2);
|
||
view[noteKey] =
|
||
value === null
|
||
? key === 'material'
|
||
? '填写每克进货料价后,系统自动乘以本行克重。'
|
||
: '填写每克工费后自动乘以克重。'
|
||
: `${quantity}g × ${p[rateKey]}元/克 = ${yuan(value)}元`;
|
||
} catch (err) {
|
||
p[key] = '';
|
||
view[noteKey] = err instanceof Error ? err.message : String(err);
|
||
}
|
||
}
|
||
return { ...line, purchase: p, view };
|
||
}
|
||
// syncLine:计价方式联动、本行销售额、日购料与进货成本。
|
||
/** @param {LineState} line @param {OrderForm} form @param {number} lineIndex @param {SyncContext} ctx @returns {LineState} */
|
||
function syncLine(line, form, lineIndex, ctx) {
|
||
const auto = line.pricingMode === 'auto';
|
||
let next = { ...line, view: { ...line.view } };
|
||
try {
|
||
const result = Calc.sale(collectLine(line, ctx.st));
|
||
next.sale = (result.sale / 100).toFixed(2);
|
||
if (auto) next.baseSale = (result.baseSale / 100).toFixed(2);
|
||
const formula = auto
|
||
? line.laborMode === 'gram'
|
||
? `${line.quantity} ×(${line.goldPrice} + ${line.laborRate})`
|
||
: `${line.quantity} × ${line.goldPrice} + ${line.laborRate} × ${line.pieces}件`
|
||
: `基础金额 ${yuan(result.baseSale)}`;
|
||
next.view.calculation =
|
||
formula +
|
||
(result.charges.length ? ' + 附加 ' + yuan(result.chargesTotal) : '') +
|
||
' = ' +
|
||
yuan(result.sale) +
|
||
' 元';
|
||
next.view.saleCents = result.sale;
|
||
} catch (err) {
|
||
next.sale = '';
|
||
next.view.calculation = err instanceof Error ? err.message : String(err);
|
||
next.view.saleCents = null;
|
||
}
|
||
if (!hasPurchase(next)) return next;
|
||
const synced = syncPoolSelection(next, form, lineIndex, ctx);
|
||
const updated = syncPurchase(synced.line, synced.pooled);
|
||
try {
|
||
updated.view.purchase = Calc.purchaseCosts({
|
||
...readPurchaseCost(updated),
|
||
unit: updated.unit,
|
||
quantity: updated.quantity,
|
||
});
|
||
} catch {
|
||
updated.view.purchase = null;
|
||
}
|
||
return updated;
|
||
}
|
||
// 字段显隐(旧页面 syncLine 的 show()):返回本行当前应显示的输入项。
|
||
/** @param {LineState} line @param {LedgerState} st */
|
||
function lineVisibility(line, st) {
|
||
const auto = line.pricingMode === 'auto';
|
||
const historicalUnknown =
|
||
line.countHistoricalUnknown &&
|
||
line.countOriginalPocket === line.pocket &&
|
||
Number(line.countOriginalQuantity) === Number(line.quantity);
|
||
/** @param {string|undefined} mode */
|
||
const gram = mode => line.unit === 'g' && mode === 'gram';
|
||
const pooled = line.pool?.source === 'pool';
|
||
return {
|
||
customName: line.nameType === '其他',
|
||
goldPrice: auto,
|
||
laborMode: auto,
|
||
laborRate: auto,
|
||
pieces: auto && line.laborMode === 'piece',
|
||
priceNote: !auto,
|
||
baseSale: !auto,
|
||
stockCount: line.unit === 'g' && pocketCountsEnabled(st, line.pocket),
|
||
stockCountOptional: historicalUnknown,
|
||
materialRate: pooled ? !line.pool?.personal : gram(line.purchase?.materialMode),
|
||
materialMode: !pooled,
|
||
materialPayer: !pooled,
|
||
materialReadOnly: pooled || gram(line.purchase?.materialMode),
|
||
laborRateInput: gram(line.purchase?.laborMode),
|
||
laborReadOnly: gram(line.purchase?.laborMode),
|
||
poolAllowed: line.unit === 'g' && !Calc.isSilver(line.nameType),
|
||
extraCosts: !(
|
||
/** @type {const} */ (['accessories', 'other']).every(
|
||
key =>
|
||
/^\d+(?:\.\d{1,2})?$/.test(String(line.purchase?.[key] ?? '').trim()) && Number(line.purchase?.[key]) === 0,
|
||
)
|
||
),
|
||
};
|
||
}
|
||
|
||
// —— 实际费用行 ——
|
||
/** @param {FeeInput} item @param {LedgerState} st @param {string} defaultPayer @returns {FeeRowState} */
|
||
function feeRow(item, st, defaultPayer) {
|
||
const automatic = Cards.isFee(item);
|
||
return {
|
||
key: item.key,
|
||
note: item.note,
|
||
amount: str(item.amount),
|
||
payer: item.payer || (automatic ? 'owner' : defaultPayer),
|
||
sourceName: item.sourceName || '',
|
||
edited: !!item.edited,
|
||
status: item.status || 'legacy',
|
||
...(item.expense_id ? { expense_id: item.expense_id } : {}),
|
||
...(item.date ? { date: item.date } : {}),
|
||
...(item.lineNumber ? { lineNumber: item.lineNumber } : {}),
|
||
...(item.funding ? { funding: clone(item.funding) } : {}),
|
||
...(automatic ? { automatic: clone(item) } : {}),
|
||
};
|
||
}
|
||
/** @param {FeeRowState} row @returns {FeeInput} */
|
||
function readFeeRow(row) {
|
||
if (row.automatic)
|
||
return { ...clone(row.automatic), ...(row.date ? { date: row.date } : {}), amount: row.amount, payer: row.payer };
|
||
return {
|
||
key: row.key,
|
||
sourceName: row.sourceName || undefined,
|
||
edited: row.edited === true,
|
||
...(row.expense_id ? { expense_id: row.expense_id } : {}),
|
||
...(row.date ? { date: row.date } : {}),
|
||
...(row.status === 'estimated' ? { status: 'estimated' } : {}),
|
||
note: row.note,
|
||
amount: row.amount,
|
||
payer: row.payer,
|
||
...(row.funding ? { funding: clone(row.funding) } : {}),
|
||
};
|
||
}
|
||
/** @param {FeeRowState} row */
|
||
const feeSourceText = row =>
|
||
row.automatic
|
||
? '已记录的信用卡收款手续费'
|
||
: row.key.startsWith('charge:')
|
||
? // 附加项目改成快递/包装等勾选类目后,旧页面保留原成本行(无商品序号)。
|
||
row.lineNumber
|
||
? '商品 ' + row.lineNumber + ' 的附加项目'
|
||
: '附加项目已改类,原成本行保留'
|
||
: '整单费用';
|
||
/** @param {OrderForm} form @param {FormLine[]} collectedLines @param {SyncContext} ctx @returns {FeeRowState[]} */
|
||
function syncFeeRows(form, collectedLines, ctx) {
|
||
const existing = form.feeRows.map(readFeeRow);
|
||
const next = [
|
||
...Fees.sync(
|
||
existing.filter(item => !Cards.isFee(item)),
|
||
collectedLines,
|
||
{
|
||
defaultPayer: teamMode(ctx.st) ? formMember(form, ctx.st) : 'assistant',
|
||
shopDefaults: shopFeeDefaults(ctx.st),
|
||
checkboxCosts: !!form.presets || form.feeCostMode === 'checkboxes',
|
||
},
|
||
),
|
||
...existing.filter(item => Cards.isFee(item)),
|
||
];
|
||
const sameKeys = existing.map(r => r.key).join('|') === next.map(r => r.key).join('|');
|
||
return next.map((item, i) => {
|
||
if (!sameKeys) return feeRow(item, ctx.st, teamDefaultPayer(form, ctx.st));
|
||
// 键序不变时就地更新名称、来源、金额与付款人;已改标记与状态沿用原行。
|
||
const row = form.feeRows[i];
|
||
return {
|
||
...row,
|
||
sourceName: item.sourceName || '',
|
||
note: item.note,
|
||
amount: str(item.amount),
|
||
payer: item.payer,
|
||
...(item.lineNumber ? { lineNumber: item.lineNumber } : {}),
|
||
};
|
||
});
|
||
}
|
||
/** @param {Pick<OrderForm,'member'>} form @param {LedgerState} st */
|
||
const teamDefaultPayer = (form, st) => (teamMode(st) ? formMember(form, st) : 'assistant');
|
||
/** @param {OrderForm} form @param {number} index @param {string} field @param {string} value @returns {OrderForm} */
|
||
function editFeeRow(form, index, field, value) {
|
||
const rows = form.feeRows.map((row, i) => (i === index ? { ...row, [field]: value, edited: true } : row));
|
||
return { ...form, feeRows: rows };
|
||
}
|
||
/** @param {OrderForm} form @param {LedgerState} st @param {Uuid} uuid @returns {OrderForm} */
|
||
function addManualFee(form, st, uuid) {
|
||
return {
|
||
...form,
|
||
feeRows: [
|
||
...form.feeRows,
|
||
feeRow(
|
||
{
|
||
key: 'manual:' + uuid(),
|
||
note: '其他费用',
|
||
amount: '',
|
||
payer: teamDefaultPayer(form, st),
|
||
status: 'estimated',
|
||
edited: true,
|
||
},
|
||
st,
|
||
teamDefaultPayer(form, st),
|
||
),
|
||
],
|
||
};
|
||
}
|
||
// removeFeeRow:移除附加项目对应的费用时标记该附加项目“内部成本已移除”,否则下次同步会重新生成。
|
||
/** @param {OrderForm} form @param {number} index @returns {OrderForm} */
|
||
function removeFeeRow(form, index) {
|
||
const row = form.feeRows[index];
|
||
if (!row || row.automatic) return form;
|
||
const key = row.key;
|
||
const lines = form.lines.map(line => ({
|
||
...line,
|
||
charges: line.charges.map(charge =>
|
||
key === 'charge:' + charge.id ||
|
||
(key === 'shipping' && Fees.normalize(String.prototype.trim.call(chargeName(charge))) === '快递')
|
||
? { ...charge, costRemoved: true }
|
||
: charge,
|
||
),
|
||
}));
|
||
return { ...form, lines, feeRows: form.feeRows.filter((_, i) => i !== index) };
|
||
}
|
||
/** @param {OrderForm} form @param {number} lineIndex @param {number} chargeIndex @returns {OrderForm} */
|
||
function restoreChargeCost(form, lineIndex, chargeIndex) {
|
||
const lines = form.lines.map((line, i) =>
|
||
i !== lineIndex
|
||
? line
|
||
: {
|
||
...line,
|
||
charges: line.charges.map((charge, j) => {
|
||
if (j !== chargeIndex) return charge;
|
||
const rest = { ...charge };
|
||
delete rest.costRemoved;
|
||
return rest;
|
||
}),
|
||
},
|
||
);
|
||
return { ...form, lines };
|
||
}
|
||
|
||
// —— 常用成本勾选(order-cost-presets-ui.js,新开单 editing=false)——
|
||
/** @param {FeeInput} item */
|
||
function orderCostFeeCategory(item) {
|
||
if (item.key === 'shipping' || item.key === 'box') return item.key;
|
||
if (String(item.note || '').trim() === '编绳') return '';
|
||
return Fees.checkboxCategory(item.note) || Fees.checkboxCategory(item.sourceName);
|
||
}
|
||
/** @param {LedgerState} st @param {FeeInput[]} [items] @param {boolean} [recorded] @returns {PresetState} */
|
||
function newPresets(st, items = [], recorded = false) {
|
||
const config = costConfig(st);
|
||
if (Fees.customPresets(config)) {
|
||
const catalog = Fees.presetCatalog(config),
|
||
selected = new Map(
|
||
items
|
||
.map(item => /** @type {const} */ ([Fees.presetKind(item, { presets: catalog, recorded }), item]))
|
||
.filter(([kind]) => kind),
|
||
);
|
||
/** @type {Record<string,boolean>} */
|
||
const checked = {};
|
||
/** @type {Record<string,string>} */
|
||
const quantity = {};
|
||
for (const [kind, row] of Object.entries(catalog)) {
|
||
checked[kind] = selected.has(kind);
|
||
if (row.byQuantity) quantity[kind] = selected.get(kind)?.note.match(/(([^)]*)个 ×/)?.[1] || '1';
|
||
}
|
||
return { configured: true, checked, quantity };
|
||
}
|
||
const selected = new Map(
|
||
items
|
||
.map(item => /** @type {const} */ ([Fees.presetKind(item, { presets: config, recorded }), item]))
|
||
.filter(([kind]) => kind),
|
||
);
|
||
const box = selected.get('box');
|
||
return {
|
||
configured: false,
|
||
checked: {
|
||
jd: selected.has('jd'),
|
||
yt: selected.has('yt'),
|
||
box: !!box,
|
||
steel: selected.has('steel'),
|
||
silver: selected.has('silver'),
|
||
},
|
||
// presetKind 仅在盒子备注含这个数量格式时返回 box。
|
||
quantity: { box: box ? /** @type {RegExpMatchArray} */ (box.note.match(/(([^)]*)个 ×/))[1] : '1' },
|
||
};
|
||
}
|
||
/** @param {PresetState} presets @param {string} kind */
|
||
const presetCategory = (presets, kind) => orderCostCategories[kind] || kind;
|
||
/** @param {FeeInput} item @param {LedgerState} st */
|
||
function configuredItemCategory(item, st) {
|
||
if (String(item.key).startsWith('manual:')) {
|
||
const kind = 'custom_' + item.key.slice(7);
|
||
if (costConfig(st)[kind]) return kind;
|
||
}
|
||
return orderCostFeeCategory(item);
|
||
}
|
||
// 勾选后替换下方同类旧费用;与该成本同键的其他旧行改为独立键,避免重复。
|
||
/** @param {EditablePresetForm} form @param {string} kind @param {boolean} checked @param {LedgerState} st @param {Uuid} uuid @returns {OrderForm} */
|
||
function togglePreset(form, kind, checked, st, uuid) {
|
||
const presets = { ...form.presets, checked: { ...form.presets.checked, [kind]: checked } };
|
||
const category = presetCategory(presets, kind);
|
||
if (presets.originals) {
|
||
presets.originals = { ...presets.originals };
|
||
for (const key of Object.keys(presets.originals))
|
||
if (presetCategory(presets, key) === category) delete presets.originals[key];
|
||
}
|
||
if (checked && category === 'shipping')
|
||
for (const other of ['jd', 'yt'])
|
||
if (other !== kind && own(presets.checked, other)) presets.checked[other] = false;
|
||
let feeRows = form.feeRows;
|
||
if (checked) {
|
||
const feeKey = presets.configured ? Fees.presetKey(kind) : category === 'silverChain' ? 'other' : category;
|
||
/** @param {FeeInput} item */
|
||
const categoryOf = item => (presets.configured ? configuredItemCategory(item, st) : orderCostFeeCategory(item));
|
||
feeRows = feeRows
|
||
.filter(row => row.automatic || row.funding || categoryOf(readFeeRow(row)) !== category)
|
||
.map(row => (!row.automatic && row.key === feeKey ? { ...row, key: 'manual:' + uuid() } : row));
|
||
}
|
||
return { ...form, presets, feeRows };
|
||
}
|
||
/** @param {EditablePresetForm} form @param {string} kind @param {string} value @returns {OrderForm} */
|
||
function setPresetQuantity(form, kind, value) {
|
||
const presets = { ...form.presets, quantity: { ...form.presets.quantity, [kind]: value } };
|
||
if (presets.originals) {
|
||
presets.originals = { ...presets.originals };
|
||
delete presets.originals[kind];
|
||
}
|
||
return { ...form, presets };
|
||
}
|
||
/** @param {Pick<OrderForm,'presets'|'member'>} form @param {LedgerState} st @returns {{items:FeeInput[],notes:Record<string,string>}} */
|
||
function readPresets(form, st) {
|
||
const presets = form.presets;
|
||
if (!presets) return { items: [], notes: {} };
|
||
const member = formMember(form, st);
|
||
/** @type {Record<string,string>} */
|
||
const notes = {};
|
||
if (presets.configured) {
|
||
const config = Fees.presetCatalog(costConfig(st)),
|
||
items = [];
|
||
for (const [kind, row] of Object.entries(config)) {
|
||
if (!row.enabled || !presets.checked[kind]) {
|
||
notes[kind] = '勾选后计费';
|
||
continue;
|
||
}
|
||
const quantity = presets.quantity[kind] ?? '1';
|
||
try {
|
||
const item = Fees.presetFee(kind, quantity, member, config);
|
||
notes[kind] = `${quantity}个 × ${row.amount}元 = ${item.amount}元`;
|
||
items.push(item);
|
||
} catch (error) {
|
||
notes[kind] = error instanceof Error ? error.message : String(error);
|
||
items.push({
|
||
key: Fees.presetKey(kind),
|
||
note: row.name,
|
||
amount: '',
|
||
payer: row.payer === 'order' ? member : row.payer,
|
||
status: 'estimated',
|
||
edited: true,
|
||
});
|
||
}
|
||
}
|
||
return { items, notes };
|
||
}
|
||
const config = costConfig(st),
|
||
quantity = presets.quantity.box;
|
||
const selection = {
|
||
shipping: presets.checked.jd ? 'jd' : presets.checked.yt ? 'yt' : '',
|
||
box: presets.checked.box,
|
||
quantity,
|
||
steel: presets.checked.steel,
|
||
silver: presets.checked.silver,
|
||
};
|
||
let items;
|
||
try {
|
||
items = Fees.checkboxFees(selection, member, config);
|
||
const boxItem = items.find(item => item.key === 'box');
|
||
notes.box =
|
||
selection.box && boxItem
|
||
? Fees.boxCount(quantity) + '个 × ' + config.box.amount + '元 = ' + boxItem.amount + '元'
|
||
: '勾选后计费';
|
||
} catch {
|
||
items = Fees.checkboxFees({ ...selection, box: false }, member, config);
|
||
items.push({
|
||
key: 'box',
|
||
note: `盒子(${quantity}个 × ${config.box.amount}元/个)`,
|
||
amount: '',
|
||
payer: config.box.payer === 'order' ? member : config.box.payer,
|
||
status: 'estimated',
|
||
edited: true,
|
||
});
|
||
notes.box = '请填写正整数数量';
|
||
}
|
||
const shipping = items.find(item => item.note === '圆通快递');
|
||
notes.ytPayer =
|
||
memberName(st, shipping?.payer || (config.yt.payer === 'order' ? member : config.yt.payer)) +
|
||
'付款' +
|
||
(config.yt.payer === 'order' ? '(订单归属人)' : '');
|
||
return { items, notes };
|
||
}
|
||
// 勾选项展示用目录(名称、单价、付款人)。
|
||
/** @param {OrderForm} form @param {LedgerState} st @returns {PresetCatalogItem[]} */
|
||
function presetCatalogView(form, st) {
|
||
if (!form.presets) return [];
|
||
const member = formMember(form, st);
|
||
if (form.presets.configured)
|
||
return Object.entries(Fees.presetCatalog(costConfig(st)))
|
||
.filter(([, row]) => row.enabled)
|
||
.map(([kind, row]) => ({
|
||
kind,
|
||
name: row.name,
|
||
price: row.amount + '元' + (row.byQuantity ? '/个' : ''),
|
||
payer: (row.payer === 'order' ? '订单归属人' : memberName(st, row.payer)) + '付款',
|
||
byQuantity: !!row.byQuantity,
|
||
shipping: kind === 'jd' || kind === 'yt',
|
||
}));
|
||
const config = costConfig(st);
|
||
/** @param {string} kind */
|
||
const payerText = kind =>
|
||
config[kind].payer === 'order'
|
||
? memberName(st, member) + '付款(订单归属人)'
|
||
: memberName(st, config[kind].payer) + '付款';
|
||
return [
|
||
{ kind: 'jd', name: '京东快递', price: config.jd.amount + '元', payer: payerText('jd'), shipping: true },
|
||
{ kind: 'yt', name: '圆通快递', price: config.yt.amount + '元', payer: payerText('yt'), shipping: true },
|
||
{ kind: 'box', name: '盒子', price: config.box.amount + '元/个', payer: payerText('box'), byQuantity: true },
|
||
{ kind: 'steel', name: '钢绳(店里)', price: config.steel.amount + '元', payer: payerText('steel') },
|
||
{ kind: 'silver', name: '银链(家里)', price: config.silver.amount + '元', payer: payerText('silver') },
|
||
];
|
||
}
|
||
|
||
// —— 收款方式与收款人 ——
|
||
/** @param {Pick<OrderForm,'member'>} form @param {LedgerState} st */
|
||
function formMember(form, st) {
|
||
return form.member || currentMember(st);
|
||
}
|
||
/** @param {Pick<OrderForm,'member'>} form @param {LedgerState} st */
|
||
function defaultRecipient(form, st) {
|
||
const member = teamMode(st) ? formMember(form, st) : 'assistant';
|
||
return memberAccountPrefix(memberEnabled(st, member) ? member : 'owner');
|
||
}
|
||
/** @param {LedgerState} st */
|
||
function paymentMethods(st) {
|
||
return ['微信', '支付宝', '现金', ...(creditCardAvailable(st) ? ['信用卡'] : [])];
|
||
}
|
||
/** @param {LedgerState} st @param {Pick<PaymentState,'recipient'|'method'>} payment @returns {[string,string][]} */
|
||
function recipientOptions(st, payment) {
|
||
/** @type {[string,string][]} */
|
||
const options = memberOptions(st, !teamMode(st)).map(([member, name]) => [memberAccountPrefix(member), name]);
|
||
const identity = accountIdentity(st, payment.recipient + payment.method);
|
||
if (identity && !memberEnabled(st, identity.member) && !options.some(([value]) => value === payment.recipient))
|
||
options.push([payment.recipient, memberName(st, identity.member) + '(已停用 · 原记录)']);
|
||
return options;
|
||
}
|
||
/** @param {string|undefined} account @param {Pick<OrderForm,'member'>} form @param {LedgerState} st @returns {PaymentState} */
|
||
function newPayment(account, form, st) {
|
||
account = normalizeAccount(account || defaultRecipient(form, st) + '微信');
|
||
const card = Cards.isAccount(account),
|
||
identity = accountIdentity(st, account),
|
||
prefix = identity ? memberAccountPrefix(identity.member) : defaultRecipient(form, st);
|
||
return {
|
||
method: identity?.channel || '微信',
|
||
recipient: card ? '麦麦' : prefix,
|
||
nonCardRecipient: card ? defaultRecipient(form, st) : prefix,
|
||
cardLocked: card,
|
||
};
|
||
}
|
||
// syncPaymentRecipient:信用卡统一由店主收款,切回其他方式时恢复原收款人。
|
||
/** @param {OrderForm} form @param {LedgerState} st @returns {OrderForm} */
|
||
function syncPayment(form, st) {
|
||
const p = { ...form.payment };
|
||
if (p.method === '信用卡') {
|
||
if (!p.cardLocked) p.nonCardRecipient = p.recipient || defaultRecipient(form, st);
|
||
p.recipient = '麦麦';
|
||
p.cardLocked = true;
|
||
} else {
|
||
if (p.cardLocked) p.recipient = p.nonCardRecipient || defaultRecipient(form, st);
|
||
p.cardLocked = false;
|
||
p.nonCardRecipient = p.recipient;
|
||
}
|
||
return { ...form, payment: p };
|
||
}
|
||
/** @param {OrderForm} form */
|
||
const readPaymentAccount = form => normalizeAccount((form.payment.recipient || '') + (form.payment.method || ''));
|
||
// 店主改订单归属:收款人跟随(信用卡除外),未改过的费用付款人跟随(包装除外)。
|
||
/** @param {OrderForm} form @param {string} member @param {LedgerState} st @returns {OrderForm} */
|
||
function changeMember(form, member, st) {
|
||
if (!teamMode(st)) return { ...form, member };
|
||
const prefix = memberAccountPrefix(member);
|
||
const payment = { ...form.payment, nonCardRecipient: prefix };
|
||
if (payment.method !== '信用卡') payment.recipient = prefix;
|
||
const feeRows = form.feeRows.map(row =>
|
||
!row.edited && Fees.normalize(row.note) !== '包装' ? { ...row, payer: member } : row,
|
||
);
|
||
return { ...form, member, payment, feeRows };
|
||
}
|
||
|
||
// —— 整张表单 ——
|
||
/** @param {EntryDraft} draft */
|
||
function draftRoundingMode(draft) {
|
||
return draft.id ? draft.rounding_mode || 'cent' : 'yuan';
|
||
}
|
||
// renderCreate 中的“空白草稿”判断:空白时日期与费用日期回到今天。
|
||
/** @param {EntryDraft} draft */
|
||
function isBlankDraft(draft) {
|
||
return (
|
||
!draft.id &&
|
||
!draft.customer &&
|
||
!draft.note &&
|
||
!draft.internal_note &&
|
||
!Number(draft.discount) &&
|
||
!draft.fee_items?.some(r => Number(r.amount) && (r.edited || r.status !== 'estimated' || r.key !== 'shipping')) &&
|
||
(draft.lines || []).every(
|
||
l =>
|
||
!l.charges?.some(c => Number(c.amount)) &&
|
||
!l.quantity &&
|
||
!l.stockCount &&
|
||
!l.sale &&
|
||
!l.goldPrice &&
|
||
!l.laborRate &&
|
||
!l.cost &&
|
||
!Object.values(l.costParts || {}).some(Number),
|
||
)
|
||
);
|
||
}
|
||
// ctx: {st, session, uuid};draft 为旧页面草稿结构(本地暂存、模板套用或 draftInputs(旧草稿订单))。
|
||
/** @param {SyncContext} ctx @param {EntryDraft|null} [input] @returns {OrderForm} */
|
||
function newForm(ctx, input) {
|
||
const { st, session, uuid } = ctx;
|
||
const source = input || { date: st.today, lines: [{}] };
|
||
let draft = { ...source, rounding_mode: draftRoundingMode(source) };
|
||
if (isBlankDraft(draft)) draft = { ...draft, date: st.today, fees_date: st.today };
|
||
const recorded = !!ctx.editing;
|
||
const presetsEnabled = !draft.id || recorded;
|
||
const member = teamMode(st)
|
||
? memberKeys(st).includes(draft.member || currentMember(st, session))
|
||
? draft.member || currentMember(st, session)
|
||
: currentMember(st, session)
|
||
: '';
|
||
const items = (draft.fee_items || []).map(f => ({
|
||
...f,
|
||
note: f.note || feeLabels[f.key],
|
||
edited: f.edited ?? true,
|
||
}));
|
||
/** @type {OrderForm} */
|
||
const form = {
|
||
payment: newPayment(draft.payment_account, { member }, st),
|
||
copy_kind: draft.copy_kind || '',
|
||
id: draft.id || '',
|
||
revision: draft.revision || '',
|
||
paper_date: draft.paper_date || '',
|
||
paper_number: draft.paper_number || '',
|
||
rounding_mode: draft.rounding_mode,
|
||
memberLocked: !!draft.id || st?.user?.role !== 'owner',
|
||
member,
|
||
date: draft.date || st.today,
|
||
customer: draft.customer || '',
|
||
customer_type: draft.customer_type === 'new' || draft.customer_type === 'returning' ? draft.customer_type : '',
|
||
customerTypeRequired: !draft.id,
|
||
original_customer_type: draft.customer_type,
|
||
salesperson:
|
||
draft.salesperson || (draft.id ? session?.user?.name || st?.user?.name || '' : defaultSalesperson(st, session)),
|
||
credit_card_fee_payer: draft.credit_card_fee_payer || 'owner',
|
||
fees_date: draft.fees_date || draft.date || st.today,
|
||
feeCostMode: presetsEnabled ? 'checkboxes' : draft.fee_cost_mode || 'legacy',
|
||
discount: draft.discount || '0',
|
||
note: draft.note || '',
|
||
internal_note: draft.internal_note || '',
|
||
presets: null,
|
||
feeRows: [],
|
||
lines: [],
|
||
};
|
||
const config = costConfig(st);
|
||
const rows = presetsEnabled ? items.filter(item => !Fees.presetKind(item, { presets: config, recorded })) : items;
|
||
form.presets = presetsEnabled ? newPresets(st, items, recorded) : null;
|
||
if (recorded && form.presets) {
|
||
form.editing = true;
|
||
form.presets.originals = Object.fromEntries(
|
||
items
|
||
.map(item => /** @type {const} */ ([Fees.presetKind(item, { presets: config, recorded }), item]))
|
||
.filter(([kind]) => kind),
|
||
);
|
||
}
|
||
form.feeRows = rows.map(item => feeRow(item, st, teamDefaultPayer(form, st)));
|
||
form.lines = (draft.lines?.length ? draft.lines : [{}]).map(l =>
|
||
newLine(l, { st, member: form.member || currentMember(st, session), historicalPocket: !!draft.id, uuid }),
|
||
);
|
||
return form;
|
||
}
|
||
/** @param {OrderForm} form @param {SyncContext} ctx @returns {OrderForm} */
|
||
function addLine(form, ctx) {
|
||
if (form.lines.length >= 60) throw new Error('每单需要1~60行商品');
|
||
return {
|
||
...form,
|
||
lines: [...form.lines, newLine({}, { st: ctx.st, member: formMember(form, ctx.st), uuid: ctx.uuid })],
|
||
};
|
||
}
|
||
/** @param {OrderForm} form @param {number} index @returns {OrderForm} */
|
||
function removeLine(form, index) {
|
||
if (form.lines.length <= 1) throw new Error('请至少保留一行商品');
|
||
return { ...form, lines: form.lines.filter((_, i) => i !== index) };
|
||
}
|
||
/** @param {OrderForm} form @param {number} lineIndex @param {Uuid} uuid @returns {OrderForm} */
|
||
function addCharge(form, lineIndex, uuid) {
|
||
const line = form.lines[lineIndex];
|
||
if (line.charges.length >= 100) throw new Error('每行最多填写100项附加项目');
|
||
return updateLine(form, lineIndex, { ...line, charges: [...line.charges, newCharge({}, uuid)] });
|
||
}
|
||
/** @param {OrderForm} form @param {number} index @param {LineState} line @returns {OrderForm} */
|
||
function updateLine(form, index, line) {
|
||
return { ...form, lines: form.lines.map((value, i) => (i === index ? line : value)) };
|
||
}
|
||
/** @param {OrderForm} form @param {LedgerState} st */
|
||
function collectDraft(form, st) {
|
||
return {
|
||
...(form.copy_kind ? { copy_kind: form.copy_kind } : {}),
|
||
id: form.id || undefined,
|
||
revision: Number(form.revision) || undefined,
|
||
paper_date: form.paper_date || '',
|
||
rounding_mode: form.rounding_mode,
|
||
...(teamMode(st) ? { member: form.member || currentMember(st) } : {}),
|
||
date: form.date,
|
||
customer: form.customer,
|
||
customer_type: form.customer_type || form.original_customer_type || 'unknown',
|
||
salesperson: form.salesperson,
|
||
paper_number: form.paper_number || '',
|
||
payment_account: readPaymentAccount(form),
|
||
credit_card_fee_payer: form.credit_card_fee_payer || 'owner',
|
||
fees_date: form.fees_date,
|
||
fee_auto_initialized: true,
|
||
fee_cost_mode: form.feeCostMode || (!form.id ? 'checkboxes' : 'legacy'),
|
||
fee_items: [
|
||
...form.feeRows.map(readFeeRow),
|
||
...readPresets(form, st).items.map(
|
||
item => form.presets?.originals?.[Fees.presetKind(item, { presets: costConfig(st) })] || item,
|
||
),
|
||
].filter(item => form.editing || !Cards.isFee(item)),
|
||
discount: form.discount,
|
||
note: form.note,
|
||
internal_note: form.internal_note,
|
||
lines: form.lines.map(line => collectLine(line, st)),
|
||
};
|
||
}
|
||
// updateTotal:同步全部商品行、附加项目费用行,计算成交合计与信用卡手续费预览。
|
||
// ctx: {st, materialPools, quote}
|
||
/** @param {OrderForm} input @param {SyncContext} ctx */
|
||
function syncForm(input, ctx) {
|
||
let form = syncPayment(input, ctx.st);
|
||
form = { ...form, lines: form.lines.map((line, i) => syncLine(line, form, i, ctx)) };
|
||
form = {
|
||
...form,
|
||
feeRows: syncFeeRows(
|
||
form,
|
||
form.lines.map(line => collectLine(line, ctx.st)),
|
||
ctx,
|
||
),
|
||
};
|
||
const draft = collectDraft(form, ctx.st);
|
||
/** @type {FormSummary} */
|
||
const summary = { total: null, totalText: '待填写', roundingHint: '', card: null, feesText: '', presetNotes: {} };
|
||
try {
|
||
const total = Calc.orderTotal(
|
||
draft.lines.map(l => Calc.cents(l.sale, '商品销售额')),
|
||
Calc.cents(draft.discount, '整单优惠'),
|
||
draft.rounding_mode,
|
||
);
|
||
summary.total = total.total;
|
||
summary.totalText = orderAmount(total.total, total.rounding_mode);
|
||
summary.roundingHint = orderRoundingHint(total);
|
||
} catch {
|
||
summary.roundingHint =
|
||
draft.rounding_mode === 'yuan' ? '合计后四舍五入到元,请先填写商品金额与优惠。' : '保留原单金额,精确到分。';
|
||
}
|
||
// syncCreditCardPreview(新开单不保留旧手续费)
|
||
/** @type {number|null} */
|
||
let cardCost = 0;
|
||
if (Cards.isAccount(draft.payment_account)) {
|
||
const rate = creditCardRate(ctx.st);
|
||
cardCost = null;
|
||
if (summary.total !== null) {
|
||
try {
|
||
cardCost = Cards.amount(summary.total, rate);
|
||
} catch {
|
||
// 金额或费率不支持时继续显示待计算提示,保留其他已知费用。
|
||
}
|
||
}
|
||
summary.card =
|
||
cardCost === null
|
||
? {
|
||
rate,
|
||
amount: null,
|
||
amountText: '',
|
||
formula: `填写客户付款金额后自动计算${rate}‰手续费;付款人默认${memberName(ctx.st, 'owner')},可按实际修改。`,
|
||
}
|
||
: {
|
||
rate,
|
||
amount: cardCost,
|
||
amountText: (cardCost / 100).toFixed(2),
|
||
formula: `成交合计 ¥${yuan(summary.total)} × ${rate}‰ = ¥${yuan(cardCost)}。计入内部成本,客户付款金额不变;退款不退回已发生的手续费。`,
|
||
};
|
||
}
|
||
// updateFeeTotal
|
||
const items = draft.fee_items.filter(item => !Cards.isFee(item));
|
||
try {
|
||
const missing = items.filter(item => item.amount === '').length,
|
||
total =
|
||
items.reduce((sum, item) => sum + (item.amount === '' ? 0 : Calc.cents(item.amount)), 0) + (cardCost ?? 0);
|
||
summary.feesText =
|
||
'实际费用合计' +
|
||
(missing || cardCost === null ? '(已知部分)' : '') +
|
||
':¥' +
|
||
yuan(total) +
|
||
(missing ? ' · 还有 ' + missing + ' 项待补齐(没有成本填0)' : '') +
|
||
(cardCost === null ? ' · 信用卡手续费待计算' : '');
|
||
} catch {
|
||
summary.feesText = '请检查费用金额';
|
||
}
|
||
summary.presetNotes = readPresets(form, ctx.st).notes;
|
||
return { form, draft, summary };
|
||
}
|
||
|
||
// —— 校验 ——
|
||
/** @template {EntryDraft} T @param {T} input */
|
||
function validateOrderIdentity(input, { requireInternalNote = true } = {}) {
|
||
const customer = String(input.customer ?? '').trim(),
|
||
salesperson = String(input.salesperson ?? '').trim();
|
||
if (!customer || customer.length > 60) throw new Error('客户称呼/代号必填,请填写 1~60 字。');
|
||
if (!salesperson || salesperson.length > 30) throw new Error('开单人必填,请填写 1~30 字。');
|
||
if (requireInternalNote && String(input.internal_note ?? '').replace(/\s/gu, '').length < 3)
|
||
throw new Error('内部备注至少填写3个字符,#号计入,空格和换行不计入。');
|
||
if (String(input.internal_note ?? '').trim().length > 500) throw new Error('内部备注最多填写500字。');
|
||
return {
|
||
...input,
|
||
customer,
|
||
salesperson,
|
||
...(requireInternalNote ? { internal_note: String(input.internal_note ?? '').trim() } : {}),
|
||
};
|
||
}
|
||
/** @param {string|undefined} value */
|
||
const validOrderDate = value =>
|
||
/^\d{4}-\d{2}-\d{2}$/.test(value || '') && new Date(value + 'T00:00:00Z').toISOString().slice(0, 10) === value;
|
||
/** @param {ReturnedStockLot} lot @param {LedgerState} st @param {string} date */
|
||
function canUseReturnedLot(lot, st, date) {
|
||
return (
|
||
lot.available === true &&
|
||
lot.remainingMg > 0 &&
|
||
activePocketKeys(st).includes(lot.pocket) &&
|
||
(!lot.date || lot.date <= date)
|
||
);
|
||
}
|
||
// 旧页面在 JS 校验之前由浏览器拦下的必填项(required / min / step),新版界面没有原生表单校验,在这里补齐。
|
||
/** @param {OrderForm} form @param {LedgerState} st */
|
||
function validateFormFields(form, st) {
|
||
const problems = [];
|
||
const selectedLots = form.lines.map(line => line.returnedStockId).filter(Boolean);
|
||
if (!form.editing && selectedLots.length) {
|
||
const list = form.returnedLots;
|
||
if (
|
||
!list ||
|
||
list.member !== formMember(form, st) ||
|
||
list.date !== form.date ||
|
||
selectedLots.some(id => !list.lots.some(lot => lot.id === id && canUseReturnedLot(lot, st, form.date)))
|
||
)
|
||
problems.push('所选售后退回现货需要重新核对,请刷新现货列表');
|
||
if (new Set(selectedLots).size !== selectedLots.length) problems.push('同一件售后退回现货不能重复开单');
|
||
}
|
||
if (form.customerTypeRequired && !['new', 'returning'].includes(form.customer_type))
|
||
problems.push('请选择客户类型(新客户或老客户)');
|
||
if (!validOrderDate(form.date) || form.date > st.today) problems.push('业务日期请选择今天或之前的有效日期');
|
||
if (form.feeRows.length || readPresets(form, st).items.length)
|
||
if (!validOrderDate(form.fees_date) || form.fees_date > st.today)
|
||
problems.push('费用实际支付日期请选择今天或之前的有效日期');
|
||
if (!/^\d+(?:\.\d{1,2})?$/.test(String(form.discount).trim())) problems.push('整单优惠请填写0或正数,最多2位小数');
|
||
form.lines.forEach((line, i) => {
|
||
const item = '商品 ' + (i + 1),
|
||
v = lineVisibility(line, st);
|
||
const q = String(line.quantity).trim();
|
||
if (q && (!/^\d+(?:\.\d{1,3})?$/.test(q) || Number(q) < 0.001))
|
||
problems.push(item + '的克重/数量须大于0,最多3位小数');
|
||
if (v.pieces && !/^[1-9]\d*$/.test(String(line.pieces).trim())) problems.push(item + '的计工费件数须为正整数');
|
||
if (hasPurchase(line) && !line.purchase.materialPayer && line.pool?.source !== 'pool')
|
||
problems.push(item + '请选择料费付款人');
|
||
if (hasPurchase(line) && !line.purchase.laborPayer) problems.push(item + '请选择进货工费付款人');
|
||
if (line.pocket && !activePocketKeys(st).includes(line.pocket) && !line.historicalPocket)
|
||
problems.push('货盘「' + pocketLabel(st, line.pocket) + '」已停用,请重新选择已启用货盘,或明确选择外配。');
|
||
});
|
||
if (form.presets) {
|
||
const notes = readPresets(form, st).notes;
|
||
if (!form.presets.configured && form.presets.checked.box && notes.box === '请填写正整数数量')
|
||
problems.push('盒子数量请填写正整数');
|
||
if (form.presets.configured)
|
||
for (const [kind, checked] of Object.entries(form.presets.checked))
|
||
if (checked && own(form.presets.quantity, kind)) {
|
||
try {
|
||
Fees.boxCount(form.presets.quantity[kind]);
|
||
} catch (err) {
|
||
problems.push(err instanceof Error ? err.message : String(err));
|
||
}
|
||
}
|
||
}
|
||
if (problems.length) throw new Error('请先修改:' + problems.join(';') + '。');
|
||
}
|
||
/** @param {OrderInput} d @param {LedgerState} st */
|
||
function validateIssueDraft(d, st, { requireIdentity = true } = {}) {
|
||
if (requireIdentity) d = validateOrderIdentity(d);
|
||
if (Cards.isAccount(d.payment_account ?? '') && !creditCardAvailable(st))
|
||
throw new Error('信用卡收款暂未准备好,请刷新后重新核对收款方式。');
|
||
/** @type {string[]} */
|
||
const missing = [];
|
||
/** @param {unknown} v */
|
||
const blank = v => v == null || String(v).trim() === '';
|
||
if (!d.lines.length) throw new Error('请至少填写一行商品。');
|
||
d.lines.forEach((l, i) => {
|
||
const item = '商品 ' + (i + 1);
|
||
if (blank(l.name)) missing.push(item + '的名称');
|
||
if (blank(l.quantity)) missing.push(item + '的克重/数量');
|
||
if (pocketCountsEnabled(st, l.pocket) && l.unit === 'g')
|
||
stockCountValue(l.stockCount, { optional: !!l.historicalUnknown, title: item + '出库数量(对)' });
|
||
if (l.pricingMode === 'auto') {
|
||
if (blank(l.goldPrice)) missing.push(item + '的金价/银价');
|
||
if (blank(l.laborRate)) missing.push(item + '的销售工费');
|
||
} else if (blank(l.baseSale ?? l.sale)) missing.push(item + '的基础金额');
|
||
(l.charges || []).forEach((c, j) => {
|
||
if (blank(c.name)) missing.push(item + '附加项目 ' + (j + 1) + '的名称');
|
||
if (blank(c.amount)) missing.push(item + '的' + (c.name || '附加项目 ' + (j + 1)) + '收费');
|
||
});
|
||
if (l.costParts) {
|
||
if (
|
||
!(
|
||
/** @type {const} */ (['material', 'labor']).every(key =>
|
||
memberKeys(st).includes(l.costPayers?.[key] ?? ''),
|
||
)
|
||
)
|
||
)
|
||
throw new Error(item + '请选择料费和进货工费付款人。');
|
||
const result = Calc.purchaseCosts(l);
|
||
if (
|
||
l.costMaterial?.mode === 'pool' &&
|
||
(!l.costMaterial.poolId || !validOrderDate(l.costMaterial.poolId) || l.costMaterial.poolId > d.date)
|
||
)
|
||
throw new Error(item + '请选择不晚于订单日期的料价日期。');
|
||
for (const [key, value] of Object.entries(result.parts))
|
||
if (value === null && !(key === 'material' && l.costMaterial?.mode === 'pool'))
|
||
missing.push(item + '的' + Calc.costLabels[key]);
|
||
} else if (blank(l.cost)) missing.push(item + '的货品成本');
|
||
});
|
||
d.fee_items.forEach((f, i) => {
|
||
if (blank(f.note)) missing.push('费用 ' + (i + 1) + '的名称');
|
||
if (blank(f.amount)) missing.push((f.note || '费用 ' + (i + 1)) + '的实际成本');
|
||
});
|
||
if (missing.length)
|
||
throw new Error('开单前请补齐:' + missing.join('、') + '。没有收费或成本的项目填0,不需要的费用请移除。');
|
||
d.lines.forEach((l, i) => {
|
||
try {
|
||
Calc.sale(l);
|
||
if (!l.costParts) Calc.cents(l.cost, '货品成本');
|
||
} catch (err) {
|
||
throw new Error('商品 ' + (i + 1) + ':' + (err instanceof Error ? err.message : String(err)));
|
||
}
|
||
});
|
||
d.fee_items.forEach(f => Calc.cents(f.amount, f.note + '实际成本'));
|
||
Calc.orderTotal(
|
||
d.lines.map(l => Calc.sale(l).sale),
|
||
Calc.cents(d.discount, '整单优惠'),
|
||
d.rounding_mode,
|
||
);
|
||
return d;
|
||
}
|
||
|
||
// —— 旧草稿订单 → 表单输入(旧页面 draftInputs)——
|
||
/** @param {IssuedOrder} o */
|
||
function draftInputs(o) {
|
||
return {
|
||
...o,
|
||
rounding_mode: o.rounding_mode || 'cent',
|
||
discount: (o.discount / 100).toFixed(2),
|
||
fee_items: o.fee_items.map(item => ({
|
||
...item,
|
||
amount: item.amount === null ? '' : (item.amount / 100).toFixed(2),
|
||
})),
|
||
lines: o.lines.map(l => ({
|
||
...l,
|
||
costMaterial:
|
||
l.costMaterial?.mode === 'pool'
|
||
? { ...l.costMaterial }
|
||
: {
|
||
mode: materialCostInput(l).mode,
|
||
...(l.costMaterial?.mode === 'gram'
|
||
? { rate: l.costMaterial.rate == null ? '' : (l.costMaterial.rate / 100).toFixed(2) }
|
||
: {}),
|
||
},
|
||
costLabor: {
|
||
mode: l.costLabor?.mode || 'total',
|
||
rate: l.costLabor?.rate == null ? '' : (l.costLabor.rate / 100).toFixed(2),
|
||
},
|
||
quantity: l.unit === 'g' ? grams(l.quantity) : l.quantity,
|
||
sale: (l.sale / 100).toFixed(2),
|
||
baseSale: ((l.baseSale ?? l.sale) / 100).toFixed(2),
|
||
charges: (l.charges || []).map(c => ({ ...c, amount: c.amount === null ? '' : (c.amount / 100).toFixed(2) })),
|
||
cost: l.cost === null ? '' : (l.cost / 100).toFixed(2),
|
||
...(l.pricingMode === 'auto'
|
||
? { goldPrice: (l.goldPrice / 100).toFixed(2), laborRate: (l.laborRate / 100).toFixed(2) }
|
||
: {}),
|
||
...(l.costParts
|
||
? {
|
||
costParts: Object.fromEntries(
|
||
Object.entries(l.costParts).map(([k, v]) => [k, v === null ? '' : (v / 100).toFixed(2)]),
|
||
),
|
||
}
|
||
: {}),
|
||
})),
|
||
};
|
||
}
|
||
|
||
// —— 公式快速开单(旧页面 fillOrderFormula 的预填部分):先填空白行,不够再追加 ——
|
||
/** @param {LineState} line */
|
||
function isFormulaBlank(line) {
|
||
return (
|
||
line.unit === 'g' &&
|
||
!(
|
||
/** @type {const} */ (['quantity', 'goldPrice', 'laborRate', 'baseSale', 'sale']).some(
|
||
name => line[name] !== '',
|
||
)
|
||
) &&
|
||
!line.charges.length
|
||
);
|
||
}
|
||
/** @param {OrderForm} form @param {import('../web/src/shared/orderEntryTypes').FormulaLine[]} parsedLines @param {SyncContext} ctx */
|
||
function applyFormulaLines(form, parsedLines, ctx) {
|
||
const blanks = form.lines.map((line, index) => index).filter(index => isFormulaBlank(form.lines[index]));
|
||
if (form.lines.length + Math.max(0, parsedLines.length - blanks.length) > 60)
|
||
throw new Error('加上本次商品后超过60件,请先整理现有商品');
|
||
let next = form;
|
||
const filled = [];
|
||
for (const parsed of parsedLines) {
|
||
let index = blanks.shift();
|
||
if (index === undefined) {
|
||
next = addLine(next, ctx);
|
||
index = next.lines.length - 1;
|
||
}
|
||
const previous = next.lines[index];
|
||
const row = {
|
||
...previous,
|
||
unit: parsed.unit,
|
||
pricingMode: parsed.pricingMode,
|
||
quantity: String(parsed.quantity),
|
||
goldPrice: String(parsed.goldPrice),
|
||
laborMode: parsed.laborMode,
|
||
laborRate: String(parsed.laborRate),
|
||
pieces: String(parsed.pieces),
|
||
charges: [
|
||
...previous.charges,
|
||
...parsed.charges.map(charge => newCharge({ ...charge, id: ctx.uuid() }, ctx.uuid)),
|
||
],
|
||
};
|
||
next = updateLine(next, index, row);
|
||
filled.push(index + 1);
|
||
}
|
||
return { form: next, filled };
|
||
}
|
||
|
||
// —— 内部备注快捷标签 ——
|
||
/** @param {string} text */
|
||
function noteTagQuery(text) {
|
||
return String(text ?? '').match(/(?:^|[\s,。;、])#([\p{L}\p{N}_-]*)$/u)?.[1] || '';
|
||
}
|
||
/** @param {string[]} tags @param {string} text */
|
||
function filterNoteTags(tags, text) {
|
||
const query = noteTagQuery(text);
|
||
return tags.filter(tag => !query || tag.slice(1).includes(query)).slice(0, 20);
|
||
}
|
||
/** @param {string} text @param {string} tag */
|
||
function insertNoteTag(text, tag) {
|
||
const before = String(text ?? ''),
|
||
match = before.match(/(?:^|[\s,。;、])#([\p{L}\p{N}_-]*)$/u);
|
||
const head = match ? before.slice(0, before.length - match[1].length - 1) : before,
|
||
prefix = head && !/\s$/.test(head) ? ' ' : '';
|
||
const next = head + prefix + tag + ' ';
|
||
if (next.length > 500) throw new Error('内部备注最多填写500字。');
|
||
return next;
|
||
}
|
||
|
||
const api = {
|
||
productNames,
|
||
chargeNames,
|
||
chargeSaleDefaults,
|
||
feeLabels,
|
||
yuan,
|
||
grams,
|
||
orderAmount,
|
||
orderRoundingHint,
|
||
teamMode,
|
||
currentMember,
|
||
memberKeys,
|
||
memberEnabled,
|
||
memberName,
|
||
memberOptions,
|
||
defaultSalesperson,
|
||
shopFeeDefaults,
|
||
costConfig,
|
||
creditCardRate,
|
||
creditCardAvailable,
|
||
memberAccountPrefix,
|
||
accountIdentity,
|
||
activePocketKeys,
|
||
pocketLabel,
|
||
pocketOptions,
|
||
pocketCountsEnabled,
|
||
stockCountValue,
|
||
newCharge,
|
||
changeChargeType,
|
||
setChargeAmount,
|
||
collectCharge,
|
||
newLine,
|
||
setLineField,
|
||
setPurchaseField,
|
||
setPoolSource,
|
||
collectLine,
|
||
syncLine,
|
||
lineVisibility,
|
||
materialPoolMg,
|
||
poolQuoteInput,
|
||
feeSourceText,
|
||
editFeeRow,
|
||
addManualFee,
|
||
removeFeeRow,
|
||
restoreChargeCost,
|
||
newPresets,
|
||
togglePreset,
|
||
setPresetQuantity,
|
||
readPresets,
|
||
presetCatalogView,
|
||
paymentMethods,
|
||
recipientOptions,
|
||
readPaymentAccount,
|
||
changeMember,
|
||
formMember,
|
||
isBlankDraft,
|
||
newForm,
|
||
addLine,
|
||
removeLine,
|
||
addCharge,
|
||
updateLine,
|
||
collectDraft,
|
||
syncForm,
|
||
validateOrderIdentity,
|
||
canUseReturnedLot,
|
||
validateFormFields,
|
||
validateIssueDraft,
|
||
draftInputs,
|
||
isFormulaBlank,
|
||
applyFormulaLines,
|
||
noteTagQuery,
|
||
filterNoteTags,
|
||
insertNoteTag,
|
||
};
|
||
if (typeof module === 'object' && module.exports) module.exports = api;
|
||
else Object.assign(root, { OrderEntryModel: api });
|
||
})(/** @type {typeof globalThis} */ (typeof globalThis === 'object' ? globalThis : this));
|