diff --git a/新账系统/eslint.config.js b/新账系统/eslint.config.js index acdb308..6f2a3a7 100644 --- a/新账系统/eslint.config.js +++ b/新账系统/eslint.config.js @@ -64,6 +64,7 @@ module.exports = [ 'public/credit-card-fees.js', 'public/fee-estimates.js', 'public/order-copy.js', + 'public/order-entry-model.js', 'public/order-formula.js', 'public/order-templates.js', ], diff --git a/新账系统/public/order-entry-model.js b/新账系统/public/order-entry-model.js new file mode 100644 index 0000000..566fc28 --- /dev/null +++ b/新账系统/public/order-entry-model.js @@ -0,0 +1,1622 @@ +'use strict'; +// 普通开单表单的纯数据模型:把旧界面(app.js、order-cost-presets-ui.js、material-pools-ui.js)里依附于 DOM 的 +// 同步、收集与校验规则抽成不读写页面的函数,供新版界面(web/)使用。旧界面暂不加载本文件,行为不变。 +// 表单状态按旧页面各输入框的取值建模(金额用元的字符串、克重用克的字符串),collectDraft 输出与旧页面 +// collectDraft() 相同结构的草稿,即提交给 /api/orders/issue 的请求体。 +(function (root, factory) { + const node = typeof module === 'object' && module.exports; + const api = factory( + node ? require('./calculations') : root.LedgerCalc, + node ? require('./fee-estimates') : root.FeeEstimates, + node ? require('./credit-card-fees') : root.CreditCardFees, + ); + if (node) module.exports = api; + else root.OrderEntryModel = api; +})(typeof globalThis === 'object' ? globalThis : this, function (Calc, Fees, Cards) { + const productNames = ['足金999', '足银999', '纯银925']; + const chargeNames = ['编绳', '证书', '包装', '快递', '附加费']; + const chargeSaleDefaults = { 编绳: '55', 证书: '10', 包装: '10', 快递: '8' }; + const feeLabels = { + shipping: '快递费', + box: '包装盒', + certificate: '证书', + braiding: '编绳', + sticker: '手机贴', + other: '其他直接费用', + }; + const legacyTeamMembers = [ + { member: 'owner', label: '麦麦' }, + { member: 'assistant', label: '娜娜' }, + { member: 'assistant2', label: '小昊' }, + ]; + const defaultPocketKeys = ['现货', '金料', '找金', '回收旧料', '君宝汇']; + const orderCostCategories = { jd: 'shipping', yt: 'shipping', box: 'box', steel: 'braiding', silver: 'silverChain' }; + const clone = value => (value === undefined ? undefined : JSON.parse(JSON.stringify(value))); + const own = (object, key) => Object.prototype.hasOwnProperty.call(object, key); + + // —— 金额与文字 —— + const yuan = n => + n == null ? '待补' : (n / 100).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); + const grams = n => (n / 1000).toFixed(3); + function orderAmount(value, mode) { + return value == null + ? '待补' + : '¥' + + (mode === 'yuan' + ? (value / 100).toLocaleString('zh-CN', { minimumFractionDigits: 0, maximumFractionDigits: 0 }) + : yuan(value)); + } + 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)—— + function memberCatalog(st) { + const rows = st?.members?.length + ? st.members + : st?.shopSettings?.members?.length + ? st.shopSettings.members + : legacyTeamMembers; + return rows.filter(row => row && typeof row.member === 'string'); + } + const memberKeys = st => memberCatalog(st).map(row => row.member); + const memberEnabled = (st, member) => + memberCatalog(st).find(row => row.member === member)?.enabled !== false && memberKeys(st).includes(member); + const activeMemberKeys = st => memberKeys(st).filter(member => memberEnabled(st, member)); + const teamMode = st => !!(st?.user?.member || st?.members?.some(member => member.member === 'assistant2')); + const currentMember = (st, session) => + st?.user?.member || session?.user?.member || (st?.user?.role === 'owner' ? 'owner' : 'assistant'); + 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 || + { owner: '麦麦', assistant: '娜娜', assistant2: '小昊' }[member] || + '待确认' + ); + } + 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')]; + 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; + } + 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 || + '' + ); + } + const shopFeeDefaults = st => ({ + certificate: '4', + packaging: '3', + shipping: '6', + packagingPayer: 'owner', + ...st?.shopSettings?.feeDefaults, + }); + const costConfig = st => Fees.presets(st?.shopSettings?.costPresets); + const creditCardRate = st => st?.shopSettings?.creditCardRatePermille ?? 6; + const creditCardAvailable = st => !!st?.accounts?.includes('麦麦信用卡'); + const memberAccountPrefix = member => ({ owner: '麦麦', assistant: '助理', assistant2: '助理2' })[member] || member; + function accountIdentity(st, value) { + const text = String(value ?? ''); + for (const member of memberKeys(st)) { + const prefixes = member === 'assistant' ? ['助理', '助理1'] : [memberAccountPrefix(member)]; + for (const prefix of prefixes) + if (text === prefix) return { member, prefix, channel: '' }; + else if (text.startsWith(prefix) && ['微信', '支付宝', '现金', '信用卡'].includes(text.slice(prefix.length))) + return { member, prefix, channel: text.slice(prefix.length) }; + } + return null; + } + const activePocketKeys = st => (Array.isArray(st?.pockets) ? st.pockets : defaultPocketKeys); + const pocketLabel = (st, key) => st?.pocketCatalog?.find(row => row.key === key)?.name || String(key ?? ''); + const pocketCountsEnabled = (st, key) => + !!key && st?.pocketCatalog?.some(row => row.key === key && row.countUnit === 'pair') === true; + function pocketOptions(st, selected = '', historical = false) { + const keys = activePocketKeys(st), + options = keys.map(key => [key, pocketLabel(st, key)]); + if (selected && !keys.includes(selected)) + options.push([ + selected, + pocketLabel(st, selected) + (historical ? '(已停用 · 原货盘)' : '(已停用,请重新选择)'), + true, + ]); + return [['', '外配/不扣黄金'], ...options]; + } + 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); + } + const normalizeAccount = account => Cards.normalizeAccount(account); + + // —— 附加项目 —— + function newCharge(c = {}, uuid) { + const type = c.nameType || (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 } : {}), + }; + } + 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 } }; + } + const setChargeAmount = (charge, amount) => ({ + ...charge, + amount, + prices: { ...charge.prices, [charge.type]: amount }, + }); + const chargeName = charge => (charge.type === '其他' ? charge.customName : charge.type); + 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 } : {}), + }); + + // —— 商品行 —— + function materialCostInput(line) { + if (['gram', 'total'].includes(line.costMaterial?.mode)) return line.costMaterial; + const amount = line.costParts?.material, + hasTotal = amount != null && String(amount).trim() !== ''; + return { mode: (line.unit || 'g') === 'g' && !hasTotal ? 'gram' : 'total' }; + } + 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 = ['gram', 'total'].includes(line.costMaterial?.mode) + ? 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', + }; + } + const str = value => (value == null ? '' : String(value)); + // 与旧页面 lineHTML(l, index, {materialPool:true}) 相同的初始取值。ctx: {st, member, historicalPocket, uuid} + 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 || (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); + const line = { + legacy, + historicalPocket: !!ctx.historicalPocket, + 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 事件里的联动:选银饰清空货盘;改为按件即改为直接填金额并清空货盘。 + 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; + } + function setPurchaseField(line, field, value) { + return { ...line, purchase: { ...line.purchase, [field]: value } }; + } + function setPoolSource(line, source) { + return { ...line, pool: { ...line.pool, source } }; + } + 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, + }; + } + function readPurchaseCost(line) { + const p = line.purchase, + mode = p.materialMode; + 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-* 输入框名,服务端不读取)。 + function collectLine(line, st) { + 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 } : {}), + }; + values.charges = line.charges.map(collectCharge); + values.name = values.nameType === '其他' ? values.customName : values.nameType; + if (!pocketCountsEnabled(st, values.pocket) || values.unit !== 'g') delete values.stockCount; + else if (String(values.stockCount ?? '').trim() === '') values.stockCount = null; + if (!line.legacy) Object.assign(values, readPurchaseCost(line)); + return values; + } + + // —— 日购料(旧 material-pools-ui.js 中与开单有关的部分)—— + function materialPoolMg(value) { + const text = String(value ?? '').trim(); + if (!/^\d+(?:\.\d{1,3})?$/.test(text)) return null; + const [whole, fraction = ''] = text.split('.'), + mg = BigInt(whole) * 1000n + BigInt(fraction.padEnd(3, '0')); + return mg > 0n && mg <= 100000000000n ? Number(mg) : null; + } + const poolHasPersonal = pool => !!pool && own(pool, 'personalPools'); + const rollingOf = pools => (pools?.rolling?.enabled === true ? pools.rolling : null); + function poolRows(pools) { + const rows = pools?.rows || []; + return pools?.rolling?.enabled && pools.current + ? [pools.current, ...rows.filter(pool => pool.id !== pools.current.id)] + : rows; + } + 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 }; + }); + 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)]; + 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)); + } + 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 相同),用于个人回收料报价接口。 + function poolQuoteInput(form, ctx) { + 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 }; + } + 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), + }; + } + 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 }; + } + 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.message; + } + 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); + 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) + .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:按克与总额分别记住,切换单位或方式时不把每克料价当作总额。 + 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] of [ + ['material', 'costMaterial'], + ['labor', 'costLabor'], + ]) { + if (key === 'material' && pooled) continue; + const modeKey = key + 'Mode', + rateKey = key + 'Rate', + noteKey = key + 'Formula'; + 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.message; + } + } + return { ...line, purchase: p, view }; + } + // syncLine:计价方式联动、本行销售额、日购料与进货成本。 + 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.message; + next.view.saleCents = null; + } + if (next.legacy) return next; + const synced = syncPoolSelection(next, form, lineIndex, ctx); + next = syncPurchase(synced.line, synced.pooled); + try { + next.view.purchase = Calc.purchaseCosts({ ...readPurchaseCost(next), unit: next.unit, quantity: next.quantity }); + } catch { + next.view.purchase = null; + } + return next; + } + // 字段显隐(旧页面 syncLine 的 show()):返回本行当前应显示的输入项。 + function lineVisibility(line, st) { + const auto = line.pricingMode === 'auto'; + const historicalUnknown = + line.countHistoricalUnknown && + line.countOriginalPocket === line.pocket && + Number(line.countOriginalQuantity) === Number(line.quantity); + 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: !['accessories', 'other'].every( + key => + /^\d+(?:\.\d{1,2})?$/.test(String(line.purchase?.[key] ?? '').trim()) && Number(line.purchase?.[key]) === 0, + ), + }; + } + + // —— 实际费用行 —— + 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) } : {}), + }; + } + 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) } : {}), + }; + } + const feeSourceText = row => + row.automatic + ? '已记录的信用卡收款手续费' + : row.key.startsWith('charge:') + ? '商品 ' + row.lineNumber + ' 的附加项目' + : '整单费用'; + 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 } : {}), + }; + }); + } + const teamDefaultPayer = (form, st) => (teamMode(st) ? formMember(form, st) : 'assistant'); + 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 }; + } + 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:移除附加项目对应的费用时标记该附加项目“内部成本已移除”,否则下次同步会重新生成。 + 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(chargeName(charge).trim()) === '快递') + ? { ...charge, costRemoved: true } + : charge, + ), + })); + return { ...form, lines, feeRows: form.feeRows.filter((_, i) => i !== index) }; + } + 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)—— + 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); + } + function newPresets(st, items = []) { + const config = costConfig(st); + if (Fees.customPresets(config)) { + const catalog = Fees.presetCatalog(config), + selected = new Map( + items.map(item => [Fees.presetKind(item, { presets: catalog }), item]).filter(([kind]) => kind), + ); + const checked = {}, + 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 => [Fees.presetKind(item, { presets: config }), 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'), + }, + quantity: { box: box ? box.note.match(/(([^)]*)个 ×/)[1] : '1' }, + }; + } + const presetCategory = (presets, kind) => orderCostCategories[kind] || kind; + 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); + } + // 勾选后替换下方同类旧费用;与该成本同键的其他旧行改为独立键,避免重复。 + function togglePreset(form, kind, checked, st, uuid) { + const presets = { ...form.presets, checked: { ...form.presets.checked, [kind]: checked } }; + const category = presetCategory(presets, kind); + 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; + 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 }; + } + function setPresetQuantity(form, kind, value) { + return { ...form, presets: { ...form.presets, quantity: { ...form.presets.quantity, [kind]: value } } }; + } + function readPresets(form, st) { + const presets = form.presets; + if (!presets) return { items: [], notes: {} }; + const member = formMember(form, st), + 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.message; + 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); + notes.box = selection.box + ? Fees.boxCount(quantity) + + '个 × ' + + config.box.amount + + '元 = ' + + items.find(item => item.key === 'box').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 }; + } + // 勾选项展示用目录(名称、单价、付款人)。 + 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), + 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') }, + ]; + } + + // —— 收款方式与收款人 —— + function formMember(form, st) { + return form.member || currentMember(st); + } + function defaultRecipient(form, st) { + const member = teamMode(st) ? formMember(form, st) : 'assistant'; + return memberAccountPrefix(memberEnabled(st, member) ? member : 'owner'); + } + function paymentMethods(st) { + return ['微信', '支付宝', '现金', ...(creditCardAvailable(st) ? ['信用卡'] : [])]; + } + function recipientOptions(st, payment) { + 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; + } + 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:信用卡统一由店主收款,切回其他方式时恢复原收款人。 + 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 }; + } + const readPaymentAccount = form => normalizeAccount((form.payment.recipient || '') + (form.payment.method || '')); + // 店主改订单归属:收款人跟随(信用卡除外),未改过的费用付款人跟随(包装除外)。 + 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 }; + } + + // —— 整张表单 —— + function draftRoundingMode(draft) { + return draft.id ? draft.rounding_mode || 'cent' : 'yuan'; + } + // renderCreate 中的“空白草稿”判断:空白时日期与费用日期回到今天。 + 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(旧草稿订单))。 + function newForm(ctx, input) { + const { st, session, uuid } = ctx; + let draft = input || { date: st.today, lines: [{}] }; + draft = { ...draft, rounding_mode: draftRoundingMode(draft) }; + if (isBlankDraft(draft)) draft = { ...draft, date: st.today, fees_date: st.today }; + const presetsEnabled = !draft.id; + 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, + })); + const form = { + 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: ['new', 'returning'].includes(draft.customer_type) ? 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: [], + }; + form.payment = newPayment(draft.payment_account, form, st); + const config = costConfig(st); + const rows = presetsEnabled ? items.filter(item => !Fees.presetKind(item, { presets: config })) : items; + form.presets = presetsEnabled ? newPresets(st, items) : null; + 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; + } + 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 })], + }; + } + function removeLine(form, index) { + if (form.lines.length <= 1) throw new Error('请至少保留一行商品'); + return { ...form, lines: form.lines.filter((_, i) => i !== index) }; + } + 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)] }); + } + function updateLine(form, index, line) { + return { ...form, lines: form.lines.map((value, i) => (i === index ? line : value)) }; + } + 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].filter(item => !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} + 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); + 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(新开单不保留旧手续费) + let cardCost = 0; + if (Cards.isAccount(draft.payment_account)) { + const rate = creditCardRate(ctx.st); + try { + const amount = Cards.amount(summary.total, rate); + summary.card = { + rate, + amount, + amountText: (amount / 100).toFixed(2), + formula: `成交合计 ¥${yuan(summary.total)} × ${rate}‰ = ¥${yuan(amount)}。计入内部成本,客户付款金额不变;退款不退回已发生的手续费。`, + }; + cardCost = amount; + } catch { + summary.card = { + rate, + amount: null, + amountText: '', + formula: `填写客户付款金额后自动计算${rate}‰手续费;付款人默认${memberName(ctx.st, 'owner')},可按实际修改。`, + }; + cardCost = null; + } + } + // 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 }; + } + + // —— 校验 —— + 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() } : {}), + }; + } + const validOrderDate = value => + /^\d{4}-\d{2}-\d{2}$/.test(value || '') && new Date(value + 'T00:00:00Z').toISOString().slice(0, 10) === value; + // 旧页面在 JS 校验之前由浏览器拦下的必填项(required / min / step),新版界面没有原生表单校验,在这里补齐。 + function validateFormFields(form, st) { + const problems = []; + 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 (!line.legacy && !line.purchase.materialPayer && line.pool?.source !== 'pool') + problems.push(item + '请选择料费付款人'); + if (!line.legacy && !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.message); + } + } + } + if (problems.length) throw new Error('请先修改:' + problems.join(';') + '。'); + } + function validateIssueDraft(d, st, { requireIdentity = true } = {}) { + if (requireIdentity) d = validateOrderIdentity(d); + if (Cards.isAccount(d.payment_account) && !creditCardAvailable(st)) + throw new Error('信用卡收款暂未准备好,请刷新后重新核对收款方式。'); + const missing = []; + 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 (!['material', 'labor'].every(key => memberKeys(st).includes(l.costPayers?.[key]))) + throw new Error(item + '请选择料费和进货工费付款人。'); + const result = Calc.purchaseCosts(l); + if ( + l.costMaterial?.mode === 'pool' && + (!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.message); + } + }); + 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)—— + 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 的预填部分):先填空白行,不够再追加 —— + function isFormulaBlank(line) { + return ( + line.unit === 'g' && + !['quantity', 'goldPrice', 'laborRate', 'baseSale', 'sale'].some(name => line[name] !== '') && + !line.charges.length + ); + } + 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 row = { ...next.lines[index] }; + for (const name of ['unit', 'pricingMode', 'quantity', 'goldPrice', 'laborMode', 'laborRate', 'pieces']) + row[name] = String(parsed[name]); + row.charges = [ + ...row.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 }; + } + + // —— 内部备注快捷标签 —— + function noteTagQuery(text) { + return String(text ?? '').match(/(?:^|[\s,。;、])#([\p{L}\p{N}_-]*)$/u)?.[1] || ''; + } + function filterNoteTags(tags, text) { + const query = noteTagQuery(text); + return tags.filter(tag => !query || tag.slice(1).includes(query)).slice(0, 20); + } + 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; + } + + return { + 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, + validateFormFields, + validateIssueDraft, + draftInputs, + isFormulaBlank, + applyFormulaLines, + noteTagQuery, + filterNoteTags, + insertNoteTag, + }; +}); diff --git a/新账系统/test/order-entry-model.test.js b/新账系统/test/order-entry-model.test.js new file mode 100644 index 0000000..0ce327f --- /dev/null +++ b/新账系统/test/order-entry-model.test.js @@ -0,0 +1,304 @@ +'use strict'; +// 共用开单模型:与旧页面相同的同步、收集与校验规则(附加项目报价、进货成本、费用行、常用成本、收款人、合计)。 +const test = require('node:test'), + assert = require('node:assert/strict'); +const M = require('../public/order-entry-model'); + +function setup(overrides = {}) { + let n = 0; + const uuid = () => '00000000-0000-4000-8000-' + String(++n).padStart(12, '0'); + const st = { + today: '2026-11-20', + user: { id: 'u1', name: '麦麦', role: 'owner', member: 'owner', operatorName: '麦麦' }, + members: [ + { member: 'owner', label: '麦麦' }, + { member: 'assistant', label: '娜娜' }, + { member: 'assistant2', label: '小昊' }, + ], + accounts: ['麦麦微信', '麦麦信用卡', '助理微信', '助理2微信'], + shopSettings: {}, + ...overrides, + }; + const ctx = { st, uuid }; + return { st, ctx, uuid }; +} +const sync = (form, ctx) => M.syncForm(form, ctx); +function editLine(form, index, patch) { + return M.updateLine(form, index, { ...form.lines[index], ...patch }); +} +function editPurchase(form, index, patch) { + const line = form.lines[index]; + return M.updateLine(form, index, { ...line, purchase: { ...line.purchase, ...patch } }); +} + +test('新单默认:按克计价、现货货盘、整单取整到元、进货料价按克、付款人为本人', () => { + const { ctx } = setup(); + const form = M.newForm(ctx); + assert.equal(form.rounding_mode, 'yuan'); + assert.equal(form.feeCostMode, 'checkboxes'); + const line = form.lines[0]; + assert.deepEqual( + [line.nameType, line.pricingMode, line.unit, line.pocket, line.pieces], + ['足金999', 'auto', 'g', '现货', '1'], + ); + assert.equal(line.purchase.materialMode, 'gram'); + assert.equal(line.purchase.laborMode, 'total'); + assert.equal(line.purchase.materialPayer, 'owner'); + assert.equal(form.salesperson, '麦麦'); + assert.equal(M.readPaymentAccount(form), '麦麦微信'); +}); + +test('克工费:销售额、按克料费与合计;整单四舍五入(x.49 舍、x.50 入)', () => { + const { ctx } = setup(); + let form = M.newForm(ctx); + form = editLine(form, 0, { quantity: '2.5', goldPrice: '950', laborRate: '30' }); + form = editPurchase(form, 0, { materialRate: '880', labor: '25' }); + let r = sync(form, ctx); + assert.equal(r.draft.lines[0].sale, '2450.00'); + assert.deepEqual(r.draft.lines[0].costParts, { material: '2200.00', labor: '25', accessories: '0', other: '0' }); + assert.deepEqual(r.draft.lines[0].costMaterial, { mode: 'gram', rate: '880' }); + assert.equal(r.summary.totalText, '¥2,450'); + r = sync({ ...r.form, discount: '0.51' }, ctx); + assert.equal(r.summary.total, 244900); + assert.match(r.summary.roundingHint, /差额 -0\.49元|2,449/); + r = sync({ ...r.form, discount: '0.50' }, ctx); + assert.equal(r.summary.total, 245000); +}); + +test('件工费与直接金额', () => { + const { ctx } = setup(); + let form = M.newForm(ctx); + form = editLine(form, 0, { quantity: '3', goldPrice: '900', laborMode: 'piece', laborRate: '50', pieces: '3' }); + let r = sync(form, ctx); + assert.equal(r.draft.lines[0].sale, '2850.00'); + form = M.updateLine(r.form, 0, M.setLineField(r.form.lines[0], 'unit', '件')); + assert.equal(form.lines[0].pricingMode, 'manual'); + assert.equal(form.lines[0].pocket, ''); + form = editLine(form, 0, { quantity: '2', baseSale: '388' }); + r = sync(form, ctx); + assert.equal(r.draft.lines[0].sale, '388.00'); + assert.equal(r.form.lines[0].purchase.materialMode, 'total', '按件时料费改为总额'); +}); + +test('附加项目:新选择预填报价,切换类目记住各自金额,手填0与清空不被覆盖', () => { + const { uuid } = setup(); + let c = M.newCharge({}, uuid); + assert.deepEqual([c.type, c.amount], ['编绳', '55']); + c = M.setChargeAmount(c, '0'); + c = M.changeChargeType(c, '证书'); + assert.equal(c.amount, '10'); + c = M.setChargeAmount(c, ''); + c = M.changeChargeType(c, '编绳'); + assert.equal(c.amount, '0', '回到编绳仍是手填的0'); + c = M.changeChargeType(c, '证书'); + assert.equal(c.amount, '', '回到证书仍是清空'); + c = M.changeChargeType(c, '附加费'); + assert.equal(c.amount, ''); + assert.equal(M.newCharge({ name: '包装', amount: null }, uuid).amount, ''); +}); + +test('附加项目带入成本行:证书按店铺默认、编绳待填,快递与包装改由常用成本勾选;手改后标记已改', () => { + const { ctx, uuid } = setup({ shopSettings: { feeDefaults: { certificate: '5' } } }); + let form = M.newForm(ctx); + form = editLine(form, 0, { quantity: '1', goldPrice: '900', laborRate: '20' }); + for (let i = 0; i < 4; i++) form = M.addCharge(form, 0, uuid); + const types = ['编绳', '证书', '包装', '快递']; + form = M.updateLine(form, 0, { + ...form.lines[0], + charges: form.lines[0].charges.map((c, i) => M.changeChargeType(c, types[i])), + }); + let r = sync(form, ctx); + assert.deepEqual( + r.form.feeRows.map(row => [row.note, row.amount, row.edited]), + [ + ['编绳', '', false], + ['证书', '5', false], + ], + ); + form = M.editFeeRow(r.form, 0, 'amount', '6'); + form = M.togglePreset(form, 'jd', true, ctx.st, uuid); + form = M.togglePreset(form, 'yt', true, ctx.st, uuid); + r = sync(form, ctx); + assert.equal(r.form.presets.checked.jd, false, '快递二选一'); + assert.deepEqual( + r.draft.fee_items.map(f => [f.key.split(':')[0], f.note, f.amount, f.payer, f.edited]), + [ + ['charge', '编绳', '6', 'owner', true], + ['charge', '证书', '5', 'owner', false], + ['shipping', '圆通快递', '6', 'owner', true], + ], + ); + assert.equal(r.draft.lines[0].sale, '1003.00'); +}); + +test('移除附加项目成本行后不再自动生成,恢复后重新带入', () => { + const { ctx, uuid } = setup(); + let form = M.addCharge(M.newForm(ctx), 0, uuid); + let r = sync(form, ctx); + assert.equal(r.form.feeRows.length, 1); + r = sync(M.removeFeeRow(r.form, 0), ctx); + assert.equal(r.form.feeRows.length, 0); + assert.equal(r.draft.lines[0].charges[0].costRemoved, true); + r = sync(M.restoreChargeCost(r.form, 0, 0), ctx); + assert.equal(r.form.feeRows.length, 1); +}); + +test('盒子按数量计费,数量无效时金额留空', () => { + const { ctx, uuid } = setup(); + let form = M.togglePreset(M.newForm(ctx), 'box', true, ctx.st, uuid); + form = M.setPresetQuantity(form, 'box', '3'); + let r = sync(form, ctx); + assert.deepEqual(r.draft.fee_items[0], { + key: 'box', + note: '盒子(3个 × 3元/个)', + amount: '9', + payer: 'owner', + status: 'estimated', + edited: true, + }); + r = sync(M.setPresetQuantity(r.form, 'box', '0'), ctx); + assert.equal(r.draft.fee_items[0].amount, ''); + assert.throws(() => M.validateFormFields(r.form, ctx.st), /盒子数量/); +}); + +test('进货成本:按克与总额分别记住,按件时不把每克料价当作总额', () => { + const { ctx } = setup(); + let form = editLine(M.newForm(ctx), 0, { quantity: '2', goldPrice: '900', laborRate: '10' }); + form = editPurchase(form, 0, { materialMode: 'total', material: '1700' }); + let r = sync(form, ctx); + r = sync(editPurchase(r.form, 0, { materialMode: 'gram', materialRate: '860' }), ctx); + assert.equal(r.form.lines[0].purchase.material, '1720.00'); + r = sync(editPurchase(r.form, 0, { materialMode: 'total' }), ctx); + assert.equal(r.form.lines[0].purchase.material, '1700', '切回总额恢复原总额'); + r = sync(editPurchase(r.form, 0, { laborMode: 'gram', laborRate: '12.5' }), ctx); + assert.equal(r.draft.lines[0].costParts.labor, '25.00'); + assert.deepEqual(r.draft.lines[0].costLabor, { mode: 'gram', rate: '12.5' }); +}); + +test('店主改订单归属:收款人与未改过的费用付款人跟随;信用卡固定由店主收款并保留原收款人', () => { + const { ctx, uuid } = setup(); + let r = sync(M.addCharge(M.newForm(ctx), 0, uuid), ctx); + r = sync(M.changeMember(r.form, 'assistant', ctx.st), ctx); + assert.equal(r.draft.member, 'assistant'); + assert.equal(r.draft.payment_account, '助理微信'); + assert.equal(r.form.feeRows[0].payer, 'assistant'); + r = sync({ ...r.form, payment: { ...r.form.payment, method: '信用卡' } }, ctx); + assert.equal(r.draft.payment_account, '麦麦信用卡'); + r = sync({ ...r.form, payment: { ...r.form.payment, method: '微信' } }, ctx); + assert.equal(r.draft.payment_account, '助理微信'); +}); + +test('信用卡手续费按成交合计 6‰ 预览', () => { + const { ctx } = setup(); + let form = editLine(M.newForm(ctx), 0, { pricingMode: 'manual', baseSale: '1000' }); + form = { ...form, payment: { ...form.payment, method: '信用卡' } }; + const r = sync(form, ctx); + assert.equal(r.summary.card.amount, 600); + assert.match(r.summary.feesText, /¥6\.00/); +}); + +test('校验:客户、开单人、内部备注至少3个字符(#计入、空白不计),客户类型必选', () => { + const { ctx, st } = setup(); + const base = { customer: '甲', salesperson: '麦麦', internal_note: '#补货' }; + assert.equal(M.validateOrderIdentity(base).internal_note, '#补货'); + assert.throws(() => M.validateOrderIdentity({ ...base, customer: ' ' }), /客户称呼/); + assert.throws(() => M.validateOrderIdentity({ ...base, salesperson: '' }), /开单人/); + assert.throws(() => M.validateOrderIdentity({ ...base, internal_note: '# 补' }), /至少填写3个字符/); + const form = M.newForm(ctx); + assert.throws(() => M.validateFormFields(form, st), /客户类型/); + const r = sync(form, ctx); + assert.throws(() => M.validateIssueDraft({ ...r.draft, ...base }, st), /开单前请补齐:商品 1的克重/数量/); +}); + +test('旧草稿订单转为表单:保留原单号、取整方式与付款人,不显示常用成本勾选', () => { + const { ctx } = setup(); + const order = { + id: '11111111-2222-4333-8444-555555555555', + revision: 1, + status: 'draft', + date: '2026-11-20', + customer: '草稿客户', + salesperson: '麦麦', + paper_number: '20261120001', + paper_date: '2026-11-20', + rounding_mode: 'cent', + discount: 0, + payment_account: '助理微信', + member: 'owner', + customer_type: 'new', + fee_items: [], + lines: [ + { + name: '足金999', + unit: 'g', + quantity: 1500, + pocket: '现货', + payer: 'owner', + pricingMode: 'auto', + goldPrice: 90000, + laborRate: 2000, + laborMode: 'gram', + pieces: 1, + sale: 138000, + baseSale: 138000, + charges: [], + cost: null, + costParts: { material: 120000, labor: null, accessories: 0, other: 0 }, + costPayers: { material: 'owner', labor: 'assistant' }, + costMaterial: { mode: 'total' }, + costLabor: { mode: 'total' }, + }, + ], + }; + const form = M.newForm(ctx, M.draftInputs(order)); + assert.equal(form.presets, null); + const r = sync(form, ctx); + assert.equal(r.draft.id, order.id); + assert.equal(r.draft.revision, 1); + assert.equal(r.draft.rounding_mode, 'cent'); + assert.equal(r.draft.fee_cost_mode, 'legacy'); + assert.equal(r.draft.lines[0].quantity, '1.500'); + assert.equal(r.draft.lines[0].costParts.material, '1200.00'); + assert.deepEqual(r.draft.lines[0].costPayers, { material: 'owner', labor: 'assistant' }); + assert.equal(r.summary.totalText, '¥1,380.00'); +}); + +test('公式预填:先填空白行再追加,附加费带入', () => { + const { ctx } = setup(); + const form = M.newForm(ctx); + const lines = [ + { + unit: 'g', + pricingMode: 'auto', + quantity: '0.79', + goldPrice: '822', + laborMode: 'piece', + laborRate: '120', + pieces: '1', + charges: [], + }, + { + unit: 'g', + pricingMode: 'auto', + quantity: '0.58', + goldPrice: '822', + laborMode: 'gram', + laborRate: '45', + pieces: '1', + charges: [{ name: '附加费', amount: '55' }], + }, + ]; + const { form: next, filled } = M.applyFormulaLines(form, lines, ctx); + assert.deepEqual(filled, [1, 2]); + const r = sync(next, ctx); + assert.deepEqual( + r.draft.lines.map(l => l.sale), + ['769.38', '557.86'], + ); +}); + +test('内部备注快捷标签:按 # 后的词筛选,插入时替换正在输入的标签', () => { + assert.deepEqual(M.filterNoteTags(['#补货', '#客户自提'], '已联系 #补'), ['#补货']); + assert.equal(M.insertNoteTag('已联系 #补', '#补货'), '已联系 #补货 '); + assert.equal(M.insertNoteTag('已联系', '#补货'), '已联系 #补货 '); +});