import { useEffect, useRef, useState } from 'react'; import { Calc as LedgerCalc, Fees, Model } from '../../shared'; import { Button } from '../Settings/controls'; import { Input, Choice } from './EditFields'; const { yuan, grams, validateOrderIdentity } = Model; const feeCategories = { jd: 'shipping', yt: 'shipping', box: 'box', steel: 'braiding', silver: 'silverChain' }; function validOrderDate(value) { if (!/^\d{4}-\d{2}-\d{2}$/.test(value || '')) return false; const date = new Date(value + 'T12:00:00Z'); return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value; } function priceLockEditAmount(value) { try { return LedgerCalc.cents(String(value), '成本'); } catch { return String(value ?? ''); } } function priceLockOrderEditMeta(entry, index) { return entry.priceLock.lines?.[index] || entry.priceLock; } function priceLockOrderEditMaterial(input, index) { return input.lines[index].price_lock_material || (input.lines.length === 1 ? input.price_lock_material : null); } function priceLockOrderEditExtra(input, index) { return ( input.lines[index].price_lock_extra_material || (input.lines.length === 1 ? input.price_lock_extra_material : null) ); } function priceLockEditFinancialValue(input) { if (input?.lines?.length > 1) return { date: input.date, fees_date: input.fees_date, fee_cost_mode: input.fee_cost_mode || 'legacy', lines: input.lines.map((line, index) => ({ lineId: line.lineId, ...priceLockEditFinancialValue({ lines: [line], price_lock_material: priceLockOrderEditMaterial(input, index), price_lock_extra_material: priceLockOrderEditExtra(input, index), fee_items: [], }), })), fees: priceLockEditFinancialValue({ ...input, lines: [] }).fees, }; const line = input?.lines?.[0] || {}, material = input?.price_lock_material || {}, extra = input?.price_lock_extra_material; return { date: input?.date, fees_date: input?.fees_date, fee_cost_mode: input?.fee_cost_mode || 'legacy', material: material.source === 'pool' ? { source: 'pool' } : { source: material.source, rate: priceLockEditAmount(material.rate), payer: material.payer }, extra: extra ? { ...(extra.source === 'pool' ? { source: 'pool' } : {}), rate: priceLockEditAmount(extra.rate), payer: extra.payer, } : null, costs: { labor: priceLockEditAmount(line.costParts?.labor), accessories: priceLockEditAmount(line.costParts?.accessories), other: priceLockEditAmount(line.costParts?.other), payer: line.payer, laborPayer: line.costPayers?.labor, laborMode: line.costLabor?.mode || 'total', ...(line.costLabor?.mode === 'gram' ? { laborRate: priceLockEditAmount(line.costLabor.rate) } : {}), }, fees: (input?.fee_items || []) .map(fee => ({ key: fee.key, expense_id: fee.expense_id || '', date: fee.date || input.fees_date, note: fee.note, payer: fee.payer, amount: priceLockEditAmount(fee.amount), funding: fee.funding ?? null, })) .sort((a, b) => String(a.key).localeCompare(String(b.key))), }; } function priceLockEditFinancialChanged(entry, input = entry?.inputs) { return ( JSON.stringify(priceLockEditFinancialValue(input)) !== JSON.stringify(priceLockEditFinancialValue(entry?.originalInputs)) ); } function priceLockEditGramCost(mg, rate) { return LedgerCalc.purchaseCosts({ unit: 'g', quantity: grams(mg), costParts: { material: '0', labor: '0', accessories: '0', other: '0' }, costMaterial: { mode: 'gram', rate }, costLabor: { mode: 'total' }, }).parts.material; } function priceLockOrderEditPreview(input, entry) { if (input.lines.length > 1) { const costs = { material: 0, labor: 0, accessories: 0, other: 0, fees: input.fee_items.reduce((sum, fee) => sum + LedgerCalc.cents(fee.amount, '实际费用'), 0), }; input.lines.forEach((line, index) => { const old = entry.originalInputs, meta = priceLockOrderEditMeta(entry, index), singleInput = { ...input, lines: [line], price_lock_material: priceLockOrderEditMaterial(input, index), price_lock_extra_material: priceLockOrderEditExtra(input, index), fee_items: [], }, singleEntry = { ...entry, originalInputs: { ...old, lines: [old.lines[index]], price_lock_material: priceLockOrderEditMaterial(old, index), price_lock_extra_material: priceLockOrderEditExtra(old, index), }, priceLock: { ...entry.priceLock, ...meta }, order: { ...entry.order, lines: [entry.order.lines[index]] }, }; const value = priceLockOrderEditPreview(singleInput, singleEntry); for (const key of ['material', 'labor', 'accessories', 'other']) costs[key] += value[key]; }); costs.total = Object.values(costs).reduce((sum, value) => sum + value, 0); costs.profit = entry.order.total - costs.total; return costs; } const original = entry.originalInputs, line = input.lines[0], extraMg = entry.priceLock.extraMg, usedMg = entry.order.lines[0].quantity - extraMg, oldExtra = extraMg ? original.price_lock_extra_material.source === 'pool' ? original.price_lock_extra_material.amount : priceLockEditGramCost(extraMg, original.price_lock_extra_material.rate) : 0; const originalMaterial = input.price_lock_material.source === 'pool' ? LedgerCalc.cents(original.lines[0].costParts.material, '原料费') - oldExtra : priceLockEditGramCost(usedMg, input.price_lock_material.rate), extra = extraMg ? input.price_lock_extra_material.source === 'pool' ? original.price_lock_extra_material.amount : priceLockEditGramCost(extraMg, input.price_lock_extra_material.rate) : 0; if (!Number.isSafeInteger(originalMaterial) || originalMaterial < 0 || !Number.isSafeInteger(extra)) throw new Error('原锁料费尚未完整,请核对原料价与补重料价。'); const costs = { material: originalMaterial + extra, labor: LedgerCalc.cents(line.costParts.labor, '进货工费'), accessories: LedgerCalc.cents(line.costParts.accessories, '配件成本'), other: LedgerCalc.cents(line.costParts.other, '其他货品成本'), fees: input.fee_items.reduce((total, fee) => total + LedgerCalc.cents(fee.amount, '实际费用'), 0), }; costs.total = Object.values(costs).reduce((total, amount) => total + amount, 0); costs.profit = entry.order.total - costs.total; return costs; } function materialPoolRate(value) { return value == null ? '待补采购' : yuan(value); } function validatePriceLockOrderEdit(input, entry, state) { if (input.lines.length > 1) { if (input.lines.length !== entry.order.lines.length) throw new Error('商品成本资料未完整读到,请重新读取订单。'); input.lines.forEach((line, index) => { const meta = priceLockOrderEditMeta(entry, index); if (line.lineId !== (meta.lineId || meta.id)) throw new Error('锁价商品身份已变化,请重新读取订单。'); validatePriceLockOrderEdit( { ...input, lines: [line], price_lock_material: priceLockOrderEditMaterial(input, index), price_lock_extra_material: priceLockOrderEditExtra(input, index), fee_items: [], }, { ...entry, priceLock: { ...entry.priceLock, ...meta } }, state, ); }); for (const fee of input.fee_items) { LedgerCalc.cents(fee.amount, '实际费用'); if (!Model.memberKeys(state).includes(fee.payer)) throw new Error('请选择每笔实际费用的付款人。'); } return { ...input, ...validateOrderIdentity({ customer: input.customer, salesperson: input.salesperson, note: input.note, internal_note: input.internal_note, }), }; } if (!validOrderDate(input.date) || input.date < entry.priceLock.date || input.date > state.today) throw new Error('交付日期请选择原锁日期至今天之间的有效日期。'); const material = input.price_lock_material, extra = input.price_lock_extra_material, line = input.lines[0]; if ( !material || !['pool', 'manual'].includes(material.source) || (material.source === 'pool' && entry.priceLock.materialSource !== 'pool') || (material.source === 'manual' && entry.priceLock.materialSource === 'pool' && !entry.priceLock.canSwitchToManual) ) throw new Error('原锁料费来源已变化,请重新读取锁价单。'); if (material.source === 'manual') { LedgerCalc.cents(material.rate, '原锁进货料价'); if (!Model.memberKeys(state).includes(material.payer)) throw new Error('请选择原锁料费的实际付款人。'); if (material.verified !== true) throw new Error('请核实手填原锁料费和实际付款人,并勾选确认。'); } if (entry.priceLock.extraMg > 0) { if (!extra) throw new Error('请带入补重料费。'); LedgerCalc.cents(extra.rate, '补重进货料价'); if (!Model.memberKeys(state).includes(extra.payer)) throw new Error('请选择补重料费的实际付款人。'); if (extra.verified !== true) throw new Error('请核实补重料费和实际付款人,并勾选确认。'); } if (!Model.memberKeys(state).includes(line.payer) || !Model.memberKeys(state).includes(line.costPayers?.labor)) throw new Error('请选择进货工费、配件及其他成本的实际付款人。'); if (!['gram', 'total'].includes(line.costLabor?.mode)) throw new Error('请选择进货工费方式。'); if (line.costLabor.mode === 'gram') LedgerCalc.cents(line.costLabor.rate, '进货克工费'); for (const [key, name] of [ ['labor', '进货总工费'], ['accessories', '配件成本'], ['other', '其他货品成本'], ]) LedgerCalc.cents(line.costParts[key], name); for (const fee of input.fee_items) { LedgerCalc.cents(fee.amount, '实际费用'); if (!Model.memberKeys(state).includes(fee.payer)) throw new Error('请选择每笔实际费用的付款人。'); } return { ...input, ...validateOrderIdentity({ customer: input.customer, salesperson: input.salesperson, note: input.note, internal_note: input.internal_note, }), }; } const moneyProps = { type: 'number', min: '0', step: '0.01', required: true }; const automaticFee = fee => fee?.system === 'credit_card' || String(fee?.key || '').startsWith('card_fee:'); const categoryOf = kind => feeCategories[kind] || kind; function feeCategory(fee, config) { if (fee.key.startsWith('manual:') && config['custom_' + fee.key.slice(7)]) return 'custom_' + fee.key.slice(7); if (fee.key === 'shipping' || fee.key === 'box') return fee.key; if (String(fee.note || '').trim() === '编绳') return ''; return Fees.checkboxCategory(fee.note) || Fees.checkboxCategory(fee.sourceName); } function costSetup(input, state) { const config = Model.costConfig(state), presets = Model.newPresets(state, input.fee_items, true), originals = {}, rows = []; for (const raw of input.fee_items || []) { const fee = { ...raw, note: raw.note || Model.feeLabels[raw.key], edited: raw.edited ?? true }; const kind = Fees.presetKind(fee, { presets: config, recorded: true }); if (kind) originals[categoryOf(kind)] = fee; else rows.push(fee); } return { presets, originals, rows, originalChecked: { ...presets.checked } }; } function feeTotals(cost, input, state) { const { items, notes } = Model.readPresets({ presets: cost.presets, member: input.member }, state); const config = Model.costConfig(state); const presets = items.map(item => { const category = categoryOf(Fees.presetKind(item, { presets: config }) || feeCategory(item, config) || 'box'); const original = cost.originals[category]; return original || item; }); const others = cost.rows.map(row => { const date = row.date || input.fees_date || input.date; if (automaticFee(row)) return { ...row, ...(date ? { date } : {}) }; return { key: row.key, sourceName: row.sourceName || undefined, edited: !!row.edited, ...(row.expense_id ? { expense_id: row.expense_id } : {}), ...(date ? { date } : {}), ...(row.status === 'estimated' ? { status: 'estimated' } : {}), note: row.note, amount: row.amount, payer: row.payer, ...(row.funding ? { funding: row.funding } : {}), }; }); return { items: [...others, ...presets], notes }; } function EditableFees({ input, state, cost, update, inputChange, removeFee }) { const config = Model.costConfig(state), catalog = Fees.presetCatalog(config), { presets, rows, originals } = cost, configured = presets.configured; const { notes } = feeTotals(cost, input, state), own = Model.formMember(input, state); // 交付后改单沿用已入账项目的付款流水和日期。数量控件保留打开本单时的录入状态。 const setPreset = (kind, quantity, value) => { const name = quantity ? 'quantity' : 'checked'; update({ ...cost, presets: { ...presets, [name]: { ...presets[name], [kind]: value } } }); }; const patchRow = (index, patch) => update({ ...cost, rows: rows.map((row, i) => (i === index ? { ...row, ...patch, edited: true } : row)) }); return (

实际费用(内部)

已有费用保留原金额、付款人与支付日期;主动勾选后才替换同类,取消已勾选项会冲回对应成本。新增费用用下方默认日期。 客户单据不显示。

inputChange({ fees_date })} />
常用成本 · 按实际发生勾选

