555 lines
22 KiB
TypeScript
555 lines
22 KiB
TypeScript
import type { FormEvent, MouseEvent, SyntheticEvent } from 'react';
|
||
import type { LedgerState, SessionInfo } from '../../shared';
|
||
import type { LedgerClient } from '../../lib/api';
|
||
import type { usePrintStatuses } from '../../lib/printStatus';
|
||
import type {
|
||
ChangeData,
|
||
OwnershipData,
|
||
CancellationData,
|
||
ChangeRequest,
|
||
OwnershipRequest,
|
||
CancellationRequest,
|
||
DetailEntry,
|
||
OrderRecord,
|
||
OrderAfterSaleData,
|
||
OrderAfterSale,
|
||
} from './orderData';
|
||
import type { OrderUi } from './viewTypes';
|
||
import { readOrderRecord, errorStatus, errorMessage as messageOf } from './readOrder';
|
||
interface DialogProps {
|
||
selected: string;
|
||
client: LedgerClient;
|
||
state: LedgerState;
|
||
session: SessionInfo;
|
||
refresh: () => void;
|
||
refreshState: () => Promise<unknown>;
|
||
listIds: string[] | null;
|
||
openOrder: (id: string) => void;
|
||
close: () => void;
|
||
onLost: (message: string) => void;
|
||
printStatuses: ReturnType<typeof usePrintStatuses>;
|
||
}
|
||
type FormKind = { type: 'after' } | { type: 'action' | 'change' | 'ownership' | 'cancellation'; kind: string };
|
||
type DetailForm = HTMLFormElement & { elements: HTMLFormControlsCollection & Record<string, HTMLInputElement> };
|
||
import { useOrderAccess } from './useOrderAccess';
|
||
import { useEffect, useRef, useState } from 'react';
|
||
import { Calc } from '../../shared';
|
||
import { navigate } from '../../lib/router';
|
||
import { orderViews } from './orderViews';
|
||
import { Dialog } from './Dialog';
|
||
import { queues, useRead } from './orderReads';
|
||
|
||
const stop = (e: SyntheticEvent) => {
|
||
e.stopPropagation();
|
||
e.preventDefault();
|
||
};
|
||
const readForm = (form: HTMLFormElement) => Object.fromEntries(new FormData(form)) as Record<string, string>;
|
||
function DetailNavigation({
|
||
ids,
|
||
id,
|
||
open,
|
||
blocked,
|
||
}: {
|
||
ids: string[] | null;
|
||
id: string;
|
||
open: (id: string) => void;
|
||
blocked: boolean;
|
||
}) {
|
||
if (!ids) return null;
|
||
const i = ids.indexOf(id);
|
||
return (
|
||
<div className="order-detail-navigation-row" role="group" aria-label="切换订单">
|
||
<button data-action="order-detail-prev" disabled={blocked || i <= 0} onClick={() => open(ids[i - 1])}>
|
||
← 上一条
|
||
</button>
|
||
<span aria-live="polite">
|
||
{i + 1} / {ids.length}
|
||
</span>
|
||
<button
|
||
data-action="order-detail-next"
|
||
disabled={blocked || i < 0 || i >= ids.length - 1}
|
||
onClick={() => open(ids[i + 1])}
|
||
>
|
||
下一条 →
|
||
</button>
|
||
<small>按当前筛选后的销售订单顺序查看</small>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
export function OrderActionDialog({
|
||
selected: id,
|
||
client,
|
||
state,
|
||
session,
|
||
refresh,
|
||
refreshState,
|
||
listIds,
|
||
openOrder,
|
||
close,
|
||
onLost,
|
||
printStatuses,
|
||
}: DialogProps) {
|
||
const base = '/api/orders/' + encodeURIComponent(id);
|
||
const [generation, reload] = useState(0),
|
||
[form, setForm] = useState<FormKind | null>(null),
|
||
[error, setError] = useState('');
|
||
const [ui, setUi] = useState<OrderUi>({}),
|
||
[expenses, setExpenses] = useState<string[]>([]);
|
||
const current = useRef(0);
|
||
useEffect(
|
||
() => () => {
|
||
current.current++;
|
||
},
|
||
[],
|
||
);
|
||
const details = useRead(async () => {
|
||
const [detail, change, ownership, cancellation] = await Promise.allSettled([
|
||
client.api<unknown>(base),
|
||
client.api<ChangeData>(base + '/change'),
|
||
client.api<OwnershipData>(base + '/ownership'),
|
||
client.api<CancellationData>(base + '/cancellation'),
|
||
]);
|
||
if (detail.status === 'rejected') {
|
||
access.revoke(detail.reason);
|
||
throw detail.reason;
|
||
}
|
||
const order = readOrderRecord(detail.value, id);
|
||
const checks = orderViews({ state, session });
|
||
function entry<Request, T extends { revision: number; requests: Request[] }>(
|
||
result: PromiseSettledResult<T>,
|
||
validate: (request: Request, id: string) => unknown,
|
||
): DetailEntry<T> {
|
||
const identity = { id, user: state.user.id, revision: order!.revision };
|
||
if (result.status === 'rejected') {
|
||
if (access.revoke(result.reason)) throw result.reason;
|
||
return { ...identity, error: messageOf(result.reason) };
|
||
}
|
||
try {
|
||
const data = result.value;
|
||
if (data.revision !== order!.revision || !Array.isArray(data.requests))
|
||
throw new Error('订单已有新记录,请重新读取订单后复核。');
|
||
data.requests.forEach(request => validate(request, id));
|
||
return { ...identity, data };
|
||
} catch (err) {
|
||
return { ...identity, error: messageOf(err) };
|
||
}
|
||
}
|
||
const entries = [
|
||
entry<ChangeRequest, ChangeData>(change, checks.validateOrderChangeRequest),
|
||
entry<OwnershipRequest, OwnershipData>(ownership, checks.validateOrderOwnershipRequest),
|
||
entry<CancellationRequest, CancellationData>(cancellation, checks.validateOrderCancellationRequest),
|
||
] as const;
|
||
return { order, entries };
|
||
}, [id, generation, state.user.id].join('/'));
|
||
const original = details.value?.order;
|
||
const access = useOrderAccess({ client, state, id, watch: !!original, onLost });
|
||
const printStatus = printStatuses[original?.printStatus?.id || id];
|
||
const order = original && printStatus ? { ...original, printStatus } : original;
|
||
const [change, ownership, cancellation] = details.value?.entries || [];
|
||
const pending = client.pending();
|
||
const ctx = {
|
||
state,
|
||
session,
|
||
currentOrder: order,
|
||
orderChangeDetail: change,
|
||
orderOwnershipDetail: ownership,
|
||
orderCancellationDetail: cancellation,
|
||
orderAfterSaleFormEntry: order && {
|
||
id,
|
||
revision: order!.revision,
|
||
user: state.user.id,
|
||
forceApproval: ui.forceApproval,
|
||
},
|
||
ui: {
|
||
...ui,
|
||
actionBlocked: client.busy || !!pending,
|
||
retryBusy: client.busy,
|
||
retryKey: pending?.key === ui.pendingKey ? ui.pendingKey : null,
|
||
},
|
||
navigation: (
|
||
<DetailNavigation ids={listIds} id={id} open={openOrder} blocked={!!form || client.busy || !!client.pending()} />
|
||
),
|
||
};
|
||
const views = orderViews(ctx);
|
||
function clearForm() {
|
||
current.current++;
|
||
setForm(null);
|
||
setError('');
|
||
setExpenses([]);
|
||
setUi({});
|
||
}
|
||
const loadAfter = useRead(
|
||
() => client.api<OrderAfterSaleData>(base + '/after-sale'),
|
||
form?.type === 'after' && id + '/' + generation,
|
||
);
|
||
let panel,
|
||
visibleError = error;
|
||
try {
|
||
if (form?.type === 'after') {
|
||
if (loadAfter.error) visibleError = loadAfter.error;
|
||
else if (!loadAfter.value) panel = <p role="status">正在读取售后资料…</p>;
|
||
else if (
|
||
loadAfter.value.orderId !== id ||
|
||
loadAfter.value.revision !== order!.revision ||
|
||
!loadAfter.value.eligible ||
|
||
loadAfter.value.record ||
|
||
!views.orderAfterSalePocketKeys().length ||
|
||
order!.lines.some(
|
||
l => l.unit !== 'g' || !l.costParts || l.costParts.material == null || l.costParts.labor == null,
|
||
)
|
||
)
|
||
visibleError = loadAfter.value.blockedReason || '请重新核对原单成本、自有货盘与售后资格。';
|
||
else
|
||
panel = orderViews({
|
||
...ctx,
|
||
ui: {
|
||
...ui,
|
||
expenses: expenses.map(key => (
|
||
<div key={key} data-expense-id={key}>
|
||
{views.orderAfterSaleExpenseHTML()}
|
||
</div>
|
||
)),
|
||
},
|
||
}).orderAfterSaleFormHTML(order!);
|
||
} else if (form?.type === 'action') panel = views.showAction(form.kind);
|
||
else if (form)
|
||
panel = {
|
||
change: views.showOrderChangeForm,
|
||
ownership: views.showOrderOwnershipForm,
|
||
cancellation: views.showOrderCancellationForm,
|
||
}[form.type](form.kind);
|
||
} catch (err) {
|
||
visibleError = messageOf(err);
|
||
}
|
||
function refreshDetail() {
|
||
clearForm();
|
||
reload(v => v + 1);
|
||
refresh();
|
||
}
|
||
async function onClick(event: MouseEvent<HTMLDivElement>) {
|
||
if (!(event.target instanceof Element)) return;
|
||
const target = event.target.closest<HTMLButtonElement>('[data-action]');
|
||
if (!target) return;
|
||
event.stopPropagation();
|
||
const { action = '', id: targetId = '' } = target.dataset;
|
||
try {
|
||
if (action === 'close-dialog' || action === 'order-detail-prev' || action === 'order-detail-next') return;
|
||
if (action === 'print') {
|
||
window.open('/print/' + encodeURIComponent(id) + '?mode=full', '_blank', 'noopener');
|
||
return await client.mutate(base + '/print', { mode: 'full' });
|
||
}
|
||
if (action === 'recovery-print')
|
||
return window.open('/print/recoveries/' + encodeURIComponent(targetId), '_blank', 'noopener');
|
||
if (action === 'edit-order') return navigate('order-edit', { search: '?order=' + encodeURIComponent(id) });
|
||
if (action === 'edit') return navigate('create', { search: '?draft=' + encodeURIComponent(id) });
|
||
if (action === 'goto-team-funds') return navigate('team-funds');
|
||
if (action === 'goto-material-pools') return navigate('material-pools');
|
||
if (action === 'open-price-lock')
|
||
return navigate('price-locks', { search: '?lock=' + encodeURIComponent(targetId) });
|
||
if (action === 'recovery-open')
|
||
return navigate('recoveries', { search: '?recovery=' + encodeURIComponent(targetId) });
|
||
if (action.includes('reload') || action.includes('retry')) return refreshDetail();
|
||
if (action.includes('close') || action === 'hide-action') return clearForm();
|
||
if (client.busy || client.pending()) throw new Error('请先恢复原操作。');
|
||
if (action === 'order-after-sale-preview') {
|
||
const node = target.form as DetailForm;
|
||
const input = views.orderAfterSaleInput(node);
|
||
const version = ++current.current;
|
||
const signature = JSON.stringify(input);
|
||
node.elements.verified.checked = false;
|
||
setUi(old => ({
|
||
...old,
|
||
preview: null,
|
||
verified: false,
|
||
afterError: '',
|
||
previewLoading: true,
|
||
previewStatus: '正在按原单成本核对售后…',
|
||
}));
|
||
let result;
|
||
try {
|
||
result = await client.api<{ before: OrderRecord; after: OrderRecord; afterSale?: OrderAfterSale }>(
|
||
base + '/after-sale-preview',
|
||
input,
|
||
);
|
||
} catch (err) {
|
||
if (current.current === version) throw err;
|
||
return;
|
||
}
|
||
if (current.current !== version) return;
|
||
if (result.before?.id !== id || result.after?.id !== id || result.before.revision !== order!.revision)
|
||
throw new Error('售后预览与当前订单不一致,请重新读取。');
|
||
const record = result.afterSale || result.after.orderAfterSale!;
|
||
views.orderAfterSaleSummaryHTML(record, { preview: true });
|
||
setUi(old => ({
|
||
...old,
|
||
preview: { record, signature },
|
||
previewLoading: false,
|
||
previewStatus: '预览已更新,请核对后勾选确认。',
|
||
}));
|
||
return;
|
||
}
|
||
if (action === 'order-after-sale-add-expense' || action === 'order-after-sale-remove-expense') {
|
||
current.current++;
|
||
const form = target.form as DetailForm | null;
|
||
if (form?.elements.verified) form.elements.verified.checked = false;
|
||
setUi(v => ({
|
||
...v,
|
||
preview: null,
|
||
previewLoading: false,
|
||
verified: false,
|
||
previewStatus: '资料已修改,请重新核对售后预览。',
|
||
}));
|
||
const key = target.closest<HTMLElement>('[data-expense-id]')?.dataset.expenseId;
|
||
setExpenses(items =>
|
||
action.endsWith('add-expense') ? [...items, crypto.randomUUID()] : items.filter(x => x !== key),
|
||
);
|
||
return;
|
||
}
|
||
clearForm();
|
||
if (action === 'order-after-sale-open') return setForm({ type: 'after' });
|
||
if (action.startsWith('order-ownership-'))
|
||
return setForm({ type: 'ownership', kind: action.slice('order-ownership-'.length) });
|
||
if (action.endsWith('-order-change')) return setForm({ type: 'change', kind: action.split('-')[0] });
|
||
if (action.endsWith('-order-cancellation')) return setForm({ type: 'cancellation', kind: action.split('-')[0] });
|
||
if (action.startsWith('show-')) {
|
||
const kind = action.slice(5);
|
||
if (views.orderActionUsesChangeForm(kind)) {
|
||
const data = change?.data;
|
||
if (!data || change.error) throw new Error('请重新读取订单并核对修改申请。');
|
||
const eligibility = data.actions?.[kind] || data;
|
||
if (!eligibility.eligible || data.pending || order!.cancellationPending)
|
||
throw new Error(eligibility.reason || '本单暂不能提交变更申请,请重新读取。');
|
||
}
|
||
setUi({ action: kind, formKey: current.current });
|
||
return setForm({ type: 'action', kind });
|
||
}
|
||
} catch (err) {
|
||
if (action === 'order-after-sale-preview')
|
||
setUi(old => ({
|
||
...old,
|
||
preview: null,
|
||
previewLoading: false,
|
||
verified: false,
|
||
stale: [403, 404, 409].includes(errorStatus(err)),
|
||
afterError: messageOf(err),
|
||
previewStatus: '预览未完成,请核对提示后重新预览。',
|
||
}));
|
||
else setError(messageOf(err));
|
||
}
|
||
}
|
||
function onChange(e: FormEvent<HTMLDivElement>) {
|
||
const target = e.target;
|
||
if (!(
|
||
target instanceof HTMLInputElement ||
|
||
target instanceof HTMLSelectElement ||
|
||
target instanceof HTMLTextAreaElement
|
||
))
|
||
return;
|
||
const node = target.form as DetailForm | null;
|
||
if (!node) return;
|
||
if (form?.type === 'action') {
|
||
const values = readForm(node);
|
||
if (
|
||
target.name === 'date' &&
|
||
views.orderActionRequiresApproval(form.kind, ui.date) !==
|
||
views.orderActionRequiresApproval(form.kind, values.date) &&
|
||
node.elements.verified
|
||
)
|
||
node.elements.verified.checked = false;
|
||
const recipient = ui.paymentMethod === '信用卡' ? ui.recipient : node.elements.payment_recipient?.value;
|
||
const showingCard = node.elements.credit_card_fee_payer?.disabled === false;
|
||
setUi(old => ({
|
||
...old,
|
||
action: form.kind,
|
||
values,
|
||
date: values.date,
|
||
paymentMethod: values.payment_method,
|
||
recipient,
|
||
lastCardBasis: showingCard ? values.amount : old.lastCardBasis,
|
||
}));
|
||
return;
|
||
}
|
||
if (form?.type !== 'after') return;
|
||
if (target.name === 'verified') {
|
||
setUi(old => ({ ...old, verified: (target as HTMLInputElement).checked }));
|
||
return;
|
||
}
|
||
current.current++;
|
||
const data = readForm(node);
|
||
let cents = null;
|
||
try {
|
||
cents = order!.netReceived - Calc.cents(data.refund_amount);
|
||
} catch {
|
||
/* 未填写时保留待填写提示。 */
|
||
}
|
||
if (target.name === 'refund_account')
|
||
node.elements.refund_payer.value = views.orderAfterSaleAccountPayer(target.value);
|
||
node.elements.verified.checked = false;
|
||
const lines = Array.from(node.querySelectorAll('[data-after-sale-line]'), row => ({
|
||
pocket: row.querySelector<HTMLSelectElement>('[name=return_pocket]')!.value,
|
||
disposition: row.querySelector<HTMLSelectElement>('[name=return_disposition]')!.value,
|
||
}));
|
||
setUi(old => ({
|
||
...old,
|
||
lines,
|
||
preview: null,
|
||
previewLoading: false,
|
||
verified: false,
|
||
date: data.date,
|
||
previewStatus: '资料已修改,请重新核对售后预览。',
|
||
reasonRequired: cents !== null && cents > 0,
|
||
retained: cents === null ? '待填写退款金额' : cents < 0 ? '退款超出净实收' : '¥' + (cents / 100).toFixed(2),
|
||
}));
|
||
}
|
||
async function submit(e: FormEvent<HTMLDivElement>) {
|
||
stop(e);
|
||
if (!form || !(e.target instanceof HTMLFormElement)) return;
|
||
const node = e.target as DetailForm,
|
||
data = readForm(node),
|
||
kind = node.dataset.kind!;
|
||
let submittedDirect = false;
|
||
let submittedKey: string | undefined;
|
||
const retryKey = ((e.nativeEvent as SubmitEvent).submitter as HTMLElement | null)?.dataset.retryKey;
|
||
try {
|
||
if (client.busy) return;
|
||
if (retryKey) {
|
||
const job = client.pending();
|
||
if (!job || job.key !== retryKey || job.key !== ui.pendingKey) return;
|
||
submittedKey = job.key;
|
||
submittedDirect = job.url === base + '/' + kind;
|
||
await client.retryPending();
|
||
refreshDetail();
|
||
await refreshState();
|
||
return;
|
||
}
|
||
if (client.pending()) return;
|
||
let url, payload;
|
||
if (form.type === 'after') {
|
||
const input = views.orderAfterSaleInput(node);
|
||
payload = input;
|
||
if (ui.stale || ui.previewLoading || ui.preview?.signature !== JSON.stringify(payload))
|
||
throw new Error('请先重新核对本次售后预览。');
|
||
if (change?.data?.pending || order!.cancellationPending || views.orderAfterSaleRecord(order))
|
||
throw new Error('本单已变动或有待复核申请,请重新读取。');
|
||
if (!ui.verified) throw new Error('请核对售后预览,并勾选实物、实际退款和成本确认。');
|
||
const approve = views.orderAfterSaleApproval(payload.date);
|
||
submittedDirect = !approve;
|
||
if (approve) payload = { ...input, action: 'return' };
|
||
url = base + (approve ? '/change' : '/return');
|
||
} else if (form.type === 'action') {
|
||
payload = views.actionInput(node);
|
||
url = base + '/' + kind;
|
||
if (views.orderActionUsesChangeForm(kind)) {
|
||
if (ui.stale || !change?.data) throw new Error('请重新读取订单后核对本次申请。');
|
||
const approve = views.orderActionRequiresApproval(kind, payload.date);
|
||
payload = {
|
||
...payload,
|
||
...(approve ? { action: kind } : {}),
|
||
revision: order!.revision,
|
||
verified: data.verified === 'on',
|
||
reason: (data.change_reason || data.reason || '').trim(),
|
||
};
|
||
if (!payload.reason || payload.reason.length > 200)
|
||
throw new Error((approve ? '申请原因' : '登记原因') + '请填写1~200字。');
|
||
if (!payload.verified) throw new Error('请核实本次金额、付款人或账户、退货去向,并勾选确认。');
|
||
submittedDirect = !approve;
|
||
if (approve) url = base + '/change';
|
||
}
|
||
} else {
|
||
const info = { change, ownership, cancellation }[form.type]!.data!,
|
||
req = info.pending;
|
||
if (kind === 'approve' || kind === 'reject') {
|
||
if (!req || req.status !== 'pending' || !info.canApprove) throw new Error('请重新读取后复核。');
|
||
if (
|
||
kind === 'approve' &&
|
||
(!req.canApprove || req.stale || req.order_revision !== order!.revision || !data.verified)
|
||
)
|
||
throw new Error('订单已有变动,请重新读取后复核。');
|
||
url = queues.find(([type]) => type === form.type)![1] + '/' + encodeURIComponent(req.id) + '/' + kind;
|
||
payload = {
|
||
...(kind === 'approve' ? { revision: req.order_revision, verified: true } : {}),
|
||
note: data.note.trim(),
|
||
};
|
||
} else if (form.type === 'ownership') {
|
||
payload = { member: data.member, revision: order!.revision, reason: data.reason.trim(), verified: true };
|
||
url = base + '/ownership';
|
||
} else {
|
||
payload = {
|
||
revision: order!.revision,
|
||
reason: data.reason.trim(),
|
||
...(kind === 'direct' ? { date: cancellation!.data!.directActionDate, verified: true } : {}),
|
||
};
|
||
url = base + (kind === 'direct' ? '/canceltoday' : '/cancellation');
|
||
}
|
||
if (data.legacyCountVerified) payload = { ...payload, legacyCountVerified: true };
|
||
}
|
||
const saving = client.mutate(url, payload);
|
||
submittedKey = client.pending()?.key;
|
||
await saving;
|
||
refreshDetail();
|
||
await refreshState();
|
||
} catch (err) {
|
||
if (await access.checkFailure(err)) return;
|
||
if (form.type === 'after') {
|
||
const forceApproval = errorStatus(err) === 403 && submittedDirect && !client.pending();
|
||
const stale = !forceApproval && [403, 404, 409].includes(errorStatus(err));
|
||
if (forceApproval || stale) node.elements.verified.checked = false;
|
||
setUi(old => ({
|
||
...old,
|
||
...(forceApproval
|
||
? { forceApproval: true, verified: false }
|
||
: stale
|
||
? { stale: true, preview: null, verified: false }
|
||
: {}),
|
||
afterError: messageOf(err) + (forceApproval ? ' 输入已保留,重新核实后提交店主复核。' : ''),
|
||
}));
|
||
} else if (
|
||
form.type === 'action' &&
|
||
views.orderActionUsesChangeForm(kind) &&
|
||
([403, 404, 409].includes(errorStatus(err)) || (submittedKey && submittedKey === client.pending()?.key))
|
||
) {
|
||
const forceApproval = errorStatus(err) === 403 && submittedDirect && !client.pending();
|
||
const rejected = [403, 404, 409].includes(errorStatus(err));
|
||
if (rejected && node.elements.verified) node.elements.verified.checked = false;
|
||
setUi(old => ({
|
||
...old,
|
||
forceApproval,
|
||
pendingKey: submittedKey,
|
||
stale: !forceApproval && rejected,
|
||
actionError: messageOf(err) + (forceApproval ? ' 输入已保留,请重新核实后提交店主审批。' : ''),
|
||
}));
|
||
} else setError(messageOf(err));
|
||
}
|
||
}
|
||
if (form?.type === 'after' && (ui.stale || client.pending() || client.busy))
|
||
panel = (
|
||
<>
|
||
<fieldset disabled>{panel}</fieldset>
|
||
<button type="button" onClick={refreshDetail}>
|
||
重新读取订单
|
||
</button>
|
||
<button type="button" onClick={clearForm} disabled={client.busy}>
|
||
收起
|
||
</button>
|
||
</>
|
||
);
|
||
return (
|
||
<Dialog id="order-dialog" label="关闭订单" close={close}>
|
||
<div id="order-content" onClick={onClick} onChange={onChange} onSubmit={submit}>
|
||
{details.error ? (
|
||
<p role="alert">
|
||
{details.error} <button onClick={refreshDetail}>重新读取</button>
|
||
</p>
|
||
) : !order ? (
|
||
'正在读取订单…'
|
||
) : (
|
||
orderViews({ ...ctx, detailForm: panel, error: visibleError }).renderDetail()
|
||
)}
|
||
</div>
|
||
</Dialog>
|
||
);
|
||
}
|
||
|
||
export { IndependentAfterSale } from './IndependentAfterSale';
|