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 (
已有费用保留原金额、付款人与支付日期;主动勾选后才替换同类,取消已勾选项会冲回对应成本。新增费用用下方默认日期。
客户单据不显示。
实际费用(内部)
{grams(raw.quantity)}g · 原锁销售金价 ¥{yuan(raw.goldPrice ?? 0)}/克 · 货盘{' '} {Model.pocketLabel(state, raw.pocket) || '未提供'}
{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(';') + '。'}
沿用交付料池的成本和付款来源,不重复登记付款;更改交付日期时按对应日期料池重新核算。
)}修改原单并重新核算,保留原单号与操作记录。