267 lines
9.6 KiB
TypeScript
267 lines
9.6 KiB
TypeScript
import { useState, type FormEvent } from 'react';
|
||
import { type LedgerClient } from '../../lib/api';
|
||
import { Calc, Fees, type MemberRow } from '../../shared';
|
||
import { Button, Choice, Dialog, Field } from './controls';
|
||
import { errorText, memberOptions, readForm, type Notice, type Shop } from './settingsModel';
|
||
import { LedgerButton, LedgerDataTable, LedgerInput } from '../../components/BusinessControls';
|
||
|
||
interface Cost {
|
||
name: string;
|
||
amount: string;
|
||
payer: string;
|
||
byQuantity: boolean;
|
||
enabled: boolean;
|
||
}
|
||
type Editor = { action: 'add' | 'edit' | 'delete'; kind: string; revision: number; original: Cost };
|
||
function formCost(form: HTMLFormElement): Cost {
|
||
const { name, amount, payer, enabled, byQuantity } = readForm(form);
|
||
return { name, amount, payer, enabled: enabled === 'true', byQuantity: byQuantity === 'true' };
|
||
}
|
||
export function Costs({
|
||
shop,
|
||
client,
|
||
members,
|
||
team,
|
||
busy,
|
||
onBusy,
|
||
dirty,
|
||
onDirty,
|
||
onSaved,
|
||
notice,
|
||
}: {
|
||
shop: Shop;
|
||
client: LedgerClient;
|
||
members: MemberRow[];
|
||
team: boolean;
|
||
busy: boolean;
|
||
onBusy: (v: boolean) => void;
|
||
dirty: boolean;
|
||
onDirty: (v: boolean) => void;
|
||
onSaved: (shop: Shop) => Promise<void>;
|
||
notice: Notice;
|
||
}) {
|
||
const rows = (
|
||
Fees as typeof Fees & { presetCatalog: (v?: Record<string, unknown>) => Record<string, Cost> }
|
||
).presetCatalog(shop.costPresets);
|
||
const [search, setSearch] = useState('');
|
||
const [editor, setEditor] = useState<Editor | null>(null);
|
||
const [saving, setSaving] = useState(false);
|
||
const [error, setError] = useState('');
|
||
function close() {
|
||
if (saving || (dirty && !window.confirm('成本修改尚未保存,放弃修改?'))) return;
|
||
setEditor(null);
|
||
onDirty(false);
|
||
setError('');
|
||
}
|
||
function open(action: Editor['action'], kind = '') {
|
||
if (busy || client.busy || client.pending()) return;
|
||
const original = rows[kind] || { name: '', amount: '0', payer: 'order', enabled: true, byQuantity: false };
|
||
setEditor({ action, kind: kind || 'custom_' + crypto.randomUUID(), original, revision: shop.revision });
|
||
onDirty(false);
|
||
setError('');
|
||
}
|
||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||
event.preventDefault();
|
||
if (!editor || saving) return;
|
||
let committed = false;
|
||
try {
|
||
if (busy || client.busy || client.pending()) throw new Error('请先确认当前操作,再保存成本');
|
||
const value = editor.action === 'delete' ? null : formCost(event.currentTarget);
|
||
if (value) {
|
||
value.name = value.name.trim();
|
||
if (!value.name || value.name.length > 40) throw new Error('成本名称请填写1~40字');
|
||
if (Calc.cents(value.amount, '成本') > 100000000) throw new Error('成本最多1000000元');
|
||
}
|
||
setSaving(true);
|
||
onBusy(true);
|
||
setError('');
|
||
const result = await client.mutate<{ shopSettings: Shop }>('/api/shop-settings', {
|
||
revision: editor.revision,
|
||
costPresets: { [editor.kind]: value },
|
||
});
|
||
committed = true;
|
||
setEditor(null);
|
||
onDirty(false);
|
||
await onSaved(result.shopSettings);
|
||
notice(editor.action === 'delete' ? '成本项目已删除' : '成本项目已保存');
|
||
} catch (err) {
|
||
const message = committed ? '成本已经保存,请刷新页面核对' : errorText(err);
|
||
setError(message);
|
||
notice(message, true);
|
||
} finally {
|
||
setSaving(false);
|
||
onBusy(false);
|
||
}
|
||
}
|
||
const visible = Object.entries(rows).filter(([, row]) =>
|
||
row.name.toLocaleLowerCase().includes(search.trim().toLocaleLowerCase()),
|
||
);
|
||
return (
|
||
<section id="shop-cost-manager" className="shop-cost-manager">
|
||
<div className="panel-title">
|
||
<div>
|
||
<h3>勾选成本管理</h3>
|
||
<p className="small muted">自行添加需要的项目。删除后不再用于新单,历史订单成本保留。</p>
|
||
</div>
|
||
<Button action="shop-cost-add" className="primary" onClick={() => open('add')}>
|
||
+ 新增成本
|
||
</Button>
|
||
</div>
|
||
<label className="shop-cost-search">
|
||
搜索成本
|
||
<LedgerInput
|
||
type="search"
|
||
id="shop-cost-search"
|
||
placeholder="输入成本名称"
|
||
autoComplete="off"
|
||
value={search}
|
||
onChange={e => setSearch(e.target.value)}
|
||
/>
|
||
</label>
|
||
<div id="shop-cost-list">
|
||
{visible.length ? (
|
||
<div className="table-wrap">
|
||
<LedgerDataTable
|
||
className="shop-cost-table"
|
||
columns={[
|
||
{ title: '成本名称' },
|
||
{ title: '金额/单价' },
|
||
{ title: '付款人' },
|
||
{ title: '计费方式' },
|
||
{ title: '状态' },
|
||
{ title: '操作' },
|
||
]}
|
||
rows={visible.map(([kind, row]) => ({
|
||
key: kind,
|
||
attributes: { 'data-cost-row': kind },
|
||
cells: [
|
||
<>
|
||
<strong>{row.name}</strong>
|
||
</>,
|
||
<>¥{row.amount}</>,
|
||
row.payer === 'order' ? '订单归属人' : members.find(m => m.member === row.payer)?.label || '待确认',
|
||
row.byQuantity ? '单价 × 数量' : '每单一次',
|
||
row.enabled ? '启用' : '停用',
|
||
<>
|
||
<div className="actions">
|
||
<Button
|
||
action="shop-cost-edit"
|
||
className="quiet"
|
||
data-kind={kind}
|
||
onClick={() => open('edit', kind)}
|
||
>
|
||
编辑
|
||
</Button>
|
||
<Button
|
||
action="shop-cost-delete"
|
||
className="danger"
|
||
data-kind={kind}
|
||
onClick={() => open('delete', kind)}
|
||
>
|
||
删除
|
||
</Button>
|
||
</div>
|
||
</>,
|
||
],
|
||
}))}
|
||
/>
|
||
</div>
|
||
) : (
|
||
<p className="empty">
|
||
{Object.keys(rows).length ? '没有匹配的成本项目。' : '还没有勾选成本,点击“新增成本”添加。'}
|
||
</p>
|
||
)}
|
||
</div>
|
||
{editor && (
|
||
<Dialog id="shop-cost-dialog" close={close}>
|
||
<Button className="dialog-close" action="shop-cost-close" aria-label="关闭成本编辑" onClick={close}>
|
||
×
|
||
</Button>
|
||
<h2>{{ add: '新增成本', delete: '删除成本', edit: '编辑成本' }[editor.action]}</h2>
|
||
<form
|
||
id="shop-cost-form"
|
||
onSubmit={submit}
|
||
onChange={e => {
|
||
const value = formCost(e.currentTarget);
|
||
onDirty((Object.keys(value) as (keyof Cost)[]).some(k => value[k] !== editor.original[k]));
|
||
}}
|
||
>
|
||
{editor.action === 'delete' ? (
|
||
<>
|
||
<p>
|
||
删除“<strong>{editor.original.name}</strong>”?
|
||
</p>
|
||
<p className="muted">删除后不会再出现在新单勾选项里,已开订单、成本和流水保留。</p>
|
||
</>
|
||
) : (
|
||
<div className="grid two">
|
||
<Field
|
||
label="成本名称"
|
||
name="name"
|
||
defaultValue={editor.original.name}
|
||
required
|
||
maxLength={40}
|
||
disabled={saving}
|
||
/>
|
||
<Field
|
||
label="金额/单价(元)"
|
||
name="amount"
|
||
type="number"
|
||
defaultValue={editor.original.amount}
|
||
required
|
||
min={0}
|
||
max={1000000}
|
||
step="0.01"
|
||
disabled={saving}
|
||
/>
|
||
<Choice
|
||
label="付款人"
|
||
name="payer"
|
||
defaultValue={editor.original.payer}
|
||
options={[['order', '订单归属人'], ...memberOptions(members, editor.original.payer, team)]}
|
||
disabled={saving}
|
||
/>
|
||
<Choice
|
||
label="计费方式"
|
||
name="byQuantity"
|
||
defaultValue={String(editor.original.byQuantity)}
|
||
options={[
|
||
['false', '每单一次'],
|
||
['true', '单价 × 数量'],
|
||
]}
|
||
disabled={saving}
|
||
/>
|
||
<Choice
|
||
label="状态"
|
||
name="enabled"
|
||
defaultValue={String(editor.original.enabled)}
|
||
options={[
|
||
['true', '启用'],
|
||
['false', '停用'],
|
||
]}
|
||
disabled={saving}
|
||
/>
|
||
</div>
|
||
)}
|
||
<div id="shop-cost-error" role="alert" className={error ? 'error' : undefined}>
|
||
{error}
|
||
</div>
|
||
<div className="form-actions">
|
||
<Button action="shop-cost-close" className="quiet" onClick={close} disabled={saving}>
|
||
取消
|
||
</Button>
|
||
<LedgerButton
|
||
type="submit"
|
||
className={editor.action === 'delete' ? 'danger' : 'primary'}
|
||
disabled={saving}
|
||
>
|
||
{editor.action === 'delete' ? '确认删除' : '保存成本'}
|
||
</LedgerButton>
|
||
</div>
|
||
</form>
|
||
</Dialog>
|
||
)}
|
||
</section>
|
||
);
|
||
}
|