Files
weiguang-jewelry-ledger/新账系统/web/src/pages/Orders/LockOrderEditor.tsx
T

1208 lines
47 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect, useRef, useState, type FormEvent } from 'react';
import type { EditInputs, EditFee, EditItem, LockMaterial, LockEntry, LockEditorProps } from './editTypes';
import type { LedgerState, PresetState } from '../../shared';
type CostKey = 'material' | 'labor' | 'accessories' | 'other';
type Preview = Record<CostKey | 'total' | 'profit' | 'fees', number>;
interface CostForm {
presets: PresetState;
originals: Record<string, EditFee>;
rows: EditFee[];
originalChecked: Record<string, boolean>;
}
type FinancialInput = Pick<EditInputs, 'lines' | 'fee_items' | 'price_lock_material' | 'price_lock_extra_material'> &
Partial<Pick<EditInputs, 'date' | 'fees_date' | 'fee_cost_mode'>>;
type FeeSnapshot = {
key: string;
expense_id: string;
date?: string;
note: string;
payer: string;
amount: string | number;
funding: Record<string, unknown> | null;
};
interface FinancialSnapshot {
fees: FeeSnapshot[];
date?: string;
fees_date?: string;
fee_cost_mode: string;
lines?: (FinancialSnapshot & { lineId?: string })[];
material?: object;
extra?: object | null;
costs?: object;
}
type UpdateInput = (fields: Partial<EditInputs>) => void;
import { Calc as LedgerCalc, Fees, Model, Values } from '../../shared';
import { Button } from '../Settings/controls';
import { Input, Choice } from './EditFields';
import { LedgerButton, LedgerInput, LedgerTextArea } from '../../components/BusinessControls';
const { yuan, grams, validateOrderIdentity } = Model;
const feeCategories: Record<string, string> = {
jd: 'shipping',
yt: 'shipping',
box: 'box',
steel: 'braiding',
silver: 'silverChain',
};
const validOrderDate = Values.validDate;
function priceLockEditAmount(value: unknown) {
try {
return LedgerCalc.cents(String(value), '成本');
} catch {
return String(value ?? '');
}
}
function priceLockOrderEditMeta(entry: LockEntry, index: number) {
return entry.priceLock.lines?.[index] || entry.priceLock;
}
function priceLockOrderEditMaterial(input: FinancialInput, index: number) {
return input.lines[index].price_lock_material || (input.lines.length === 1 ? input.price_lock_material : undefined);
}
function priceLockOrderEditExtra(input: FinancialInput, index: number) {
return (
input.lines[index].price_lock_extra_material ||
(input.lines.length === 1 ? input.price_lock_extra_material : undefined)
);
}
function priceLockEditFinancialValue(input: FinancialInput): FinancialSnapshot {
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: Partial<EditItem> = input?.lines?.[0] || {},
material: Partial<LockMaterial> = 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: LockEntry, input: EditInputs = entry.inputs) {
return (
JSON.stringify(priceLockEditFinancialValue(input)) !==
JSON.stringify(priceLockEditFinancialValue(entry?.originalInputs))
);
}
function priceLockEditGramCost(mg: number, rate: string) {
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: EditInputs, entry: LockEntry): Preview {
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'] as const) costs[key] += value[key];
});
const total = Object.values(costs).reduce((sum, value) => sum + value, 0);
return { ...costs, total, profit: entry.order.total - total };
}
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),
};
const total = Object.values(costs).reduce((sum, amount) => sum + amount, 0);
return { ...costs, total, profit: entry.order.total - total };
}
function materialPoolRate(value: number | null | undefined) {
return value == null ? '待补采购' : yuan(value);
}
function validatePriceLockOrderEdit(input: EditInputs, entry: LockEntry, state: LedgerState): EditInputs {
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', '其他货品成本'],
] as const)
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: EditFee) => fee?.system === 'credit_card' || String(fee?.key || '').startsWith('card_fee:');
const categoryOf = (kind: string) => feeCategories[kind] || kind;
function feeCategory(fee: EditFee, config: Record<string, unknown>) {
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: EditInputs, state: LedgerState): CostForm {
const config = Model.costConfig(state),
presets = Model.newPresets(state, input.fee_items, true),
originals: Record<string, EditFee> = {},
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: CostForm, input: EditInputs, state: LedgerState) {
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,
}: {
input: EditInputs;
state: LedgerState;
cost: CostForm;
update: (cost: CostForm) => void;
inputChange: UpdateInput;
removeFee: (index: number) => void;
}) {
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: string, quantity: boolean, value: string | boolean) => {
const name = quantity ? 'quantity' : 'checked';
update({ ...cost, presets: { ...presets, [name]: { ...presets[name], [kind]: value } } });
};
const patchRow = (index: number, patch: Partial<EditFee>) =>
update({ ...cost, rows: rows.map((row, i) => (i === index ? { ...row, ...patch, edited: true } : row)) });
return (
<section className="panel internal">
<div className="panel-title">
<h2>实际费用(内部)</h2>
<Button
action="add-fee"
onClick={() =>
update({
...cost,
rows: [
...rows,
{
key: 'manual:' + crypto.randomUUID(),
note: '其他费用',
amount: '',
payer: own,
status: 'estimated',
edited: true,
date: input.fees_date || input.date,
},
],
})
}
>
+ 添加其他成本
</Button>
</div>
<p className="small muted">
已有费用保留原金额、付款人与支付日期;主动勾选后才替换同类,取消已勾选项会冲回对应成本。新增费用用下方默认日期。
客户单据不显示。
</p>
<Input
label="新增费用默认支付日期"
name="fees_date"
type="date"
value={input.fees_date || input.date}
required
max={state.today}
onChange={fees_date => inputChange({ fees_date })}
/>
<fieldset
id="order-cost-presets"
className="order-cost-presets"
data-cost-editing="true"
data-configured={configured || undefined}
>
<legend>常用成本 · 按实际发生勾选</legend>
<p className="small muted">
{configured
? '按当前店铺配置勾选;保留原记录的日期与付款人。'
: '快递二选一,也可不选;已有费用保留原支付日期,取消后保存会冲回对应成本。'}
</p>
<div className="order-cost-options">
{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 (
<div key={kind} className="order-cost-box">
<label className="order-cost-option">
<LedgerInput
type="checkbox"
name={'cost_' + kind}
checked={checked}
disabled={funded}
onChange={e => setPreset(kind, false, e.target.checked)}
/>
<span>
<strong>{row.name}</strong>
<span className="order-cost-price">
{row.amount}元{row.byQuantity ? '/个' : ''}
</span>
<small>
{!configured && kind === 'yt'
? Model.memberName(state, orig?.payer || (row.payer === 'order' ? own : row.payer)) +
'付款' +
(checked && !!orig ? '(原费用)' : row.payer === 'order' ? '(订单归属人)' : '')
: payer + '付款'}
</small>
{orig?.date && <small>原支付日期 {orig.date}</small>}
<small>{hint}</small>
</span>
</label>
{row.byQuantity && (
<label className="order-cost-quantity">
{configured ? '数量(个)' : '盒子数量(个)'}
<LedgerInput
type="number"
name={'cost_' + kind + '_quantity'}
min="1"
max="333333333"
step="1"
inputMode="numeric"
value={count}
required={!!cost.originalChecked[kind] && !funded}
disabled={!cost.originalChecked[kind] || funded}
onChange={e => setPreset(kind, true, e.target.value)}
/>
<small>{notes[kind] || '勾选后计费'}</small>
</label>
)}
</div>
);
})}
</div>
</fieldset>
<div id="fee-rows" className="fee-grid" data-fee-cost-mode="checkboxes">
{rows.map((row, i) => {
const automatic = automaticFee(row),
manual = !automatic && row.key.startsWith('manual:');
return (
<div className={'fee-row' + (automatic ? ' fee-automatic' : '')} key={row.key} data-fee={row.key}>
<div className="fee-title">
<strong className="fee-name" hidden={manual}>
{row.note}
</strong>
{manual && (
<Input
label="费用项目名称"
name="feeNote"
value={row.note}
required
maxLength={150}
onChange={note => patchRow(i, { note })}
/>
)}
<span className="small muted fee-source">
{automatic
? '已记录的信用卡收款手续费'
: row.key.startsWith('charge:')
? '商品 ' + row.lineNumber + ' 的附加项目'
: '整单费用'}
</span>
</div>
<Input
label={automatic ? '手续费(元,自动)' : '实际成本(元)'}
name="feeAmount"
value={row.amount}
{...moneyProps}
readOnly={automatic}
placeholder={automatic ? undefined : '没有成本填0'}
onChange={amount => patchRow(i, { amount })}
/>
<Choice
label="费用付款人"
name="feePayer"
value={row.payer}
options={Model.memberOptions(state, true, { selected: row.payer })}
onChange={payer => patchRow(i, { payer })}
/>
<Input
label="本笔费用支付日期"
name="feeDate"
type="date"
required
value={row.date || input.fees_date || input.date}
max={state.today}
readOnly={automatic}
onChange={date => patchRow(i, { date })}
/>
{automatic ? (
<small className="muted">沿用已记录的手续费金额与费率,支付日期保留。</small>
) : (
<Button action="remove-fee" className="quiet" onClick={() => removeFee(i)}>
移除费用
</Button>
)}
{!automatic && row.funding && (
<LedgerInput
type="hidden"
className="cost-funding"
data-component="fee"
data-reference={JSON.stringify(row.funding)}
/>
)}
</div>
);
})}
</div>
<div className="small" id="fees-total"></div>
</section>
);
}
function editPayload(input: EditInputs, fees: CostForm, state: LedgerState, entry: LockEntry): EditInputs {
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,
}: {
entry: LockEntry;
state: LedgerState;
input: EditInputs;
multi: boolean;
index: number;
update: UpdateInput;
}) {
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: string): [string, string][] => [
['', '请选择'],
...Model.memberOptions(state, false, { selected: value }),
];
function change(linePatch: Partial<EditItem> = {}, 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: string, value?: string) {
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 (
<div
data-lock-edit-line={multi ? '' : undefined}
data-line-id={multi ? line.lineId : undefined}
className={multi ? 'lock-edit-product' : undefined}
>
{multi && (
<div className="panel lock-edit-product-heading">
<h2>
商品 {index + 1} · {line.name}
</h2>
<p className="small muted">
{grams(raw.quantity)}g · 原锁销售金价 ¥{yuan(raw.goldPrice ?? 0)}/克 · 货盘{' '}
{Model.pocketLabel(state, raw.pocket) || '未提供'}
</p>
</div>
)}
<section className="panel internal price-lock-edit-costs">
<h2>原锁金料与补重</h2>
<Choice
label="原锁料费来源"
name="lock_material_source"
value={mat.source}
options={
meta.materialSource === 'pool'
? [['pool', '保留原锁料池'], ...(meta.canSwitchToManual ? [['manual', '改为手填原锁料价'] as const] : [])]
: [['manual', '手填原锁料价']]
}
onChange={source =>
change(
{},
{
...mat,
source,
verified: false,
...(source === 'manual' && meta.materialSource === 'pool' ? { payer: '' } : {}),
},
)
}
/>
<p
id={multi ? undefined : 'lock-edit-material-note'}
data-lock-edit-part={multi ? 'material-note' : undefined}
className="note"
aria-live="polite"
>
{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(';') +
'。'}
</p>
<div
id={multi ? undefined : 'lock-edit-manual-material'}
data-lock-edit-part={multi ? 'manual-material' : undefined}
hidden={!manual}
>
<div className="grid two">
<Input
label="原锁进货料价(元/克)"
name="lock_material_rate"
value={mat.rate ?? ''}
{...moneyProps}
required={manual}
disabled={!manual}
onChange={rate => change({}, { ...mat, rate, verified: false })}
/>
<Choice
label="原锁料费实际付款人"
name="lock_material_payer"
value={mat.payer || ''}
options={payers(mat.payer)}
required={manual}
disabled={!manual}
onChange={payer => change({}, { ...mat, payer, verified: false })}
/>
</div>
<label className="check">
<LedgerInput
type="checkbox"
name="lock_material_verified"
checked={!!mat.verified}
required={manual}
disabled={!manual}
onChange={e => change({}, { ...mat, verified: e.target.checked })}
/>
已核实手填原锁料费和实际付款人。
</label>
</div>
{extra && (
<div className="lock-edit-extra">
<h3>补重金料 {grams(meta.extraMg)}g</h3>
{raw.priceLockExtraPool && (
<Choice
label="补重料费来源"
name="lock_extra_source"
value={extra.source}
options={[
['pool', '保留交付料池'],
['manual', '改为手填补重料价'],
]}
onChange={source => change({}, mat, { ...extra, source })}
/>
)}
<div className="grid two">
<Input
label="补重进货料价(元/克)"
name="lock_extra_rate"
value={extra.rate ?? ''}
{...moneyProps}
hidden={pooledExtra}
onChange={rate => change({}, mat, { ...extra, rate, verified: false })}
/>
<Choice
label="补重料费实际付款人"
name="lock_extra_payer"
value={extra.payer || ''}
options={payers(extra.payer)}
hidden={pooledExtra}
onChange={payer => change({}, mat, { ...extra, payer, verified: false })}
/>
</div>
<label className="check" hidden={pooledExtra}>
<LedgerInput
type="checkbox"
name="lock_extra_verified"
checked={!!extra.verified}
disabled={pooledExtra}
onChange={e => change({}, mat, { ...extra, verified: e.target.checked })}
/>
已核实补重料费和实际付款人。
</label>
{raw.priceLockExtraPool && (
<p className="note" data-extra-pool-note hidden={!pooledExtra}>
沿用交付料池的成本和付款来源,不重复登记付款;更改交付日期时按对应日期料池重新核算。
</p>
)}
</div>
)}
</section>
<section className="panel internal price-lock-edit-costs">
<h2>交付进货成本</h2>
<div className="grid three">
<Choice
label="进货工费方式"
name="lock_cost_labor_mode"
options={[
['total', '总工费'],
['gram', '克工费'],
]}
value={line.costLabor?.mode || 'total'}
onChange={mode => labor(mode)}
/>
<Input
label="进货克工费(元/克)"
name="lock_cost_labor_rate"
value={line.costLabor?.rate ?? ''}
{...moneyProps}
required={gram}
hidden={!gram}
onChange={rate => labor('gram', rate)}
/>
<Input
label="进货总工费(元)"
name="lock_cost_labor_total"
value={line.costParts?.labor ?? ''}
{...moneyProps}
readOnly={gram}
onChange={v => change({ costParts: { ...line.costParts, labor: v } })}
/>
<Choice
label="进货工费付款人"
name="lock_cost_labor_payer"
value={line.costPayers?.labor || ''}
options={payers(line.costPayers?.labor)}
onChange={v => change({ costPayers: { ...line.costPayers, labor: v } })}
/>
<Input
label="配件成本(元)"
name="lock_cost_accessories"
value={line.costParts?.accessories ?? '0'}
{...moneyProps}
onChange={accessories => change({ costParts: { ...line.costParts, accessories } })}
/>
<Input
label="其他货品成本(元)"
name="lock_cost_other"
value={line.costParts?.other ?? '0'}
{...moneyProps}
onChange={other => change({ costParts: { ...line.costParts, other } })}
/>
<Choice
label="配件及其他成本付款人"
name="lock_cost_payer"
value={line.payer || ''}
options={payers(line.payer)}
onChange={payer => change({ payer })}
/>
</div>
</section>
</div>
);
}
export function LockOrderEditor({
client,
state,
session,
entry,
serverFeedback,
onDraft,
onSave,
onCancel,
}: LockEditorProps) {
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<string[]>([]);
const textarea = useRef<HTMLTextAreaElement>(null),
lastEntry = useRef(entry.id);
useEffect(() => {
let active = true;
client
.api<{ tags: string[] }>('/api/order-note-tags')
.then(r => {
if (active) setTags(r.tags);
})
.catch(err => {
if (active) setError(err instanceof Error ? err.message : String(err));
});
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: EditInputs, nextFees: CostForm, newReason: string, checked: boolean) {
const draft = editPayload(next, nextFees, state, entry);
onDraft(draft, newReason, checked);
}
function update(fields: Partial<EditInputs>) {
const next = { ...input, ...fields };
setInput(next);
setVerified(false);
setError('');
persist(next, fees, reason, false);
}
function updateFees(value: CostForm) {
setFees(value);
setVerified(false);
setError('');
persist(input, value, reason, false);
}
function removeFee(index: number) {
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: string) {
setReason(value);
persist(input, fees, value, verified);
}
function verify(value: boolean) {
setVerified(value);
persist(input, fees, reason, value);
}
let costs: Preview | undefined,
previewError = '';
try {
costs = priceLockOrderEditPreview(wire, entry);
} catch (err) {
previewError = err instanceof Error ? err.message : String(err);
}
async function save(event: FormEvent<HTMLFormElement>) {
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 instanceof Error ? err.message : String(err));
}
}
const filteredTags = Model.filterNoteTags(tags, input.internal_note || '');
return (
<>
<div className="page-heading">
<div>
<div className="eyebrow">EDIT ORDER</div>
<h1 id="order-edit-title">{approval ? '申请修改订单' : '修改订单'}</h1>
<p className="muted">修改原单并重新核算,保留原单号与操作记录。</p>
</div>
</div>
<div className="note" id="order-edit-save-intro">
更正交付日期与实际成本,原锁日期、销售金价、克重和收付款保留。
</div>
<form id="order-edit-meta-form" data-price-lock-edit="true" onSubmit={save}>
<section className="panel">
<div className="panel-title">
<h2>交付与客户资料</h2>
<span className="small muted">原单号 {entry.order.paper_number || entry.order.number}</span>
</div>
<div className="grid three">
<Input
label="交付日期"
name="date"
type="date"
value={input.date}
min={entry.priceLock.date}
max={state.today}
required
onChange={date => update({ date })}
/>
<Input
label="客户称呼/代号(必填)"
name="customer"
value={input.customer}
required
maxLength={60}
onChange={customer => update({ customer })}
/>
<fieldset className="customer-type-field">
<legend>客户类型</legend>
<div className="customer-type-options">
{[
['new', '新客户'],
['returning', '老客户'],
].map(([key, text]) => (
<label key={key} title={key === 'new' ? '首次成交' : '再次成交'}>
<LedgerInput
type="radio"
name="customer_type"
value={key}
checked={key === input.customer_type}
onChange={() => update({ customer_type: key })}
/>
<span>{text}</span>
</label>
))}
</div>
</fieldset>
<Input
label="开单人(必填)"
name="salesperson"
value={input.salesperson}
required
maxLength={30}
onChange={salesperson => update({ salesperson })}
/>
</div>
<p className="small muted">
原锁日期 {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)}
</p>
<label>
客户单备注
<LedgerTextArea
name="note"
maxLength={240}
rows={2}
value={input.note || ''}
onChange={e => update({ note: e.target.value })}
/>
</label>
<label>
内部备注(客户不可见)<span className="small muted">必填,至少3个字符(含#号),最多500字</span>
<LedgerTextArea
name="internal_note"
ref={textarea}
maxLength={500}
rows={3}
required
minLength={3}
placeholder="仅供内部跟进,不会出现在客户销售单或打印件中"
value={input.internal_note || ''}
onChange={e => update({ internal_note: e.target.value })}
/>
</label>
<div className="order-note-tags">
<p className="small muted">
输入 #词语 添加标签,例如 #补货、#客户自提。保存订单后可复用,点击下方标签即可填入。
</p>
<div data-order-note-tags className="order-note-tag-options" aria-label="内部备注快捷标签">
{filteredTags.length ? (
filteredTags.map(tag => (
<LedgerButton
type="button"
className="quiet"
key={tag}
data-order-note-tag={tag}
onClick={() => {
try {
update({ internal_note: Model.insertNoteTag(input.internal_note, tag) });
textarea.current?.focus();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
}
}}
>
{tag}
</LedgerButton>
))
) : (
<span className="small muted">
{Model.noteTagQuery(input.internal_note)
? '没有匹配标签,可继续输入新标签。'
: '暂无已保存标签,填写 #词语 并保存订单后即可复用。'}
</span>
)}
</div>
</div>
</section>
{input.lines.map((line, index) => (
<LockLine key={line.lineId || index} {...{ entry, state, input, multi, index, update }} />
))}
<EditableFees
state={state}
input={{ ...input, member: entry.order.member }}
cost={fees}
update={updateFees}
inputChange={update}
removeFee={removeFee}
/>
<section className="panel">
<h2>{multi ? '整单更正后成本预览' : '更正后成本预览'}</h2>
<div
id="lock-edit-cost-preview"
className="lock-edit-cost-preview"
style={{ display: 'flex', flexWrap: 'wrap', gap: '12px 26px' }}
aria-live="polite"
>
{costs
? (
[
['料费', costs.material],
['进货工费', costs.labor],
['配件及其他', costs.accessories + costs.other],
['实际费用', costs.fees],
['成本合计', costs.total],
['利润预览', costs.profit],
] as const
).map(([text, value]) => (
<span key={text}>
{text} <strong>¥{yuan(value)}</strong>
</span>
))
: previewError}
</div>
{!multi && <p className="small muted">按本页成本预估,保存或复核同意后按原账更新利润。</p>}
</section>
<section className="panel">
<div className="note" data-order-edit-approval-note hidden={state.user.role !== 'assistant'}>
{approval
? approvedFinance
? entry.priceLock.approvalReason || entry.approvalReason || '涉及历史锁价购料或料池,请提交店主复核。'
: '提交的是修改申请。店主复核同意后才生效,填写内容已经保留。'
: '今天的订单可直接保存,改为其他日期须店主复核。'}
</div>
<label>
修改原因
<LedgerTextArea
name="edit_reason"
required
maxLength={200}
rows={2}
placeholder="例如:更正交付日期、进货工费或料费付款人"
value={reason}
onChange={e => editReason(e.target.value)}
/>
</label>
<label className="check">
<LedgerInput
type="checkbox"
name="edit_verified"
required
checked={verified}
onChange={e => verify(e.target.checked)}
/>
已核实交付日期、实际成本与付款人,原锁销售条件和收付款保持不变。
</label>
<p id="order-edit-save-status" className="small muted" role="status" aria-live="polite" hidden />
<div className="form-actions">
<Button action="cancel-order-edit" className="quiet" onClick={onCancel}>
取消修改
</Button>
<LedgerButton
className="primary"
type="submit"
data-order-edit-submit
disabled={client.busy || !!client.pending() || entry.conflicted}
>
{approval ? '提交修改申请' : '保存修改'}
</LedgerButton>
</div>
<div id="order-error" aria-live="polite">
{serverFeedback}
{error && <div className="error">{error}</div>}
</div>
</section>
</form>
</>
);
}
export default LockOrderEditor;