新版界面(React + TypeScript + Vite + Ant Design):登录页与开单页
共用计算经构建插件直接导入 public/ 下的 UMD 源文件;请求客户端沿用旧界面的重试、 同一操作号自动确认、恢复原操作与账号切换约定;附 vitest 单元与组件测试。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
bdffbcab85
commit
ec5889075f
39 files changed
+8772
No files matched your search
@@ -0,0 +1,97 @@
|
||||
import { Button } from 'antd';
|
||||
import { Model } from '../../shared';
|
||||
import type { ChargeState, LineState, OrderForm } from '../../shared';
|
||||
import { uuid } from './useOrderForm';
|
||||
import { ChoiceField, TextField } from './fields';
|
||||
|
||||
type Update = (change: (form: OrderForm) => OrderForm) => void;
|
||||
|
||||
// 工费附加项目:新选择按店铺报价预填(编绳55、证书10、包装10、快递8),手改金额、填0或清空都原样保留;
|
||||
// 切换类目时记住每个类目各自填过的金额。
|
||||
export function ChargeList({ index, line, update }: { index: number; line: LineState; update: Update }) {
|
||||
const setCharge = (j: number, change: (charge: ChargeState) => ChargeState) =>
|
||||
update(form => {
|
||||
const current = form.lines[index];
|
||||
return Model.updateLine(form, index, {
|
||||
...current,
|
||||
charges: current.charges.map((charge, k) => (k === j ? change(charge) : charge)),
|
||||
});
|
||||
});
|
||||
return (
|
||||
<div className="sale-charges">
|
||||
<div className="panel-title">
|
||||
<strong>工费附加项目(选填)</strong>
|
||||
<Button
|
||||
size="small"
|
||||
data-action="add-charge"
|
||||
onClick={() => update(form => Model.addCharge(form, index, uuid))}
|
||||
>
|
||||
+ 添加附加项目
|
||||
</Button>
|
||||
</div>
|
||||
<p className="small muted">
|
||||
向客户收费预填:编绳55元、证书10元、包装10元、快递8元,均可修改;按填写金额自动加进本行销售额。
|
||||
</p>
|
||||
<div className="charge-list">
|
||||
{line.charges.map((charge, j) => (
|
||||
<div className="charge-row" key={charge.id} data-charge={j}>
|
||||
<ChoiceField
|
||||
label="附加项目"
|
||||
field="chargeType"
|
||||
value={charge.type}
|
||||
options={[...Model.chargeNames, '其他'].map(name => [name, name] as [string, string])}
|
||||
onChange={type => setCharge(j, c => Model.changeChargeType(c, type))}
|
||||
/>
|
||||
<TextField
|
||||
label="附加项目名称"
|
||||
field="chargeName"
|
||||
hidden={charge.type !== '其他'}
|
||||
value={charge.customName}
|
||||
maxLength={40}
|
||||
onChange={value => setCharge(j, c => ({ ...c, customName: value }))}
|
||||
/>
|
||||
<TextField
|
||||
label="附加金额(元)"
|
||||
field="chargeAmount"
|
||||
numeric
|
||||
value={charge.amount}
|
||||
placeholder="没有收费填0,可修改金额"
|
||||
onChange={value => setCharge(j, c => Model.setChargeAmount(c, value))}
|
||||
/>
|
||||
<div className="charge-actions">
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
data-action="remove-charge"
|
||||
onClick={() =>
|
||||
update(form => {
|
||||
const current = form.lines[index];
|
||||
return Model.updateLine(form, index, {
|
||||
...current,
|
||||
charges: current.charges.filter((_, k) => k !== j),
|
||||
});
|
||||
})
|
||||
}
|
||||
>
|
||||
移除附加项
|
||||
</Button>
|
||||
{charge.costRemoved && (
|
||||
<small className="muted">
|
||||
内部成本已移除{' '}
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
data-action="restore-charge-cost"
|
||||
onClick={() => update(form => Model.restoreChargeCost(form, index, j))}
|
||||
>
|
||||
恢复内部成本
|
||||
</Button>
|
||||
</small>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Alert, App as AntApp, Button, Spin, Typography } from 'antd';
|
||||
import type { ApiError, LedgerClient, PendingJob } from '../../lib/api';
|
||||
import { clearDraft, loadDraft } from '../../lib/drafts';
|
||||
import { searchParam } from '../../lib/router';
|
||||
import { useClientSnapshot } from '../../lib/useClient';
|
||||
import { Model } from '../../shared';
|
||||
import type { LedgerState, OrderDraft, SessionInfo } from '../../shared';
|
||||
import { useOrderForm } from './useOrderForm';
|
||||
import { CustomerSection } from './CustomerSection';
|
||||
import { LineItems } from './LineItems';
|
||||
import { FeeCosts } from './FeeCosts';
|
||||
import { SummarySection } from './SummarySection';
|
||||
import { EntryTools } from './EntryTools';
|
||||
import { IssuedResult, type IssuedOrder } from './IssuedResult';
|
||||
|
||||
interface Props {
|
||||
client: LedgerClient;
|
||||
state: LedgerState;
|
||||
session: SessionInfo;
|
||||
refreshState: () => Promise<LedgerState>;
|
||||
onAccountChanged: () => void;
|
||||
}
|
||||
|
||||
// 开单页:先确定初始草稿(地址中的旧草稿订单 ?draft=<订单号>,或本机暂存),再进入表单。
|
||||
export function CreateOrderPage(props: Props) {
|
||||
const { client, state } = props;
|
||||
const draftId = searchParam('draft');
|
||||
const [initial, setInitial] = useState<{ draft: Record<string, unknown> | null; note: string } | null>(
|
||||
draftId ? null : { draft: loadDraft(window.localStorage, state.user.id), note: '' },
|
||||
);
|
||||
useEffect(() => {
|
||||
if (!draftId) return;
|
||||
let current = true;
|
||||
(async () => {
|
||||
try {
|
||||
if (state.user.role !== 'owner') throw new Error('已有草稿由店主继续填写并开单;无单号的新开单流程照常使用。');
|
||||
const order = await client.api<{ status: string } & Record<string, unknown>>(
|
||||
'/api/orders/' + encodeURIComponent(draftId),
|
||||
);
|
||||
if (order.status !== 'draft') throw new Error('这张订单不是未开单的旧草稿,请在旧版界面查看。');
|
||||
if (current) setInitial({ draft: Model.draftInputs(order), note: '正在继续填写旧草稿,生成销售单据后完成记账。' });
|
||||
} catch (err) {
|
||||
if (current)
|
||||
setInitial({ draft: loadDraft(window.localStorage, state.user.id), note: '旧草稿未能打开:' + (err as Error).message });
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
current = false;
|
||||
};
|
||||
}, [client, draftId, state.user.id, state.user.role]);
|
||||
if (!initial)
|
||||
return (
|
||||
<div className="page-loading">
|
||||
<Spin tip="正在读取旧草稿…">
|
||||
<div style={{ height: 60 }} />
|
||||
</Spin>
|
||||
</div>
|
||||
);
|
||||
return <CreateOrderForm {...props} initialDraft={initial.draft} initialNote={initial.note} />;
|
||||
}
|
||||
|
||||
function CreateOrderForm({
|
||||
client,
|
||||
state,
|
||||
session,
|
||||
refreshState,
|
||||
onAccountChanged,
|
||||
initialDraft,
|
||||
initialNote,
|
||||
}: Props & { initialDraft: Record<string, unknown> | null; initialNote: string }) {
|
||||
const { message } = AntApp.useApp();
|
||||
useClientSnapshot(client);
|
||||
const { store, update, reset, ctx, poolError, loadPools } = useOrderForm({ client, state, session, initialDraft });
|
||||
const { form, summary } = store;
|
||||
const [error, setError] = useState('');
|
||||
const [accountChanged, setAccountChanged] = useState(false);
|
||||
const [issued, setIssued] = useState<{ order: IssuedOrder; error: string } | null>(null);
|
||||
const [tags, setTags] = useState<string[]>([]);
|
||||
const [tagsStatus, setTagsStatus] = useState('正在读取快捷标签…');
|
||||
const busy = client.busy;
|
||||
const pending = client.pending();
|
||||
|
||||
// 纸单号预览(旧页面 updatePaperNumber):旧草稿沿用原号(换日期时替换日期段),新单读取预计号码。
|
||||
const [preview, setPreview] = useState<{ date: string; number: string } | null>(null);
|
||||
const paperNumber = useMemo(() => {
|
||||
if (form.paper_number) {
|
||||
const match = form.paper_date && form.paper_number.match(/^\d{8}-?(\d+)$/);
|
||||
return match ? form.date.replaceAll('-', '') + match[1] : form.paper_number;
|
||||
}
|
||||
return preview?.date === form.date ? preview.number + '(预计)' : '保存时分配';
|
||||
}, [form.paper_number, form.paper_date, form.date, preview]);
|
||||
useEffect(() => {
|
||||
if (form.paper_number) return;
|
||||
let current = true;
|
||||
const date = form.date;
|
||||
client
|
||||
.api<{ number: string }>('/api/paper-number?date=' + encodeURIComponent(date))
|
||||
.then(r => current && setPreview({ date, number: r.number }))
|
||||
.catch(() => {
|
||||
/* 日期校验由表单和服务端提示 */
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
};
|
||||
}, [client, form.date, form.paper_number]);
|
||||
// 内部备注快捷标签。
|
||||
useEffect(() => {
|
||||
let current = true;
|
||||
client
|
||||
.api<{ tags?: unknown[] }>('/api/order-note-tags')
|
||||
.then(result => {
|
||||
if (!current) return;
|
||||
setTags(Array.isArray(result.tags) ? result.tags.filter((tag): tag is string => typeof tag === 'string') : []);
|
||||
setTagsStatus('');
|
||||
})
|
||||
.catch(() => current && setTagsStatus('快捷标签暂未读取成功,可直接填写备注。'));
|
||||
return () => {
|
||||
current = false;
|
||||
};
|
||||
}, [client]);
|
||||
|
||||
const showError = useCallback(
|
||||
(err: unknown) => {
|
||||
const e = err as ApiError;
|
||||
if (e.code === 'ACCOUNT_CHANGED') setAccountChanged(true);
|
||||
setError(e.message);
|
||||
message.error(e.message);
|
||||
},
|
||||
[message],
|
||||
);
|
||||
const finishIssued = useCallback(
|
||||
async (input: OrderDraft, result: { id: string }) => {
|
||||
clearDraft(window.localStorage, state.user.id);
|
||||
setIssued({ order: { id: result.id }, error: '' });
|
||||
try {
|
||||
const order = await client.api<IssuedOrder>('/api/orders/' + encodeURIComponent(result.id));
|
||||
setIssued({ order: { ...order, id: result.id }, error: '' });
|
||||
message.success(
|
||||
order.materialCostPending
|
||||
? '销售单据已生成;料费待补,补足购料后自动核算利润'
|
||||
: '销售单据已生成,收款、费用、出库和利润已记账',
|
||||
);
|
||||
void refreshState().catch(() => {});
|
||||
} catch {
|
||||
setIssued({
|
||||
order: { id: result.id, customer: input.customer },
|
||||
error: '销售单据已经生成,最新订单暂未读到。请重新读取或查看已生成销售单;不要重复开单。',
|
||||
});
|
||||
}
|
||||
},
|
||||
[client, message, refreshState, state.user.id],
|
||||
);
|
||||
|
||||
async function submit() {
|
||||
setError('');
|
||||
try {
|
||||
Model.validateFormFields(form, state);
|
||||
const draft = Model.validateIssueDraft(Model.collectDraft(form, state), state);
|
||||
if (draft.id && state.user.role !== 'owner')
|
||||
throw new Error('已有草稿由店主继续填写并开单;无单号的新开单流程照常使用。');
|
||||
const result = await client.mutate<{ id: string }>('/api/orders/issue', draft);
|
||||
await finishIssued(draft, result);
|
||||
} catch (err) {
|
||||
showError(err);
|
||||
}
|
||||
}
|
||||
async function recover(job: PendingJob) {
|
||||
setError('');
|
||||
try {
|
||||
const recovered = await client.retryPending<{ id?: string }>();
|
||||
if (!recovered) return;
|
||||
if (job.url === '/api/orders/issue' && recovered.result.id)
|
||||
return await finishIssued(job.data as OrderDraft, recovered.result as { id: string });
|
||||
message.success('原操作已确认,不会重复记账');
|
||||
} catch (err) {
|
||||
showError(err);
|
||||
}
|
||||
}
|
||||
function startNew() {
|
||||
clearDraft(window.localStorage, state.user.id);
|
||||
if (window.location.search) window.history.replaceState(null, '', window.location.pathname);
|
||||
setIssued(null);
|
||||
setError('');
|
||||
reset(null);
|
||||
}
|
||||
|
||||
if (issued)
|
||||
return (
|
||||
<IssuedResult
|
||||
order={issued.order}
|
||||
error={issued.error}
|
||||
onRetry={() => void finishIssued({ customer: issued.order.customer } as OrderDraft, { id: issued.order.id })}
|
||||
onNew={startNew}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<div className="create-page">
|
||||
<div className="page-heading">
|
||||
<div>
|
||||
<div className="eyebrow">NEW ORDER · 新版界面</div>
|
||||
<Typography.Title level={2}>开一张新单</Typography.Title>
|
||||
<Typography.Paragraph type="secondary">
|
||||
开单即交付,一次记录全额收款、实际费用、出库和利润。订单列表、报表等其他功能请
|
||||
<a href="/">返回旧版界面</a>。
|
||||
</Typography.Paragraph>
|
||||
</div>
|
||||
<Button data-action="clear-draft" disabled={busy} onClick={startNew}>
|
||||
清空表单
|
||||
</Button>
|
||||
</div>
|
||||
{pending && (
|
||||
<Alert
|
||||
className="pending"
|
||||
type="warning"
|
||||
showIcon
|
||||
data-testid="pending"
|
||||
message="上次提交结果尚未确认,请先恢复原操作。重试会使用同一个操作号。"
|
||||
action={
|
||||
<Button danger size="small" disabled={busy} data-action="retry" onClick={() => void recover(pending)}>
|
||||
恢复原操作
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{accountChanged && (
|
||||
<Alert
|
||||
type="error"
|
||||
showIcon
|
||||
message="登录账号已在其他页面切换,原操作已暂停。"
|
||||
action={
|
||||
<Button size="small" onClick={onAccountChanged}>
|
||||
重新读取登录状态
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{initialNote && <Alert type="info" showIcon message={initialNote} />}
|
||||
{form.copy_kind && <Alert type="info" showIcon message="已复制为未保存的新订单,客户称呼已留空。" />}
|
||||
{poolError && <Alert type="warning" showIcon message={poolError} />}
|
||||
<EntryTools
|
||||
client={client}
|
||||
state={state}
|
||||
session={session}
|
||||
form={form}
|
||||
ctx={ctx}
|
||||
update={update}
|
||||
reset={draft => reset(draft)}
|
||||
/>
|
||||
<form
|
||||
id="order-form"
|
||||
className="order-form"
|
||||
noValidate
|
||||
onSubmit={event => {
|
||||
event.preventDefault();
|
||||
if (!busy) void submit();
|
||||
}}
|
||||
>
|
||||
<fieldset disabled={busy} className="form-fieldset">
|
||||
<CustomerSection form={form} state={state} paperNumber={paperNumber} update={update} />
|
||||
<LineItems
|
||||
form={form}
|
||||
state={state}
|
||||
update={update}
|
||||
onError={text => message.error(text)}
|
||||
onReloadPools={() => void loadPools()}
|
||||
/>
|
||||
<FeeCosts form={form} state={state} summary={summary} update={update} />
|
||||
<SummarySection
|
||||
form={form}
|
||||
summary={summary}
|
||||
tags={tags}
|
||||
tagsStatus={tagsStatus}
|
||||
busy={busy}
|
||||
error={error}
|
||||
update={update}
|
||||
onError={text => message.error(text)}
|
||||
/>
|
||||
</fieldset>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { Card, Typography } from 'antd';
|
||||
import { Model } from '../../shared';
|
||||
import type { LedgerState, OrderForm } from '../../shared';
|
||||
import { ChoiceField, RadioField, TextField } from './fields';
|
||||
|
||||
// 客户与单据:业务日期、纸单号、客户、客户类型、开单人、订单归属、收款方式与收款人。
|
||||
export function CustomerSection({
|
||||
form,
|
||||
state,
|
||||
paperNumber,
|
||||
update,
|
||||
}: {
|
||||
form: OrderForm;
|
||||
state: LedgerState;
|
||||
paperNumber: string;
|
||||
update: (change: (form: OrderForm) => OrderForm) => void;
|
||||
}) {
|
||||
const set = (key: keyof OrderForm) => (value: string) => update(f => ({ ...f, [key]: value }));
|
||||
const team = Model.teamMode(state);
|
||||
const card = form.payment.method === '信用卡';
|
||||
return (
|
||||
<Card
|
||||
className="panel"
|
||||
title="客户与单据"
|
||||
extra={
|
||||
<span className="small muted">
|
||||
{form.id ? '补齐原草稿,生成销售单据后完成记账' : '填写内容自动暂存,生成单据即完成记账'}
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<div className="grid four">
|
||||
<TextField label="业务日期" field="date" type="date" value={form.date} onChange={set('date')} />
|
||||
<TextField label="纸单编号(自动)" field="paper_number" value={paperNumber} readOnly />
|
||||
<TextField
|
||||
label="客户称呼/代号(必填)"
|
||||
field="customer"
|
||||
value={form.customer}
|
||||
maxLength={60}
|
||||
placeholder="方便找回订单即可"
|
||||
onChange={set('customer')}
|
||||
/>
|
||||
<RadioField
|
||||
label={'客户类型' + (form.customerTypeRequired ? '(必选)' : '')}
|
||||
field="customer_type"
|
||||
value={form.customer_type}
|
||||
options={[
|
||||
['new', '新客户'],
|
||||
['returning', '老客户'],
|
||||
]}
|
||||
onChange={set('customer_type')}
|
||||
/>
|
||||
<TextField
|
||||
label="开单人(必填)"
|
||||
field="salesperson"
|
||||
value={form.salesperson}
|
||||
maxLength={30}
|
||||
onChange={set('salesperson')}
|
||||
/>
|
||||
{team &&
|
||||
(form.memberLocked ? (
|
||||
<TextField label="订单归属(经营款与业绩)" field="member" value={Model.memberName(state, form.member)} readOnly />
|
||||
) : (
|
||||
<ChoiceField
|
||||
label="订单归属(经营款与业绩)"
|
||||
field="member"
|
||||
value={form.member}
|
||||
options={Model.memberOptions(state)}
|
||||
onChange={member => update(f => Model.changeMember(f, member, state))}
|
||||
/>
|
||||
))}
|
||||
<RadioField
|
||||
label="收款方式"
|
||||
field="payment_method"
|
||||
value={form.payment.method}
|
||||
options={Model.paymentMethods(state).map(method => [method, method] as [string, string])}
|
||||
onChange={method => update(f => ({ ...f, payment: { ...f.payment, method } }))}
|
||||
/>
|
||||
<ChoiceField
|
||||
label="收款人"
|
||||
field="payment_recipient"
|
||||
value={form.payment.recipient}
|
||||
disabled={card}
|
||||
options={Model.recipientOptions(state, form.payment)}
|
||||
hint={card && Model.creditCardAvailable(state) ? `信用卡统一由${Model.memberName(state, 'owner')}收款。` : undefined}
|
||||
onChange={recipient => update(f => ({ ...f, payment: { ...f.payment, recipient } }))}
|
||||
/>
|
||||
</div>
|
||||
<Typography.Paragraph type="secondary" className="small section-note">
|
||||
纸单号前半段为业务日期,后半段序号持续累计,中间不加横线,换日期不归零;生成时分配。生成单据即按成交合计记录全额收款,同时按所选货盘扣减黄金库存并计入实际利润。请核对商品已交付,选择实际收款方式与收款人;业务日期作为收款和出库日期。
|
||||
</Typography.Paragraph>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { Alert, App as AntApp, Button, Collapse, Input, Modal, Select, Space } from 'antd';
|
||||
import type { LedgerClient } from '../../lib/api';
|
||||
import { Copy, Formula, Model, Templates } from '../../shared';
|
||||
import type { LedgerState, OrderForm, SessionInfo, SyncContext } from '../../shared';
|
||||
import { uuid } from './useOrderForm';
|
||||
|
||||
type Update = (change: (form: OrderForm) => OrderForm) => void;
|
||||
interface TemplateRow {
|
||||
id: string;
|
||||
name: string;
|
||||
revision: number;
|
||||
}
|
||||
|
||||
// 开单模板与公式快速开单。模板接口与旧界面相同;公式识别使用共用的 order-formula.js。
|
||||
export function EntryTools({
|
||||
client,
|
||||
state,
|
||||
session,
|
||||
form,
|
||||
ctx,
|
||||
update,
|
||||
reset,
|
||||
}: {
|
||||
client: LedgerClient;
|
||||
state: LedgerState;
|
||||
session: SessionInfo;
|
||||
form: OrderForm;
|
||||
ctx: SyncContext;
|
||||
update: Update;
|
||||
reset: (draft: Record<string, unknown>) => void;
|
||||
}) {
|
||||
return (
|
||||
<Collapse
|
||||
className="entry-tools"
|
||||
items={[
|
||||
{
|
||||
key: 'templates',
|
||||
label: (
|
||||
<span>
|
||||
开单模板 <span className="small muted">选择或保存常用模板</span>
|
||||
</span>
|
||||
),
|
||||
children: <TemplatePanel client={client} state={state} session={session} form={form} reset={reset} />,
|
||||
},
|
||||
...(!form.id
|
||||
? [
|
||||
{
|
||||
key: 'formula',
|
||||
label: (
|
||||
<span>
|
||||
公式快速开单 <span className="small muted">粘贴公式,自动填入商品</span>
|
||||
</span>
|
||||
),
|
||||
children: <FormulaPanel form={form} ctx={ctx} update={update} />,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TemplatePanel({
|
||||
client,
|
||||
state,
|
||||
session,
|
||||
form,
|
||||
reset,
|
||||
}: {
|
||||
client: LedgerClient;
|
||||
state: LedgerState;
|
||||
session: SessionInfo;
|
||||
form: OrderForm;
|
||||
reset: (draft: Record<string, unknown>) => void;
|
||||
}) {
|
||||
const { message, modal } = AntApp.useApp();
|
||||
const [rows, setRows] = useState<TemplateRow[] | null>(null);
|
||||
const [selected, setSelected] = useState('');
|
||||
const [status, setStatus] = useState<{ text: string; error?: boolean }>({ text: '' });
|
||||
const [dialog, setDialog] = useState<null | { kind: 'new' | 'update'; name: string; error: string }>(null);
|
||||
const member = form.member || Model.currentMember(state);
|
||||
const team = Model.teamMode(state);
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const query = team && state.user.role === 'owner' ? '?' + new URLSearchParams({ member }) : '';
|
||||
const result = await client.api<{ rows: TemplateRow[] }>('/api/order-templates' + query);
|
||||
if (!Array.isArray(result.rows)) throw new Error('模板列表未完整返回,请重试。');
|
||||
setRows(result.rows);
|
||||
setSelected(current => (result.rows.some(row => row.id === current) ? current : ''));
|
||||
return true;
|
||||
} catch (err) {
|
||||
setStatus({ text: '模板尚未读到:' + (err as Error).message, error: true });
|
||||
return false;
|
||||
}
|
||||
}, [client, member, team, state.user.role]);
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
const salesperson = Model.defaultSalesperson(state, session);
|
||||
async function apply(id: string) {
|
||||
if (client.busy) throw new Error('正在处理订单,请稍候再套用模板。');
|
||||
if (client.pending()) throw new Error('请先恢复上次未确认的操作,再套用模板。');
|
||||
const user = state.user.id;
|
||||
const [template, latest] = await Promise.all([
|
||||
client.api<{ preset: { lines?: { pocket?: string }[] }; member?: string; name: string }>(
|
||||
'/api/order-templates/' + encodeURIComponent(id),
|
||||
),
|
||||
client.api<SessionInfo>('/api/session'),
|
||||
]);
|
||||
if (latest.user?.id !== user) throw new Error('登录账号已变化,请刷新后再套用模板。');
|
||||
const draft = Templates.apply(template.preset, {
|
||||
today: latest.today,
|
||||
salesperson,
|
||||
pocketKeys: [
|
||||
...new Set([
|
||||
...Model.activePocketKeys(state),
|
||||
...(template.preset.lines || []).map(line => line.pocket || '').filter(Boolean),
|
||||
]),
|
||||
],
|
||||
});
|
||||
draft.salesperson = salesperson;
|
||||
if (team) draft.member = template.member || member;
|
||||
const current = Model.collectDraft(form, state);
|
||||
const hasContent =
|
||||
Copy.hasDraftContent(current, { today: latest.today, salesperson }) ||
|
||||
!!selected ||
|
||||
current.lines.some(
|
||||
line =>
|
||||
line.pricingMode === 'manual' ||
|
||||
(line.laborMode && line.laborMode !== 'gram') ||
|
||||
(line.pieces != null && String(line.pieces) !== '1') ||
|
||||
(line.costLabor as { mode?: string })?.mode === 'gram' ||
|
||||
(line.costMaterial as { mode?: string })?.mode === 'total',
|
||||
);
|
||||
const proceed =
|
||||
!hasContent ||
|
||||
(await modal.confirm({
|
||||
title: '套用模板',
|
||||
content: '当前还有未保存的开单内容。套用模板会替换这份草稿,客户称呼将留空、日期改为今天,是否继续?',
|
||||
okText: '继续',
|
||||
cancelText: '取消',
|
||||
}));
|
||||
if (!proceed) return;
|
||||
reset(draft);
|
||||
setSelected(id);
|
||||
setStatus({ text: '已套用「' + template.name + '」,请核对本次克重、报价和费用后生成单据。' });
|
||||
message.success('模板已填入,生成销售单据后才记账');
|
||||
}
|
||||
async function save() {
|
||||
if (!dialog) return;
|
||||
const name = dialog.name.trim();
|
||||
try {
|
||||
if (!name || name.length > 60) throw new Error('模板名称请填写1~60字。');
|
||||
const row = dialog.kind === 'update' ? rows?.find(value => value.id === selected) : null;
|
||||
const input = {
|
||||
...(team ? { member } : {}),
|
||||
name,
|
||||
preset: Templates.fromDraft(Model.collectDraft(form, state), {
|
||||
pocketKeys: Model.activePocketKeys(state),
|
||||
newId: uuid,
|
||||
}),
|
||||
...(row ? { revision: row.revision } : {}),
|
||||
};
|
||||
const url = '/api/order-templates' + (row ? '/' + encodeURIComponent(row.id) + '/update' : '');
|
||||
const result = await client.mutate<{ id: string; name?: string }>(url, input);
|
||||
setDialog(null);
|
||||
setSelected(result.id);
|
||||
const loaded = await load();
|
||||
setStatus({
|
||||
text:
|
||||
'已保存模板「' + (result.name || name) + '」' + (loaded ? '。' : ';列表暂未读到,可重新读取,当前表单已保留。'),
|
||||
});
|
||||
message.success('模板已保存,当前开单内容保留');
|
||||
} catch (err) {
|
||||
setDialog(current => current && { ...current, error: (err as Error).message.replace('不要重新开单', '不要重复保存模板') });
|
||||
}
|
||||
}
|
||||
async function remove() {
|
||||
const row = rows?.find(value => value.id === selected);
|
||||
if (!row) return;
|
||||
const ok = await modal.confirm({
|
||||
title: '删除模板',
|
||||
content: '删除模板「' + row.name + '」?当前开单内容和已保存订单会保留。',
|
||||
okText: '删除',
|
||||
cancelText: '取消',
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
await client.mutate('/api/order-templates/' + encodeURIComponent(row.id) + '/delete', { revision: row.revision });
|
||||
setSelected('');
|
||||
await load();
|
||||
setStatus({ text: '模板已删除。' });
|
||||
} catch (err) {
|
||||
setStatus({ text: (err as Error).message, error: true });
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div className="template-panel">
|
||||
<Space wrap>
|
||||
<Select
|
||||
aria-label="选择模板"
|
||||
data-testid="template-select"
|
||||
style={{ minWidth: 220 }}
|
||||
value={selected || undefined}
|
||||
placeholder={rows ? '选择后自动填入预设' : '正在读取模板…'}
|
||||
disabled={!rows}
|
||||
options={(rows || []).map(row => ({ value: row.id, label: row.name }))}
|
||||
onChange={id => apply(id).catch(err => setStatus({ text: (err as Error).message, error: true }))}
|
||||
/>
|
||||
<Button onClick={() => setDialog({ kind: 'new', name: '', error: '' })}>保存为新模板</Button>
|
||||
<Button
|
||||
disabled={!selected}
|
||||
onClick={() =>
|
||||
setDialog({ kind: 'update', name: rows?.find(row => row.id === selected)?.name || '', error: '' })
|
||||
}
|
||||
>
|
||||
更新所选模板
|
||||
</Button>
|
||||
<Button disabled={!selected} onClick={() => void remove()}>
|
||||
删除模板
|
||||
</Button>
|
||||
</Space>
|
||||
<p className="small muted">
|
||||
用于普通开单,可以保存未填完的表单。客户称呼和内部备注不存入模板,套用时留空;业务日期和费用日期用今天;每日料价随本次订单日期读取。
|
||||
</p>
|
||||
{status.text && <p className={'small ' + (status.error ? 'danger-text' : 'muted')}>{status.text}</p>}
|
||||
<Modal
|
||||
open={!!dialog}
|
||||
title={dialog?.kind === 'update' ? '更新模板' : '保存为新模板'}
|
||||
okText={dialog?.kind === 'update' ? '保存更新' : '保存模板'}
|
||||
cancelText="取消"
|
||||
onOk={() => void save()}
|
||||
onCancel={() => setDialog(null)}
|
||||
confirmLoading={client.busy}
|
||||
>
|
||||
<p className="small muted">
|
||||
将当前普通开单表单保存为预设,允许金额和克重留空。客户、内部备注、日期及订单编号不存入模板;本次正在填写的内容会保留。
|
||||
</p>
|
||||
<Input
|
||||
aria-label="模板名称"
|
||||
maxLength={60}
|
||||
placeholder="例如:足金手链常用报价"
|
||||
value={dialog?.name || ''}
|
||||
onChange={event => setDialog(current => current && { ...current, name: event.target.value })}
|
||||
/>
|
||||
{dialog?.error && <Alert type="error" showIcon message={dialog.error} style={{ marginTop: 12 }} />}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface FormulaResult {
|
||||
kind: 'note' | 'warning' | 'error';
|
||||
lines: string[];
|
||||
title?: string;
|
||||
pending?: string;
|
||||
}
|
||||
function FormulaPanel({ form, ctx, update }: { form: OrderForm; ctx: SyncContext; update: Update }) {
|
||||
const [text, setText] = useState('');
|
||||
const [result, setResult] = useState<FormulaResult | null>(null);
|
||||
function fill(acceptCalculated: boolean) {
|
||||
try {
|
||||
const parsed = Formula.parseBatch(text, { roundingMode: form.rounding_mode });
|
||||
const summaries = parsed.items.map((item, index) => {
|
||||
const line = item.line,
|
||||
base =
|
||||
line.laborMode === 'gram'
|
||||
? `${line.quantity}克 ×(金价 ${line.goldPrice} + 克工费 ${line.laborRate})`
|
||||
: `${line.quantity}克 × 金价 ${line.goldPrice} + 1件 × 件工费 ${line.laborRate}`;
|
||||
return `本次第 ${index + 1} 件:${base}${line.charges.map(c => ' + 附加费 ' + c.amount).join('')} = ${Model.yuan(item.subtotal)}元`;
|
||||
});
|
||||
summaries.push(
|
||||
`本次商品合计 ${Model.yuan(parsed.subtotal)}元${parsed.roundingMode === 'yuan' ? ',整单取整为 ' + Model.yuan(parsed.total) + '元' : ''}。`,
|
||||
);
|
||||
if (parsed.mismatch && !acceptCalculated) {
|
||||
setResult({
|
||||
kind: 'warning',
|
||||
title: '公式金额与计算结果不一致',
|
||||
lines: [...summaries, ...parsed.warnings, '请修改公式,或按计算结果预填。'],
|
||||
pending: text,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (acceptCalculated && result?.pending !== text) throw new Error('公式已改变,请重新点击“识别并预填”核对');
|
||||
const applied = Model.applyFormulaLines(form, parsed.lines, ctx),
|
||||
filled = applied.filled;
|
||||
update(() => applied.form);
|
||||
setResult({
|
||||
kind: 'note',
|
||||
title: `已预填商品 ${filled.join('、')},共 ${filled.length} 件`,
|
||||
lines: [
|
||||
...summaries,
|
||||
...(parsed.mismatch ? ['已采用左侧公式计算金额,未采用不一致的手写金额。'] : []),
|
||||
(parsed.lines.some(line => line.charges.length)
|
||||
? '附加费已填金额,未判断编绳、烤漆等类目,可自行改名;内部成本请另行核对。'
|
||||
: '') + '已有商品、优惠和客户资料保留,尚未生成订单。',
|
||||
],
|
||||
});
|
||||
setText('');
|
||||
} catch (err) {
|
||||
setResult({ kind: 'error', lines: [(err as Error).message] });
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div className="formula-panel">
|
||||
<Input.TextArea
|
||||
aria-label="粘贴销售公式"
|
||||
rows={4}
|
||||
maxLength={18000}
|
||||
autoComplete="off"
|
||||
placeholder={'0.79×822+120=769\n0.58×(822+45)+55=558\n769+558=1327'}
|
||||
value={text}
|
||||
onChange={event => setText(event.target.value)}
|
||||
/>
|
||||
<Space style={{ marginTop: 8 }}>
|
||||
<Button type="primary" onClick={() => fill(false)}>
|
||||
识别并预填
|
||||
</Button>
|
||||
{result?.kind === 'warning' && <Button onClick={() => fill(true)}>按计算金额预填</Button>}
|
||||
</Space>
|
||||
<p className="small muted">
|
||||
括号内是克工费;金价乘克重后加的是一件工费,再加的金额记为附加费。合计行只校验,不增加商品。客户、货盘及内部成本仍按实际填写。
|
||||
</p>
|
||||
{result && (
|
||||
<Alert
|
||||
role="status"
|
||||
type={result.kind === 'note' ? 'success' : result.kind}
|
||||
message={result.title || (result.kind === 'error' ? result.lines[0] : '')}
|
||||
description={
|
||||
result.kind === 'error' ? undefined : (
|
||||
<div>
|
||||
{result.lines.filter(Boolean).map((line, i) => (
|
||||
<p key={i}>{line}</p>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import { Button, Card, Checkbox, Input } from 'antd';
|
||||
import { Model } from '../../shared';
|
||||
import type { FormSummary, LedgerState, OrderForm } from '../../shared';
|
||||
import { uuid } from './useOrderForm';
|
||||
import { ChoiceField, Field, TextField } from './fields';
|
||||
|
||||
type Update = (change: (form: OrderForm) => OrderForm) => void;
|
||||
|
||||
// 实际费用(内部):费用支付日期、常用成本勾选、附加项目带入的成本行、其他成本、信用卡手续费预览与费用合计。
|
||||
export function FeeCosts({
|
||||
form,
|
||||
state,
|
||||
summary,
|
||||
update,
|
||||
}: {
|
||||
form: OrderForm;
|
||||
state: LedgerState;
|
||||
summary: FormSummary;
|
||||
update: Update;
|
||||
}) {
|
||||
const presets = form.presets;
|
||||
const catalog = Model.presetCatalogView(form, state);
|
||||
const defaults = { certificate: '4', packaging: '3', shipping: '6', ...state.shopSettings?.feeDefaults };
|
||||
return (
|
||||
<Card
|
||||
className="panel internal"
|
||||
title="实际费用(内部)"
|
||||
extra={
|
||||
<Button size="small" data-action="add-fee" onClick={() => update(f => Model.addManualFee(f, state, uuid))}>
|
||||
+ 添加其他成本
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<p className="small muted">
|
||||
{presets
|
||||
? '按实际发生勾选,快递最多选一项;盒子按配置单价和数量计费。取消勾选不记成本,客户收费不受影响。'
|
||||
: form.feeCostMode === 'checkboxes'
|
||||
? '沿用本单已有费用、付款人与支付日期。普通费用按凭据核对;信用卡手续费金额和日期自动维护。'
|
||||
: `上方附加项目自动带入成本。证书默认${defaults.certificate}元、包装${defaults.packaging}元;快递按整单默认${defaults.shipping}元,均可修改。请填写实际已付金额,没有成本填0;不需要的整单费用可移除。开单时记录费用和付款人。`}{' '}
|
||||
客户单据不显示。
|
||||
</p>
|
||||
<div className="grid four">
|
||||
<TextField
|
||||
label="费用实际支付日期"
|
||||
field="fees_date"
|
||||
type="date"
|
||||
value={form.fees_date}
|
||||
onChange={value => update(f => ({ ...f, fees_date: value }))}
|
||||
/>
|
||||
</div>
|
||||
{presets && (
|
||||
<fieldset className="order-cost-presets" data-testid="cost-presets">
|
||||
<legend>常用成本 · 按实际发生勾选</legend>
|
||||
<p className="small muted">快递二选一,也可不选;取消勾选不记成本。</p>
|
||||
<div className="order-cost-options">
|
||||
{catalog.length === 0 && <p>暂无启用的勾选成本,可在店铺配置中添加。</p>}
|
||||
{catalog.map(item => (
|
||||
<div className="order-cost-option" key={item.kind} data-preset={item.kind}>
|
||||
<Checkbox
|
||||
checked={!!presets.checked[item.kind]}
|
||||
onChange={event => update(f => Model.togglePreset(f, item.kind, event.target.checked, state, uuid))}
|
||||
>
|
||||
<strong>{item.name}</strong> <span className="order-cost-price">{item.price}</span>
|
||||
<small className="muted"> {item.kind === 'yt' && !presets.configured ? summary.presetNotes.ytPayer : item.payer}</small>
|
||||
</Checkbox>
|
||||
{item.byQuantity && (
|
||||
<Field label="数量(个)" field={'cost_' + item.kind + '_quantity'} hint={summary.presetNotes[item.kind]}>
|
||||
<Input
|
||||
name={'cost_' + item.kind + '_quantity'}
|
||||
inputMode="numeric"
|
||||
value={presets.quantity[item.kind] ?? '1'}
|
||||
disabled={!presets.checked[item.kind]}
|
||||
onChange={event => update(f => Model.setPresetQuantity(f, item.kind, event.target.value))}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
)}
|
||||
<div className="fee-grid">
|
||||
{form.feeRows.map((row, index) => {
|
||||
const manual = row.key.startsWith('manual:');
|
||||
return (
|
||||
<div className="fee-row" key={row.key} data-fee={row.key} data-fee-index={index}>
|
||||
<div className="fee-title">
|
||||
{manual ? (
|
||||
<TextField
|
||||
label="费用项目名称"
|
||||
field="feeNote"
|
||||
value={row.note}
|
||||
maxLength={150}
|
||||
onChange={value => update(f => Model.editFeeRow(f, index, 'note', value))}
|
||||
/>
|
||||
) : (
|
||||
<strong className="fee-name">{row.note}</strong>
|
||||
)}
|
||||
<span className="small muted fee-source">{Model.feeSourceText(row)}</span>
|
||||
</div>
|
||||
<TextField
|
||||
label="实际成本(元)"
|
||||
field="feeAmount"
|
||||
numeric
|
||||
value={row.amount}
|
||||
placeholder="没有成本填0"
|
||||
onChange={value => update(f => Model.editFeeRow(f, index, 'amount', value))}
|
||||
/>
|
||||
<ChoiceField
|
||||
label="费用付款人"
|
||||
field="feePayer"
|
||||
value={row.payer}
|
||||
options={Model.memberOptions(state, true, { selected: row.payer })}
|
||||
onChange={value => update(f => Model.editFeeRow(f, index, 'payer', value))}
|
||||
/>
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
data-action="remove-fee"
|
||||
onClick={() => update(f => Model.removeFeeRow(f, index))}
|
||||
>
|
||||
移除费用
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{summary.card && (
|
||||
<div className="credit-card-preview" data-testid="credit-card-preview">
|
||||
<div className="credit-card-heading">
|
||||
<strong>信用卡手续费(内部)</strong>
|
||||
<span className="small muted">自动计算 · 客户单据不显示</span>
|
||||
</div>
|
||||
<div className="grid two">
|
||||
<TextField label="手续费(元,自动)" field="credit_card_fee" value={summary.card.amountText} readOnly />
|
||||
<ChoiceField
|
||||
label="手续费付款人"
|
||||
field="credit_card_fee_payer"
|
||||
value={form.credit_card_fee_payer}
|
||||
options={Model.memberOptions(state)}
|
||||
onChange={value => update(f => ({ ...f, credit_card_fee_payer: value }))}
|
||||
/>
|
||||
</div>
|
||||
<p className="small muted" aria-live="polite">
|
||||
{summary.card.formula}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<div className="small fees-total" data-testid="fees-total">
|
||||
{summary.feesText}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
import { Button } from 'antd';
|
||||
import { Model } from '../../shared';
|
||||
import type { LedgerState, LineState, OrderForm } from '../../shared';
|
||||
import { ChoiceField, RadioField, TextField } from './fields';
|
||||
|
||||
type Update = (change: (form: OrderForm) => OrderForm) => void;
|
||||
|
||||
// 内部成本(客户单据不显示):出库货盘、对数、料费(按克料价/总料费/当日加权料价)、进货工费(克工费/总工费)、付款人。
|
||||
export function InternalCosts({
|
||||
index,
|
||||
line,
|
||||
state,
|
||||
update,
|
||||
onReloadPools,
|
||||
}: {
|
||||
index: number;
|
||||
line: LineState;
|
||||
state: LedgerState;
|
||||
update: Update;
|
||||
onReloadPools: () => void;
|
||||
}) {
|
||||
const v = Model.lineVisibility(line, state);
|
||||
const setLine = (change: (line: LineState) => LineState) =>
|
||||
update(form => Model.updateLine(form, index, change(form.lines[index])));
|
||||
const setPurchase = (field: string) => (value: string) => setLine(l => Model.setPurchaseField(l, field, value));
|
||||
const payers = Model.memberOptions(state);
|
||||
const p = line.purchase;
|
||||
const pooled = line.pool?.source === 'pool';
|
||||
const payerOptions = (value: string): [string, string][] =>
|
||||
Model.memberKeys(state).includes(value) ? Model.memberOptions(state, false, { selected: value }) : payers;
|
||||
return (
|
||||
<div className="internal">
|
||||
<div className="internal-title">内部成本 · 客户单据不显示</div>
|
||||
<div className="grid two cost-source-fields">
|
||||
<ChoiceField
|
||||
label="出库货盘(仅黄金)"
|
||||
field="pocket"
|
||||
value={line.pocket}
|
||||
options={Model.pocketOptions(state, line.pocket, line.historicalPocket)}
|
||||
onChange={value => setLine(l => Model.setLineField(l, 'pocket', value))}
|
||||
/>
|
||||
<TextField
|
||||
label="出库数量(对)"
|
||||
field="stockCount"
|
||||
numeric
|
||||
hidden={!v.stockCount}
|
||||
value={line.stockCount}
|
||||
placeholder="一对填1"
|
||||
hint={v.stockCountOptional ? '历史未记录对数,可保留空白;与计工费件数分别填写。' : '与计工费件数分别填写。'}
|
||||
onChange={value => setLine(l => Model.setLineField(l, 'stockCount', value))}
|
||||
/>
|
||||
</div>
|
||||
{line.legacy ? (
|
||||
<TextField label="原单货品成本(旧版未分项)" field="cost" value={line.cost} readOnly />
|
||||
) : (
|
||||
p && (
|
||||
<div className="cost-fields">
|
||||
{line.pool && (
|
||||
<div className="material-source">
|
||||
<div className="grid three">
|
||||
<RadioField
|
||||
label="料费成本来源"
|
||||
field="materialSource"
|
||||
value={line.pool.source}
|
||||
options={[
|
||||
['manual', '手动填写成本'],
|
||||
['pool', '当日加权料价', !v.poolAllowed],
|
||||
]}
|
||||
onChange={value => setLine(l => Model.setPoolSource(l, value as 'manual' | 'pool'))}
|
||||
/>
|
||||
{pooled && (
|
||||
<ChoiceField
|
||||
label="料价日期"
|
||||
field="materialPoolId"
|
||||
value={line.pool.poolId}
|
||||
options={line.pool.options.map(option => [option.value, option.label] as [string, string])}
|
||||
onChange={value =>
|
||||
setLine(l => ({ ...l, pool: l.pool ? { ...l.pool, poolId: value } : l.pool }))
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{pooled && (
|
||||
<div className="field">
|
||||
<label className="field-label"> </label>
|
||||
<Button size="small" data-action="reload-material-choices" onClick={onReloadPools}>
|
||||
刷新料价
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<p className="small muted">{line.pool.help}</p>
|
||||
{pooled && line.view.poolNote && (
|
||||
<p className="small material-pool-note" aria-live="polite" data-testid="pool-note">
|
||||
{line.view.poolNote}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="grid four purchase-cost-grid">
|
||||
{v.materialMode && (
|
||||
<RadioField
|
||||
label="进货料费方式"
|
||||
field="cost-materialMode"
|
||||
value={p.materialMode}
|
||||
options={[
|
||||
['gram', '按克料价', line.unit !== 'g'],
|
||||
['total', '直接填总料费'],
|
||||
]}
|
||||
onChange={setPurchase('materialMode')}
|
||||
/>
|
||||
)}
|
||||
<TextField
|
||||
label={pooled ? '加权进货料价(元/克,自动)' : '进货料价(元/克)'}
|
||||
field="cost-materialRate"
|
||||
numeric
|
||||
hidden={!v.materialRate}
|
||||
readOnly={pooled}
|
||||
value={p.materialRate}
|
||||
placeholder={pooled ? '待核算' : '填写每克进货料价'}
|
||||
onChange={setPurchase('materialRate')}
|
||||
/>
|
||||
<TextField
|
||||
label={pooled ? '耗用料费合计(元,自动)' : '料费成本合计(元)'}
|
||||
field="cost-material"
|
||||
numeric
|
||||
readOnly={v.materialReadOnly}
|
||||
value={p.material}
|
||||
placeholder={pooled ? '待核算' : '开单前必填,没有填0'}
|
||||
onChange={setPurchase('material')}
|
||||
/>
|
||||
{v.materialPayer ? (
|
||||
<ChoiceField
|
||||
label="料费付款人"
|
||||
field="cost-materialPayer"
|
||||
value={p.materialPayer}
|
||||
placeholder="请选择"
|
||||
options={payerOptions(p.materialPayer)}
|
||||
onChange={setPurchase('materialPayer')}
|
||||
/>
|
||||
) : (
|
||||
<TextField
|
||||
label={line.pool?.personal ? '材料原付款人' : '本批购料付款人'}
|
||||
field="cost-materialPoolPayer"
|
||||
value={line.pool?.payerText || ''}
|
||||
readOnly
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<p className="purchase-formula small muted" aria-live="polite">
|
||||
{line.view.materialFormula}
|
||||
</p>
|
||||
{line.view.materialOriginal && <p className="small muted">{line.view.materialOriginal}</p>}
|
||||
<div className="grid four purchase-cost-grid">
|
||||
<RadioField
|
||||
label="进货工费方式"
|
||||
field="cost-laborMode"
|
||||
value={p.laborMode}
|
||||
options={[
|
||||
['gram', '克工费', line.unit !== 'g'],
|
||||
['total', '总工费'],
|
||||
]}
|
||||
onChange={setPurchase('laborMode')}
|
||||
/>
|
||||
<TextField
|
||||
label="进货克工费(元/克)"
|
||||
field="cost-laborRate"
|
||||
numeric
|
||||
hidden={!v.laborRateInput}
|
||||
value={p.laborRate}
|
||||
placeholder="填写每克工费"
|
||||
onChange={setPurchase('laborRate')}
|
||||
/>
|
||||
<TextField
|
||||
label="进货总工费(元)"
|
||||
field="cost-labor"
|
||||
numeric
|
||||
readOnly={v.laborReadOnly}
|
||||
value={p.labor}
|
||||
placeholder="开单前必填,没有填0"
|
||||
onChange={setPurchase('labor')}
|
||||
/>
|
||||
<ChoiceField
|
||||
label="进货工费付款人"
|
||||
field="cost-laborPayer"
|
||||
value={p.laborPayer}
|
||||
placeholder="请选择"
|
||||
options={payerOptions(p.laborPayer)}
|
||||
onChange={setPurchase('laborPayer')}
|
||||
/>
|
||||
</div>
|
||||
<p className="purchase-formula small muted" aria-live="polite">
|
||||
{line.view.laborFormula}
|
||||
</p>
|
||||
{v.extraCosts && (
|
||||
<div className="legacy-extra-costs">
|
||||
<p className="small muted">这里保留原来填写的货品成本,不要在下方实际费用重复登记。</p>
|
||||
<div className="grid three">
|
||||
<TextField
|
||||
label="配件成本(元,本行合计)"
|
||||
field="cost-accessories"
|
||||
numeric
|
||||
value={p.accessories}
|
||||
onChange={setPurchase('accessories')}
|
||||
/>
|
||||
<TextField
|
||||
label="其他货品成本(元,本行合计)"
|
||||
field="cost-other"
|
||||
numeric
|
||||
value={p.other}
|
||||
onChange={setPurchase('other')}
|
||||
/>
|
||||
<ChoiceField
|
||||
label="原有配件及其他成本付款人"
|
||||
field="payer"
|
||||
value={line.payer}
|
||||
options={payers}
|
||||
onChange={value => setLine(l => ({ ...l, payer: value }))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<p className="cost-summary small">
|
||||
本行货品成本合计:
|
||||
{line.view.purchase?.total == null
|
||||
? pooled
|
||||
? '料费待核算'
|
||||
: '请补齐(没有的项目填0)'
|
||||
: '¥' + Model.yuan(line.view.purchase.total)}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { Button, Result, Space, Typography } from 'antd';
|
||||
import { orderAmount } from '../../lib/format';
|
||||
|
||||
export interface IssuedOrder {
|
||||
id: string;
|
||||
paper_number?: string;
|
||||
number?: string;
|
||||
total?: number;
|
||||
rounding_mode?: string;
|
||||
customer?: string;
|
||||
materialCostPending?: boolean;
|
||||
}
|
||||
|
||||
// 开单成功:显示纸单号与成交合计,可打开服务端打印预览 /print/<订单号>,或开始下一张单。
|
||||
export function IssuedResult({
|
||||
order,
|
||||
error,
|
||||
onRetry,
|
||||
onNew,
|
||||
}: {
|
||||
order: IssuedOrder;
|
||||
error: string;
|
||||
onRetry: () => void;
|
||||
onNew: () => void;
|
||||
}) {
|
||||
const loaded = order.total !== undefined;
|
||||
return (
|
||||
<Result
|
||||
status="success"
|
||||
title="销售单据已生成"
|
||||
subTitle={
|
||||
loaded
|
||||
? order.materialCostPending
|
||||
? '收款、费用和出库已记账;料费待补,补足购料后自动核算利润。'
|
||||
: '收款、费用、出库和利润已记账。'
|
||||
: error || '正在读取已生成的销售单…'
|
||||
}
|
||||
extra={
|
||||
<Space direction="vertical" size="large" style={{ width: '100%' }}>
|
||||
{loaded && (
|
||||
<div className="issued-summary" data-testid="issued-summary">
|
||||
<div>
|
||||
<Typography.Text type="secondary">纸单号</Typography.Text>
|
||||
<div className="issued-value" data-testid="issued-paper-number">
|
||||
{order.paper_number || '未分配'}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Typography.Text type="secondary">成交合计</Typography.Text>
|
||||
<div className="issued-value" data-testid="issued-total">
|
||||
{orderAmount(order.total ?? null, order.rounding_mode || 'cent')}
|
||||
</div>
|
||||
</div>
|
||||
{order.customer && (
|
||||
<div>
|
||||
<Typography.Text type="secondary">客户</Typography.Text>
|
||||
<div className="issued-value small">{order.customer}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<Space wrap className="issued-actions">
|
||||
<Button
|
||||
type="primary"
|
||||
size="large"
|
||||
href={'/print/' + encodeURIComponent(order.id)}
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
data-action="print-preview"
|
||||
>
|
||||
打开打印预览
|
||||
</Button>
|
||||
<Button size="large" onClick={onNew} data-action="new-order">
|
||||
开始新的一单
|
||||
</Button>
|
||||
{!loaded && <Button onClick={onRetry}>重新读取订单</Button>}
|
||||
<Button size="large" href="/" type="link">
|
||||
到旧版界面查看订单
|
||||
</Button>
|
||||
</Space>
|
||||
</Space>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
import { Button, Card, Typography } from 'antd';
|
||||
import { Model } from '../../shared';
|
||||
import type { LedgerState, LineState, OrderForm } from '../../shared';
|
||||
import { uuid } from './useOrderForm';
|
||||
import { ChoiceField, RadioField, TextField } from './fields';
|
||||
import { ChargeList } from './ChargeList';
|
||||
import { InternalCosts } from './InternalCosts';
|
||||
|
||||
type Update = (change: (form: OrderForm) => OrderForm) => void;
|
||||
|
||||
// 商品明细:每行商品的名称、计价方式、克重、金价与工费或直接金额、附加项目、本行销售额与内部成本。
|
||||
export function LineItems({
|
||||
form,
|
||||
state,
|
||||
update,
|
||||
onError,
|
||||
onReloadPools,
|
||||
}: {
|
||||
form: OrderForm;
|
||||
state: LedgerState;
|
||||
update: Update;
|
||||
onError: (message: string) => void;
|
||||
onReloadPools: () => void;
|
||||
}) {
|
||||
const guarded = (change: (form: OrderForm) => OrderForm) => {
|
||||
try {
|
||||
update(change);
|
||||
} catch (err) {
|
||||
onError((err as Error).message);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Card className="panel" title="商品明细" extra={<span className="small muted">金价与工费分开填写</span>}>
|
||||
{form.lines.map((line, index) => (
|
||||
<LineCard
|
||||
key={index}
|
||||
index={index}
|
||||
line={line}
|
||||
state={state}
|
||||
canRemove={form.lines.length > 1}
|
||||
update={update}
|
||||
onRemove={() => {
|
||||
if (form.lines.length <= 1) return onError('请至少保留一行商品');
|
||||
guarded(f => Model.removeLine(f, index));
|
||||
}}
|
||||
onReloadPools={onReloadPools}
|
||||
/>
|
||||
))}
|
||||
<div className="form-actions">
|
||||
<Button data-action="add-line" onClick={() => guarded(f => Model.addLine(f, { st: state, uuid }))}>
|
||||
+ 添加商品
|
||||
</Button>
|
||||
<span className="small muted">银饰不扣黄金货盘;外配使用店内金料时,选实际出库货盘。</span>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function LineCard({
|
||||
index,
|
||||
line,
|
||||
state,
|
||||
canRemove,
|
||||
update,
|
||||
onRemove,
|
||||
onReloadPools,
|
||||
}: {
|
||||
index: number;
|
||||
line: LineState;
|
||||
state: LedgerState;
|
||||
canRemove: boolean;
|
||||
update: Update;
|
||||
onRemove: () => void;
|
||||
onReloadPools: () => void;
|
||||
}) {
|
||||
const v = Model.lineVisibility(line, state);
|
||||
const setLine = (change: (line: LineState) => LineState) =>
|
||||
update(form => Model.updateLine(form, index, change(form.lines[index])));
|
||||
const set = (field: string) => (value: string) => setLine(l => Model.setLineField(l, field, value));
|
||||
return (
|
||||
<section className="line-item" data-line={index} aria-label={'商品 ' + (index + 1)}>
|
||||
<div className="line-top">
|
||||
<strong>商品 {String(index + 1).padStart(2, '0')}</strong>
|
||||
<Button type="text" size="small" data-action="remove-line" disabled={!canRemove} onClick={onRemove}>
|
||||
移除
|
||||
</Button>
|
||||
</div>
|
||||
<div className="grid four">
|
||||
<ChoiceField
|
||||
label="商品名称"
|
||||
field="nameType"
|
||||
value={line.nameType}
|
||||
options={[...Model.productNames, '其他'].map(name => [name, name] as [string, string])}
|
||||
onChange={set('nameType')}
|
||||
/>
|
||||
<TextField
|
||||
label="其他商品名称"
|
||||
field="customName"
|
||||
hidden={!v.customName}
|
||||
value={line.customName}
|
||||
maxLength={60}
|
||||
onChange={set('customName')}
|
||||
/>
|
||||
<RadioField
|
||||
label="计价方式"
|
||||
field="pricingMode"
|
||||
value={line.pricingMode}
|
||||
options={[
|
||||
['auto', '按金价与工费计算'],
|
||||
['manual', '直接填写金额'],
|
||||
]}
|
||||
onChange={set('pricingMode')}
|
||||
/>
|
||||
<RadioField
|
||||
label="单位"
|
||||
field="unit"
|
||||
value={line.unit}
|
||||
options={[
|
||||
['g', 'g'],
|
||||
['件', '件'],
|
||||
]}
|
||||
onChange={set('unit')}
|
||||
/>
|
||||
<TextField label="克重/数量" field="quantity" numeric value={line.quantity} onChange={set('quantity')} />
|
||||
</div>
|
||||
<div className="grid four sale-inputs">
|
||||
<TextField
|
||||
label="金价/银价(元/克)"
|
||||
field="goldPrice"
|
||||
numeric
|
||||
hidden={!v.goldPrice}
|
||||
value={line.goldPrice}
|
||||
onChange={set('goldPrice')}
|
||||
/>
|
||||
<RadioField
|
||||
label="销售工费方式"
|
||||
field="laborMode"
|
||||
hidden={!v.laborMode}
|
||||
value={line.laborMode}
|
||||
options={[
|
||||
['gram', '克工费'],
|
||||
['piece', '件工费'],
|
||||
]}
|
||||
onChange={set('laborMode')}
|
||||
/>
|
||||
<TextField
|
||||
label="销售工费"
|
||||
field="laborRate"
|
||||
numeric
|
||||
hidden={!v.laborRate}
|
||||
value={line.laborRate}
|
||||
onChange={set('laborRate')}
|
||||
/>
|
||||
<TextField
|
||||
label="计工费件数"
|
||||
field="pieces"
|
||||
numeric
|
||||
hidden={!v.pieces}
|
||||
value={line.pieces}
|
||||
onChange={set('pieces')}
|
||||
/>
|
||||
<TextField
|
||||
label="销售单价说明(客户可见)"
|
||||
field="priceNote"
|
||||
hidden={!v.priceNote}
|
||||
value={line.priceNote}
|
||||
maxLength={100}
|
||||
onChange={set('priceNote')}
|
||||
/>
|
||||
<TextField
|
||||
label="商品基础金额(不含附加项目)"
|
||||
field="baseSale"
|
||||
numeric
|
||||
hidden={!v.baseSale}
|
||||
value={line.baseSale}
|
||||
onChange={set('baseSale')}
|
||||
/>
|
||||
</div>
|
||||
<ChargeList index={index} line={line} update={update} />
|
||||
<div className="grid two sale-result">
|
||||
<TextField label="本行销售额(元,含附加项目)" field="sale" value={line.sale} readOnly />
|
||||
<Typography.Paragraph className="calculation small" aria-live="polite" data-testid="line-calculation">
|
||||
{line.view.calculation}
|
||||
</Typography.Paragraph>
|
||||
</div>
|
||||
<InternalCosts index={index} line={line} state={state} update={update} onReloadPools={onReloadPools} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { Alert, Button, Card, Input } from 'antd';
|
||||
import { Model } from '../../shared';
|
||||
import type { FormSummary, OrderForm } from '../../shared';
|
||||
import { TextField, Field } from './fields';
|
||||
|
||||
type Update = (change: (form: OrderForm) => OrderForm) => void;
|
||||
|
||||
// 整单优惠、客户单备注、内部备注(快捷标签)、成交合计与提交。
|
||||
export function SummarySection({
|
||||
form,
|
||||
summary,
|
||||
tags,
|
||||
tagsStatus,
|
||||
busy,
|
||||
error,
|
||||
update,
|
||||
onError,
|
||||
}: {
|
||||
form: OrderForm;
|
||||
summary: FormSummary;
|
||||
tags: string[];
|
||||
tagsStatus: string;
|
||||
busy: boolean;
|
||||
error: string;
|
||||
update: Update;
|
||||
onError: (message: string) => void;
|
||||
}) {
|
||||
const shown = Model.filterNoteTags(tags, form.internal_note);
|
||||
const query = /(?:^|[\s,。;、])#([\p{L}\p{N}_-]*)$/u.test(form.internal_note);
|
||||
return (
|
||||
<Card className="panel">
|
||||
<div className="grid two">
|
||||
<TextField
|
||||
label="整单优惠/抹零(元)"
|
||||
field="discount"
|
||||
numeric
|
||||
value={form.discount}
|
||||
onChange={value => update(f => ({ ...f, discount: value }))}
|
||||
/>
|
||||
<Field label="客户单备注" field="note">
|
||||
<Input.TextArea
|
||||
name="note"
|
||||
aria-label="客户单备注"
|
||||
maxLength={240}
|
||||
rows={2}
|
||||
placeholder="只写可让客户看到的内容"
|
||||
value={form.note}
|
||||
onChange={event => update(f => ({ ...f, note: event.target.value }))}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
<Field
|
||||
label={
|
||||
<>
|
||||
内部备注(客户不可见)<span className="small muted">必填,至少3个字符(含#号),最多500字</span>
|
||||
</>
|
||||
}
|
||||
field="internal_note"
|
||||
>
|
||||
<Input.TextArea
|
||||
name="internal_note"
|
||||
aria-label="内部备注"
|
||||
maxLength={500}
|
||||
rows={3}
|
||||
placeholder="仅供内部跟进,不会出现在客户销售单或打印件中"
|
||||
value={form.internal_note}
|
||||
onChange={event => update(f => ({ ...f, internal_note: event.target.value }))}
|
||||
/>
|
||||
</Field>
|
||||
<div className="order-note-tags">
|
||||
<p className="small muted">
|
||||
输入 #词语 添加标签,例如 #补货、#客户自提。保存订单后可复用,点击下方标签即可填入。
|
||||
</p>
|
||||
<div className="order-note-tag-options" aria-label="内部备注快捷标签" data-testid="note-tags">
|
||||
{tagsStatus ? (
|
||||
<span className="small muted">{tagsStatus}</span>
|
||||
) : shown.length ? (
|
||||
shown.map(tag => (
|
||||
<Button
|
||||
key={tag}
|
||||
size="small"
|
||||
data-note-tag={tag}
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
try {
|
||||
const next = Model.insertNoteTag(form.internal_note, tag);
|
||||
update(f => ({ ...f, internal_note: next }));
|
||||
} catch (err) {
|
||||
onError((err as Error).message);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{tag}
|
||||
</Button>
|
||||
))
|
||||
) : (
|
||||
<span className="small muted">
|
||||
{query ? '没有匹配标签,可继续输入新标签。' : '暂无已保存标签,填写 #词语 并保存订单后即可复用。'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="create-submit-bar">
|
||||
<div>
|
||||
<span className="small muted">成交合计</span>
|
||||
<div className="summary-amount" data-testid="create-total">
|
||||
{summary.totalText}
|
||||
</div>
|
||||
<div className="small muted" aria-live="polite" data-testid="rounding-note">
|
||||
{summary.roundingHint}
|
||||
</div>
|
||||
</div>
|
||||
<Button type="primary" htmlType="submit" size="large" loading={busy} data-action="issue">
|
||||
生成销售单据
|
||||
</Button>
|
||||
</div>
|
||||
{error && (
|
||||
<Alert type="error" showIcon message={error} className="order-error" role="alert" data-testid="order-error" />
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
// 表单小部件:带标签的文本、数字、选择与单选。每个字段外层带 data-field,便于核对与自动化操作。
|
||||
import type { ReactNode } from 'react';
|
||||
import { Input, Radio, Select } from 'antd';
|
||||
|
||||
interface Base {
|
||||
label: ReactNode;
|
||||
field: string;
|
||||
hint?: ReactNode;
|
||||
hidden?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
export function Field({ label, field, hint, hidden, className, children }: Base & { children: ReactNode }) {
|
||||
if (hidden) return null;
|
||||
return (
|
||||
<div className={'field ' + (className || '')} data-field={field}>
|
||||
<label className="field-label">{label}</label>
|
||||
{children}
|
||||
{hint ? <div className="field-hint">{hint}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function TextField({
|
||||
value,
|
||||
onChange,
|
||||
numeric,
|
||||
readOnly,
|
||||
disabled,
|
||||
placeholder,
|
||||
maxLength,
|
||||
type,
|
||||
...base
|
||||
}: Base & {
|
||||
value: string;
|
||||
onChange?: (value: string) => void;
|
||||
numeric?: boolean;
|
||||
readOnly?: boolean;
|
||||
disabled?: boolean;
|
||||
placeholder?: string;
|
||||
maxLength?: number;
|
||||
type?: string;
|
||||
}) {
|
||||
return (
|
||||
<Field {...base}>
|
||||
<Input
|
||||
name={base.field}
|
||||
aria-label={typeof base.label === 'string' ? base.label : base.field}
|
||||
value={value}
|
||||
type={type}
|
||||
inputMode={numeric ? 'decimal' : undefined}
|
||||
autoComplete="off"
|
||||
readOnly={readOnly}
|
||||
disabled={disabled}
|
||||
placeholder={placeholder}
|
||||
maxLength={maxLength}
|
||||
className={readOnly ? 'readonly-input' : undefined}
|
||||
onChange={event => onChange?.(event.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
export function ChoiceField({
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
disabled,
|
||||
placeholder,
|
||||
...base
|
||||
}: Base & {
|
||||
value: string;
|
||||
options: [string, string, boolean?][];
|
||||
onChange: (value: string) => void;
|
||||
disabled?: boolean;
|
||||
placeholder?: string;
|
||||
}) {
|
||||
return (
|
||||
<Field {...base}>
|
||||
<Select
|
||||
aria-label={typeof base.label === 'string' ? base.label : base.field}
|
||||
value={value === '' && placeholder ? undefined : value}
|
||||
placeholder={placeholder}
|
||||
disabled={disabled}
|
||||
popupMatchSelectWidth={false}
|
||||
options={options.map(([v, label, off]) => ({ value: v, label, disabled: !!off, title: label }))}
|
||||
onChange={onChange}
|
||||
getPopupContainer={() => document.body}
|
||||
/>
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
export function RadioField({
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
disabled,
|
||||
...base
|
||||
}: Base & {
|
||||
value: string;
|
||||
options: [string, string, boolean?][];
|
||||
onChange: (value: string) => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Field {...base}>
|
||||
<Radio.Group
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
optionType="button"
|
||||
buttonStyle="solid"
|
||||
size="middle"
|
||||
onChange={event => onChange(event.target.value)}
|
||||
options={options.map(([v, label, off]) => ({ value: v, label, disabled: !!off }))}
|
||||
/>
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
// 开单表单状态:每次修改都经共用模型 syncForm 重新同步(等同旧页面每次输入后的 updateTotal)。
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { LedgerClient } from '../../lib/api';
|
||||
import { saveDraft } from '../../lib/drafts';
|
||||
import { Model } from '../../shared';
|
||||
import type {
|
||||
FormSummary,
|
||||
LedgerState,
|
||||
MaterialPools,
|
||||
OrderDraft,
|
||||
OrderForm,
|
||||
QuoteState,
|
||||
SessionInfo,
|
||||
SyncContext,
|
||||
} from '../../shared';
|
||||
|
||||
export interface FormStore {
|
||||
form: OrderForm;
|
||||
draft: OrderDraft;
|
||||
summary: FormSummary;
|
||||
}
|
||||
export const uuid = () => window.crypto.randomUUID();
|
||||
|
||||
export function useOrderForm({
|
||||
client,
|
||||
state,
|
||||
session,
|
||||
initialDraft,
|
||||
}: {
|
||||
client: LedgerClient;
|
||||
state: LedgerState;
|
||||
session: SessionInfo;
|
||||
initialDraft: Record<string, unknown> | null;
|
||||
}) {
|
||||
const [pools, setPools] = useState<MaterialPools | null>(null);
|
||||
const [poolError, setPoolError] = useState('');
|
||||
const [quote, setQuote] = useState<QuoteState | null>(null);
|
||||
const ctx = useMemo<SyncContext>(
|
||||
() => ({ st: state, session, uuid, materialPools: pools, quote }),
|
||||
[state, session, pools, quote],
|
||||
);
|
||||
const ctxRef = useRef(ctx);
|
||||
const [store, setStore] = useState<FormStore>(() =>
|
||||
Model.syncForm(Model.newForm({ st: state, session, uuid }, initialDraft || undefined), {
|
||||
st: state,
|
||||
session,
|
||||
uuid,
|
||||
}),
|
||||
);
|
||||
// 同步计算并立即生效:模型抛出的提示(如“请至少保留一行商品”)直接返回给调用方。
|
||||
const storeRef = useRef(store);
|
||||
const commit = useCallback((next: FormStore) => {
|
||||
storeRef.current = next;
|
||||
setStore(next);
|
||||
}, []);
|
||||
const update = useCallback(
|
||||
(change: (form: OrderForm) => OrderForm) => commit(Model.syncForm(change(storeRef.current.form), ctxRef.current)),
|
||||
[commit],
|
||||
);
|
||||
const reset = useCallback(
|
||||
(draft?: Record<string, unknown> | null) =>
|
||||
commit(Model.syncForm(Model.newForm(ctxRef.current, draft || undefined), ctxRef.current)),
|
||||
[commit],
|
||||
);
|
||||
// 每日料价或分来源报价读到后重新同步(旧页面在读取完成后调用 updateTotal)。
|
||||
useEffect(() => {
|
||||
ctxRef.current = ctx;
|
||||
commit(Model.syncForm(storeRef.current.form, ctx));
|
||||
}, [ctx, commit]);
|
||||
// 填写内容自动暂存。
|
||||
useEffect(() => {
|
||||
saveDraft(window.localStorage, state.user.id, store.draft);
|
||||
}, [store.draft, state.user.id]);
|
||||
|
||||
const [poolsRequest, setPoolsRequest] = useState(0);
|
||||
const loadPools = useCallback(() => setPoolsRequest(value => value + 1), []);
|
||||
useEffect(() => {
|
||||
let current = true;
|
||||
client
|
||||
.api<MaterialPools>('/api/material-pools')
|
||||
.then(result => {
|
||||
if (!Array.isArray(result.rows)) throw new Error('每日料价记录未完整返回,请重新读取。');
|
||||
if (!current) return;
|
||||
setPools(result);
|
||||
setPoolError('');
|
||||
})
|
||||
.catch(err => {
|
||||
if (current)
|
||||
setPoolError(
|
||||
'每日料价尚未读到:' +
|
||||
((err as Error).name === 'AbortError' ? '读取超时,请点击“刷新料价”。' : (err as Error).message),
|
||||
);
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
};
|
||||
}, [client, poolsRequest]);
|
||||
|
||||
// 个人回收料需要服务端分来源报价(旧页面 materialQuoteFor,180ms 去抖)。
|
||||
const quoteInput = useMemo(() => {
|
||||
const input = Model.poolQuoteInput(store.form, ctx);
|
||||
const rows = (pools?.rows || []) as { id: string; personalPools?: unknown }[];
|
||||
const personal = input.entries.some(entry =>
|
||||
rows.some(row => row.id === (entry as { poolId: string }).poolId && row.personalPools !== undefined),
|
||||
);
|
||||
return personal ? JSON.stringify(input) : '';
|
||||
}, [store.form, ctx, pools]);
|
||||
useEffect(() => {
|
||||
if (!quoteInput || (quote && JSON.stringify(quote.input) === quoteInput)) return;
|
||||
let current = true;
|
||||
const timer = window.setTimeout(async () => {
|
||||
const input = JSON.parse(quoteInput);
|
||||
try {
|
||||
const result = await client.api('/api/material-pools/quote', input);
|
||||
if (current) setQuote({ input, result, error: '' });
|
||||
} catch (err) {
|
||||
if (current) setQuote({ input, result: null, error: (err as Error).message });
|
||||
}
|
||||
}, 180);
|
||||
return () => {
|
||||
current = false;
|
||||
window.clearTimeout(timer);
|
||||
};
|
||||
}, [quoteInput, quote, client]);
|
||||
|
||||
return { store, update, reset, ctx, pools, poolError, loadPools };
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import { useState } from 'react';
|
||||
import { Alert, Button, Card, Form, Input, Select, Space, Typography } from 'antd';
|
||||
import type { LedgerClient } from '../../lib/api';
|
||||
import { demoLogin, login, setup, shopName, type SetupInput } from '../../lib/session';
|
||||
import type { SessionInfo } from '../../shared';
|
||||
|
||||
// 登录页:与旧界面相同的三种入口——演示模式一键进入、试用空库初始化、员工下拉加密码登录。
|
||||
export function LoginPage({
|
||||
client,
|
||||
session,
|
||||
onLoggedIn,
|
||||
}: {
|
||||
client: LedgerClient;
|
||||
session: SessionInfo;
|
||||
onLoggedIn: () => void | Promise<void>;
|
||||
}) {
|
||||
const [error, setError] = useState('');
|
||||
const [working, setWorking] = useState('');
|
||||
const name = shopName(null, session);
|
||||
const options = session.loginOptions || [];
|
||||
const intro =
|
||||
session.mode === 'demo'
|
||||
? '用虚构订单练习完整流程,演示数据与新账隔离。'
|
||||
: '先设置账号。当前是本机试用,正式云端开账另行配置。';
|
||||
async function run(key: string, action: () => Promise<unknown>) {
|
||||
setError('');
|
||||
setWorking(key);
|
||||
try {
|
||||
await action();
|
||||
await onLoggedIn();
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
} finally {
|
||||
setWorking('');
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div className="login-wrap">
|
||||
<Card className="login-card">
|
||||
<div className="brand-mark large" aria-hidden="true">
|
||||
{Array.from(name)[0] || '店'}
|
||||
</div>
|
||||
<Typography.Title level={3}>{name} · 新账系统</Typography.Title>
|
||||
<Typography.Paragraph type="secondary">
|
||||
{session.setup || session.mode === 'demo' ? intro : '录入、收款与复核,从同一张订单开始。'}
|
||||
</Typography.Paragraph>
|
||||
<Typography.Paragraph type="secondary" className="small">
|
||||
新版界面(对照试用)·{' '}
|
||||
<a href="/" className="old-ui-link">
|
||||
返回旧版界面
|
||||
</a>
|
||||
</Typography.Paragraph>
|
||||
{error && <Alert type="error" showIcon message={error} className="login-error" role="alert" />}
|
||||
{session.mode === 'demo' ? (
|
||||
<Space direction="vertical" style={{ width: '100%' }}>
|
||||
{options.map(row => (
|
||||
<Button
|
||||
key={row.member}
|
||||
block
|
||||
size="large"
|
||||
type={row.member === 'owner' ? 'primary' : 'default'}
|
||||
loading={working === row.member}
|
||||
disabled={!!working && working !== row.member}
|
||||
onClick={() => run(row.member, () => demoLogin(client, row.member))}
|
||||
>
|
||||
{'以' + row.label + '身份进入演示'}
|
||||
</Button>
|
||||
))}
|
||||
</Space>
|
||||
) : session.setup ? (
|
||||
<SetupForm working={working === 'setup'} onSubmit={input => run('setup', () => setup(client, input))} />
|
||||
) : (
|
||||
<LoginForm
|
||||
options={options}
|
||||
working={working === 'login'}
|
||||
onSubmit={(member, password) => run('login', () => login(client, member, password))}
|
||||
/>
|
||||
)}
|
||||
<Typography.Paragraph type="secondary" className="small login-foot">
|
||||
云端数据库和飞书同步的真实状态,会在系统内显示。
|
||||
</Typography.Paragraph>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LoginForm({
|
||||
options,
|
||||
working,
|
||||
onSubmit,
|
||||
}: {
|
||||
options: { member: string; label: string }[];
|
||||
working: boolean;
|
||||
onSubmit: (member: string, password: string) => void;
|
||||
}) {
|
||||
const [member, setMember] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
return (
|
||||
<form
|
||||
className="login-form"
|
||||
onSubmit={event => {
|
||||
event.preventDefault();
|
||||
onSubmit(member, password);
|
||||
}}
|
||||
>
|
||||
<Form layout="vertical" component={false}>
|
||||
<Form.Item label="登录账号" required>
|
||||
<Select
|
||||
aria-label="登录账号"
|
||||
data-testid="login-member"
|
||||
value={member || undefined}
|
||||
placeholder="请选择账号"
|
||||
options={options.map(row => ({ value: row.member, label: row.label }))}
|
||||
onChange={setMember}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label="密码" required>
|
||||
<Input.Password
|
||||
name="password"
|
||||
aria-label="密码"
|
||||
autoComplete="current-password"
|
||||
value={password}
|
||||
onChange={event => setPassword(event.target.value)}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Button type="primary" htmlType="submit" block size="large" loading={working}>
|
||||
登录
|
||||
</Button>
|
||||
</Form>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function SetupForm({ working, onSubmit }: { working: boolean; onSubmit: (input: SetupInput) => void }) {
|
||||
const [value, setValue] = useState<SetupInput>({
|
||||
storeName: '',
|
||||
ownerLabel: '店主',
|
||||
ownerLoginName: 'owner',
|
||||
ownerPassword: '',
|
||||
});
|
||||
const field = (key: keyof SetupInput) => ({
|
||||
value: value[key],
|
||||
onChange: (event: React.ChangeEvent<HTMLInputElement>) => setValue({ ...value, [key]: event.target.value }),
|
||||
});
|
||||
return (
|
||||
<form
|
||||
className="setup-form"
|
||||
onSubmit={event => {
|
||||
event.preventDefault();
|
||||
onSubmit(value);
|
||||
}}
|
||||
>
|
||||
<Form layout="vertical" component={false}>
|
||||
<Form.Item label="店铺名称" required>
|
||||
<Input name="storeName" aria-label="店铺名称" maxLength={80} {...field('storeName')} />
|
||||
</Form.Item>
|
||||
<Form.Item label="店主显示名" required>
|
||||
<Input name="ownerLabel" aria-label="店主显示名" maxLength={30} {...field('ownerLabel')} />
|
||||
</Form.Item>
|
||||
<Form.Item label="店主登录名" required>
|
||||
<Input name="ownerLoginName" aria-label="店主登录名" maxLength={60} {...field('ownerLoginName')} />
|
||||
</Form.Item>
|
||||
<Form.Item label="店主密码(至少12个字符)" required>
|
||||
<Input.Password
|
||||
name="ownerPassword"
|
||||
aria-label="店主密码"
|
||||
autoComplete="new-password"
|
||||
{...field('ownerPassword')}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Typography.Paragraph type="secondary">进入系统后,在设置 → 员工管理中添加员工。</Typography.Paragraph>
|
||||
<Button type="primary" htmlType="submit" block size="large" loading={working}>
|
||||
建立试用账号
|
||||
</Button>
|
||||
</Form>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user