{configured ? '按当前店铺配置勾选;保留原记录的日期与付款人。' : '快递二选一,也可不选;已有费用保留原支付日期,取消后保存会冲回对应成本。'}

{Object.entries(catalog) .filter(([, row]) => row.enabled) .map(([kind, row]) => { const cat = categoryOf(kind), orig = originals[cat], count = presets.quantity[kind] || '1', checked = !!presets.checked[kind], matching = rows.filter(f => feeCategory(f, config) === cat), funded = matching.some(f => f.funding) || !!orig?.funding; const hint = funded ? '已有报销关联费用,请在原费用行核对' : matching.length ? configured ? '已有同类费用,勾选后替换;请核对下方原记录' : '已有' + ({ shipping: '快递', box: '包装', braiding: '店内钢绳', silverChain: '家里银链' }[cat] || '同类') + '费用' + (matching.length > 1 ? '(' + matching.length + '项)' : '') + ',勾选后替换' + (matching.length > 1 ? '全部' : '') : ''; const payer = row.payer === 'order' ? '订单归属人' : Model.memberName(state, row.payer); return (
{row.byQuantity && ( )}
); })}
{rows.map((row, i) => { const automatic = automaticFee(row), manual = !automatic && row.key.startsWith('manual:'); return (
{manual && ( patchRow(i, { note })} /> )} {automatic ? '已记录的信用卡收款手续费' : row.key.startsWith('charge:') ? '商品 ' + row.lineNumber + ' 的附加项目' : '整单费用'}
patchRow(i, { amount })} /> patchRow(i, { payer })} /> patchRow(i, { date })} /> {automatic ? ( 沿用已记录的手续费金额与费率,支付日期保留。 ) : ( )} {!automatic && row.funding && ( )}
); })}
); } function editPayload(input, fees, state, entry) { const lines = input.lines.map(line => ({ ...line, costLabor: line.costLabor?.mode === 'gram' ? line.costLabor : { mode: 'total' }, })); return { ...input, lines, fee_cost_mode: 'checkboxes', fee_items: feeTotals(fees, { ...input, member: entry.order.member }, state).items, }; } function LockLine({ entry, state, input, multi, index, update }) { const line = input.lines[index], raw = entry.order.lines[index], meta = priceLockOrderEditMeta(entry, index); const mat = multi ? priceLockOrderEditMaterial(input, index) : input.price_lock_material, extra = multi ? priceLockOrderEditExtra(input, index) : input.price_lock_extra_material, manual = mat.source === 'manual', pooledExtra = extra?.source === 'pool' && !!raw.priceLockExtraPool; const gram = line.costLabor?.mode === 'gram', payers = value => [['', '请选择'], ...Model.memberOptions(state, false, { selected: value })]; function change(linePatch = {}, material = mat, extraCost = extra) { const next = { ...line, ...linePatch }; const lines = input.lines.map((r, i) => i === index ? !multi ? next : { ...next, price_lock_material: material, ...(extraCost ? { price_lock_extra_material: extraCost } : {}) } : r, ); update({ lines, ...(!multi ? { price_lock_material: material, ...(extraCost ? { price_lock_extra_material: extraCost } : {}) } : {}), }); } function labor(mode, value) { const costLabor = { mode, ...(mode === 'gram' ? { rate: value ?? line.costLabor?.rate ?? '' } : {}) }; let total = line.costParts.labor; if (mode === 'gram') { try { const cost = LedgerCalc.purchaseCosts({ unit: line.unit, quantity: line.quantity, costParts: { material: '0', labor: '0', accessories: '0', other: '0' }, costMaterial: { mode: 'total' }, costLabor, }); total = cost.parts.labor === null ? '' : (cost.parts.labor / 100).toFixed(2); } catch { total = ''; } } change({ costLabor, costParts: { ...line.costParts, labor: total } }); } const sourceNote = manual ? meta.materialSource === 'pool' ? '改为手填后,释放' + (multi ? '本件' : '') + '原锁料池占用。请重新确认原锁料价与实际付款人。' : '按核实后的' + (multi ? '本件' : '') + '原锁料价与付款人更正成本,原锁日期保持不变。' : multi ? '保留本件原锁 ' + entry.priceLock.date + ' 的原料来源与成本。' : '保留原锁 ' + entry.priceLock.date + ' 的原料来源与成本;只改交付日期不会改用新日期料池。'; const sources = raw.priceLockPool?.materialSources || raw.materialPool?.materialSources; return (
{multi && (

商品 {index + 1} · {line.name}

{grams(raw.quantity)}g · 原锁销售金价 ¥{yuan(raw.goldPrice ?? 0)}/克 · 货盘{' '} {Model.pocketLabel(state, raw.pocket) || '未提供'}

)}

原锁金料与补重

change( {}, { ...mat, source, verified: false, ...(source === 'manual' && meta.materialSource === 'pool' ? { payer: '' } : {}), }, ) } />

{sourceNote} {!multi && !manual && !!sources?.length && ' ' + sources .map( s => (s.kind === 'personal_recovery' ? Model.memberName(state, s.member) + '个人回收料' : '公共料') + ' ' + grams(s.quantity) + 'g · ' + (s.amount == null ? '料费待补' : '¥' + yuan(s.amount)) + (s.averageRate == null ? '' : '(加权约 ¥' + materialPoolRate(s.averageRate) + '/克)'), ) .join(';') + '。'}

{extra && (

补重金料 {grams(meta.extraMg)}g

{raw.priceLockExtraPool && ( change({}, mat, { ...extra, source })} /> )}
change({}, mat, { ...extra, rate, verified: false })} />
{raw.priceLockExtraPool && ( )}
)}

