1063 lines
41 KiB
TypeScript
1063 lines
41 KiB
TypeScript
import type { ChangeEvent, FormEvent, InputHTMLAttributes, SelectHTMLAttributes } from 'react';
|
||
import type { ApiError } from '../../lib/api';
|
||
import type { Choice } from './controls';
|
||
import type {
|
||
EditDetail,
|
||
Draft,
|
||
RecoveryModel,
|
||
Derived,
|
||
TextField,
|
||
PageProps,
|
||
Deposit,
|
||
Input,
|
||
Saved,
|
||
QuoteItem,
|
||
MaterialPool,
|
||
ExtraKinds,
|
||
ExtraFields,
|
||
ProductDraft,
|
||
PoolChoice,
|
||
} from './types';
|
||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||
import { Model, Cards } from '../../shared';
|
||
import { grams } from '../../lib/format';
|
||
import { memberAccountPrefix, recoveryModel } from './model';
|
||
import { LegacyCount, Settlement, loadDraft, money, options, pocketOptions, rowLabel } from './controls';
|
||
import { IndependentItems } from './IndependentItems';
|
||
import { localMaterialNote, quotedMaterialNote } from './materialPreview';
|
||
import { useRead } from '../Inventory/data';
|
||
|
||
function normalize(draft: Draft) {
|
||
const result = { ...draft, customer_type: draft.mode === 'direct' ? '' : draft.customer_type };
|
||
for (const [key, value] of Object.entries(result))
|
||
if (typeof value === 'string') Object.assign(result, { [key]: value.trim() });
|
||
if (draft.old_lines?.length)
|
||
result.old_lines = [
|
||
{
|
||
...draft.old_lines[0],
|
||
name: draft.old_name,
|
||
incoming_weight: draft.incoming_weight,
|
||
melted_weight: draft.melted_weight,
|
||
purity: draft.purity,
|
||
},
|
||
...draft.old_lines.slice(1),
|
||
];
|
||
if (draft.charges)
|
||
result.charges = [
|
||
...(draft.charges.length || Number(draft.charge_amount) > 0
|
||
? [{ name: draft.charge_name, amount: draft.charge_amount }]
|
||
: []),
|
||
...draft.charges.slice(1),
|
||
];
|
||
if (draft.fee_items)
|
||
result.fee_items = [
|
||
...(draft.fee_items.length || Number(draft.fee_amount) > 0
|
||
? [
|
||
{
|
||
...draft.fee_items[0],
|
||
key: draft.fee_items[0]?.key || 'other',
|
||
note: draft.fee_note,
|
||
amount: draft.fee_amount,
|
||
payer: draft.fee_payer,
|
||
},
|
||
]
|
||
: []),
|
||
...draft.fee_items.slice(1),
|
||
];
|
||
return result;
|
||
}
|
||
function derive(model: RecoveryModel, raw: Draft): Derived {
|
||
if (raw.independent_products && raw.mode === 'exchange') {
|
||
const parts = [raw, ...(raw.extra_products || [])].map((item, index) =>
|
||
derive(model, {
|
||
...raw,
|
||
...item,
|
||
cost_payer: index === 0 ? raw.cost_payer : item.labor_payer,
|
||
independent_products: false,
|
||
extra_products: [],
|
||
charges: [],
|
||
fee_items: [],
|
||
charge_amount: '0',
|
||
fee_amount: '0',
|
||
rounding_mode: 'cent',
|
||
discount: '0',
|
||
}),
|
||
);
|
||
const draft = {
|
||
...raw,
|
||
...parts[0].draft,
|
||
charge_amount: raw.charge_amount,
|
||
fee_amount: raw.fee_amount,
|
||
charges: raw.charges,
|
||
fee_items: raw.fee_items,
|
||
rounding_mode: raw.rounding_mode,
|
||
discount: raw.discount,
|
||
independent_products: true,
|
||
extra_products: parts.slice(1).map(x => x.draft),
|
||
};
|
||
try {
|
||
const input = model.input(draft, { quote: true });
|
||
return { draft, parts, input, q: model.calculate(input), error: '' };
|
||
} catch (error) {
|
||
return { draft, parts, input: null, q: null, error: (error as Error).message };
|
||
}
|
||
}
|
||
|
||
let draft = normalize(raw),
|
||
old = null,
|
||
newMg = null,
|
||
q = null,
|
||
input = null,
|
||
error;
|
||
try {
|
||
old = model.calculate(
|
||
model.input(
|
||
{
|
||
...draft,
|
||
mode: 'direct',
|
||
buy_rate: '1',
|
||
buy_total: '1',
|
||
buy_total_manual: true,
|
||
...(draft.mode === 'exchange' && draft.old_source === 'deposit'
|
||
? {
|
||
old_lines: [
|
||
{
|
||
name: '客户寄存料',
|
||
incoming_weight: draft.deposit_weight,
|
||
melted_weight: draft.deposit_weight,
|
||
purity: '100',
|
||
},
|
||
],
|
||
}
|
||
: {}),
|
||
},
|
||
{ quote: true },
|
||
),
|
||
);
|
||
} catch {
|
||
// 草稿可以缺少旧料行;下方完整试算会显示对应的输入错误。
|
||
}
|
||
if (draft.mode === 'exchange') {
|
||
try {
|
||
newMg = model.newWeight(draft);
|
||
} catch {
|
||
// 新料未填全时保留空的克重预览,下方完整试算给出提示。
|
||
}
|
||
}
|
||
if (old && newMg !== null && !draft.depreciation_manual)
|
||
draft = { ...draft, depreciation_weight: grams(Math.min(old.oldMg, newMg)) };
|
||
const hasBuy = draft.mode !== 'exchange' || !!(old && newMg !== null && old.oldMg > newMg),
|
||
diff = draft.mode === 'exchange' && !!(old && newMg !== null && newMg > old.oldMg);
|
||
if (!hasBuy) draft = { ...draft, buy_total_manual: false, buy_total: '0.00' };
|
||
try {
|
||
input = model.input(draft, { quote: true });
|
||
q = model.calculate(input);
|
||
error = '';
|
||
if (!draft.buy_total_manual) draft = { ...draft, buy_total: (q.defaultPurchaseAmount / 100).toFixed(2) };
|
||
} catch (e) {
|
||
error = (e as Error).message;
|
||
}
|
||
return { draft, old, newMg, q, input, error, hasBuy, diff };
|
||
}
|
||
function RecoveryCardFee({ state, edit, net }: { state: PageProps['state']; edit: EditDetail | null; net: number }) {
|
||
const rate = edit ? edit.record.credit_card_rate_permille : state.shopSettings?.creditCardRatePermille;
|
||
const unavailable = <p role="status">信用卡手续费率未能确认,请重新读取后核对。</p>;
|
||
if (rate == null) return unavailable;
|
||
let fee;
|
||
try {
|
||
fee = Cards.amount(net, rate);
|
||
} catch {
|
||
return unavailable;
|
||
}
|
||
return (
|
||
<p>
|
||
内部信用卡手续费:{money(net)} × {rate}‰ = {money(fee)},由{Model.memberName(state, 'owner')}
|
||
承担。客户结算金额不变。
|
||
</p>
|
||
);
|
||
}
|
||
|
||
const basicMethods = ['微信', '支付宝', '现金'];
|
||
export function RecoveryForm({
|
||
client,
|
||
state,
|
||
edit,
|
||
materials = [],
|
||
deposit,
|
||
saved,
|
||
exitEdit,
|
||
refreshEdit,
|
||
}: PageProps & {
|
||
edit: EditDetail | null;
|
||
materials?: Deposit[];
|
||
deposit(): void;
|
||
saved(input: Input, result: Saved): void;
|
||
exitEdit(): void;
|
||
refreshEdit(): Promise<EditDetail>;
|
||
}) {
|
||
const model = useMemo(() => recoveryModel(state, edit), [state, edit]),
|
||
key = 'mm-recovery-draft-' + state.user.id;
|
||
const editKey = edit ? 'mm-recovery-edit-' + state.user.id + '-' + edit.id : null;
|
||
const existing = useMemo(() => {
|
||
const v = editKey ? loadDraft<{ id: string; draft: Draft; revision: number; reason?: string }>(editKey) : null;
|
||
return v?.id === edit?.id && v?.draft?.mode === edit?.inputs?.mode && v?.draft?.member === edit?.inputs?.member
|
||
? v
|
||
: null;
|
||
}, [edit, editKey]);
|
||
const [raw, setRaw] = useState<Draft>(() => {
|
||
if (edit)
|
||
return {
|
||
...(existing?.draft || model.forEdit(edit.inputs)),
|
||
customer_type: existing?.draft?.customer_type || '',
|
||
change_reason: existing?.reason || '',
|
||
verified: false,
|
||
};
|
||
const stored = loadDraft<Partial<Draft>>(key);
|
||
if (stored?.independent_products && !localStorage.getItem(key + '-before-shared-old'))
|
||
localStorage.setItem(key + '-before-shared-old', JSON.stringify(stored));
|
||
const d = model.sharedDraft({
|
||
...model.defaults(),
|
||
shared_old_notice: '',
|
||
customer_type: '',
|
||
...stored,
|
||
verified: false,
|
||
});
|
||
if (state.user.role !== 'owner') d.member = Model.currentMember(state);
|
||
return d;
|
||
});
|
||
const [error, setError] = useState(''),
|
||
[quote, setQuote] = useState<{ signature?: string; text?: string; materialText?: string; value?: QuoteItem }>({}),
|
||
[rate, setRate] = useState<{ name?: TextField; index?: number; text?: string }>({}),
|
||
[conflict, setConflict] = useState<{ latest?: EditDetail } | null>(
|
||
existing && existing.revision !== edit?.revision ? {} : null,
|
||
),
|
||
[revision, setRevision] = useState(existing?.revision ?? edit?.revision);
|
||
const { draft: d, old, newMg, q, input, error: calcError, hasBuy, diff, parts } = derive(model, raw),
|
||
exchange = d.mode === 'exchange',
|
||
disabled = client.busy || !!client.pending(),
|
||
net = q?.netSettlement ?? (exchange ? 0 : -1),
|
||
card = net > 0 && d.payment_method === '信用卡';
|
||
const signature = input && q ? JSON.stringify(edit ? { ...input, revision } : input) : '',
|
||
live = useRef<Draft | null>(raw);
|
||
useEffect(() => {
|
||
live.current = raw;
|
||
if (edit)
|
||
localStorage.setItem(
|
||
editKey!,
|
||
JSON.stringify({ id: edit.id, revision, draft: raw, reason: raw.change_reason || '' }),
|
||
);
|
||
else localStorage.setItem(key, JSON.stringify(raw));
|
||
return () => {
|
||
live.current = null;
|
||
};
|
||
}, [edit, editKey, key, raw, revision]);
|
||
const quoteUrl = edit ? '/api/recoveries/' + encodeURIComponent(edit.id) + '/quote' : '/api/recoveries/quote',
|
||
expected = q?.netSettlement,
|
||
differenceMg = q?.differenceMg;
|
||
useEffect(() => {
|
||
if (!signature || conflict) return;
|
||
let valid = true;
|
||
const timer = setTimeout(async () => {
|
||
try {
|
||
const payload: Input = JSON.parse(signature),
|
||
value = await client.api<QuoteItem>(quoteUrl, payload);
|
||
if (!Number.isSafeInteger(value.netSettlement) || value.netSettlement !== expected)
|
||
throw new Error('结算规则已更新,请重新读取页面再核对。');
|
||
if (!valid) return;
|
||
const materialText = await quotedMaterialNote(client, state, payload, value, differenceMg!, edit);
|
||
if (valid) setQuote({ signature, text: '结算已核对;保存时按最新账务记录确认。', materialText, value });
|
||
} catch (e) {
|
||
if (valid)
|
||
setQuote({
|
||
signature,
|
||
text:
|
||
(e as Error).name === 'AbortError'
|
||
? '结算核对超时,保存时将再次核验。'
|
||
: '结算核对:' + (e as Error).message,
|
||
});
|
||
}
|
||
}, 350);
|
||
return () => {
|
||
valid = false;
|
||
clearTimeout(timer);
|
||
};
|
||
}, [client, state, signature, expected, differenceMg, quoteUrl, edit, conflict]);
|
||
const pools =
|
||
useRead<{ rows: MaterialPool[] }>(client, exchange ? '/api/material-pools' : null, 0)?.value?.rows || [],
|
||
members = Model.memberOptions(state),
|
||
recipients = members.map(([k, t]) => [memberAccountPrefix(k), t]);
|
||
function setField<K extends keyof Draft>(k: K, v: Draft[K], index = -1) {
|
||
setError('');
|
||
setRaw(previous => {
|
||
const next = { ...previous },
|
||
row = index < 0 ? next : { ...previous.extra_products![index] };
|
||
row[k] = v;
|
||
if (k === 'incoming_weight' && !row.melted_manual) row.melted_weight = String(v);
|
||
if (k === 'melted_weight') row.melted_manual = true;
|
||
if (k === 'buy_total') row.buy_total_manual = true;
|
||
if (k === 'depreciation_weight') row.depreciation_manual = true;
|
||
if (k === 'member')
|
||
Object.assign(next, {
|
||
payer: v,
|
||
material_payer: v,
|
||
labor_payer: v,
|
||
fee_payer: v,
|
||
payment_recipient: memberAccountPrefix(String(v)),
|
||
});
|
||
if (k === 'date' && (!row.material_pool_id || row.material_pool_id > String(v))) row.material_pool_id = String(v);
|
||
if (index >= 0) next.extra_products = next.extra_products!.map((item, i) => (i === index ? row : item));
|
||
return next;
|
||
});
|
||
}
|
||
function add() {
|
||
if ((d.extra_products?.length || 0) >= 59) {
|
||
setError('每单最多60件新货。');
|
||
return;
|
||
}
|
||
setRaw({
|
||
...d,
|
||
extra_products: [
|
||
...(d.extra_products || []),
|
||
{ ...model.defaults('exchange'), labor_rate: '0', cost_labor_value: '0', labor_payer: d.member },
|
||
],
|
||
});
|
||
}
|
||
function remove(i: number) {
|
||
setRaw({ ...d, extra_products: d.extra_products!.filter((_, index) => index !== i) });
|
||
}
|
||
async function daily(name: TextField, index = -1) {
|
||
const target = live.current;
|
||
setRate({ name, index, text: '正在读取当日加权料价…' });
|
||
try {
|
||
const v = await client.api<MaterialPool & { averageRate: number; totalAmount: number }>(
|
||
'/api/material-pools/' + encodeURIComponent(d.date) + '?member=' + encodeURIComponent(d.member),
|
||
);
|
||
if (!live.current) return;
|
||
if (live.current !== target) throw new Error('表单已变化,请重新点击带入料价。');
|
||
if (
|
||
v.id !== d.date ||
|
||
v.date !== d.date ||
|
||
!Number.isSafeInteger(v.averageRate) ||
|
||
v.averageRate <= 0 ||
|
||
!Number.isSafeInteger(v.totalMg) ||
|
||
v.totalMg <= 0 ||
|
||
!Number.isSafeInteger(v.totalAmount)
|
||
)
|
||
throw new Error(d.date + ' 暂无可用的公共加权料价,请手填或先补录购料。');
|
||
const value = (v.averageRate / 100).toFixed(2);
|
||
setField(name, value, index);
|
||
setField('verified', false);
|
||
if (name === 'buy_rate') setField('buy_total_manual', false, index);
|
||
setRate({ name, index, text: '已带入 ' + d.date + ' 公共加权 ¥' + value + '/克,可继续手改。' });
|
||
} catch (e) {
|
||
setRate({ name, index, text: (e as Error).message });
|
||
}
|
||
}
|
||
function fields(row: ProductDraft = d, index = -1, off = false) {
|
||
const prefix = index < 0 ? '' : 'extra_',
|
||
attrs = (name: TextField) => ({
|
||
name: prefix + name,
|
||
value: row[name] ?? '',
|
||
onChange: (e: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) =>
|
||
setField(name, e.target.value, index),
|
||
disabled: off,
|
||
});
|
||
const text = (
|
||
title: string,
|
||
k: TextField,
|
||
limit: number,
|
||
attrsMore: InputHTMLAttributes<HTMLInputElement> = {},
|
||
) => (
|
||
<label>
|
||
{title}
|
||
<input
|
||
type="text"
|
||
{...attrs(k)}
|
||
value={(index < 0 ? raw : raw.extra_products![index])[k] ?? ''}
|
||
maxLength={limit}
|
||
{...attrsMore}
|
||
/>
|
||
</label>
|
||
);
|
||
const num = (title: string, k: TextField, places = 2, props: InputHTMLAttributes<HTMLInputElement> = {}) => (
|
||
<label>
|
||
{title}
|
||
<input
|
||
type="number"
|
||
min="0"
|
||
step={places === 3 ? '0.001' : '0.01'}
|
||
inputMode="decimal"
|
||
{...attrs(k)}
|
||
{...props}
|
||
/>
|
||
</label>
|
||
);
|
||
const select = (
|
||
title: string,
|
||
k: TextField,
|
||
choices: readonly Choice[],
|
||
props: SelectHTMLAttributes<HTMLSelectElement> = {},
|
||
) => (
|
||
<label>
|
||
{title}
|
||
<select {...attrs(k)} {...props}>
|
||
{options(choices)}
|
||
</select>
|
||
</label>
|
||
);
|
||
const pairs = (title: string, k: TextField, pocket: string, visible = true, optional = false) => (
|
||
<label hidden={!visible || !Model.pocketCountsEnabled(state, pocket)}>
|
||
{title}
|
||
<input
|
||
type="number"
|
||
min="1"
|
||
max="1000000000"
|
||
step="1"
|
||
inputMode="numeric"
|
||
{...attrs(k)}
|
||
required={visible && Model.pocketCountsEnabled(state, pocket) && !optional}
|
||
disabled={off || !visible || !Model.pocketCountsEnabled(state, pocket)}
|
||
placeholder="一对填1"
|
||
/>
|
||
</label>
|
||
);
|
||
const rateField = (title: string, k: TextField, use = true, props: InputHTMLAttributes<HTMLInputElement> = {}) => (
|
||
<div className="recovery-customer-rate">
|
||
{num(title, k, 2, { required: true, ...props })}
|
||
{use && (
|
||
<>
|
||
<button
|
||
type="button"
|
||
data-action="recovery-use-daily-rate"
|
||
data-rate-field={prefix + k}
|
||
disabled={off}
|
||
onClick={() => daily(k, index)}
|
||
>
|
||
使用当日加权料价
|
||
</button>
|
||
<p data-rate-status>{rate.name === k && rate.index === index ? rate.text : ''}</p>
|
||
</>
|
||
)}
|
||
</div>
|
||
);
|
||
return { attrs, text, num, select, pairs, rateField };
|
||
}
|
||
const { attrs, text, num, select, pairs } = fields();
|
||
function product(row: ProductDraft, index: number) {
|
||
const f = fields(row, index, !exchange),
|
||
original =
|
||
edit?.inputs.exchange?.products?.[index + 1] ||
|
||
(!edit?.inputs.exchange?.products && index === -1 ? edit?.inputs.exchange : null);
|
||
return (
|
||
<section
|
||
key={index}
|
||
data-recovery-product={index >= 0 ? index : undefined}
|
||
data-recovery-first-product={index === -1 ? '' : undefined}
|
||
className="recovery-new-product"
|
||
>
|
||
<h3>置换新货 {index + 2}</h3>
|
||
{index >= 0 && (
|
||
<button type="button" data-action="recovery-remove-product" data-index={index} onClick={() => remove(index)}>
|
||
移除商品
|
||
</button>
|
||
)}
|
||
<div className="recovery-row">
|
||
{f.text('新货商品', 'new_name', 60, { list: 'recovery-product-names', required: true })}
|
||
{f.num('新货克重(g)', 'new_quantity', 3, { required: true })}
|
||
{f.select('出货货盘', 'pocket', pocketOptions(state, row.pocket, !!original, '外配(不扣店内库存)'))}
|
||
{f.pairs(
|
||
'出库数量(对)',
|
||
'stockCount',
|
||
row.pocket,
|
||
exchange,
|
||
!!original && original.stockCount == null && original.pocket === row.pocket,
|
||
)}
|
||
{f.select('销售工费方式', 'labor_mode', [
|
||
['gram', '按克'],
|
||
['total', '总额'],
|
||
])}
|
||
{f.num(row.labor_mode === 'total' ? '销售工费(元)' : '销售工费(元/g)', 'labor_rate', 2, {
|
||
required: true,
|
||
})}
|
||
</div>
|
||
<h4>本件内部成本</h4>
|
||
<div className="recovery-row">
|
||
{f.select('进货工费方式', 'cost_labor_mode', [
|
||
['gram', '按本件新货克重'],
|
||
['total', '总额'],
|
||
])}
|
||
{f.num(row.cost_labor_mode === 'total' ? '进货工费(元)' : '进货工费(元/g)', 'cost_labor_value', 2, {
|
||
required: true,
|
||
placeholder: '没有发生请填0',
|
||
})}
|
||
{f.select('工费付款人', 'labor_payer', members)}
|
||
</div>
|
||
</section>
|
||
);
|
||
}
|
||
const available: PoolChoice[] = pools.filter(
|
||
p =>
|
||
p.date <= d.date &&
|
||
(p.id === d.date ||
|
||
p.id === d.material_pool_id ||
|
||
p.remainingMg + (p.personalPools?.[d.member]?.remainingMg || 0) > 0),
|
||
);
|
||
for (const day of [d.date, d.material_pool_id])
|
||
if (day && !available.some(p => p.id === day)) available.push({ id: day, date: day, remainingMg: 0, totalMg: 0 });
|
||
const depositMode = exchange && d.old_source === 'deposit',
|
||
surplusDeposit = exchange && d.surplus_mode === 'deposit',
|
||
approval =
|
||
edit &&
|
||
(!edit.permissions.canDirect ||
|
||
edit.permissions.requiresApproval ||
|
||
(state.user.role !== 'owner' && (edit.inputs.date !== state.today || d.date !== state.today)));
|
||
async function submit(e: FormEvent<HTMLFormElement>) {
|
||
e.preventDefault();
|
||
try {
|
||
const payload = model.validate(model.input(d));
|
||
if (edit) {
|
||
const f = new FormData(e.currentTarget);
|
||
const reason = String(d.change_reason || '').trim();
|
||
if (!reason || reason.length > 200) throw new Error('修改原因请填写1~200字。');
|
||
Object.assign(payload, {
|
||
revision,
|
||
reason,
|
||
verified: true,
|
||
...(edit.permissions.requiresLegacyCountVerified && f.has('legacyCountVerified')
|
||
? { legacyCountVerified: true }
|
||
: {}),
|
||
});
|
||
}
|
||
const result = await client.mutate<Saved>(
|
||
edit ? '/api/recoveries/' + encodeURIComponent(edit.id) + '/update' : '/api/recoveries',
|
||
payload,
|
||
);
|
||
localStorage.removeItem(editKey || key);
|
||
saved(payload, result);
|
||
} catch (err) {
|
||
setError((err as Error).message);
|
||
if (edit && [403, 404, 409].includes((err as ApiError).status ?? 0)) setConflict({});
|
||
}
|
||
}
|
||
function extras<K extends keyof ExtraKinds>(kind: K, rows: ExtraKinds[K][], keys: ExtraFields<K>, caption: string) {
|
||
if (!edit) return null;
|
||
const prop = kind === 'old' ? 'old_lines' : kind === 'fee' ? 'fee_items' : 'charges',
|
||
defaults: ExtraKinds[K] = {
|
||
old: { name: 'Au旧料', incoming_weight: '', melted_weight: '', purity: '100' },
|
||
fee: { key: 'other', note: '其他费用', amount: '0', payer: d.member },
|
||
charge: { name: '其他收费', amount: '0' },
|
||
}[kind];
|
||
function updateRows(value: ExtraKinds[K][]) {
|
||
setError('');
|
||
setRaw(previous => ({ ...previous, [prop]: value }));
|
||
}
|
||
const change = (i: number, key: keyof ExtraKinds[K], value: string) =>
|
||
updateRows(rows.map((r, num) => (num === i ? { ...r, [key]: value } : r)));
|
||
return (
|
||
<>
|
||
{rows.slice(1).map((r, i) => (
|
||
<div className="recovery-row" data-recovery-edit-row={kind} data-index={i + 1} key={i}>
|
||
{keys.map(([k, t]) => {
|
||
const name =
|
||
'extra_' + (kind === 'old' && k === 'name' ? 'old_name' : kind === 'old' ? k : kind + '_' + k);
|
||
const number = ['grams', 'amount', 'incoming_weight', 'melted_weight', 'purity'].includes(k);
|
||
return (
|
||
<label key={k}>
|
||
{kind === 'charge'
|
||
? k === 'amount'
|
||
? '收费金额(元)'
|
||
: '收费名称'
|
||
: kind === 'fee'
|
||
? k === 'amount'
|
||
? '费用金额(元)'
|
||
: k === 'payer'
|
||
? '实际付款人'
|
||
: '费用名称'
|
||
: t}
|
||
{k === 'payer' ? (
|
||
<select name={name} value={String(r[k] || '')} onChange={e => change(i + 1, k, e.target.value)}>
|
||
{options(members)}
|
||
</select>
|
||
) : (
|
||
<input
|
||
name={name}
|
||
type={number ? 'number' : 'text'}
|
||
required
|
||
min={number ? '0' : undefined}
|
||
max={k === 'purity' ? '100' : undefined}
|
||
step={number ? (kind === 'old' ? '0.001' : '0.01') : undefined}
|
||
inputMode={number ? 'decimal' : undefined}
|
||
maxLength={number ? undefined : k === 'note' ? 100 : 60}
|
||
value={String(r[k] || '')}
|
||
onChange={e => change(i + 1, k, e.target.value)}
|
||
/>
|
||
)}
|
||
</label>
|
||
);
|
||
})}
|
||
<button
|
||
type="button"
|
||
data-action="recovery-edit-remove-row"
|
||
data-kind={kind}
|
||
data-index={i + 1}
|
||
onClick={() => updateRows(rows.filter((_, j) => j !== i + 1))}
|
||
>
|
||
移除这项
|
||
</button>
|
||
</div>
|
||
))}
|
||
<button
|
||
type="button"
|
||
data-action="recovery-edit-add-row"
|
||
data-kind={kind}
|
||
onClick={() => updateRows([...(rows.length ? rows : [defaults]), { ...defaults }])}
|
||
>
|
||
+ 添加{caption}
|
||
</button>
|
||
</>
|
||
);
|
||
}
|
||
return (
|
||
<form id="recovery-form" data-recovery-edit={edit ? 'true' : undefined} onSubmit={submit}>
|
||
<input type="hidden" name="mode" value={d.mode} />
|
||
<input type="hidden" name="shared_old_notice" value={d.shared_old_notice || ''} />
|
||
{!edit && (
|
||
<div className="actions">
|
||
{(
|
||
[
|
||
['direct', '直接回收'],
|
||
['exchange', '置换'],
|
||
] as const
|
||
).map(([mode, name]) => (
|
||
<button
|
||
type="button"
|
||
key={mode}
|
||
data-action="recovery-mode"
|
||
data-mode={mode}
|
||
aria-pressed={mode === d.mode}
|
||
onClick={() => setRaw({ ...d, mode, buy_total_manual: false, buy_total: '', verified: false })}
|
||
>
|
||
{name}
|
||
</button>
|
||
))}
|
||
<button type="button" data-action="customer-material-new" onClick={deposit}>
|
||
寄存,暂不结算
|
||
</button>
|
||
</div>
|
||
)}
|
||
<section className="panel">
|
||
<h2>客户与单据</h2>
|
||
<span>保存后自动编号</span>
|
||
<div className="recovery-row">
|
||
<label>
|
||
业务日期
|
||
<input type="date" {...attrs('date')} max={state.today} required />
|
||
</label>
|
||
{text('客户称呼/代号', 'customer', 60, { required: true, placeholder: '必填' })}
|
||
{exchange && (
|
||
<div>
|
||
客户类型
|
||
{[
|
||
['new', '新客户'],
|
||
['returning', '老客户'],
|
||
].map(([k, t]) => (
|
||
<label key={k}>
|
||
<input
|
||
type="radio"
|
||
name="customer_type"
|
||
value={k}
|
||
required={!edit}
|
||
checked={d.customer_type === k}
|
||
onChange={() => setField('customer_type', k)}
|
||
/>
|
||
{t}
|
||
</label>
|
||
))}
|
||
</div>
|
||
)}
|
||
{text('开单人', 'salesperson', 30, { required: true })}
|
||
{state.user.role === 'owner' && !edit ? (
|
||
select('归属成员', 'member', members)
|
||
) : (
|
||
<label>
|
||
归属成员
|
||
<input value={Model.memberName(state, d.member)} readOnly />
|
||
<input type="hidden" name="member" value={d.member} />
|
||
</label>
|
||
)}
|
||
</div>
|
||
</section>
|
||
{parts ? (
|
||
<IndependentItems
|
||
parts={parts}
|
||
quotedItems={quote.signature === signature ? quote.value?.exchangeItems : undefined}
|
||
draft={d}
|
||
edit={edit!}
|
||
state={state}
|
||
fields={fields}
|
||
materials={materials}
|
||
pools={pools}
|
||
add={add}
|
||
remove={remove}
|
||
setField={setField}
|
||
extras={extras}
|
||
/>
|
||
) : (
|
||
<>
|
||
{' '}
|
||
<section className="panel">
|
||
<h2>旧料称重</h2>
|
||
<span>成色按百分数填写,例如99表示99%</span>
|
||
{d.shared_old_notice && <p>{d.shared_old_notice}</p>}
|
||
{exchange && (
|
||
<div className="recovery-row">
|
||
{select('旧料来源', 'old_source', [
|
||
['incoming', '本次交来的旧料'],
|
||
['deposit', '使用寄存料'],
|
||
])}
|
||
<div hidden={!depositMode}>
|
||
{select(
|
||
'选择寄存记录',
|
||
'deposit_id',
|
||
[
|
||
['', '请选择寄存记录'],
|
||
...materials
|
||
.filter(x => x.remainingMg > 0 || x.id === d.deposit_id)
|
||
.map(r => [
|
||
r.id,
|
||
r.date + ' · ' + r.number + ' · 可用 ' + grams(r.remainingMg) + 'g · ' + r.memo,
|
||
]),
|
||
],
|
||
{ disabled: !depositMode },
|
||
)}
|
||
{num('本次使用寄存克重(g)', 'deposit_weight', 3, { required: true, disabled: !depositMode })}
|
||
<p>只扣本次使用克重,剩余继续寄存。这里不填写回收金价。</p>
|
||
</div>
|
||
</div>
|
||
)}
|
||
<div className="recovery-row">
|
||
<div hidden={depositMode}>
|
||
{text('旧料名称', 'old_name', 60, { required: true, disabled: depositMode })}
|
||
</div>
|
||
<div hidden={depositMode}>
|
||
{num('来料重量(g)', 'incoming_weight', 3, { required: true, disabled: depositMode })}
|
||
</div>
|
||
<div hidden={depositMode}>
|
||
{num('熔后重量(g)', 'melted_weight', 3, { required: true, disabled: depositMode })}
|
||
</div>
|
||
<div hidden={depositMode}>
|
||
{num('成色(%)', 'purity', 3, { max: '100', required: true, disabled: depositMode })}
|
||
</div>
|
||
{num('折后重量(g,自动)', 'folded_weight', 3, {
|
||
readOnly: true,
|
||
tabIndex: -1,
|
||
value: old ? grams(old.oldMg) : '',
|
||
})}
|
||
</div>
|
||
{extras(
|
||
'old',
|
||
d.old_lines || [],
|
||
[
|
||
['name', '旧料名称'],
|
||
['incoming_weight', '来料重量(g)'],
|
||
['melted_weight', '熔后重量(g)'],
|
||
['purity', '成色(%)'],
|
||
],
|
||
'旧料',
|
||
)}
|
||
<p id="recovery-folded-formula">
|
||
{old
|
||
? '折后重量 = ' + d.melted_weight + 'g × ' + d.purity + '% = ' + grams(old.oldMg) + 'g。'
|
||
: '折后重量 = 熔后重量 × 成色 ÷ 100。'}
|
||
</p>
|
||
<div className="recovery-row">
|
||
{select('旧料入库货盘', 'old_pocket', pocketOptions(state, d.old_pocket, !!edit))}
|
||
{pairs(
|
||
'旧料入库数量(对)',
|
||
'old_stock_count',
|
||
d.old_pocket,
|
||
true,
|
||
!!edit && edit.inputs.old_stock_count == null && edit.inputs.old_pocket === d.old_pocket,
|
||
)}
|
||
</div>
|
||
<p>已结算的旧料入所选货盘;暂存余料单独记入客户寄存料。置换新货按出货货盘扣减。</p>
|
||
</section>
|
||
<section className="panel" data-recovery-exchange hidden={!exchange}>
|
||
<h2>置换新货</h2>
|
||
<p>每件新货分别填写工费、成本和货盘</p>
|
||
<p>上方旧料只录一次,供下面所有新货共同抵扣。补金、折旧和余料按整单统一结算。</p>
|
||
<p id="recovery-new-total">
|
||
新货共 {1 + (d.extra_products?.length || 0)} 件 · 合计 {newMg == null ? '待填写' : grams(newMg) + 'g'}
|
||
{old && ' · 共用折后旧料 ' + grams(old.oldMg) + 'g'}
|
||
</p>
|
||
<datalist id="recovery-product-names">
|
||
<option value="足金999" />
|
||
</datalist>
|
||
{product(d, -1)}
|
||
{d.extra_products?.map((r, i) => product(r, i))}
|
||
<button type="button" data-action="recovery-add-product" onClick={add} disabled={!exchange}>
|
||
+ 添加置换新货
|
||
</button>
|
||
<span>补金、折旧和余料按新货总克重结算;每件可选不同货盘或外配。</span>
|
||
<h3>整单差重与折旧</h3>
|
||
<div className="recovery-row">
|
||
<div hidden={!diff}>
|
||
{fields(d, -1, !exchange).rateField('补金销售单价(元/g)', 'gold_price', true, {
|
||
disabled: !diff,
|
||
required: diff,
|
||
})}
|
||
</div>
|
||
{num('折旧费单价(元/g)', 'depreciation_rate', 2, { required: true, disabled: !exchange })}
|
||
{num('折旧计费克重(g,可改)', 'depreciation_weight', 3, { required: true, disabled: !exchange })}
|
||
</div>
|
||
<button
|
||
type="button"
|
||
data-action="recovery-reset-depreciation"
|
||
disabled={!exchange}
|
||
onClick={() => setField('depreciation_manual', false)}
|
||
>
|
||
恢复默认克重
|
||
</button>
|
||
<details>
|
||
<summary>其他收费与优惠(选填)</summary>
|
||
<div className="recovery-row">
|
||
{text('其他收费名称', 'charge_name', 60, { disabled: !exchange })}
|
||
{num('其他收费(元)', 'charge_amount', 2, { disabled: !exchange })}
|
||
{num('优惠金额(元)', 'discount', 2, { disabled: !exchange })}
|
||
{select(
|
||
'置换费用取整',
|
||
'rounding_mode',
|
||
[
|
||
['yuan', '四舍五入到元'],
|
||
['cent', '保留到分'],
|
||
],
|
||
{ disabled: !exchange },
|
||
)}
|
||
</div>
|
||
{extras(
|
||
'charge',
|
||
d.charges || [],
|
||
[
|
||
['name', '其他收费名称'],
|
||
['amount', '其他收费(元)'],
|
||
],
|
||
'收费',
|
||
)}
|
||
</details>
|
||
</section>
|
||
<section className="panel recovery-buy-panel" hidden={!hasBuy}>
|
||
<h2 id="recovery-buy-title">{exchange ? '余料处理' : '回收结算'}</h2>
|
||
<span id="recovery-buy-help">
|
||
{exchange
|
||
? '余料可按价回收,也可寄存暂不结算'
|
||
: '保存后自动记购料与' + rowLabel(state, d.old_pocket) + '库存'}
|
||
</span>
|
||
{exchange && (
|
||
<div className="recovery-row">
|
||
{select(
|
||
'余料处理方式',
|
||
'surplus_mode',
|
||
[
|
||
['buy', '按回收价结算'],
|
||
['deposit', '添加到寄存料,暂不结算'],
|
||
],
|
||
{ disabled: !hasBuy },
|
||
)}
|
||
<div hidden={!surplusDeposit}>
|
||
{text('寄存备忘(选填)', 'surplus_memo', 160, {
|
||
disabled: !hasBuy || !surplusDeposit,
|
||
placeholder: '例如:袋号、客户代号',
|
||
})}
|
||
</div>
|
||
</div>
|
||
)}
|
||
<div className="recovery-row" hidden={surplusDeposit}>
|
||
{fields(d, -1, !hasBuy || surplusDeposit).rateField('回收单价(元/g)', 'buy_rate', exchange)}
|
||
{num(exchange ? '余料回收款(元,可改)' : '回收结算额(元,可改)', 'buy_total', 2, {
|
||
required: true,
|
||
disabled: !hasBuy || surplusDeposit,
|
||
})}
|
||
<button
|
||
type="button"
|
||
data-action="recovery-reset-buy"
|
||
disabled={!hasBuy || surplusDeposit}
|
||
onClick={() => setField('buy_total_manual', false)}
|
||
>
|
||
恢复自动金额
|
||
</button>
|
||
</div>
|
||
<p>
|
||
{q
|
||
? (exchange ? '余料' : '折后') +
|
||
' ' +
|
||
grams(q.surplusMg) +
|
||
'g × ' +
|
||
d.buy_rate +
|
||
'元/g = ' +
|
||
(q.defaultPurchaseAmount / 100).toFixed(2) +
|
||
'元' +
|
||
(d.buy_total_manual ? ';本单采用手动核实金额。' : '。')
|
||
: '按折后重量与回收单价自动计算,实际结算有调整时可修改金额。'}
|
||
</p>
|
||
</section>
|
||
</>
|
||
)}
|
||
<section className="panel">
|
||
<h2>本次结算</h2>
|
||
<span>保存前请核对实际收付款</span>
|
||
<div id="recovery-calculation">{q ? <Settlement q={q} draft={d} input={input} /> : <p>{calcError}</p>}</div>
|
||
<div className="recovery-row" hidden={net <= 0}>
|
||
{select(
|
||
'收款方式',
|
||
'payment_method',
|
||
[...basicMethods, ...(Model.creditCardAvailable(state) ? ['信用卡'] : [])],
|
||
{ disabled: net <= 0 },
|
||
)}
|
||
{select('收款人', 'payment_recipient', recipients, {
|
||
disabled: net <= 0 || card,
|
||
value: card ? '麦麦' : d.payment_recipient,
|
||
})}
|
||
</div>
|
||
{card && <RecoveryCardFee state={state} edit={edit} net={net} />}
|
||
<div className="recovery-row" hidden={net >= 0}>
|
||
{select('付款方式', 'payout_method', basicMethods, { disabled: net >= 0 })}
|
||
{select('付款人', 'payer', members, { disabled: net >= 0 })}
|
||
</div>
|
||
</section>
|
||
{!parts && (
|
||
<section className="panel" hidden={!exchange}>
|
||
<h2>内部成本</h2>
|
||
<h3>补金差重的料费</h3>
|
||
<div className="recovery-row" hidden={!diff}>
|
||
{select(
|
||
'差重料费来源',
|
||
'material_source',
|
||
[
|
||
['pool', '每日料池'],
|
||
['manual', '手动进货料价'],
|
||
],
|
||
{ disabled: !diff },
|
||
)}
|
||
<div hidden={d.material_source !== 'pool'}>
|
||
{select(
|
||
'料池日期',
|
||
'material_pool_id',
|
||
exchange
|
||
? available
|
||
.sort((a, b) => b.date.localeCompare(a.date))
|
||
.map(p => [
|
||
p.id,
|
||
p.date +
|
||
' · ' +
|
||
(p.personalPools
|
||
? '个人余 ' +
|
||
grams(p.personalPools[d.member]?.remainingMg || 0) +
|
||
'g/公共余 ' +
|
||
grams(p.remainingMg) +
|
||
'g'
|
||
: p.totalMg
|
||
? '余 ' + grams(p.remainingMg) + 'g'
|
||
: '待补采购'),
|
||
])
|
||
: [[d.material_pool_id || d.date, d.material_pool_id || d.date]],
|
||
{ disabled: !diff || d.material_source !== 'pool' },
|
||
)}
|
||
</div>
|
||
<div hidden={d.material_source === 'pool'}>
|
||
{num('差重进货料价(元/g)', 'material_rate', 2, { disabled: !diff || d.material_source === 'pool' })}
|
||
{select('料费付款人', 'material_payer', members, { disabled: !diff || d.material_source === 'pool' })}
|
||
</div>
|
||
</div>
|
||
<p id="recovery-material-note">
|
||
{(quote.signature === signature && quote.materialText) ||
|
||
localMaterialNote(d, q, pools, state, model, edit)}
|
||
</p>
|
||
<details>
|
||
<summary>其他实际成本(选填)</summary>
|
||
<div className="recovery-row">
|
||
{text('费用名称', 'fee_note', 100, { disabled: !exchange })}
|
||
{num('其他实际成本(元)', 'fee_amount', 2, { disabled: !exchange })}
|
||
{select('费用付款人', 'fee_payer', members, { disabled: !exchange })}
|
||
</div>
|
||
{extras(
|
||
'fee',
|
||
d.fee_items || [],
|
||
[
|
||
['note', '费用名称'],
|
||
['amount', '其他实际成本(元)'],
|
||
['payer', '费用付款人'],
|
||
],
|
||
'实际费用',
|
||
)}
|
||
</details>
|
||
</section>
|
||
)}
|
||
<section className="panel">
|
||
{edit && (
|
||
<>
|
||
<p>{approval ? '提交后等待店主复核,原记录继续生效。' : '保存后直接更新回收/置换记录。'}</p>
|
||
<LegacyCount value={edit.permissions} />
|
||
{text('修改原因', 'change_reason', 200, { required: true })}
|
||
{conflict && (
|
||
<div>
|
||
记录已有变动,填写已保留,请核对最新记录。
|
||
<button
|
||
type="button"
|
||
data-action="recovery-edit-reload"
|
||
onClick={async () => {
|
||
try {
|
||
setConflict({ latest: await refreshEdit() });
|
||
} catch (e) {
|
||
setError((e as Error).message);
|
||
}
|
||
}}
|
||
>
|
||
重新读取并核对
|
||
</button>
|
||
{conflict.latest && (
|
||
<button
|
||
type="button"
|
||
data-action="recovery-edit-keep"
|
||
onClick={() => {
|
||
setRevision(conflict.latest!.revision);
|
||
setConflict(null);
|
||
setField('verified', false);
|
||
}}
|
||
>
|
||
已核对最新记录,保留填写继续
|
||
</button>
|
||
)}
|
||
</div>
|
||
)}
|
||
</>
|
||
)}
|
||
{text('备注(选填,可打印)', 'note', 240)}
|
||
<label>
|
||
<input
|
||
type="checkbox"
|
||
name="verified"
|
||
required
|
||
checked={!!d.verified}
|
||
onChange={e => setField('verified', e.target.checked)}
|
||
/>
|
||
已核实重量、结算金额和实际收付款
|
||
</label>
|
||
{edit && (
|
||
<button type="button" data-action="recovery-edit-close" onClick={exitEdit}>
|
||
取消修改
|
||
</button>
|
||
)}
|
||
<button className="primary" id="recovery-save" type="submit" disabled={disabled || !!conflict}>
|
||
{edit ? (approval ? '提交修改申请' : '保存修改') : '保存' + (exchange ? '置换' : '回收') + '单'}
|
||
</button>
|
||
<span id="recovery-quote-status" aria-live="polite">
|
||
{signature ? (quote.signature === signature ? quote.text : '正在核对结算…') : ''}
|
||
</span>
|
||
<div id="recovery-form-error" role="status">
|
||
{error}
|
||
</div>
|
||
</section>
|
||
</form>
|
||
);
|
||
}
|