283 lines
11 KiB
TypeScript
283 lines
11 KiB
TypeScript
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>
|
||
|
|
);
|
||
|
|
}
|