交付进货成本

labor(mode)} /> labor('gram', rate)} /> change({ costParts: { ...line.costParts, labor: v } })} /> change({ costPayers: { ...line.costPayers, labor: v } })} /> change({ costParts: { ...line.costParts, accessories } })} /> change({ costParts: { ...line.costParts, other } })} /> change({ payer })} />
); } export function LockOrderEditor({ client, state, session, entry, serverFeedback, onDraft, onSave, onCancel }) { const [input, setInput] = useState(() => entry.inputs), [fees, setFees] = useState(() => costSetup(entry.inputs, state)); const [reason, setReason] = useState(entry.reason || ''), [verified, setVerified] = useState(!!entry.verified), [error, setError] = useState(''), [tags, setTags] = useState([]); const textarea = useRef(null), lastEntry = useRef(entry.id); useEffect(() => { let active = true; client .api('/api/order-note-tags') .then(r => { if (active) setTags(r.tags); }) .catch(err => { if (active) setError(err.message); }); return () => { active = false; }; }, [client, state.user.id]); const multi = input.lines.length > 1; const wire = editPayload(input, fees, state, entry); const approvedFinance = entry.priceLock.financeRequiresApproval && priceLockEditFinancialChanged(entry, wire); const approval = session.user.role === 'assistant' && (!entry.sameDayDirectEdit || !entry.directEditDate || entry.order.date !== entry.directEditDate || wire.date !== entry.directEditDate || approvedFinance); function persist(next, nextFees, newReason, checked) { const draft = editPayload(next, nextFees, state, entry); onDraft(draft, newReason, checked); } function update(fields) { const next = { ...input, ...fields }; setInput(next); setVerified(false); setError(''); persist(next, fees, reason, false); } function updateFees(value) { setFees(value); setVerified(false); setError(''); persist(input, value, reason, false); } function removeFee(index) { const key = fees.rows[index].key; const next = { ...input, lines: input.lines.map(line => ({ ...line, ...(line.charges ? { charges: line.charges.map(charge => key === 'charge:' + charge.id || (key === 'shipping' && Fees.normalize(charge.name) === '快递') ? { ...charge, costRemoved: true } : charge, ), } : {}), })), }; const nextFees = { ...fees, rows: fees.rows.filter((_, i) => i !== index) }; setInput(next); setFees(nextFees); setVerified(false); setError(''); persist(next, nextFees, reason, false); } function editReason(value) { setReason(value); persist(input, fees, value, verified); } function verify(value) { setVerified(value); persist(input, fees, reason, value); } let costs, previewError; try { costs = priceLockOrderEditPreview(wire, entry); } catch (err) { previewError = err.message; } async function save(event) { event.preventDefault(); try { if (entry.user !== client.user || lastEntry.current !== entry.id) throw new Error('请重新打开这张订单,再核对修改。'); if (entry.conflicted) throw new Error('订单已有新记录,请先读取最新订单并核对,填写内容已经保留。'); if (!reason.trim() || reason.trim().length > 200) throw new Error('请填写1~200字的修改原因。'); if (!verified) throw new Error('请先核实交付日期、实际成本及付款人,并勾选确认。'); const payload = validatePriceLockOrderEdit(wire, entry, state); setError(''); await onSave(payload, reason.trim(), true, approval); } catch (err) { setError(err.message); } } const filteredTags = Model.filterNoteTags(tags, input.internal_note || ''); return ( <>
EDIT ORDER

{approval ? '申请修改订单' : '修改订单'}

修改原单并重新核算,保留原单号与操作记录。

更正交付日期与实际成本,原锁日期、销售金价、克重和收付款保留。

交付与客户资料

原单号 {entry.order.paper_number || entry.order.number}
update({ date })} /> update({ customer })} />
客户类型
{[ ['new', '新客户'], ['returning', '老客户'], ].map(([key, text]) => ( ))}
update({ salesperson })} />

原锁日期 {entry.priceLock.date} ·{' '} {multi ? '共 ' + input.lines.length + '件' : entry.order.lines[0].name + ' · ' + grams(entry.order.lines[0].quantity) + 'g · 原锁销售金价 ¥' + yuan(entry.order.lines[0].goldPrice ?? 0) + '/克'}{' '} · 成交 {Model.orderAmount(entry.order.total, entry.order.rounding_mode)}