第4项:对页面、表单及两版共享规则启用严格类型检查
This commit is contained in:
1 parent
389952f31c
commit
f570929cfe
77 files changed
+7629
-2981
No files matched your search
@@ -0,0 +1,39 @@
|
||||
import { useRef, useEffect, type ReactNode } from 'react';
|
||||
export function Dialog({
|
||||
id,
|
||||
label,
|
||||
close,
|
||||
children,
|
||||
ownClose = false,
|
||||
}: {
|
||||
id: string;
|
||||
label: string;
|
||||
close: () => void;
|
||||
children: ReactNode;
|
||||
ownClose?: boolean;
|
||||
}) {
|
||||
const ref = useRef<HTMLDialogElement>(null);
|
||||
useEffect(() => {
|
||||
const node = ref.current!;
|
||||
node.showModal();
|
||||
return () => node.close();
|
||||
}, []);
|
||||
return (
|
||||
<dialog
|
||||
id={id}
|
||||
ref={ref}
|
||||
aria-label={label}
|
||||
onCancel={event => {
|
||||
event.preventDefault();
|
||||
close();
|
||||
}}
|
||||
>
|
||||
{!ownClose && (
|
||||
<button type="button" className="dialog-close" data-action="close-dialog" aria-label={label} onClick={close}>
|
||||
×
|
||||
</button>
|
||||
)}
|
||||
{children}
|
||||
</dialog>
|
||||
);
|
||||
}
|
||||
+67
-29
@@ -1,8 +1,24 @@
|
||||
import { Fragment } from 'react';
|
||||
import { Fragment, type InputHTMLAttributes, type SelectHTMLAttributes, type ReactNode } from 'react';
|
||||
import type { ChargeState, OrderForm, LineState, PurchaseState, SyncContext, LedgerState } from '../../shared';
|
||||
import type { FormStore } from '../CreateOrder/useOrderForm';
|
||||
|
||||
interface FieldProps {
|
||||
label: ReactNode;
|
||||
help?: ReactNode;
|
||||
onChange?: (value: string) => void;
|
||||
value?: string | number | null;
|
||||
}
|
||||
type InputProps = FieldProps & Omit<InputHTMLAttributes<HTMLInputElement>, keyof FieldProps>;
|
||||
type Option = string | readonly [string, string, boolean?];
|
||||
type ChoiceProps = FieldProps &
|
||||
Omit<SelectHTMLAttributes<HTMLSelectElement>, keyof FieldProps> & { options: readonly Option[] };
|
||||
type UpdateForm = (change: (form: OrderForm) => OrderForm) => void;
|
||||
type TextKey<T> = { [K in keyof T]-?: T[K] extends string ? K : never }[keyof T];
|
||||
|
||||
import { Fees, Model } from '../../shared';
|
||||
import { uuid } from '../CreateOrder/useOrderForm';
|
||||
|
||||
export function Input({ label, name, value, type = 'text', hidden, help, onChange, ...props }) {
|
||||
export function Input({ label, name, value, type = 'text', hidden, help, onChange, ...props }: InputProps) {
|
||||
return (
|
||||
<label hidden={hidden}>
|
||||
{label}
|
||||
@@ -18,7 +34,7 @@ export function Input({ label, name, value, type = 'text', hidden, help, onChang
|
||||
</label>
|
||||
);
|
||||
}
|
||||
export function Choice({ label, name, value, options, hidden, help, onChange, ...props }) {
|
||||
export function Choice({ label, name, value, options, hidden, help, onChange, ...props }: ChoiceProps) {
|
||||
return (
|
||||
<label hidden={hidden}>
|
||||
{label}
|
||||
@@ -26,11 +42,11 @@ export function Choice({ label, name, value, options, hidden, help, onChange, ..
|
||||
{...props}
|
||||
name={name}
|
||||
value={value ?? ''}
|
||||
onChange={e => onChange(e.target.value)}
|
||||
onChange={e => onChange?.(e.target.value)}
|
||||
disabled={hidden || props.disabled}
|
||||
>
|
||||
{options.map(option => {
|
||||
const [key, name, disabled] = Array.isArray(option) ? option : [option, option];
|
||||
const [key, name, disabled] = typeof option === 'string' ? [option, option] : option;
|
||||
return (
|
||||
<option key={key} value={key} disabled={!!disabled}>
|
||||
{name}
|
||||
@@ -43,27 +59,52 @@ export function Choice({ label, name, value, options, hidden, help, onChange, ..
|
||||
);
|
||||
}
|
||||
const money = { type: 'number', step: '0.01', min: '0' };
|
||||
const categories: Record<string, string> = {
|
||||
jd: 'shipping',
|
||||
yt: 'shipping',
|
||||
box: 'box',
|
||||
steel: 'braiding',
|
||||
silver: 'silverChain',
|
||||
};
|
||||
const amountPlaceholder = '开单前必填,没有填0';
|
||||
export function EditLine({ index, line, state, ctx, form, update, reloadPools, error }) {
|
||||
export function EditLine({
|
||||
index,
|
||||
line,
|
||||
state,
|
||||
ctx,
|
||||
form,
|
||||
update,
|
||||
reloadPools,
|
||||
error,
|
||||
}: {
|
||||
index: number;
|
||||
line: LineState;
|
||||
state: LedgerState;
|
||||
ctx: SyncContext;
|
||||
form: OrderForm;
|
||||
update: UpdateForm;
|
||||
reloadPools: () => void;
|
||||
error: (message: string) => void;
|
||||
}) {
|
||||
const v = Model.lineVisibility(line, state),
|
||||
p = line.purchase,
|
||||
pool = line.pool,
|
||||
pooled = pool?.source === 'pool',
|
||||
prefix = 'cost-';
|
||||
const change = fn => update(f => Model.updateLine(f, index, fn(f.lines[index])));
|
||||
const prop = name => ({
|
||||
const change = (fn: (line: LineState) => LineState) => update(f => Model.updateLine(f, index, fn(f.lines[index])));
|
||||
const prop = (name: TextKey<LineState>) => ({
|
||||
name,
|
||||
value: line[name],
|
||||
onChange: value => change(l => Model.setLineField(l, name, value)),
|
||||
onChange: (value: string) => change(l => Model.setLineField(l, name, value)),
|
||||
});
|
||||
const cost = name => ({
|
||||
const cost = (name: TextKey<PurchaseState>) => ({
|
||||
name: prefix + name,
|
||||
value: p[name],
|
||||
onChange: value => change(l => Model.setPurchaseField(l, name, value)),
|
||||
value: p![name],
|
||||
onChange: (value: string) => change(l => Model.setPurchaseField(l, name, value)),
|
||||
});
|
||||
const laborFunding = p?.costFundings?.labor;
|
||||
const members = value => Model.memberOptions(state, false, { selected: value });
|
||||
function updateCharge(i, fn) {
|
||||
const members = (value: string) => Model.memberOptions(state, false, { selected: value });
|
||||
function updateCharge(i: number, fn: (charge: ChargeState) => ChargeState) {
|
||||
change(l => ({ ...l, charges: l.charges.map((c, j) => (j === i ? fn(c) : c)) }));
|
||||
}
|
||||
return (
|
||||
@@ -77,7 +118,7 @@ export function EditLine({ index, line, state, ctx, form, update, reloadPools, e
|
||||
try {
|
||||
update(f => Model.removeLine(f, index));
|
||||
} catch (err) {
|
||||
error(err.message);
|
||||
error(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}}
|
||||
>
|
||||
@@ -226,7 +267,7 @@ export function EditLine({ index, line, state, ctx, form, update, reloadPools, e
|
||||
]}
|
||||
value={pool.source}
|
||||
disabled={!v.poolAllowed}
|
||||
onChange={source => change(l => Model.setPoolSource(l, source))}
|
||||
onChange={source => change(l => Model.setPoolSource(l, source as 'manual' | 'pool'))}
|
||||
/>
|
||||
<Choice
|
||||
label="料价日期"
|
||||
@@ -234,7 +275,7 @@ export function EditLine({ index, line, state, ctx, form, update, reloadPools, e
|
||||
value={pool.poolId}
|
||||
options={pool.options.map(x => [x.value, x.label])}
|
||||
hidden={!pooled}
|
||||
onChange={poolId => change(l => ({ ...l, pool: { ...l.pool, poolId, defaultDate: false } }))}
|
||||
onChange={poolId => change(l => ({ ...l, pool: { ...l.pool!, poolId, defaultDate: false } }))}
|
||||
/>
|
||||
<button type="button" onClick={reloadPools}>
|
||||
刷新料价
|
||||
@@ -272,7 +313,7 @@ export function EditLine({ index, line, state, ctx, form, update, reloadPools, e
|
||||
label="料费付款人"
|
||||
{...cost('materialPayer')}
|
||||
required
|
||||
options={members(p.materialPayer)}
|
||||
options={members(p!.materialPayer)}
|
||||
hidden={!v.materialPayer}
|
||||
/>
|
||||
</div>
|
||||
@@ -308,7 +349,7 @@ export function EditLine({ index, line, state, ctx, form, update, reloadPools, e
|
||||
{...cost('laborPayer')}
|
||||
required
|
||||
disabled={!!laborFunding}
|
||||
options={members(p.laborPayer)}
|
||||
options={members(p!.laborPayer)}
|
||||
/>
|
||||
{laborFunding && (
|
||||
<input
|
||||
@@ -329,8 +370,8 @@ export function EditLine({ index, line, state, ctx, form, update, reloadPools, e
|
||||
</details>
|
||||
) : (
|
||||
<>
|
||||
{['accessories', 'other'].map(key => (
|
||||
<input key={key} type="hidden" name={prefix + key} value={p[key]} />
|
||||
{(['accessories', 'other'] as const).map(key => (
|
||||
<input key={key} type="hidden" name={prefix + key} value={p![key]} />
|
||||
))}
|
||||
<input type="hidden" name="payer" value={line.payer} />
|
||||
</>
|
||||
@@ -341,16 +382,12 @@ export function EditLine({ index, line, state, ctx, form, update, reloadPools, e
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function EditFees({ store, state, update }) {
|
||||
export function EditFees({ store, state, update }: { store: FormStore; state: LedgerState; update: UpdateForm }) {
|
||||
const { form, summary } = store,
|
||||
presets = form.presets;
|
||||
const hasLinkedCost = kind =>
|
||||
const hasLinkedCost = (kind: string) =>
|
||||
form.feeRows.some(
|
||||
row =>
|
||||
row.funding &&
|
||||
(row.key === Fees.presetKey(kind) ||
|
||||
Fees.checkboxCategory(row.note) ===
|
||||
{ jd: 'shipping', yt: 'shipping', box: 'box', steel: 'braiding', silver: 'silverChain' }[kind]),
|
||||
row => row.funding && (row.key === Fees.presetKey(kind) || Fees.checkboxCategory(row.note) === categories[kind]),
|
||||
);
|
||||
return (
|
||||
<section className="panel internal">
|
||||
@@ -406,7 +443,8 @@ export function EditFees({ store, state, update }) {
|
||||
)}
|
||||
<div id="fee-rows">
|
||||
{form.feeRows.map((row, i) => {
|
||||
const edit = (key, value) => update(f => Model.editFeeRow(f, i, key, value));
|
||||
const edit = (key: 'note' | 'payer' | 'amount' | 'date', value: string) =>
|
||||
update(f => Model.editFeeRow(f, i, key, value));
|
||||
const ref = row.funding;
|
||||
return (
|
||||
<div key={row.key} className="fee-row grid four">
|
||||
@@ -0,0 +1,310 @@
|
||||
import { App as AntApp } from 'antd';
|
||||
import { useEffect, useRef, useState, type FormEvent, type MouseEvent } from 'react';
|
||||
import { Calc, type LedgerState, type SessionInfo } from '../../shared';
|
||||
import type { LedgerClient } from '../../lib/api';
|
||||
import { orderViews } from './orderViews';
|
||||
import { Dialog } from './Dialog';
|
||||
import { useRead } from './orderReads';
|
||||
import type { IndependentRequest } from './orderData';
|
||||
|
||||
interface SaleProps {
|
||||
client: LedgerClient;
|
||||
state: LedgerState;
|
||||
session: SessionInfo;
|
||||
sale: { action: string; id?: string };
|
||||
refreshState: () => Promise<unknown>;
|
||||
refreshBook: () => void;
|
||||
openList: () => void;
|
||||
close: () => void;
|
||||
saved: (date?: string) => void;
|
||||
}
|
||||
const object = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === 'object';
|
||||
const messageOf = (err: unknown) => (err instanceof Error ? err.message : String(err));
|
||||
const staleError = (err: unknown) => object(err) && (err.status === 403 || err.status === 404 || err.status === 409);
|
||||
export function IndependentAfterSale({
|
||||
client,
|
||||
state,
|
||||
session,
|
||||
sale,
|
||||
refreshState,
|
||||
refreshBook,
|
||||
openList,
|
||||
close,
|
||||
saved,
|
||||
}: SaleProps) {
|
||||
const { message } = AntApp.useApp();
|
||||
const [review, setReview] = useState(sale.action === 'after-sale-change-open' ? sale.id || '' : '');
|
||||
const [kind, setKind] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [invalid, setInvalid] = useState(false);
|
||||
const [date, setDate] = useState<string | null>(null);
|
||||
const [savedRequest, setSavedRequest] = useState<IndependentRequest | null>(null);
|
||||
const [receipt, setReceipt] = useState('');
|
||||
const [generation, reload] = useState(0);
|
||||
const version = useRef(0);
|
||||
useEffect(
|
||||
() => () => {
|
||||
version.current++;
|
||||
},
|
||||
[],
|
||||
);
|
||||
const id = review || sale.id;
|
||||
const path = review
|
||||
? '/api/after-sales/changes/' + encodeURIComponent(review)
|
||||
: sale.id
|
||||
? '/api/after-sales/' + encodeURIComponent(sale.id)
|
||||
: '';
|
||||
const views = orderViews({ state, session });
|
||||
const read = useRead(
|
||||
async () => {
|
||||
if (!review) await refreshState();
|
||||
const data = await client.api(path);
|
||||
if (!review) return { kind: 'record' as const, data: views.validateAfterSaleDetail(data, sale.id || '') };
|
||||
const request = views.validateAfterSaleRequest(data);
|
||||
if (request.id !== review) throw new Error('申请编号不一致,请重新读取。');
|
||||
return { kind: 'request' as const, data: request };
|
||||
},
|
||||
path && state.user.id + '/' + path + '/' + generation,
|
||||
);
|
||||
const detail = read.value?.kind === 'record' ? read.value.data : undefined;
|
||||
const request = savedRequest ?? (read.value?.kind === 'request' ? read.value.data : undefined);
|
||||
const approval =
|
||||
!!detail?.permissions &&
|
||||
(detail.permissions.requiresApproval ||
|
||||
!detail.permissions.canDirectEdit ||
|
||||
(state.user.role !== 'owner' &&
|
||||
(detail.record.date !== state.today || (date ?? detail.record.date) !== state.today)));
|
||||
const blocked = !!(invalid || client.busy || client.pending());
|
||||
|
||||
function reset() {
|
||||
version.current++;
|
||||
setKind('');
|
||||
setError('');
|
||||
setDate(null);
|
||||
setSavedRequest(null);
|
||||
setReceipt('');
|
||||
setInvalid(false);
|
||||
reload(value => value + 1);
|
||||
}
|
||||
function dismiss() {
|
||||
version.current++;
|
||||
close();
|
||||
}
|
||||
function fail(err: unknown) {
|
||||
const text = messageOf(err).replace('不要重新开单', id ? '不要重复提交售后修改' : '不要重复新增售后');
|
||||
if (staleError(err) && id) setInvalid(true);
|
||||
setError(text);
|
||||
message.error(text);
|
||||
}
|
||||
async function finish(url: string, input: unknown, result: unknown, at: number) {
|
||||
if (client.user !== state.user.id) return;
|
||||
const savedDate = object(input) && typeof input.date === 'string' ? input.date : undefined;
|
||||
const active = () => version.current === at && client.user === state.user.id;
|
||||
if (url === '/api/after-sales') {
|
||||
if (active()) saved(savedDate);
|
||||
else refreshBook();
|
||||
message.success('售后已保存,已计入 ' + savedDate + ' 的费用与利润');
|
||||
await refreshState();
|
||||
return;
|
||||
}
|
||||
const update = url.endsWith('/update');
|
||||
const applied = update && object(result) && result.applied === true;
|
||||
const text = update
|
||||
? applied
|
||||
? '售后修改已保存'
|
||||
: '售后修改申请已提交,待店主审批'
|
||||
: url.endsWith('/approve')
|
||||
? '已同意售后修改'
|
||||
: '已驳回售后修改申请';
|
||||
if (active()) {
|
||||
setKind('');
|
||||
setError('');
|
||||
setReceipt(text);
|
||||
}
|
||||
try {
|
||||
await refreshState();
|
||||
if (client.user !== state.user.id) return;
|
||||
if (active() && applied)
|
||||
saved(
|
||||
object(result.record) && object(result.record.record) && typeof result.record.record.date === 'string'
|
||||
? result.record.record.date
|
||||
: savedDate,
|
||||
);
|
||||
else {
|
||||
refreshBook();
|
||||
if (active() && update) reset();
|
||||
if (active() && !update) {
|
||||
const finalRequest = views.validateAfterSaleRequest(result);
|
||||
if (finalRequest.id !== review) throw new Error('申请编号不一致,请重新读取。');
|
||||
setSavedRequest(finalRequest);
|
||||
setReceipt('');
|
||||
}
|
||||
}
|
||||
message.success(text);
|
||||
} catch (err) {
|
||||
if (active()) setError('结果已保存,刷新失败:' + messageOf(err) + '。请重新读取查看结果。');
|
||||
}
|
||||
}
|
||||
async function handle(event: MouseEvent<HTMLDivElement>) {
|
||||
const button = event.target instanceof Element && event.target.closest<HTMLElement>('[data-action]');
|
||||
if (!button) return;
|
||||
event.stopPropagation();
|
||||
const { action, id: requestedId, kind: choice } = button.dataset;
|
||||
if (action === 'close-after-sale' || action === 'after-sale-changes-close') return dismiss();
|
||||
if (action === 'after-sale-changes-reload') {
|
||||
version.current++;
|
||||
openList();
|
||||
return;
|
||||
}
|
||||
if (action === 'after-sale-change-open' || action === 'after-sale-edit') {
|
||||
if (client.busy) return;
|
||||
if (action === 'after-sale-change-open' && requestedId) setReview(requestedId);
|
||||
reset();
|
||||
return;
|
||||
}
|
||||
if (action === 'after-sale-review-decision') {
|
||||
if (invalid || request?.status !== 'pending') return fail(new Error('请重新读取申请后再复核。'));
|
||||
if (choice === 'approve' || choice === 'reject') setKind(choice);
|
||||
setError('');
|
||||
return;
|
||||
}
|
||||
if (action === 'after-sale-review-cancel') {
|
||||
setKind('');
|
||||
setError('');
|
||||
return;
|
||||
}
|
||||
if (action === 'retry') {
|
||||
const at = version.current;
|
||||
try {
|
||||
const restored = await client.retryPending();
|
||||
if (restored) await finish(restored.job.url, restored.job.data, restored.result, at);
|
||||
} catch (err) {
|
||||
if (at === version.current) fail(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
async function submit(event: FormEvent<HTMLDivElement>) {
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
const node = event.target;
|
||||
if (!(node instanceof HTMLFormElement)) return;
|
||||
const values = Object.fromEntries(Array.from(new FormData(node), ([key, value]) => [key, String(value)]));
|
||||
const at = version.current;
|
||||
try {
|
||||
let url, input;
|
||||
if (review) {
|
||||
if (state.user.role !== 'owner') throw new Error('请使用店主账号复核。');
|
||||
if (blocked || request?.status !== 'pending' || node.dataset.id !== request.id || node.dataset.kind !== kind)
|
||||
throw new Error('请重新读取申请后再复核。');
|
||||
const note = values.note.trim();
|
||||
if (kind === 'approve' && (!request.canApprove || request.stale))
|
||||
throw new Error('原记录已有变动,请重新读取并核对。');
|
||||
if (kind === 'reject' && !note) throw new Error('请填写驳回意见。');
|
||||
if (note.length > 200) throw new Error('复核意见最多200字。');
|
||||
if (kind === 'approve' && !values.verified) throw new Error('请核对修改前后内容并勾选确认。');
|
||||
url = path + '/' + kind;
|
||||
input = { revision: request.revision, note, ...(kind === 'approve' ? { verified: true } : {}) };
|
||||
} else {
|
||||
if (id && (blocked || !detail || !detail.permissions.canEdit || detail.pending || node.dataset.id !== id))
|
||||
throw new Error('请重新读取售后记录后再修改。');
|
||||
input = {
|
||||
date: values.date,
|
||||
project: values.project.trim(),
|
||||
customer: values.customer.trim(),
|
||||
amount: values.amount.trim(),
|
||||
payer: values.payer,
|
||||
};
|
||||
if (!views.validOrderDate(input.date) || input.date > state.today)
|
||||
throw new Error('售后日期请选择今天或之前的有效日期。');
|
||||
if (!input.project || input.project.length > 100) throw new Error('售后项目请填写1~100字。');
|
||||
if (!input.customer || input.customer.length > 60) throw new Error('客户请填写1~60字的称呼或代号。');
|
||||
if (!views.teamMemberKeys().includes(input.payer)) throw new Error('请选择这笔售后由谁支付。');
|
||||
Calc.cents(input.amount, '售后金额');
|
||||
if (id && detail) {
|
||||
const reason = values.reason.trim();
|
||||
if (reason.length > 200) throw new Error('修改说明最多200字。');
|
||||
url = path + '/update';
|
||||
input = { revision: detail.revision, ...input, reason };
|
||||
} else {
|
||||
url = '/api/after-sales';
|
||||
if (views.teamMode()) Object.assign(input, { member: values.member || views.currentMember() });
|
||||
}
|
||||
}
|
||||
setError('');
|
||||
const result = await client.mutate(url, input);
|
||||
await finish(url, input, result, at);
|
||||
} catch (err) {
|
||||
if (at !== version.current) return;
|
||||
const verified = node.elements.namedItem('verified');
|
||||
if (staleError(err) && verified instanceof HTMLInputElement) verified.checked = false;
|
||||
fail(err);
|
||||
}
|
||||
}
|
||||
const reread = (
|
||||
<button
|
||||
type="button"
|
||||
disabled={client.busy}
|
||||
data-action={review ? 'after-sale-change-open' : 'after-sale-edit'}
|
||||
data-id={id}
|
||||
>
|
||||
{review ? '重新读取申请并复核' : '重新读取售后'}
|
||||
</button>
|
||||
);
|
||||
const feedback = error && (
|
||||
<div className="error" role="alert">
|
||||
{error}{' '}
|
||||
{id &&
|
||||
(client.pending() ? (
|
||||
<button type="button" data-action="retry" disabled={client.busy}>
|
||||
恢复原操作
|
||||
</button>
|
||||
) : (
|
||||
reread
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
const ui = { approval, blocked, busy: client.busy, feedback };
|
||||
const panel = orderViews({ state, session, ui });
|
||||
let content;
|
||||
if (receipt || (path && (review ? !request : !detail))) {
|
||||
content = (
|
||||
<>
|
||||
<button
|
||||
className="dialog-close"
|
||||
data-action={review ? 'after-sale-changes-close' : 'close-after-sale'}
|
||||
aria-label={review ? '关闭售后修改复核' : '关闭售后记录'}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
<h2>{receipt || (review ? '售后修改复核' : '修改售后')}</h2>
|
||||
{read.error || error ? (
|
||||
<div className="error" role="alert">
|
||||
{read.error || error} {reread}
|
||||
{review && <button data-action="after-sale-changes-reload">返回申请列表</button>}
|
||||
</div>
|
||||
) : (
|
||||
<p role="status">{receipt ? '正在刷新…' : review ? '正在读取申请…' : '正在读取售后记录…'}</p>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
} else if (review && request) content = panel.independentReview(request, kind);
|
||||
else content = id && detail ? panel.editIndependentSale(detail) : panel.newIndependentSale();
|
||||
return (
|
||||
<Dialog
|
||||
id={review ? 'after-sale-changes-dialog' : 'after-sale-dialog'}
|
||||
ownClose
|
||||
label={review ? '售后修改复核' : '售后记录'}
|
||||
close={dismiss}
|
||||
>
|
||||
<div
|
||||
onClick={handle}
|
||||
onSubmit={submit}
|
||||
onChange={event => {
|
||||
if (event.target instanceof HTMLInputElement && event.target.name === 'date') setDate(event.target.value);
|
||||
}}
|
||||
>
|
||||
{content}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
+161
-79
@@ -1,29 +1,70 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useEffect, useRef, useState, type FormEvent } from 'react';
|
||||
import type { EditInputs, EditFee, EditItem, LockMaterial, LockEntry, LockEditorProps } from './editTypes';
|
||||
import type { LedgerState, PresetState } from '../../shared';
|
||||
|
||||
type CostKey = 'material' | 'labor' | 'accessories' | 'other';
|
||||
type Preview = Record<CostKey | 'total' | 'profit' | 'fees', number>;
|
||||
interface CostForm {
|
||||
presets: PresetState;
|
||||
originals: Record<string, EditFee>;
|
||||
rows: EditFee[];
|
||||
originalChecked: Record<string, boolean>;
|
||||
}
|
||||
type FinancialInput = Pick<EditInputs, 'lines' | 'fee_items' | 'price_lock_material' | 'price_lock_extra_material'> &
|
||||
Partial<Pick<EditInputs, 'date' | 'fees_date' | 'fee_cost_mode'>>;
|
||||
type FeeSnapshot = {
|
||||
key: string;
|
||||
expense_id: string;
|
||||
date?: string;
|
||||
note: string;
|
||||
payer: string;
|
||||
amount: string | number;
|
||||
funding: Record<string, unknown> | null;
|
||||
};
|
||||
interface FinancialSnapshot {
|
||||
fees: FeeSnapshot[];
|
||||
date?: string;
|
||||
fees_date?: string;
|
||||
fee_cost_mode: string;
|
||||
lines?: (FinancialSnapshot & { lineId?: string })[];
|
||||
material?: object;
|
||||
extra?: object | null;
|
||||
costs?: object;
|
||||
}
|
||||
type UpdateInput = (fields: Partial<EditInputs>) => void;
|
||||
|
||||
import { Calc as LedgerCalc, Fees, Model, Values } from '../../shared';
|
||||
import { Button } from '../Settings/controls';
|
||||
import { Input, Choice } from './EditFields';
|
||||
const { yuan, grams, validateOrderIdentity } = Model;
|
||||
const feeCategories = { jd: 'shipping', yt: 'shipping', box: 'box', steel: 'braiding', silver: 'silverChain' };
|
||||
const feeCategories: Record<string, string> = {
|
||||
jd: 'shipping',
|
||||
yt: 'shipping',
|
||||
box: 'box',
|
||||
steel: 'braiding',
|
||||
silver: 'silverChain',
|
||||
};
|
||||
const validOrderDate = Values.validDate;
|
||||
function priceLockEditAmount(value) {
|
||||
function priceLockEditAmount(value: unknown) {
|
||||
try {
|
||||
return LedgerCalc.cents(String(value), '成本');
|
||||
} catch {
|
||||
return String(value ?? '');
|
||||
}
|
||||
}
|
||||
function priceLockOrderEditMeta(entry, index) {
|
||||
function priceLockOrderEditMeta(entry: LockEntry, index: number) {
|
||||
return entry.priceLock.lines?.[index] || entry.priceLock;
|
||||
}
|
||||
function priceLockOrderEditMaterial(input, index) {
|
||||
return input.lines[index].price_lock_material || (input.lines.length === 1 ? input.price_lock_material : null);
|
||||
function priceLockOrderEditMaterial(input: FinancialInput, index: number) {
|
||||
return input.lines[index].price_lock_material || (input.lines.length === 1 ? input.price_lock_material : undefined);
|
||||
}
|
||||
function priceLockOrderEditExtra(input, index) {
|
||||
function priceLockOrderEditExtra(input: FinancialInput, index: number) {
|
||||
return (
|
||||
input.lines[index].price_lock_extra_material || (input.lines.length === 1 ? input.price_lock_extra_material : null)
|
||||
input.lines[index].price_lock_extra_material ||
|
||||
(input.lines.length === 1 ? input.price_lock_extra_material : undefined)
|
||||
);
|
||||
}
|
||||
function priceLockEditFinancialValue(input) {
|
||||
function priceLockEditFinancialValue(input: FinancialInput): FinancialSnapshot {
|
||||
if (input?.lines?.length > 1)
|
||||
return {
|
||||
date: input.date,
|
||||
@@ -40,8 +81,8 @@ function priceLockEditFinancialValue(input) {
|
||||
})),
|
||||
fees: priceLockEditFinancialValue({ ...input, lines: [] }).fees,
|
||||
};
|
||||
const line = input?.lines?.[0] || {},
|
||||
material = input?.price_lock_material || {},
|
||||
const line: Partial<EditItem> = input?.lines?.[0] || {},
|
||||
material: Partial<LockMaterial> = input?.price_lock_material || {},
|
||||
extra = input?.price_lock_extra_material;
|
||||
return {
|
||||
date: input?.date,
|
||||
@@ -80,22 +121,22 @@ function priceLockEditFinancialValue(input) {
|
||||
.sort((a, b) => String(a.key).localeCompare(String(b.key))),
|
||||
};
|
||||
}
|
||||
function priceLockEditFinancialChanged(entry, input = entry?.inputs) {
|
||||
function priceLockEditFinancialChanged(entry: LockEntry, input: EditInputs = entry.inputs) {
|
||||
return (
|
||||
JSON.stringify(priceLockEditFinancialValue(input)) !==
|
||||
JSON.stringify(priceLockEditFinancialValue(entry?.originalInputs))
|
||||
);
|
||||
}
|
||||
function priceLockEditGramCost(mg, rate) {
|
||||
function priceLockEditGramCost(mg: number, rate: string) {
|
||||
return LedgerCalc.purchaseCosts({
|
||||
unit: 'g',
|
||||
quantity: grams(mg),
|
||||
costParts: { material: '0', labor: '0', accessories: '0', other: '0' },
|
||||
costMaterial: { mode: 'gram', rate },
|
||||
costLabor: { mode: 'total' },
|
||||
}).parts.material;
|
||||
}).parts.material!;
|
||||
}
|
||||
function priceLockOrderEditPreview(input, entry) {
|
||||
function priceLockOrderEditPreview(input: EditInputs, entry: LockEntry): Preview {
|
||||
if (input.lines.length > 1) {
|
||||
const costs = {
|
||||
material: 0,
|
||||
@@ -126,29 +167,28 @@ function priceLockOrderEditPreview(input, entry) {
|
||||
order: { ...entry.order, lines: [entry.order.lines[index]] },
|
||||
};
|
||||
const value = priceLockOrderEditPreview(singleInput, singleEntry);
|
||||
for (const key of ['material', 'labor', 'accessories', 'other']) costs[key] += value[key];
|
||||
for (const key of ['material', 'labor', 'accessories', 'other'] as const) costs[key] += value[key];
|
||||
});
|
||||
costs.total = Object.values(costs).reduce((sum, value) => sum + value, 0);
|
||||
costs.profit = entry.order.total - costs.total;
|
||||
return costs;
|
||||
const total = Object.values(costs).reduce((sum, value) => sum + value, 0);
|
||||
return { ...costs, total, profit: entry.order.total - total };
|
||||
}
|
||||
const original = entry.originalInputs,
|
||||
line = input.lines[0],
|
||||
extraMg = entry.priceLock.extraMg,
|
||||
usedMg = entry.order.lines[0].quantity - extraMg,
|
||||
oldExtra = extraMg
|
||||
? original.price_lock_extra_material.source === 'pool'
|
||||
? original.price_lock_extra_material.amount
|
||||
: priceLockEditGramCost(extraMg, original.price_lock_extra_material.rate)
|
||||
? original.price_lock_extra_material!.source === 'pool'
|
||||
? original.price_lock_extra_material!.amount!
|
||||
: priceLockEditGramCost(extraMg, original.price_lock_extra_material!.rate)
|
||||
: 0;
|
||||
const originalMaterial =
|
||||
input.price_lock_material.source === 'pool'
|
||||
input.price_lock_material!.source === 'pool'
|
||||
? LedgerCalc.cents(original.lines[0].costParts.material, '原料费') - oldExtra
|
||||
: priceLockEditGramCost(usedMg, input.price_lock_material.rate),
|
||||
: priceLockEditGramCost(usedMg, input.price_lock_material!.rate),
|
||||
extra = extraMg
|
||||
? input.price_lock_extra_material.source === 'pool'
|
||||
? original.price_lock_extra_material.amount
|
||||
: priceLockEditGramCost(extraMg, input.price_lock_extra_material.rate)
|
||||
? input.price_lock_extra_material!.source === 'pool'
|
||||
? original.price_lock_extra_material!.amount!
|
||||
: priceLockEditGramCost(extraMg, input.price_lock_extra_material!.rate)
|
||||
: 0;
|
||||
if (!Number.isSafeInteger(originalMaterial) || originalMaterial < 0 || !Number.isSafeInteger(extra))
|
||||
throw new Error('原锁料费尚未完整,请核对原料价与补重料价。');
|
||||
@@ -159,14 +199,13 @@ function priceLockOrderEditPreview(input, entry) {
|
||||
other: LedgerCalc.cents(line.costParts.other, '其他货品成本'),
|
||||
fees: input.fee_items.reduce((total, fee) => total + LedgerCalc.cents(fee.amount, '实际费用'), 0),
|
||||
};
|
||||
costs.total = Object.values(costs).reduce((total, amount) => total + amount, 0);
|
||||
costs.profit = entry.order.total - costs.total;
|
||||
return costs;
|
||||
const total = Object.values(costs).reduce((sum, amount) => sum + amount, 0);
|
||||
return { ...costs, total, profit: entry.order.total - total };
|
||||
}
|
||||
function materialPoolRate(value) {
|
||||
function materialPoolRate(value: number | null | undefined) {
|
||||
return value == null ? '待补采购' : yuan(value);
|
||||
}
|
||||
function validatePriceLockOrderEdit(input, entry, state) {
|
||||
function validatePriceLockOrderEdit(input: EditInputs, entry: LockEntry, state: LedgerState): EditInputs {
|
||||
if (input.lines.length > 1) {
|
||||
if (input.lines.length !== entry.order.lines.length) throw new Error('商品成本资料未完整读到,请重新读取订单。');
|
||||
input.lines.forEach((line, index) => {
|
||||
@@ -205,7 +244,7 @@ function validatePriceLockOrderEdit(input, entry, state) {
|
||||
line = input.lines[0];
|
||||
if (
|
||||
!material ||
|
||||
!['pool', 'manual'].includes(material.source) ||
|
||||
!['pool', 'manual'].includes(material.source || '') ||
|
||||
(material.source === 'pool' && entry.priceLock.materialSource !== 'pool') ||
|
||||
(material.source === 'manual' && entry.priceLock.materialSource === 'pool' && !entry.priceLock.canSwitchToManual)
|
||||
)
|
||||
@@ -229,7 +268,7 @@ function validatePriceLockOrderEdit(input, entry, state) {
|
||||
['labor', '进货总工费'],
|
||||
['accessories', '配件成本'],
|
||||
['other', '其他货品成本'],
|
||||
])
|
||||
] as const)
|
||||
LedgerCalc.cents(line.costParts[key], name);
|
||||
for (const fee of input.fee_items) {
|
||||
LedgerCalc.cents(fee.amount, '实际费用');
|
||||
@@ -247,18 +286,18 @@ function validatePriceLockOrderEdit(input, entry, state) {
|
||||
}
|
||||
|
||||
const moneyProps = { type: 'number', min: '0', step: '0.01', required: true };
|
||||
const automaticFee = fee => fee?.system === 'credit_card' || String(fee?.key || '').startsWith('card_fee:');
|
||||
const categoryOf = kind => feeCategories[kind] || kind;
|
||||
function feeCategory(fee, config) {
|
||||
const automaticFee = (fee: EditFee) => fee?.system === 'credit_card' || String(fee?.key || '').startsWith('card_fee:');
|
||||
const categoryOf = (kind: string) => feeCategories[kind] || kind;
|
||||
function feeCategory(fee: EditFee, config: Record<string, unknown>) {
|
||||
if (fee.key.startsWith('manual:') && config['custom_' + fee.key.slice(7)]) return 'custom_' + fee.key.slice(7);
|
||||
if (fee.key === 'shipping' || fee.key === 'box') return fee.key;
|
||||
if (String(fee.note || '').trim() === '编绳') return '';
|
||||
return Fees.checkboxCategory(fee.note) || Fees.checkboxCategory(fee.sourceName);
|
||||
return Fees.checkboxCategory(fee.note) || Fees.checkboxCategory(fee.sourceName ?? '');
|
||||
}
|
||||
function costSetup(input, state) {
|
||||
function costSetup(input: EditInputs, state: LedgerState): CostForm {
|
||||
const config = Model.costConfig(state),
|
||||
presets = Model.newPresets(state, input.fee_items, true),
|
||||
originals = {},
|
||||
originals: Record<string, EditFee> = {},
|
||||
rows = [];
|
||||
for (const raw of input.fee_items || []) {
|
||||
const fee = { ...raw, note: raw.note || Model.feeLabels[raw.key], edited: raw.edited ?? true };
|
||||
@@ -268,7 +307,7 @@ function costSetup(input, state) {
|
||||
}
|
||||
return { presets, originals, rows, originalChecked: { ...presets.checked } };
|
||||
}
|
||||
function feeTotals(cost, input, state) {
|
||||
function feeTotals(cost: CostForm, input: EditInputs, state: LedgerState) {
|
||||
const { items, notes } = Model.readPresets({ presets: cost.presets, member: input.member }, state);
|
||||
const config = Model.costConfig(state);
|
||||
const presets = items.map(item => {
|
||||
@@ -294,7 +333,21 @@ function feeTotals(cost, input, state) {
|
||||
});
|
||||
return { items: [...others, ...presets], notes };
|
||||
}
|
||||
function EditableFees({ input, state, cost, update, inputChange, removeFee }) {
|
||||
function EditableFees({
|
||||
input,
|
||||
state,
|
||||
cost,
|
||||
update,
|
||||
inputChange,
|
||||
removeFee,
|
||||
}: {
|
||||
input: EditInputs;
|
||||
state: LedgerState;
|
||||
cost: CostForm;
|
||||
update: (cost: CostForm) => void;
|
||||
inputChange: UpdateInput;
|
||||
removeFee: (index: number) => void;
|
||||
}) {
|
||||
const config = Model.costConfig(state),
|
||||
catalog = Fees.presetCatalog(config),
|
||||
{ presets, rows, originals } = cost,
|
||||
@@ -302,11 +355,11 @@ function EditableFees({ input, state, cost, update, inputChange, removeFee }) {
|
||||
const { notes } = feeTotals(cost, input, state),
|
||||
own = Model.formMember(input, state);
|
||||
// 交付后改单沿用已入账项目的付款流水和日期。数量控件保留打开本单时的录入状态。
|
||||
const setPreset = (kind, quantity, value) => {
|
||||
const setPreset = (kind: string, quantity: boolean, value: string | boolean) => {
|
||||
const name = quantity ? 'quantity' : 'checked';
|
||||
update({ ...cost, presets: { ...presets, [name]: { ...presets[name], [kind]: value } } });
|
||||
};
|
||||
const patchRow = (index, patch) =>
|
||||
const patchRow = (index: number, patch: Partial<EditFee>) =>
|
||||
update({ ...cost, rows: rows.map((row, i) => (i === index ? { ...row, ...patch, edited: true } : row)) });
|
||||
return (
|
||||
<section className="panel internal">
|
||||
@@ -511,7 +564,7 @@ function EditableFees({ input, state, cost, update, inputChange, removeFee }) {
|
||||
);
|
||||
}
|
||||
|
||||
function editPayload(input, fees, state, entry) {
|
||||
function editPayload(input: EditInputs, fees: CostForm, state: LedgerState, entry: LockEntry): EditInputs {
|
||||
const lines = input.lines.map(line => ({
|
||||
...line,
|
||||
costLabor: line.costLabor?.mode === 'gram' ? line.costLabor : { mode: 'total' },
|
||||
@@ -523,17 +576,34 @@ function editPayload(input, fees, state, entry) {
|
||||
fee_items: feeTotals(fees, { ...input, member: entry.order.member }, state).items,
|
||||
};
|
||||
}
|
||||
function LockLine({ entry, state, input, multi, index, update }) {
|
||||
function LockLine({
|
||||
entry,
|
||||
state,
|
||||
input,
|
||||
multi,
|
||||
index,
|
||||
update,
|
||||
}: {
|
||||
entry: LockEntry;
|
||||
state: LedgerState;
|
||||
input: EditInputs;
|
||||
multi: boolean;
|
||||
index: number;
|
||||
update: UpdateInput;
|
||||
}) {
|
||||
const line = input.lines[index],
|
||||
raw = entry.order.lines[index],
|
||||
meta = priceLockOrderEditMeta(entry, index);
|
||||
const mat = multi ? priceLockOrderEditMaterial(input, index) : input.price_lock_material,
|
||||
const mat = (multi ? priceLockOrderEditMaterial(input, index) : input.price_lock_material)!,
|
||||
extra = multi ? priceLockOrderEditExtra(input, index) : input.price_lock_extra_material,
|
||||
manual = mat.source === 'manual',
|
||||
pooledExtra = extra?.source === 'pool' && !!raw.priceLockExtraPool;
|
||||
const gram = line.costLabor?.mode === 'gram',
|
||||
payers = value => [['', '请选择'], ...Model.memberOptions(state, false, { selected: value })];
|
||||
function change(linePatch = {}, material = mat, extraCost = extra) {
|
||||
payers = (value: string): [string, string][] => [
|
||||
['', '请选择'],
|
||||
...Model.memberOptions(state, false, { selected: value }),
|
||||
];
|
||||
function change(linePatch: Partial<EditItem> = {}, material = mat, extraCost = extra) {
|
||||
const next = { ...line, ...linePatch };
|
||||
const lines = input.lines.map((r, i) =>
|
||||
i === index
|
||||
@@ -549,7 +619,7 @@ function LockLine({ entry, state, input, multi, index, update }) {
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
function labor(mode, value) {
|
||||
function labor(mode: string, value?: string) {
|
||||
const costLabor = { mode, ...(mode === 'gram' ? { rate: value ?? line.costLabor?.rate ?? '' } : {}) };
|
||||
let total = line.costParts.labor;
|
||||
if (mode === 'gram') {
|
||||
@@ -601,7 +671,7 @@ function LockLine({ entry, state, input, multi, index, update }) {
|
||||
value={mat.source}
|
||||
options={
|
||||
meta.materialSource === 'pool'
|
||||
? [['pool', '保留原锁料池'], ...(meta.canSwitchToManual ? [['manual', '改为手填原锁料价']] : [])]
|
||||
? [['pool', '保留原锁料池'], ...(meta.canSwitchToManual ? [['manual', '改为手填原锁料价'] as const] : [])]
|
||||
: [['manual', '手填原锁料价']]
|
||||
}
|
||||
onChange={source =>
|
||||
@@ -630,7 +700,7 @@ function LockLine({ entry, state, input, multi, index, update }) {
|
||||
sources
|
||||
.map(
|
||||
s =>
|
||||
(s.kind === 'personal_recovery' ? Model.memberName(state, s.member) + '个人回收料' : '公共料') +
|
||||
(s.kind === 'personal_recovery' ? Model.memberName(state, s.member!) + '个人回收料' : '公共料') +
|
||||
' ' +
|
||||
grams(s.quantity) +
|
||||
'g · ' +
|
||||
@@ -792,24 +862,33 @@ function LockLine({ entry, state, input, multi, index, update }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function LockOrderEditor({ client, state, session, entry, serverFeedback, onDraft, onSave, onCancel }) {
|
||||
export function LockOrderEditor({
|
||||
client,
|
||||
state,
|
||||
session,
|
||||
entry,
|
||||
serverFeedback,
|
||||
onDraft,
|
||||
onSave,
|
||||
onCancel,
|
||||
}: LockEditorProps) {
|
||||
const [input, setInput] = useState(() => entry.inputs),
|
||||
[fees, setFees] = useState(() => costSetup(entry.inputs, state));
|
||||
const [reason, setReason] = useState(entry.reason || ''),
|
||||
[verified, setVerified] = useState(!!entry.verified),
|
||||
[error, setError] = useState(''),
|
||||
[tags, setTags] = useState([]);
|
||||
const textarea = useRef(null),
|
||||
[tags, setTags] = useState<string[]>([]);
|
||||
const textarea = useRef<HTMLTextAreaElement>(null),
|
||||
lastEntry = useRef(entry.id);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
client
|
||||
.api('/api/order-note-tags')
|
||||
.api<{ tags: string[] }>('/api/order-note-tags')
|
||||
.then(r => {
|
||||
if (active) setTags(r.tags);
|
||||
})
|
||||
.catch(err => {
|
||||
if (active) setError(err.message);
|
||||
if (active) setError(err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
@@ -819,30 +898,30 @@ export function LockOrderEditor({ client, state, session, entry, serverFeedback,
|
||||
const wire = editPayload(input, fees, state, entry);
|
||||
const approvedFinance = entry.priceLock.financeRequiresApproval && priceLockEditFinancialChanged(entry, wire);
|
||||
const approval =
|
||||
session.user.role === 'assistant' &&
|
||||
session.user?.role === 'assistant' &&
|
||||
(!entry.sameDayDirectEdit ||
|
||||
!entry.directEditDate ||
|
||||
entry.order.date !== entry.directEditDate ||
|
||||
wire.date !== entry.directEditDate ||
|
||||
approvedFinance);
|
||||
function persist(next, nextFees, newReason, checked) {
|
||||
function persist(next: EditInputs, nextFees: CostForm, newReason: string, checked: boolean) {
|
||||
const draft = editPayload(next, nextFees, state, entry);
|
||||
onDraft(draft, newReason, checked);
|
||||
}
|
||||
function update(fields) {
|
||||
function update(fields: Partial<EditInputs>) {
|
||||
const next = { ...input, ...fields };
|
||||
setInput(next);
|
||||
setVerified(false);
|
||||
setError('');
|
||||
persist(next, fees, reason, false);
|
||||
}
|
||||
function updateFees(value) {
|
||||
function updateFees(value: CostForm) {
|
||||
setFees(value);
|
||||
setVerified(false);
|
||||
setError('');
|
||||
persist(input, value, reason, false);
|
||||
}
|
||||
function removeFee(index) {
|
||||
function removeFee(index: number) {
|
||||
const key = fees.rows[index].key;
|
||||
const next = {
|
||||
...input,
|
||||
@@ -851,7 +930,7 @@ export function LockOrderEditor({ client, state, session, entry, serverFeedback,
|
||||
...(line.charges
|
||||
? {
|
||||
charges: line.charges.map(charge =>
|
||||
key === 'charge:' + charge.id || (key === 'shipping' && Fees.normalize(charge.name) === '快递')
|
||||
key === 'charge:' + charge.id || (key === 'shipping' && Fees.normalize(charge.name ?? '') === '快递')
|
||||
? { ...charge, costRemoved: true }
|
||||
: charge,
|
||||
),
|
||||
@@ -866,21 +945,22 @@ export function LockOrderEditor({ client, state, session, entry, serverFeedback,
|
||||
setError('');
|
||||
persist(next, nextFees, reason, false);
|
||||
}
|
||||
function editReason(value) {
|
||||
function editReason(value: string) {
|
||||
setReason(value);
|
||||
persist(input, fees, value, verified);
|
||||
}
|
||||
function verify(value) {
|
||||
function verify(value: boolean) {
|
||||
setVerified(value);
|
||||
persist(input, fees, reason, value);
|
||||
}
|
||||
let costs, previewError;
|
||||
let costs: Preview | undefined,
|
||||
previewError = '';
|
||||
try {
|
||||
costs = priceLockOrderEditPreview(wire, entry);
|
||||
} catch (err) {
|
||||
previewError = err.message;
|
||||
previewError = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
async function save(event) {
|
||||
async function save(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
try {
|
||||
if (entry.user !== client.user || lastEntry.current !== entry.id)
|
||||
@@ -892,7 +972,7 @@ export function LockOrderEditor({ client, state, session, entry, serverFeedback,
|
||||
setError('');
|
||||
await onSave(payload, reason.trim(), true, approval);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
const filteredTags = Model.filterNoteTags(tags, input.internal_note || '');
|
||||
@@ -1015,7 +1095,7 @@ export function LockOrderEditor({ client, state, session, entry, serverFeedback,
|
||||
update({ internal_note: Model.insertNoteTag(input.internal_note, tag) });
|
||||
textarea.current?.focus();
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}}
|
||||
>
|
||||
@@ -1052,14 +1132,16 @@ export function LockOrderEditor({ client, state, session, entry, serverFeedback,
|
||||
aria-live="polite"
|
||||
>
|
||||
{costs
|
||||
? [
|
||||
['料费', costs.material],
|
||||
['进货工费', costs.labor],
|
||||
['配件及其他', costs.accessories + costs.other],
|
||||
['实际费用', costs.fees],
|
||||
['成本合计', costs.total],
|
||||
['利润预览', costs.profit],
|
||||
].map(([text, value]) => (
|
||||
? (
|
||||
[
|
||||
['料费', costs.material],
|
||||
['进货工费', costs.labor],
|
||||
['配件及其他', costs.accessories + costs.other],
|
||||
['实际费用', costs.fees],
|
||||
['成本合计', costs.total],
|
||||
['利润预览', costs.profit],
|
||||
] as const
|
||||
).map(([text, value]) => (
|
||||
<span key={text}>
|
||||
{text} <strong>¥{yuan(value)}</strong>
|
||||
</span>
|
||||
@@ -1069,7 +1151,7 @@ export function LockOrderEditor({ client, state, session, entry, serverFeedback,
|
||||
{!multi && <p className="small muted">按本页成本预估,保存或复核同意后按原账更新利润。</p>}
|
||||
</section>
|
||||
<section className="panel">
|
||||
<div className="note" data-order-edit-approval-note hidden={session.user.role !== 'assistant'}>
|
||||
<div className="note" data-order-edit-approval-note hidden={state.user.role !== 'assistant'}>
|
||||
{approval
|
||||
? approvedFinance
|
||||
? entry.priceLock.approvalReason || entry.approvalReason || '涉及历史锁价购料或料池,请提交店主复核。'
|
||||
+144
-357
@@ -1,18 +1,60 @@
|
||||
import { App as AntApp } from 'antd';
|
||||
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, queues, useRead } from './OrdersPage';
|
||||
import { Dialog } from './Dialog';
|
||||
import { queues, useRead } from './orderReads';
|
||||
|
||||
const stop = e => {
|
||||
const stop = (e: SyntheticEvent) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
};
|
||||
const messageOf = err => (err instanceof Error ? err.message : String(err));
|
||||
const readForm = form => Object.fromEntries(new FormData(form));
|
||||
function DetailNavigation({ ids, id, open, blocked }) {
|
||||
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 (
|
||||
@@ -47,13 +89,13 @@ export function OrderActionDialog({
|
||||
close,
|
||||
onLost,
|
||||
printStatuses,
|
||||
}) {
|
||||
}: DialogProps) {
|
||||
const base = '/api/orders/' + encodeURIComponent(id);
|
||||
const [generation, reload] = useState(0),
|
||||
[form, setForm] = useState(null),
|
||||
[form, setForm] = useState<FormKind | null>(null),
|
||||
[error, setError] = useState('');
|
||||
const [ui, setUi] = useState({}),
|
||||
[expenses, setExpenses] = useState([]);
|
||||
const [ui, setUi] = useState<OrderUi>({}),
|
||||
[expenses, setExpenses] = useState<string[]>([]);
|
||||
const current = useRef(0);
|
||||
useEffect(
|
||||
() => () => {
|
||||
@@ -62,37 +104,43 @@ export function OrderActionDialog({
|
||||
[],
|
||||
);
|
||||
const details = useRead(async () => {
|
||||
const [order, ...results] = await Promise.allSettled(
|
||||
['', '/change', '/ownership', '/cancellation'].map(path => client.api(base + path)),
|
||||
);
|
||||
if (order.status === 'rejected') {
|
||||
access.revoke(order.reason);
|
||||
throw order.reason;
|
||||
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;
|
||||
}
|
||||
if (order.value.id !== id) throw new Error('返回的订单与所选订单不一致,请重试读取。');
|
||||
const order = readOrderRecord(detail.value, id);
|
||||
const checks = orderViews({ state, session });
|
||||
const validators = [
|
||||
checks.validateOrderChangeRequest,
|
||||
checks.validateOrderOwnershipRequest,
|
||||
checks.validateOrderCancellationRequest,
|
||||
];
|
||||
const entries = results.map((r, i) => {
|
||||
const entry = { id, user: state.user.id, revision: order.value.revision };
|
||||
if (r.status === 'rejected') {
|
||||
if (access.revoke(r.reason)) throw r.reason;
|
||||
return { ...entry, error: r.reason.message };
|
||||
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 = r.value;
|
||||
if (data.revision !== order.value.revision || !Array.isArray(data.requests))
|
||||
const data = result.value;
|
||||
if (data.revision !== order!.revision || !Array.isArray(data.requests))
|
||||
throw new Error('订单已有新记录,请重新读取订单后复核。');
|
||||
data.requests.forEach(request => validators[i](request, id));
|
||||
return { ...entry, data };
|
||||
data.requests.forEach(request => validate(request, id));
|
||||
return { ...identity, data };
|
||||
} catch (err) {
|
||||
return { ...entry, error: err.message };
|
||||
return { ...identity, error: messageOf(err) };
|
||||
}
|
||||
});
|
||||
return { order: order.value, entries };
|
||||
}
|
||||
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 });
|
||||
@@ -109,7 +157,7 @@ export function OrderActionDialog({
|
||||
orderCancellationDetail: cancellation,
|
||||
orderAfterSaleFormEntry: order && {
|
||||
id,
|
||||
revision: order.revision,
|
||||
revision: order!.revision,
|
||||
user: state.user.id,
|
||||
forceApproval: ui.forceApproval,
|
||||
},
|
||||
@@ -131,7 +179,10 @@ export function OrderActionDialog({
|
||||
setExpenses([]);
|
||||
setUi({});
|
||||
}
|
||||
const loadAfter = useRead(() => client.api(base + '/after-sale'), form?.type === 'after' && id + '/' + generation);
|
||||
const loadAfter = useRead(
|
||||
() => client.api<OrderAfterSaleData>(base + '/after-sale'),
|
||||
form?.type === 'after' && id + '/' + generation,
|
||||
);
|
||||
let panel,
|
||||
visibleError = error;
|
||||
try {
|
||||
@@ -140,11 +191,11 @@ export function OrderActionDialog({
|
||||
else if (!loadAfter.value) panel = <p role="status">正在读取售后资料…</p>;
|
||||
else if (
|
||||
loadAfter.value.orderId !== id ||
|
||||
loadAfter.value.revision !== order.revision ||
|
||||
loadAfter.value.revision !== order!.revision ||
|
||||
!loadAfter.value.eligible ||
|
||||
loadAfter.value.record ||
|
||||
!views.orderAfterSalePocketKeys().length ||
|
||||
order.lines.some(
|
||||
order!.lines.some(
|
||||
l => l.unit !== 'g' || !l.costParts || l.costParts.material == null || l.costParts.labor == null,
|
||||
)
|
||||
)
|
||||
@@ -160,7 +211,7 @@ export function OrderActionDialog({
|
||||
</div>
|
||||
)),
|
||||
},
|
||||
}).orderAfterSaleFormHTML(order);
|
||||
}).orderAfterSaleFormHTML(order!);
|
||||
} else if (form?.type === 'action') panel = views.showAction(form.kind);
|
||||
else if (form)
|
||||
panel = {
|
||||
@@ -176,11 +227,12 @@ export function OrderActionDialog({
|
||||
reload(v => v + 1);
|
||||
refresh();
|
||||
}
|
||||
async function onClick(event) {
|
||||
const target = event.target.closest('[data-action]');
|
||||
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;
|
||||
const { action = '', id: targetId = '' } = target.dataset;
|
||||
try {
|
||||
if (action === 'close-dialog' || action === 'order-detail-prev' || action === 'order-detail-next') return;
|
||||
if (action === 'print') {
|
||||
@@ -201,7 +253,7 @@ export function OrderActionDialog({
|
||||
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;
|
||||
const node = target.form as DetailForm;
|
||||
const input = views.orderAfterSaleInput(node);
|
||||
const version = ++current.current;
|
||||
const signature = JSON.stringify(input);
|
||||
@@ -216,15 +268,18 @@ export function OrderActionDialog({
|
||||
}));
|
||||
let result;
|
||||
try {
|
||||
result = await client.api(base + '/after-sale-preview', input);
|
||||
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)
|
||||
if (result.before?.id !== id || result.after?.id !== id || result.before.revision !== order!.revision)
|
||||
throw new Error('售后预览与当前订单不一致,请重新读取。');
|
||||
const record = result.afterSale || result.after.orderAfterSale;
|
||||
const record = result.afterSale || result.after.orderAfterSale!;
|
||||
views.orderAfterSaleSummaryHTML(record, { preview: true });
|
||||
setUi(old => ({
|
||||
...old,
|
||||
@@ -236,7 +291,8 @@ export function OrderActionDialog({
|
||||
}
|
||||
if (action === 'order-after-sale-add-expense' || action === 'order-after-sale-remove-expense') {
|
||||
current.current++;
|
||||
if (target.form?.elements.verified) target.form.elements.verified.checked = false;
|
||||
const form = target.form as DetailForm | null;
|
||||
if (form?.elements.verified) form.elements.verified.checked = false;
|
||||
setUi(v => ({
|
||||
...v,
|
||||
preview: null,
|
||||
@@ -244,7 +300,7 @@ export function OrderActionDialog({
|
||||
verified: false,
|
||||
previewStatus: '资料已修改,请重新核对售后预览。',
|
||||
}));
|
||||
const key = target.closest('[data-expense-id]')?.dataset.expenseId;
|
||||
const key = target.closest<HTMLElement>('[data-expense-id]')?.dataset.expenseId;
|
||||
setExpenses(items =>
|
||||
action.endsWith('add-expense') ? [...items, crypto.randomUUID()] : items.filter(x => x !== key),
|
||||
);
|
||||
@@ -262,7 +318,7 @@ export function OrderActionDialog({
|
||||
const data = change?.data;
|
||||
if (!data || change.error) throw new Error('请重新读取订单并核对修改申请。');
|
||||
const eligibility = data.actions?.[kind] || data;
|
||||
if (!eligibility.eligible || data.pending || order.cancellationPending)
|
||||
if (!eligibility.eligible || data.pending || order!.cancellationPending)
|
||||
throw new Error(eligibility.reason || '本单暂不能提交变更申请,请重新读取。');
|
||||
}
|
||||
setUi({ action: kind, formKey: current.current });
|
||||
@@ -275,16 +331,22 @@ export function OrderActionDialog({
|
||||
preview: null,
|
||||
previewLoading: false,
|
||||
verified: false,
|
||||
stale: [403, 404, 409].includes(err.status),
|
||||
stale: [403, 404, 409].includes(errorStatus(err)),
|
||||
afterError: messageOf(err),
|
||||
previewStatus: '预览未完成,请核对提示后重新预览。',
|
||||
}));
|
||||
else setError(messageOf(err));
|
||||
}
|
||||
}
|
||||
function onChange(e) {
|
||||
const target = e.target,
|
||||
node = target.form;
|
||||
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);
|
||||
@@ -310,14 +372,14 @@ export function OrderActionDialog({
|
||||
}
|
||||
if (form?.type !== 'after') return;
|
||||
if (target.name === 'verified') {
|
||||
setUi(old => ({ ...old, verified: target.checked }));
|
||||
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);
|
||||
cents = order!.netReceived - Calc.cents(data.refund_amount);
|
||||
} catch {
|
||||
/* 未填写时保留待填写提示。 */
|
||||
}
|
||||
@@ -325,8 +387,8 @@ export function OrderActionDialog({
|
||||
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('[name=return_pocket]').value,
|
||||
disposition: row.querySelector('[name=return_disposition]').value,
|
||||
pocket: row.querySelector<HTMLSelectElement>('[name=return_pocket]')!.value,
|
||||
disposition: row.querySelector<HTMLSelectElement>('[name=return_disposition]')!.value,
|
||||
}));
|
||||
setUi(old => ({
|
||||
...old,
|
||||
@@ -336,18 +398,19 @@ export function OrderActionDialog({
|
||||
verified: false,
|
||||
date: data.date,
|
||||
previewStatus: '资料已修改,请重新核对售后预览。',
|
||||
reasonRequired: cents > 0,
|
||||
reasonRequired: cents !== null && cents > 0,
|
||||
retained: cents === null ? '待填写退款金额' : cents < 0 ? '退款超出净实收' : '¥' + (cents / 100).toFixed(2),
|
||||
}));
|
||||
}
|
||||
async function submit(e) {
|
||||
async function submit(e: FormEvent<HTMLDivElement>) {
|
||||
stop(e);
|
||||
const node = e.target,
|
||||
if (!form || !(e.target instanceof HTMLFormElement)) return;
|
||||
const node = e.target as DetailForm,
|
||||
data = readForm(node),
|
||||
kind = node.dataset.kind;
|
||||
kind = node.dataset.kind!;
|
||||
let submittedDirect = false;
|
||||
let submittedKey;
|
||||
const retryKey = e.nativeEvent.submitter?.dataset.retryKey;
|
||||
let submittedKey: string | undefined;
|
||||
const retryKey = ((e.nativeEvent as SubmitEvent).submitter as HTMLElement | null)?.dataset.retryKey;
|
||||
try {
|
||||
if (client.busy) return;
|
||||
if (retryKey) {
|
||||
@@ -363,15 +426,16 @@ export function OrderActionDialog({
|
||||
if (client.pending()) return;
|
||||
let url, payload;
|
||||
if (form.type === 'after') {
|
||||
payload = views.orderAfterSaleInput(node);
|
||||
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))
|
||||
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.action = 'return';
|
||||
if (approve) payload = { ...input, action: 'return' };
|
||||
url = base + (approve ? '/change' : '/return');
|
||||
} else if (form.type === 'action') {
|
||||
payload = views.actionInput(node);
|
||||
@@ -382,7 +446,7 @@ export function OrderActionDialog({
|
||||
payload = {
|
||||
...payload,
|
||||
...(approve ? { action: kind } : {}),
|
||||
revision: order.revision,
|
||||
revision: order!.revision,
|
||||
verified: data.verified === 'on',
|
||||
reason: (data.change_reason || data.reason || '').trim(),
|
||||
};
|
||||
@@ -393,32 +457,32 @@ export function OrderActionDialog({
|
||||
if (approve) url = base + '/change';
|
||||
}
|
||||
} else {
|
||||
const info = { change, ownership, cancellation }[form.type].data,
|
||||
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)
|
||||
(!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;
|
||||
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 };
|
||||
payload = { member: data.member, revision: order!.revision, reason: data.reason.trim(), verified: true };
|
||||
url = base + '/ownership';
|
||||
} else {
|
||||
payload = {
|
||||
revision: order.revision,
|
||||
revision: order!.revision,
|
||||
reason: data.reason.trim(),
|
||||
...(kind === 'direct' ? { date: info.directActionDate, verified: true } : {}),
|
||||
...(kind === 'direct' ? { date: cancellation!.data!.directActionDate, verified: true } : {}),
|
||||
};
|
||||
url = base + (kind === 'direct' ? '/canceltoday' : '/cancellation');
|
||||
}
|
||||
if (data.legacyCountVerified) payload.legacyCountVerified = true;
|
||||
if (data.legacyCountVerified) payload = { ...payload, legacyCountVerified: true };
|
||||
}
|
||||
const saving = client.mutate(url, payload);
|
||||
submittedKey = client.pending()?.key;
|
||||
@@ -428,8 +492,8 @@ export function OrderActionDialog({
|
||||
} catch (err) {
|
||||
if (await access.checkFailure(err)) return;
|
||||
if (form.type === 'after') {
|
||||
const forceApproval = err.status === 403 && submittedDirect && !client.pending();
|
||||
const stale = !forceApproval && [403, 404, 409].includes(err.status);
|
||||
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,
|
||||
@@ -443,10 +507,10 @@ export function OrderActionDialog({
|
||||
} else if (
|
||||
form.type === 'action' &&
|
||||
views.orderActionUsesChangeForm(kind) &&
|
||||
([403, 404, 409].includes(err.status) || (submittedKey && submittedKey === client.pending()?.key))
|
||||
([403, 404, 409].includes(errorStatus(err)) || (submittedKey && submittedKey === client.pending()?.key))
|
||||
) {
|
||||
const forceApproval = err.status === 403 && submittedDirect && !client.pending();
|
||||
const rejected = [403, 404, 409].includes(err.status);
|
||||
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,
|
||||
@@ -487,281 +551,4 @@ export function OrderActionDialog({
|
||||
);
|
||||
}
|
||||
|
||||
export function IndependentAfterSale({
|
||||
client,
|
||||
state,
|
||||
session,
|
||||
sale,
|
||||
refreshState,
|
||||
refreshBook,
|
||||
openList,
|
||||
close,
|
||||
saved,
|
||||
}) {
|
||||
const { message } = AntApp.useApp();
|
||||
const [review, setReview] = useState(sale.action === 'after-sale-change-open' ? sale.id : '');
|
||||
const [kind, setKind] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [invalid, setInvalid] = useState(false);
|
||||
const [date, setDate] = useState(null);
|
||||
const [savedRequest, setSavedRequest] = useState(null);
|
||||
const [receipt, setReceipt] = useState('');
|
||||
const [generation, reload] = useState(0);
|
||||
const version = useRef(0);
|
||||
useEffect(
|
||||
() => () => {
|
||||
version.current++;
|
||||
},
|
||||
[],
|
||||
);
|
||||
const id = review || sale.id;
|
||||
const path = review
|
||||
? '/api/after-sales/changes/' + encodeURIComponent(review)
|
||||
: sale.id
|
||||
? '/api/after-sales/' + encodeURIComponent(sale.id)
|
||||
: '';
|
||||
const views = orderViews({ state, session });
|
||||
const read = useRead(
|
||||
async () => {
|
||||
if (!review) await refreshState();
|
||||
const data = await client.api(path);
|
||||
if (!review) return views.validateAfterSaleDetail(data, sale.id);
|
||||
const request = views.validateAfterSaleRequest(data);
|
||||
if (request.id !== review) throw new Error('申请编号不一致,请重新读取。');
|
||||
return request;
|
||||
},
|
||||
path && state.user.id + '/' + path + '/' + generation,
|
||||
);
|
||||
const detail = read.value;
|
||||
const request = review && (savedRequest || detail);
|
||||
const approval =
|
||||
!!detail?.permissions &&
|
||||
(detail.permissions.requiresApproval ||
|
||||
!detail.permissions.canDirectEdit ||
|
||||
(state.user.role !== 'owner' &&
|
||||
(detail.record.date !== state.today || (date ?? detail.record.date) !== state.today)));
|
||||
const blocked = !!(invalid || client.busy || client.pending());
|
||||
|
||||
function reset() {
|
||||
version.current++;
|
||||
setKind('');
|
||||
setError('');
|
||||
setDate(null);
|
||||
setSavedRequest(null);
|
||||
setReceipt('');
|
||||
setInvalid(false);
|
||||
reload(value => value + 1);
|
||||
}
|
||||
function dismiss() {
|
||||
version.current++;
|
||||
close();
|
||||
}
|
||||
function fail(err) {
|
||||
const text = messageOf(err).replace('不要重新开单', id ? '不要重复提交售后修改' : '不要重复新增售后');
|
||||
if ([403, 404, 409].includes(err.status) && id) setInvalid(true);
|
||||
setError(text);
|
||||
message.error(text);
|
||||
}
|
||||
async function finish(url, input, result, at) {
|
||||
if (client.user !== state.user.id) return;
|
||||
const active = () => version.current === at && client.user === state.user.id;
|
||||
if (url === '/api/after-sales') {
|
||||
if (active()) saved(input.date);
|
||||
else refreshBook();
|
||||
message.success('售后已保存,已计入 ' + input.date + ' 的费用与利润');
|
||||
await refreshState();
|
||||
return;
|
||||
}
|
||||
const update = url.endsWith('/update');
|
||||
const applied = update && result.applied === true;
|
||||
const text = update
|
||||
? applied
|
||||
? '售后修改已保存'
|
||||
: '售后修改申请已提交,待店主审批'
|
||||
: url.endsWith('/approve')
|
||||
? '已同意售后修改'
|
||||
: '已驳回售后修改申请';
|
||||
if (active()) {
|
||||
setKind('');
|
||||
setError('');
|
||||
setReceipt(text);
|
||||
}
|
||||
try {
|
||||
await refreshState();
|
||||
if (client.user !== state.user.id) return;
|
||||
if (active() && applied) saved(result.record?.record?.date || input.date);
|
||||
else {
|
||||
refreshBook();
|
||||
if (active() && update) reset();
|
||||
if (active() && !update) {
|
||||
const finalRequest = views.validateAfterSaleRequest(result);
|
||||
if (finalRequest.id !== review) throw new Error('申请编号不一致,请重新读取。');
|
||||
setSavedRequest(finalRequest);
|
||||
setReceipt('');
|
||||
}
|
||||
}
|
||||
message.success(text);
|
||||
} catch (err) {
|
||||
if (active()) setError('结果已保存,刷新失败:' + messageOf(err) + '。请重新读取查看结果。');
|
||||
}
|
||||
}
|
||||
async function handle(event) {
|
||||
const button = event.target.closest('[data-action]');
|
||||
if (!button) return;
|
||||
event.stopPropagation();
|
||||
const { action, id: requestedId, kind: choice } = button.dataset;
|
||||
if (action === 'close-after-sale' || action === 'after-sale-changes-close') return dismiss();
|
||||
if (action === 'after-sale-changes-reload') {
|
||||
version.current++;
|
||||
openList();
|
||||
return;
|
||||
}
|
||||
if (action === 'after-sale-change-open' || action === 'after-sale-edit') {
|
||||
if (client.busy) return;
|
||||
if (action === 'after-sale-change-open') setReview(requestedId);
|
||||
reset();
|
||||
return;
|
||||
}
|
||||
if (action === 'after-sale-review-decision') {
|
||||
if (invalid || request?.status !== 'pending') return fail(new Error('请重新读取申请后再复核。'));
|
||||
setKind(choice);
|
||||
setError('');
|
||||
return;
|
||||
}
|
||||
if (action === 'after-sale-review-cancel') {
|
||||
setKind('');
|
||||
setError('');
|
||||
return;
|
||||
}
|
||||
if (action === 'retry') {
|
||||
const at = version.current;
|
||||
try {
|
||||
const restored = await client.retryPending();
|
||||
if (restored) await finish(restored.job.url, restored.job.data, restored.result, at);
|
||||
} catch (err) {
|
||||
if (at === version.current) fail(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
async function submit(event) {
|
||||
stop(event);
|
||||
const node = event.target;
|
||||
const values = readForm(node);
|
||||
const at = version.current;
|
||||
try {
|
||||
let url, input;
|
||||
if (review) {
|
||||
if (state.user.role !== 'owner') throw new Error('请使用店主账号复核。');
|
||||
if (blocked || request?.status !== 'pending' || node.dataset.id !== request.id || node.dataset.kind !== kind)
|
||||
throw new Error('请重新读取申请后再复核。');
|
||||
const note = values.note.trim();
|
||||
if (kind === 'approve' && (!request.canApprove || request.stale))
|
||||
throw new Error('原记录已有变动,请重新读取并核对。');
|
||||
if (kind === 'reject' && !note) throw new Error('请填写驳回意见。');
|
||||
if (note.length > 200) throw new Error('复核意见最多200字。');
|
||||
if (kind === 'approve' && !values.verified) throw new Error('请核对修改前后内容并勾选确认。');
|
||||
url = path + '/' + kind;
|
||||
input = { revision: request.revision, note, ...(kind === 'approve' ? { verified: true } : {}) };
|
||||
} else {
|
||||
if (id && (blocked || !detail.permissions.canEdit || detail.pending || node.dataset.id !== id))
|
||||
throw new Error('请重新读取售后记录后再修改。');
|
||||
input = {
|
||||
date: values.date,
|
||||
project: values.project.trim(),
|
||||
customer: values.customer.trim(),
|
||||
amount: values.amount.trim(),
|
||||
payer: values.payer,
|
||||
};
|
||||
if (!views.validOrderDate(input.date) || input.date > state.today)
|
||||
throw new Error('售后日期请选择今天或之前的有效日期。');
|
||||
if (!input.project || input.project.length > 100) throw new Error('售后项目请填写1~100字。');
|
||||
if (!input.customer || input.customer.length > 60) throw new Error('客户请填写1~60字的称呼或代号。');
|
||||
if (!views.teamMemberKeys().includes(input.payer)) throw new Error('请选择这笔售后由谁支付。');
|
||||
Calc.cents(input.amount, '售后金额');
|
||||
if (id) {
|
||||
const reason = values.reason.trim();
|
||||
if (reason.length > 200) throw new Error('修改说明最多200字。');
|
||||
url = path + '/update';
|
||||
input = { revision: detail.revision, ...input, reason };
|
||||
} else {
|
||||
url = '/api/after-sales';
|
||||
if (views.teamMode()) input.member = values.member || views.currentMember();
|
||||
}
|
||||
}
|
||||
setError('');
|
||||
const result = await client.mutate(url, input);
|
||||
await finish(url, input, result, at);
|
||||
} catch (err) {
|
||||
if (at !== version.current) return;
|
||||
if ([403, 404, 409].includes(err.status) && node.elements.verified) node.elements.verified.checked = false;
|
||||
fail(err);
|
||||
}
|
||||
}
|
||||
const reread = (
|
||||
<button
|
||||
type="button"
|
||||
disabled={client.busy}
|
||||
data-action={review ? 'after-sale-change-open' : 'after-sale-edit'}
|
||||
data-id={id}
|
||||
>
|
||||
{review ? '重新读取申请并复核' : '重新读取售后'}
|
||||
</button>
|
||||
);
|
||||
const feedback = error && (
|
||||
<div className="error" role="alert">
|
||||
{error}{' '}
|
||||
{id &&
|
||||
(client.pending() ? (
|
||||
<button type="button" data-action="retry" disabled={client.busy}>
|
||||
恢复原操作
|
||||
</button>
|
||||
) : (
|
||||
reread
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
const ui = { approval, blocked, busy: client.busy, feedback };
|
||||
const panel = orderViews({ state, session, ui });
|
||||
let content;
|
||||
if (receipt || (path && !detail)) {
|
||||
content = (
|
||||
<>
|
||||
<button
|
||||
className="dialog-close"
|
||||
data-action={review ? 'after-sale-changes-close' : 'close-after-sale'}
|
||||
aria-label={review ? '关闭售后修改复核' : '关闭售后记录'}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
<h2>{receipt || (review ? '售后修改复核' : '修改售后')}</h2>
|
||||
{read.error || error ? (
|
||||
<div className="error" role="alert">
|
||||
{read.error || error} {reread}
|
||||
{review && <button data-action="after-sale-changes-reload">返回申请列表</button>}
|
||||
</div>
|
||||
) : (
|
||||
<p role="status">{receipt ? '正在刷新…' : review ? '正在读取申请…' : '正在读取售后记录…'}</p>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
} else if (review) content = panel.independentReview(request, kind);
|
||||
else content = id ? panel.editIndependentSale(detail) : panel.newIndependentSale();
|
||||
return (
|
||||
<Dialog
|
||||
id={review ? 'after-sale-changes-dialog' : 'after-sale-dialog'}
|
||||
ownClose
|
||||
label={review ? '售后修改复核' : '售后记录'}
|
||||
close={dismiss}
|
||||
>
|
||||
<div
|
||||
onClick={handle}
|
||||
onSubmit={submit}
|
||||
onChange={event => {
|
||||
if (event.target.name === 'date') setDate(event.target.value);
|
||||
}}
|
||||
>
|
||||
{content}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
export { IndependentAfterSale } from './IndependentAfterSale';
|
||||
+124
-37
@@ -1,21 +1,66 @@
|
||||
import { useOrderAccess, ownershipNoticeKey } from './useOrderAccess';
|
||||
import { useCallback, useEffect, useEffectEvent, useRef, useState } from 'react';
|
||||
import type { ReactNode, FormEvent, ComponentType } from 'react';
|
||||
import type { LedgerClient } from '../../lib/api';
|
||||
import type {
|
||||
EditEntry,
|
||||
EditInputs,
|
||||
EditResponse,
|
||||
EditPayload,
|
||||
LockEditorProps,
|
||||
SaveDraft,
|
||||
SaveOrder,
|
||||
} from './editTypes';
|
||||
import type { LedgerState, OrderForm, SessionInfo } from '../../shared';
|
||||
import { Model } from '../../shared';
|
||||
import { navigate, searchParam } from '../../lib/router';
|
||||
import { useOrderForm } from '../CreateOrder/useOrderForm';
|
||||
import { EditLine, EditFees, Input, Choice } from './EditFields';
|
||||
import { useRead } from './OrdersPage';
|
||||
import { isRecord, errorMessage, errorStatus } from './readOrder';
|
||||
import { useRead } from './orderReads';
|
||||
|
||||
function storedDraft(key, id) {
|
||||
let saved;
|
||||
interface SavedEdit {
|
||||
id: string;
|
||||
revision: number;
|
||||
inputs: EditInputs;
|
||||
reason?: string;
|
||||
verified?: boolean;
|
||||
}
|
||||
type DraftMode = 'open' | 'reset' | 'keep' | 'review';
|
||||
interface PageProps {
|
||||
client: LedgerClient;
|
||||
state: LedgerState;
|
||||
session: SessionInfo;
|
||||
refreshState: () => Promise<LedgerState>;
|
||||
registerLeaveGuard: (check: () => boolean) => () => void;
|
||||
LockEditor: ComponentType<LockEditorProps>;
|
||||
}
|
||||
function storedDraft(key: string, id: string): SavedEdit | null {
|
||||
let saved: unknown;
|
||||
try {
|
||||
saved = JSON.parse(localStorage.getItem(key));
|
||||
saved = JSON.parse(localStorage.getItem(key) || 'null');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return saved?.id === id && Number.isSafeInteger(saved.revision) && Array.isArray(saved.inputs?.lines) ? saved : null;
|
||||
if (
|
||||
!isRecord(saved) ||
|
||||
saved.id !== id ||
|
||||
typeof saved.revision !== 'number' ||
|
||||
!Number.isSafeInteger(saved.revision) ||
|
||||
!isRecord(saved.inputs) ||
|
||||
!Array.isArray(saved.inputs.lines)
|
||||
)
|
||||
return null;
|
||||
// Older local drafts can omit item metadata. The form loads its normal defaults when restoring those drafts.
|
||||
return {
|
||||
id,
|
||||
revision: saved.revision,
|
||||
inputs: saved.inputs as EditInputs,
|
||||
...(typeof saved.reason === 'string' ? { reason: saved.reason } : {}),
|
||||
verified: saved.verified === true,
|
||||
};
|
||||
}
|
||||
function makeEntry(result, id, saved, state) {
|
||||
function makeEntry(result: EditResponse, id: string, saved: SavedEdit | null, state: LedgerState): EditEntry {
|
||||
if (result.eligible !== true) throw new Error(result.reason || '这张订单暂不能修改,请重新读取订单后核对。');
|
||||
if (
|
||||
result.order?.id !== id ||
|
||||
@@ -42,13 +87,16 @@ function makeEntry(result, id, saved, state) {
|
||||
for (const [index, line] of lines.entries()) {
|
||||
const meta = metas[index],
|
||||
lineId = meta?.lineId || meta?.id;
|
||||
const material = line.price_lock_material || (lines.length === 1 && result.inputs.price_lock_material);
|
||||
const extra = line.price_lock_extra_material || (lines.length === 1 && result.inputs.price_lock_extra_material);
|
||||
const material = line.price_lock_material || (lines.length === 1 ? result.inputs.price_lock_material : undefined);
|
||||
const extra =
|
||||
line.price_lock_extra_material || (lines.length === 1 ? result.inputs.price_lock_extra_material : undefined);
|
||||
if (
|
||||
!['pool', 'manual'].includes(meta?.materialSource) ||
|
||||
!meta ||
|
||||
!['pool', 'manual'].includes(meta.materialSource) ||
|
||||
!Number.isSafeInteger(meta.extraMg) ||
|
||||
meta.extraMg < 0 ||
|
||||
!['pool', 'manual'].includes(material?.source) ||
|
||||
!material?.source ||
|
||||
!['pool', 'manual'].includes(material.source) ||
|
||||
(meta.extraMg > 0 && !extra) ||
|
||||
(lines.length > 1 && (!line.lineId || line.lineId !== lineId || seen.has(lineId)))
|
||||
)
|
||||
@@ -89,7 +137,15 @@ function makeEntry(result, id, saved, state) {
|
||||
};
|
||||
}
|
||||
|
||||
function ConflictPanel({ entry, read, disabled }) {
|
||||
function ConflictPanel({
|
||||
entry,
|
||||
read,
|
||||
disabled,
|
||||
}: {
|
||||
entry: EditEntry;
|
||||
read: (mode: DraftMode) => void;
|
||||
disabled: boolean;
|
||||
}) {
|
||||
const order = entry.latest?.order;
|
||||
return (
|
||||
<section className="panel" id="order-edit-conflict" role="status">
|
||||
@@ -147,18 +203,18 @@ function ConflictPanel({ entry, read, disabled }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function OrderEditPage({ client, state, session, refreshState, registerLeaveGuard, LockEditor }) {
|
||||
export function OrderEditPage({ client, state, session, refreshState, registerLeaveGuard, LockEditor }: PageProps) {
|
||||
const activeKey = 'mm-order-edit-active-' + state.user.id;
|
||||
const id = searchParam('order') || searchParam('id') || localStorage.getItem(activeKey) || '';
|
||||
const key = 'mm-order-edit-' + state.user.id + '-' + id;
|
||||
const [entry, setEntry] = useState(null),
|
||||
const [entry, setEntry] = useState<EditEntry | null>(null),
|
||||
[epoch, reset] = useState(0),
|
||||
[error, setError] = useState(''),
|
||||
[success, setSuccess] = useState(false),
|
||||
[reading, setReading] = useState(false);
|
||||
const live = useRef(false),
|
||||
generation = useRef(0);
|
||||
const onDraft = useCallback(
|
||||
const onDraft = useCallback<SaveDraft>(
|
||||
(inputs, reason, verified) => {
|
||||
if (!live.current || client.user !== state.user.id) return;
|
||||
localStorage.setItem(key, JSON.stringify({ id, revision: inputs.revision, inputs, reason, verified }));
|
||||
@@ -166,7 +222,7 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
||||
},
|
||||
[id, key, activeKey, client, state.user.id],
|
||||
);
|
||||
const lost = message => {
|
||||
const lost = (message: string) => {
|
||||
live.current = false;
|
||||
sessionStorage.setItem(ownershipNoticeKey(state.user.id), message);
|
||||
navigate('orders', { replace: true, fromPage: true });
|
||||
@@ -177,13 +233,13 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
||||
};
|
||||
const { checkFailure } = useOrderAccess({ client, state, id, watch: !!entry && !reading, onLost: lost });
|
||||
const active = () => live.current && client.user === state.user.id;
|
||||
async function read(mode = 'open') {
|
||||
async function read(mode: DraftMode = 'open') {
|
||||
if (!id || (mode !== 'open' && (client.busy || client.pending() || reading))) return;
|
||||
if (mode === 'reset' && !window.confirm('改用当前已保存的订单内容?这张订单尚未保存的修改草稿将被替换。')) return;
|
||||
const request = ++generation.current;
|
||||
setReading(true);
|
||||
try {
|
||||
const result = await client.api('/api/orders/' + encodeURIComponent(id) + '/edit');
|
||||
const result = await client.api<EditResponse>('/api/orders/' + encodeURIComponent(id) + '/edit');
|
||||
if (!active() || request !== generation.current) return;
|
||||
let draft = storedDraft(key, id);
|
||||
if (mode === 'reset') draft = null;
|
||||
@@ -195,7 +251,7 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
||||
inputs: { ...draft.inputs, revision: result.revision },
|
||||
};
|
||||
const fresh = makeEntry(result, id, draft, state);
|
||||
if (mode === 'review' || (mode === 'keep' && result.revision !== entry.latest?.revision)) {
|
||||
if (mode === 'review' || (mode === 'keep' && result.revision !== entry?.latest?.revision)) {
|
||||
fresh.conflicted = true;
|
||||
fresh.verified = false;
|
||||
}
|
||||
@@ -205,23 +261,32 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
||||
reset(n => n + 1);
|
||||
setError('');
|
||||
} catch (err) {
|
||||
if (active() && request === generation.current && !(await checkFailure(err)) && active()) setError(err.message);
|
||||
if (active() && request === generation.current && !(await checkFailure(err)) && active())
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
if (active() && request === generation.current) setReading(false);
|
||||
}
|
||||
}
|
||||
const firstRead = useEffectEvent(() => read());
|
||||
const cancelRead = useEffectEvent(() => {
|
||||
live.current = false;
|
||||
generation.current++;
|
||||
});
|
||||
useEffect(() => {
|
||||
let disposed = false;
|
||||
live.current = true;
|
||||
void firstRead();
|
||||
void Promise.resolve().then(() => {
|
||||
if (!disposed) return firstRead();
|
||||
});
|
||||
return () => {
|
||||
live.current = false;
|
||||
generation.current++;
|
||||
disposed = true;
|
||||
cancelRead();
|
||||
if (localStorage.getItem(activeKey) === id) localStorage.removeItem(activeKey);
|
||||
};
|
||||
}, [id, activeKey]);
|
||||
const go = () => navigate('orders', { search: '?order=' + encodeURIComponent(id) });
|
||||
async function save(inputs, reason, verified, approval) {
|
||||
async function save(inputs: EditPayload, reason: string, verified: boolean, approval: boolean) {
|
||||
if (!entry) return;
|
||||
try {
|
||||
if (entry.conflicted) throw new Error('订单已有新记录,请先读取最新订单并核对,填写内容已经保留。');
|
||||
if (!reason.trim() || reason.trim().length > 200) throw new Error('请填写1~200字的修改原因。');
|
||||
@@ -234,9 +299,9 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
||||
});
|
||||
} catch (err) {
|
||||
if (!active() || (await checkFailure(err)) || !active()) return;
|
||||
let message = err.message.replace('不要重新开单', '不要重复保存修改');
|
||||
const forceApproval = err.status === 403 && session.user.role === 'assistant';
|
||||
if (forceApproval || err.status === 409) {
|
||||
let message = errorMessage(err).replace('不要重新开单', '不要重复保存修改');
|
||||
const forceApproval = errorStatus(err) === 403 && state.user.role === 'assistant';
|
||||
if (forceApproval || errorStatus(err) === 409) {
|
||||
const saved = storedDraft(key, id);
|
||||
const next = {
|
||||
...entry,
|
||||
@@ -244,7 +309,7 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
||||
reason: saved?.reason ?? reason,
|
||||
verified: false,
|
||||
sameDayDirectEdit: forceApproval ? false : entry.sameDayDirectEdit,
|
||||
conflicted: err.status === 409,
|
||||
conflicted: errorStatus(err) === 409,
|
||||
latest: null,
|
||||
};
|
||||
if (forceApproval) message += '。填写内容已保留,请重新核对并勾选后提交修改申请。';
|
||||
@@ -262,7 +327,7 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
||||
if (approval) navigate('orders', { search: '?order=' + encodeURIComponent(id), fromPage: true });
|
||||
else {
|
||||
setSuccess(true);
|
||||
const date = inputs.date || entry.order.date;
|
||||
const date = ('date' in inputs && inputs.date) || entry.order.date;
|
||||
const bookKey = 'mm-order-book-' + state.user.id;
|
||||
let before = {};
|
||||
try {
|
||||
@@ -275,7 +340,7 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
||||
try {
|
||||
await refreshState();
|
||||
} catch (err) {
|
||||
setError('修改已保存,最新订单暂未读到。' + err.message);
|
||||
setError('修改已保存,最新订单暂未读到。' + (err instanceof Error ? err.message : String(err)));
|
||||
}
|
||||
}
|
||||
if (success)
|
||||
@@ -327,7 +392,7 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
||||
client,
|
||||
state,
|
||||
session,
|
||||
entry,
|
||||
entry: { ...entry, priceLock: entry.priceLock },
|
||||
serverFeedback,
|
||||
onDraft,
|
||||
onSave: save,
|
||||
@@ -347,7 +412,27 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
||||
);
|
||||
}
|
||||
|
||||
function EditForm({ client, state, session, entry, serverFeedback, onDraft, save, go, blocked }) {
|
||||
function EditForm({
|
||||
client,
|
||||
state,
|
||||
session,
|
||||
entry,
|
||||
serverFeedback,
|
||||
onDraft,
|
||||
save,
|
||||
go,
|
||||
blocked,
|
||||
}: {
|
||||
client: LedgerClient;
|
||||
state: LedgerState;
|
||||
session: SessionInfo;
|
||||
entry: EditEntry;
|
||||
serverFeedback: ReactNode;
|
||||
onDraft: SaveDraft;
|
||||
save: SaveOrder;
|
||||
go: () => void;
|
||||
blocked: boolean;
|
||||
}) {
|
||||
const { store, update, ctx, loadPools, poolError } = useOrderForm({
|
||||
client,
|
||||
state,
|
||||
@@ -360,9 +445,9 @@ function EditForm({ client, state, session, entry, serverFeedback, onDraft, save
|
||||
const [reason, setReason] = useState(entry.reason),
|
||||
[verified, setVerified] = useState(entry.verified),
|
||||
[error, setError] = useState('');
|
||||
const tags = useRead(() => client.api('/api/order-note-tags'), state.user.id);
|
||||
const set = key => value => change(f => ({ ...f, [key]: value }));
|
||||
const change = fn => {
|
||||
const tags = useRead(() => client.api<{ tags: string[] }>('/api/order-note-tags'), state.user.id);
|
||||
const set = (key: keyof OrderForm) => (value: string) => change(f => ({ ...f, [key]: value }));
|
||||
const change = (fn: (form: OrderForm) => OrderForm) => {
|
||||
setVerified(false);
|
||||
update(fn);
|
||||
};
|
||||
@@ -375,7 +460,7 @@ function EditForm({ client, state, session, entry, serverFeedback, onDraft, save
|
||||
!entry.directEditDate ||
|
||||
entry.order.date !== entry.directEditDate ||
|
||||
(finance ? form.date : entry.order.date) !== entry.directEditDate);
|
||||
function submit(event) {
|
||||
function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
try {
|
||||
let input;
|
||||
@@ -386,7 +471,9 @@ function EditForm({ client, state, session, entry, serverFeedback, onDraft, save
|
||||
input = {
|
||||
...input,
|
||||
lines: input.lines.map((line, index) => {
|
||||
const controls = Array.from(rows[index].querySelectorAll('input[name],select[name]')).filter(
|
||||
const controls = Array.from(
|
||||
rows[index].querySelectorAll<HTMLInputElement | HTMLSelectElement>('input[name],select[name]'),
|
||||
).filter(
|
||||
field =>
|
||||
!field.closest('.charge-row') && (field.name !== 'stockCount' || Object.hasOwn(line, 'stockCount')),
|
||||
);
|
||||
@@ -406,7 +493,7 @@ function EditForm({ client, state, session, entry, serverFeedback, onDraft, save
|
||||
setError('');
|
||||
void save(input, reason, verified, approval);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
const card = form.payment.method === '信用卡';
|
||||
+87
-105
@@ -1,90 +1,64 @@
|
||||
import { Dialog } from './Dialog';
|
||||
import { useRead, queues, type Queue } from './orderReads';
|
||||
import type { MouseEvent } from 'react';
|
||||
import type { LedgerClient } from '../../lib/api';
|
||||
import type { LedgerState, SessionInfo } from '../../shared';
|
||||
import type {
|
||||
BookData,
|
||||
BookRow,
|
||||
Filters,
|
||||
ReviewList,
|
||||
ChangeRequest,
|
||||
OwnershipRequest,
|
||||
CancellationRequest,
|
||||
IndependentRequest,
|
||||
} from './orderData';
|
||||
interface OrdersProps {
|
||||
client: LedgerClient;
|
||||
state: LedgerState;
|
||||
session: SessionInfo;
|
||||
refreshState: () => Promise<unknown>;
|
||||
saleListStatus: string;
|
||||
setSaleListStatus: (status: string) => void;
|
||||
}
|
||||
import { ownershipNoticeKey } from './useOrderAccess';
|
||||
import { usePrintStatuses } from '../../lib/printStatus';
|
||||
import { useCallback, useEffect, useEffectEvent, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { navigate, searchParam } from '../../lib/router';
|
||||
import { orderViews } from './orderViews';
|
||||
import { OrderActionDialog, IndependentAfterSale } from './OrderDialogs';
|
||||
|
||||
export const queues = [
|
||||
['change', '/api/order-changes', '待变更复核', 'open-order-changes', 'order-changes-entry'],
|
||||
['ownership', '/api/order-ownership-changes', '归属复核', 'order-ownership-open-list', 'order-ownership-entry'],
|
||||
['cancellation', '/api/order-cancellations', '待取消复核', 'open-order-cancellations', 'order-cancellations-entry'],
|
||||
['after-sale', '/api/after-sales/changes', '售后修改', 'after-sale-changes-open', 'after-sale-changes-entry'],
|
||||
];
|
||||
|
||||
export function Dialog({ id, label, close, children, ownClose = false }) {
|
||||
const ref = useRef(null);
|
||||
useEffect(() => {
|
||||
const node = ref.current;
|
||||
node.showModal();
|
||||
return () => node.close();
|
||||
}, []);
|
||||
return (
|
||||
<dialog
|
||||
id={id}
|
||||
ref={ref}
|
||||
aria-label={label}
|
||||
onCancel={event => {
|
||||
event.preventDefault();
|
||||
close();
|
||||
}}
|
||||
>
|
||||
{!ownClose && (
|
||||
<button type="button" className="dialog-close" data-action="close-dialog" aria-label={label} onClick={close}>
|
||||
×
|
||||
</button>
|
||||
)}
|
||||
{children}
|
||||
</dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export function useRead(read, key) {
|
||||
const [entry, set] = useState(null);
|
||||
const task = useEffectEvent(read);
|
||||
useEffect(() => {
|
||||
if (!key) return;
|
||||
let active = true;
|
||||
Promise.resolve()
|
||||
.then(() => task())
|
||||
.then(
|
||||
value => {
|
||||
if (active) set({ key, value });
|
||||
},
|
||||
error => {
|
||||
if (active) set({ key, error: error.message });
|
||||
},
|
||||
);
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [key]);
|
||||
return entry?.key === key ? entry : {};
|
||||
}
|
||||
|
||||
function initialFilters(state) {
|
||||
let saved;
|
||||
function initialFilters(state: LedgerState): Filters {
|
||||
const defaults: Filters = { mode: 'today', date: '', from: '', to: '', q: '', status: '', member: '', pocket: '' };
|
||||
const raw = sessionStorage.getItem('mm-order-book-' + state.user.id);
|
||||
if (!raw) return defaults;
|
||||
let values: unknown;
|
||||
try {
|
||||
saved = JSON.parse(sessionStorage.getItem('mm-order-book-' + state.user.id));
|
||||
values = JSON.parse(raw);
|
||||
} catch {
|
||||
saved = null;
|
||||
return defaults;
|
||||
}
|
||||
return { mode: 'today', date: '', from: '', to: '', q: '', status: '', member: '', pocket: '', ...saved };
|
||||
if (!values || typeof values !== 'object') return defaults;
|
||||
for (const key of Object.keys(defaults) as (keyof Filters)[]) {
|
||||
const value: unknown = Reflect.get(values, key);
|
||||
if (typeof value === 'string') defaults[key] = value;
|
||||
}
|
||||
return defaults;
|
||||
}
|
||||
const options = rows =>
|
||||
const options = (rows: readonly (readonly string[])[]) =>
|
||||
rows.map(([value, name]) => (
|
||||
<option key={value} value={value}>
|
||||
{name}
|
||||
</option>
|
||||
));
|
||||
|
||||
export function OrdersPage({ client, state, session, refreshState, saleListStatus, setSaleListStatus }) {
|
||||
export function OrdersPage({ client, state, session, refreshState, saleListStatus, setSaleListStatus }: OrdersProps) {
|
||||
const [filters, setFilters] = useState(() => initialFilters(state));
|
||||
const noticeKey = ownershipNoticeKey(state.user.id);
|
||||
const [error, setError] = useState(() => sessionStorage.getItem(noticeKey) || '');
|
||||
useEffect(() => {
|
||||
sessionStorage.removeItem(noticeKey);
|
||||
const failed = event => setError(previous => previous + ' ' + event.detail);
|
||||
const failed = (event: Event) => setError(previous => previous + ' ' + (event as CustomEvent<string>).detail);
|
||||
window.addEventListener('order-access-refresh-error', failed);
|
||||
return () => window.removeEventListener('order-access-refresh-error', failed);
|
||||
}, [noticeKey]);
|
||||
@@ -96,10 +70,10 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
||||
if (document.hidden || checking || client.busy) return;
|
||||
checking = true;
|
||||
try {
|
||||
const latest = await client.api('/api/state');
|
||||
const latest = await client.api<LedgerState>('/api/state');
|
||||
if (active && latest.user.id === state.user.id && latest.today !== state.today) await refreshState();
|
||||
} catch (err) {
|
||||
if (active) setError(err.message);
|
||||
if (active) setError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
checking = false;
|
||||
}
|
||||
@@ -114,19 +88,15 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
||||
}, [client, state.user.id, state.today, refreshState]);
|
||||
const [generation, reload] = useState(0);
|
||||
const [selected, setSelected] = useState(searchParam('order'));
|
||||
const [listIds, setListIds] = useState(null);
|
||||
const [queue, setQueue] = useState('');
|
||||
const [listIds, setListIds] = useState<string[] | null>(null);
|
||||
const [queue, setQueue] = useState<Queue | ''>('');
|
||||
const [orderStatus, setOrderStatus] = useState('pending');
|
||||
const status = queue === 'after-sale' ? saleListStatus : orderStatus;
|
||||
const [sale, setSale] = useState(() =>
|
||||
const [sale, setSale] = useState<{ action: string; id?: string } | null>(() =>
|
||||
searchParam('afterSale') ? { action: 'after-sale-edit', id: searchParam('afterSale') } : null,
|
||||
);
|
||||
const refresh = useCallback(() => reload(i => i + 1), []);
|
||||
const currentQuery = searchParam('order');
|
||||
useEffect(() => {
|
||||
setSelected(currentQuery);
|
||||
}, [currentQuery]);
|
||||
function filter(values) {
|
||||
function filter(values: Partial<Filters>) {
|
||||
const next = { ...filters, ...values };
|
||||
setFilters(next);
|
||||
sessionStorage.setItem('mm-order-book-' + state.user.id, JSON.stringify(next));
|
||||
@@ -140,11 +110,11 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
||||
orderCancellationListStatus: status,
|
||||
afterSaleChangesStatus: status,
|
||||
});
|
||||
let range, invalid;
|
||||
let range: ReturnType<typeof views.orderBookRange> | undefined, invalid: string | undefined;
|
||||
try {
|
||||
range = views.orderBookRange();
|
||||
} catch (err) {
|
||||
invalid = err.message;
|
||||
invalid = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
const params =
|
||||
range &&
|
||||
@@ -158,8 +128,8 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
||||
});
|
||||
const book = useRead(
|
||||
async () => {
|
||||
const data = await client.api('/api/order-book?' + params);
|
||||
if (data.from !== range.from || data.date !== range.date || (data.pocket ?? '') !== filters.pocket)
|
||||
const data = await client.api<BookData>('/api/order-book?' + params);
|
||||
if (data.from !== range!.from || data.date !== range!.date || (data.pocket ?? '') !== filters.pocket)
|
||||
throw new Error('返回账本与所选日期或货盘不一致,请重新读取。');
|
||||
return data;
|
||||
},
|
||||
@@ -170,7 +140,7 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
||||
Promise.all(
|
||||
queues.map(async ([, url]) => {
|
||||
try {
|
||||
return (await client.api(url + '?status=pending')).counts.pending;
|
||||
return (await client.api<ReviewList<unknown>>(url + '?status=pending')).counts.pending;
|
||||
} catch {
|
||||
return '读取失败';
|
||||
}
|
||||
@@ -179,21 +149,28 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
||||
state.user.id + '/' + generation,
|
||||
);
|
||||
const qdef = queues.find(([kind]) => kind === queue);
|
||||
const list = useRead(() => client.api(qdef[1] + '?status=' + status), queue && [queue, status, generation].join('/'));
|
||||
const review =
|
||||
qdef &&
|
||||
list.value &&
|
||||
{
|
||||
change: views.orderChangeListHTML,
|
||||
ownership: views.orderOwnershipListHTML,
|
||||
cancellation: views.orderCancellationListHTML,
|
||||
'after-sale': views.afterSaleChangeListHTML,
|
||||
}[queue](list.value);
|
||||
const list = useRead(
|
||||
async () => {
|
||||
const url = qdef![1] + '?status=' + status;
|
||||
switch (queue) {
|
||||
case 'change':
|
||||
return views.orderChangeListHTML(await client.api<ReviewList<ChangeRequest>>(url));
|
||||
case 'ownership':
|
||||
return views.orderOwnershipListHTML(await client.api<ReviewList<OwnershipRequest>>(url));
|
||||
case 'cancellation':
|
||||
return views.orderCancellationListHTML(await client.api<ReviewList<CancellationRequest>>(url));
|
||||
case 'after-sale':
|
||||
return views.afterSaleChangeListHTML(await client.api<ReviewList<IndependentRequest>>(url));
|
||||
}
|
||||
},
|
||||
queue && [queue, status, generation].join('/'),
|
||||
);
|
||||
const review = list.value;
|
||||
let content,
|
||||
bookError = invalid || book.error;
|
||||
if (book.value) {
|
||||
try {
|
||||
const withPrint = rows =>
|
||||
const withPrint = (rows: BookRow[]) =>
|
||||
rows.map(row =>
|
||||
printStatuses[row.printStatus?.id || row.id]
|
||||
? { ...row, printStatus: printStatuses[row.printStatus?.id || row.id] }
|
||||
@@ -205,20 +182,22 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
||||
rows: withPrint(book.value.rows),
|
||||
...(book.value.displayRows ? { displayRows: withPrint(book.value.displayRows) } : {}),
|
||||
},
|
||||
range,
|
||||
range!,
|
||||
);
|
||||
} catch (err) {
|
||||
bookError = err.message;
|
||||
bookError = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
}
|
||||
const openOrder = (id, fromList = false) => {
|
||||
const openOrder = (id: string, fromList = false) => {
|
||||
setQueue('');
|
||||
setError('');
|
||||
setListIds(
|
||||
fromList
|
||||
? [
|
||||
...new Set(
|
||||
book.value.rows.filter(row => !['afterSale', 'orderAfterSale'].includes(row.kind)).map(row => row.id),
|
||||
book
|
||||
.value!.rows.filter(row => !['afterSale', 'orderAfterSale'].includes(row.kind ?? ''))
|
||||
.map(row => row.id),
|
||||
),
|
||||
]
|
||||
: null,
|
||||
@@ -229,7 +208,7 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
||||
setSelected('');
|
||||
if (searchParam('order')) navigate('orders', { replace: true, fromPage: true });
|
||||
}
|
||||
function lostAccess(message) {
|
||||
function lostAccess(message: string) {
|
||||
setListIds(null);
|
||||
setQueue('');
|
||||
setSelected('');
|
||||
@@ -239,12 +218,13 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
||||
navigate('orders', { replace: true, fromPage: true });
|
||||
}
|
||||
refresh();
|
||||
void refreshState().catch(err => setError(message + ' ' + err.message));
|
||||
void refreshState().catch(err => setError(message + ' ' + (err instanceof Error ? err.message : String(err))));
|
||||
}
|
||||
function click(event) {
|
||||
const node = event.target.closest('[data-action]');
|
||||
if (!node || event.defaultPrevented) return;
|
||||
const { action, id, period, status: newStatus } = node.dataset;
|
||||
function click(event: MouseEvent<HTMLElement>) {
|
||||
if (!(event.target instanceof Element)) return;
|
||||
const node = event.target.closest<HTMLElement>('[data-action]');
|
||||
if (!node || !node.dataset.action || event.defaultPrevented) return;
|
||||
const { action = '', id = '', period, status: newStatus } = node.dataset;
|
||||
const match = queues.find(row => row[3] === action);
|
||||
if (match) {
|
||||
setQueue(match[0]);
|
||||
@@ -273,7 +253,9 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
||||
});
|
||||
if (action === 'refresh' || action.includes('retry') || action.includes('reload')) refresh();
|
||||
}
|
||||
const countSum = counts.value?.every(Number.isInteger) ? counts.value.reduce((acc, n) => acc + n, 0) : null;
|
||||
const countSum = counts.value?.every((n): n is number => typeof n === 'number' && Number.isInteger(n))
|
||||
? counts.value.reduce((acc, n) => acc + n, 0)
|
||||
: null;
|
||||
const memberOptions = (state.members || []).map(m => [
|
||||
m.member,
|
||||
views.teamMemberName(m.member) + (m.enabled === false ? '(已停用)' : ''),
|
||||
@@ -306,7 +288,7 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
||||
(state.user.role === 'owner' ? '跨日期查看售后修改,核对原值与申请值后复核。' : '查看自己归属售后的修改申请。') +
|
||||
'待审批期间仍按原记录计账。',
|
||||
],
|
||||
}[queue];
|
||||
}[queue || 'change'];
|
||||
return (
|
||||
<div className="business-pages" onClick={click}>
|
||||
<div className="page-heading">
|
||||
@@ -365,7 +347,7 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
|
||||
/>
|
||||
</label>
|
||||
<div id="order-range-fields" hidden={filters.mode !== 'range'}>
|
||||
{['from', 'to'].map((key, i) => (
|
||||
{(['from', 'to'] as const).map((key, i) => (
|
||||
<label key={key}>
|
||||
{i ? '结束' : '开始'}日期
|
||||
<input
|
||||
@@ -0,0 +1,152 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import type { LedgerClient } from '../../lib/api';
|
||||
import type { LedgerState, OrderDraft, SessionInfo } from '../../shared';
|
||||
|
||||
export interface EditFee extends Record<string, unknown> {
|
||||
key: string;
|
||||
note: string;
|
||||
payer: string;
|
||||
amount: string;
|
||||
status?: string;
|
||||
date?: string;
|
||||
edited?: boolean;
|
||||
funding?: Record<string, unknown>;
|
||||
sourceName?: string;
|
||||
lineNumber?: number;
|
||||
system?: string;
|
||||
expense_id?: string;
|
||||
chargeId?: string;
|
||||
source_kind?: string;
|
||||
source_id?: string;
|
||||
}
|
||||
export interface LockMaterial {
|
||||
source?: string;
|
||||
rate: string;
|
||||
payer: string;
|
||||
amount?: number;
|
||||
verified: boolean;
|
||||
}
|
||||
export interface EditItem extends Record<string, unknown> {
|
||||
lineId?: string;
|
||||
name: string;
|
||||
unit: string;
|
||||
quantity: string;
|
||||
payer: string;
|
||||
costParts: { material: string; labor: string; accessories: string; other: string };
|
||||
costPayers: { material: string; labor: string };
|
||||
costLabor: { mode: string; rate?: string };
|
||||
charges?: { id?: string; costRemoved?: boolean; name?: string }[];
|
||||
costFundings?: { labor?: Record<string, unknown> };
|
||||
price_lock_material?: LockMaterial;
|
||||
price_lock_extra_material?: LockMaterial;
|
||||
}
|
||||
export interface EditInputs extends OrderDraft {
|
||||
note: string;
|
||||
date: string;
|
||||
fees_date: string;
|
||||
fee_cost_mode: string;
|
||||
member?: string;
|
||||
customer_type?: string;
|
||||
lines: EditItem[];
|
||||
fee_items: EditFee[];
|
||||
price_lock_material?: LockMaterial;
|
||||
price_lock_extra_material?: LockMaterial;
|
||||
}
|
||||
export interface LockLineMeta {
|
||||
id: string;
|
||||
lineId?: string;
|
||||
line_index?: number;
|
||||
lockedMg: number;
|
||||
materialSource: string;
|
||||
materialLocked: boolean;
|
||||
canSwitchToManual: boolean;
|
||||
extraMg: number;
|
||||
}
|
||||
export interface LockEditMeta extends LockLineMeta {
|
||||
date: string;
|
||||
lines?: LockLineMeta[];
|
||||
financeRequiresApproval: boolean;
|
||||
approvalReason?: string;
|
||||
}
|
||||
export interface PoolCost {
|
||||
poolId: string;
|
||||
date: string;
|
||||
amount: number | null;
|
||||
averageRate: number | null;
|
||||
allocations: { payer: string; amount: number }[];
|
||||
materialSources?: {
|
||||
kind: string;
|
||||
quantity: number;
|
||||
amount: number | null;
|
||||
averageRate?: number | null;
|
||||
member?: string;
|
||||
}[];
|
||||
}
|
||||
export interface EditOrderRecord {
|
||||
id: string;
|
||||
number: string;
|
||||
date: string;
|
||||
paper_date: string;
|
||||
paper_number: string;
|
||||
member: string;
|
||||
customer: string;
|
||||
salesperson: string;
|
||||
note: string;
|
||||
internal_note?: string;
|
||||
payment_account: string;
|
||||
total: number;
|
||||
directCost: number;
|
||||
rounding_mode: string;
|
||||
price_lock_id?: string;
|
||||
lines: {
|
||||
name: string;
|
||||
unit: string;
|
||||
quantity: number;
|
||||
sale: number;
|
||||
cost: number | null;
|
||||
pocket: string;
|
||||
goldPrice?: number;
|
||||
priceLockPool?: PoolCost;
|
||||
materialPool?: PoolCost;
|
||||
priceLockExtraPool?: PoolCost;
|
||||
}[];
|
||||
}
|
||||
export interface EditResponse {
|
||||
eligible: boolean;
|
||||
reason: string;
|
||||
revision: number;
|
||||
inputs: EditInputs;
|
||||
order: EditOrderRecord;
|
||||
priceLock?: LockEditMeta | null;
|
||||
requiresApproval?: boolean;
|
||||
financialEditable: boolean;
|
||||
directEditDate?: string;
|
||||
approvalReason?: string;
|
||||
requiresLegacyCountVerified?: boolean;
|
||||
legacyCountNotice?: string;
|
||||
}
|
||||
export interface EditEntry extends EditResponse {
|
||||
id: string;
|
||||
user: string;
|
||||
reason: string;
|
||||
verified: boolean;
|
||||
originalInputs: EditInputs;
|
||||
sameDayDirectEdit: boolean;
|
||||
conflicted: boolean;
|
||||
latest?: EditResponse | null;
|
||||
}
|
||||
export type LockEntry = EditEntry & { priceLock: LockEditMeta };
|
||||
export type SaveDraft = (inputs: OrderDraft, reason: string, verified: boolean) => void;
|
||||
export type EditPayload =
|
||||
OrderDraft | { customer: string; salesperson: string; customer_type?: string; note: string; internal_note: string };
|
||||
export type SaveOrder = (inputs: EditPayload, reason: string, verified: boolean, approval: boolean) => Promise<void>;
|
||||
export interface LockEditorProps {
|
||||
client: LedgerClient;
|
||||
state: LedgerState;
|
||||
session: SessionInfo;
|
||||
entry: LockEntry;
|
||||
serverFeedback: ReactNode;
|
||||
onDraft: SaveDraft;
|
||||
onSave: SaveOrder;
|
||||
onCancel: () => void;
|
||||
}
|
||||
@@ -0,0 +1,774 @@
|
||||
export interface OrderRecord {
|
||||
id: string;
|
||||
number: string;
|
||||
date: string;
|
||||
customer: string;
|
||||
salesperson: string;
|
||||
note: string;
|
||||
paper_number: string;
|
||||
status: string;
|
||||
lines: OrderLine[];
|
||||
discount: number;
|
||||
total: number;
|
||||
revision: number;
|
||||
reviewed_revision: number;
|
||||
created: string;
|
||||
delivered_date: null | string;
|
||||
returned_date: null | string;
|
||||
paper_date: string;
|
||||
payment_account: string;
|
||||
fee_items: Fee[];
|
||||
fees_date: string;
|
||||
rounding_mode: string;
|
||||
internal_note: string;
|
||||
fee_cost_mode: string;
|
||||
customer_type: string;
|
||||
member: string;
|
||||
cancellationPending?: CancellationRequest | null;
|
||||
cancellationApproved?: null | CancellationRequest;
|
||||
changePending?: ChangeRequest | null;
|
||||
ownershipPending: OwnershipRequest | null;
|
||||
payments: Payment[];
|
||||
expenses: Expense[];
|
||||
settlements: Settlement[];
|
||||
corrections: Correction[];
|
||||
netReceived: number;
|
||||
balance: number;
|
||||
rounding_adjustment: number;
|
||||
goodsCost: number | null;
|
||||
directCost: number;
|
||||
materialCostPending: boolean;
|
||||
knownGoodsCost: number;
|
||||
pendingFees: Fee[];
|
||||
profit: number | null;
|
||||
ownerCost: number;
|
||||
ownerDirect: number;
|
||||
ownerCredit: number;
|
||||
costTransferred: number;
|
||||
profitTransferred: number;
|
||||
costDue: number;
|
||||
profitDue: number;
|
||||
settlementDue: number | null;
|
||||
audit?: OrderRecordAudit[];
|
||||
funds_mode: string;
|
||||
credit_card_rate_permille?: number;
|
||||
printStatus?: PrintStatus;
|
||||
orderAfterSale?: OrderAfterSale;
|
||||
assistantInventoryCredit?: number;
|
||||
assistantInventoryCreditExplanation?: string;
|
||||
kind?: string;
|
||||
price_lock_id?: string;
|
||||
recovery_id?: string;
|
||||
recovery_mode?: string;
|
||||
priceLockCosts?: LockCosts;
|
||||
}
|
||||
|
||||
export interface BookData {
|
||||
from: string;
|
||||
date: string;
|
||||
pocket: string;
|
||||
rows: BookRow[];
|
||||
displayRows?: BookRow[];
|
||||
recoveryCount: number;
|
||||
summary: BookSummary;
|
||||
priceLockActivity: LockActivity;
|
||||
summaryWithoutCancelled: BookSummary;
|
||||
receiptsWithoutCancelled: ReceiptSummary;
|
||||
}
|
||||
|
||||
export interface ChangeRequest {
|
||||
id: string;
|
||||
order_id: string;
|
||||
order_revision: number;
|
||||
action: string;
|
||||
reason: string;
|
||||
status: 'pending' | 'approved' | 'rejected';
|
||||
requester_name: string;
|
||||
created: string;
|
||||
reviewer_name: null | string;
|
||||
reviewed: null | string;
|
||||
note: string;
|
||||
action_label: string;
|
||||
order_number?: string;
|
||||
order_date?: string;
|
||||
stale?: boolean;
|
||||
canApprove?: boolean;
|
||||
before: OrderRecord;
|
||||
after: OrderRecord;
|
||||
summary: ChangeSummary;
|
||||
relatedOrders?: RelatedOrder[];
|
||||
action_details?: ChangeActionInput;
|
||||
action_input?: ChangeActionInput;
|
||||
relatedPriceLocks?: RelatedLock[];
|
||||
}
|
||||
|
||||
export interface OwnershipRequest {
|
||||
id: string;
|
||||
order_id: string;
|
||||
order_revision: number;
|
||||
reason: string;
|
||||
status: 'pending' | 'approved' | 'rejected';
|
||||
direct: boolean;
|
||||
requester_name: string;
|
||||
created: string;
|
||||
reviewer_name: null | string;
|
||||
reviewed: null | string;
|
||||
note: string;
|
||||
before: Member;
|
||||
after: Member;
|
||||
order_number?: string;
|
||||
order_customer?: string;
|
||||
order_date?: string;
|
||||
stale?: boolean;
|
||||
canApprove?: boolean;
|
||||
}
|
||||
|
||||
export interface CancellationRequest {
|
||||
executedAt?: string;
|
||||
operator_name?: string;
|
||||
id: string;
|
||||
order_id: string;
|
||||
order_revision: number;
|
||||
reason: string;
|
||||
status: 'pending' | 'approved' | 'rejected';
|
||||
requester_name: string;
|
||||
created: string;
|
||||
reviewer_name: null | string;
|
||||
reviewed: null | string;
|
||||
note: string;
|
||||
order_number?: string;
|
||||
order_date?: string;
|
||||
requiresLegacyCountVerified?: boolean;
|
||||
legacyCountNotice?: string;
|
||||
stale?: boolean;
|
||||
canApprove?: boolean;
|
||||
summary: CancelSummary;
|
||||
direct?: boolean;
|
||||
}
|
||||
|
||||
export interface ChangeData {
|
||||
eligible: boolean;
|
||||
reason: string;
|
||||
actions: ActionRules;
|
||||
directActionDate: string;
|
||||
revision: number;
|
||||
pending: ChangeRequest | null;
|
||||
requests: ChangeRequest[];
|
||||
canApprove: boolean;
|
||||
}
|
||||
|
||||
export interface OwnershipData {
|
||||
eligible: boolean;
|
||||
reason: string;
|
||||
revision: number;
|
||||
member: string;
|
||||
members: Member[];
|
||||
requiresApproval: boolean;
|
||||
canDirect: boolean;
|
||||
canApprove: boolean;
|
||||
pending: OwnershipRequest | null;
|
||||
requests: OwnershipRequest[];
|
||||
}
|
||||
|
||||
export interface CancellationData {
|
||||
eligible: boolean;
|
||||
reason: string;
|
||||
revision: number;
|
||||
requiresLegacyCountVerified: boolean;
|
||||
legacyCountNotice: string;
|
||||
directActionDate: string;
|
||||
directToday: boolean;
|
||||
pending: CancellationRequest | null;
|
||||
requests: CancellationRequest[];
|
||||
canApprove: boolean;
|
||||
summary?: CancelSummary;
|
||||
}
|
||||
|
||||
export interface OrderAfterSaleData {
|
||||
orderId: string;
|
||||
revision: number;
|
||||
eligible: boolean;
|
||||
blockedReason: string;
|
||||
record: null | OrderAfterSale;
|
||||
}
|
||||
|
||||
export interface IndependentDetail {
|
||||
id: string;
|
||||
revision: number;
|
||||
record: IndependentRecord;
|
||||
values: IndependentValues;
|
||||
permissions: AfterPermissions;
|
||||
pending: IndependentRequest | null;
|
||||
history: IndependentRequest[];
|
||||
}
|
||||
|
||||
export interface IndependentRequest {
|
||||
id: string;
|
||||
afterSaleId: string;
|
||||
revision: number;
|
||||
recordRevision: number;
|
||||
status: 'pending' | 'approved' | 'rejected';
|
||||
reason: string;
|
||||
before: IndependentValues;
|
||||
after: IndependentValues;
|
||||
member: string;
|
||||
requesterName: string;
|
||||
created: string;
|
||||
reviewerName: string | null;
|
||||
reviewed: string | null;
|
||||
note: string;
|
||||
stale: boolean;
|
||||
staleReason: string;
|
||||
canApprove: boolean;
|
||||
}
|
||||
|
||||
export interface OrderLine {
|
||||
name: string;
|
||||
code: string;
|
||||
unit: string;
|
||||
quantity: number;
|
||||
pocket: string;
|
||||
payer: string;
|
||||
cost: number;
|
||||
sale: number;
|
||||
baseSale: number;
|
||||
charges: Charge[];
|
||||
pricingMode: string;
|
||||
priceNote: string;
|
||||
costPayers?: OrderLineCostPayers;
|
||||
costParts?: CostParts;
|
||||
costMaterial?: CostMode;
|
||||
costLabor?: CostMode;
|
||||
goldPrice?: number;
|
||||
laborRate?: number;
|
||||
laborMode?: string;
|
||||
pieces?: number;
|
||||
materialPool?: LinePool;
|
||||
stockCount?: number | null;
|
||||
priceLockPool?: LinePool;
|
||||
priceLockExtraPool?: LinePool;
|
||||
}
|
||||
|
||||
export interface OrderRecordAudit {
|
||||
action: string;
|
||||
actor: string;
|
||||
detail: { reason?: string };
|
||||
created: string;
|
||||
}
|
||||
|
||||
export interface PrintStatus {
|
||||
kind: string;
|
||||
id: string;
|
||||
printed: boolean;
|
||||
revision?: number;
|
||||
actor?: string | null;
|
||||
}
|
||||
|
||||
export interface Fee {
|
||||
key: string;
|
||||
system?: string;
|
||||
source_kind?: string;
|
||||
source_id?: string;
|
||||
date?: string;
|
||||
amount: number;
|
||||
payer: string;
|
||||
note: string;
|
||||
status: string;
|
||||
expense_id?: string;
|
||||
edited?: boolean;
|
||||
lineNumber?: number;
|
||||
sourceName?: string;
|
||||
}
|
||||
|
||||
export interface Payment {
|
||||
price_lock_event_id?: string;
|
||||
id: string;
|
||||
order_id: string;
|
||||
date: string;
|
||||
kind: string;
|
||||
amount: number;
|
||||
account: string;
|
||||
reference: string;
|
||||
actor: string;
|
||||
created: string;
|
||||
}
|
||||
|
||||
export interface Expense {
|
||||
id: string;
|
||||
order_id: string;
|
||||
date: string;
|
||||
amount: number;
|
||||
payer: string;
|
||||
note: string;
|
||||
actor: string;
|
||||
created: string;
|
||||
}
|
||||
|
||||
export interface Correction {
|
||||
target: string;
|
||||
type: string;
|
||||
reason: string;
|
||||
actor: string;
|
||||
created: string;
|
||||
}
|
||||
|
||||
export interface BookRow {
|
||||
[key: `${string}Cost`]: number | null | undefined;
|
||||
assistant2Cost?: number;
|
||||
id: string;
|
||||
order_id?: string;
|
||||
kind?: string;
|
||||
orderAfterSale?: OrderAfterSale;
|
||||
member?: string;
|
||||
number: string;
|
||||
paper_number: string;
|
||||
date: string;
|
||||
order_date?: string;
|
||||
created: string;
|
||||
customer: string;
|
||||
salesperson: string;
|
||||
status: string;
|
||||
note: string;
|
||||
project?: string;
|
||||
types: string[];
|
||||
mg: number;
|
||||
pieces: number;
|
||||
originalSale?: number;
|
||||
sale?: number;
|
||||
material?: number | null;
|
||||
laborAndFees?: number | null;
|
||||
unallocated?: number;
|
||||
totalCost?: number;
|
||||
profit?: number;
|
||||
ownerCost?: number;
|
||||
assistantCost?: number;
|
||||
known?: Known;
|
||||
costItems?: BookCost[];
|
||||
laborAndFeeItems?: BookCost[];
|
||||
pendingCosts?: number;
|
||||
unknownCosts?: number;
|
||||
legacyUnallocated?: boolean;
|
||||
incomplete?: boolean;
|
||||
costHint: string;
|
||||
balance?: number;
|
||||
revision?: number;
|
||||
reviewed_revision?: number;
|
||||
funds_mode?: string;
|
||||
price_lock_id?: string;
|
||||
recovery_id?: string;
|
||||
recovery_mode?: string;
|
||||
cancellationApproved?: CancellationRequest | null;
|
||||
materialCostPending?: boolean;
|
||||
printStatus?: PrintStatus;
|
||||
after_sale_id?: string;
|
||||
amount?: number;
|
||||
payer?: string;
|
||||
cashPayment?: number;
|
||||
}
|
||||
|
||||
export interface BookSummary {
|
||||
[key: `${string}Cost`]: number;
|
||||
assistant2Cost: number;
|
||||
orderCount: number;
|
||||
completedCount: number;
|
||||
draftCount: number;
|
||||
cancelledCount: number;
|
||||
incompleteCount: number;
|
||||
pendingCosts: number;
|
||||
unknownCosts: number;
|
||||
unknownCostCount: number;
|
||||
unknownProfitCount: number;
|
||||
sale: number;
|
||||
material: number;
|
||||
laborAndFees: number;
|
||||
unallocated: number;
|
||||
totalCost: number;
|
||||
profit: number;
|
||||
ownerCost: number;
|
||||
assistantCost: number;
|
||||
mg: number;
|
||||
pieces: number;
|
||||
knownCounts: Counts;
|
||||
unknownCounts: Counts;
|
||||
afterSaleCount: number;
|
||||
recordCount: number;
|
||||
}
|
||||
|
||||
export interface LockActivity {
|
||||
basis: string;
|
||||
from: string;
|
||||
date: string;
|
||||
customerCash: LockActivityRow[];
|
||||
orderPayments: LockActivityRow[];
|
||||
materialOutlays: LockActivityRow[];
|
||||
directOutlays: LockActivityRow[];
|
||||
deliveryGoodsOutlays: LockActivityRow[];
|
||||
summary: LockActivitySummary;
|
||||
}
|
||||
|
||||
export interface ReceiptSummary {
|
||||
basis: string;
|
||||
filterScope: string;
|
||||
from: string;
|
||||
date: string;
|
||||
receipt: number;
|
||||
refund: number;
|
||||
net: number;
|
||||
channels: ReceiptSummaryChannels[];
|
||||
orderCount: number;
|
||||
}
|
||||
|
||||
export interface ChangeSummary {
|
||||
before: CostSummary;
|
||||
after: CostSummary;
|
||||
inventory: InventoryChange;
|
||||
}
|
||||
|
||||
export interface Member {
|
||||
member: string;
|
||||
label: string;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export interface CancelSummary extends CostSummary {
|
||||
legacyCountNotice?: string;
|
||||
requiresLegacyCountVerified?: boolean;
|
||||
inventory: InventoryRow[];
|
||||
}
|
||||
|
||||
export interface ActionRules {
|
||||
[kind: string]: ActionRule;
|
||||
}
|
||||
|
||||
export interface OrderAfterSale {
|
||||
orderId: string;
|
||||
date: string;
|
||||
reason: string;
|
||||
deductionReason: string;
|
||||
refund: Refund;
|
||||
expenses: { note: string; amount: number; payer: string }[];
|
||||
summary: AfterSummary;
|
||||
lines: AfterSaleLine[];
|
||||
order_id?: string;
|
||||
created?: string;
|
||||
number?: string;
|
||||
paper_number?: string;
|
||||
customer?: string;
|
||||
salesperson?: string;
|
||||
note?: string;
|
||||
order_date?: string;
|
||||
member?: string;
|
||||
}
|
||||
|
||||
export interface IndependentRecord {
|
||||
id: string;
|
||||
date: string;
|
||||
project: string;
|
||||
customer: string;
|
||||
amount: number;
|
||||
payer: string;
|
||||
actor: string;
|
||||
created: string;
|
||||
member: string;
|
||||
revision: number;
|
||||
}
|
||||
|
||||
export interface IndependentValues {
|
||||
date: string;
|
||||
project: string;
|
||||
customer: string;
|
||||
amount: string | number;
|
||||
payer: string;
|
||||
}
|
||||
|
||||
export interface AfterPermissions {
|
||||
canEdit: boolean;
|
||||
canDirectEdit: boolean;
|
||||
requiresApproval: boolean;
|
||||
reason: string;
|
||||
}
|
||||
|
||||
export interface OrderLineCostPayers {
|
||||
[component: string]: string;
|
||||
material: string;
|
||||
labor: string;
|
||||
accessories: string;
|
||||
other: string;
|
||||
}
|
||||
|
||||
export interface CostParts {
|
||||
[component: string]: number | null;
|
||||
material: number | null;
|
||||
labor: number | null;
|
||||
accessories: number | null;
|
||||
other: number | null;
|
||||
}
|
||||
|
||||
export interface CostMode {
|
||||
mode: string;
|
||||
rate?: number | null;
|
||||
poolId?: string;
|
||||
}
|
||||
|
||||
export interface Charge {
|
||||
id: string;
|
||||
name: string;
|
||||
amount: number;
|
||||
}
|
||||
|
||||
export interface LinePool {
|
||||
poolId: string;
|
||||
date: string;
|
||||
status: string;
|
||||
amount: number;
|
||||
quantity: number;
|
||||
averageRate: number;
|
||||
allocations: LinePoolAllocations[];
|
||||
revision: string;
|
||||
}
|
||||
|
||||
export interface Known {
|
||||
[key: `${string}Cost`]: number | undefined;
|
||||
assistant2Cost?: number;
|
||||
sale: number;
|
||||
material: number;
|
||||
laborAndFees: number;
|
||||
unallocated: number;
|
||||
totalCost: number;
|
||||
profit: number;
|
||||
ownerCost: number;
|
||||
assistantCost: number;
|
||||
}
|
||||
|
||||
export interface BookCost {
|
||||
kind: string;
|
||||
component: string;
|
||||
name: string;
|
||||
source: string;
|
||||
amount: number;
|
||||
payer: string;
|
||||
materialPoolId?: string;
|
||||
calculation?: BookCostCalculation;
|
||||
excluded?: boolean;
|
||||
priceLockSource?: string;
|
||||
after_sale_id?: string;
|
||||
}
|
||||
|
||||
export interface Counts {
|
||||
[key: `${string}Cost`]: number;
|
||||
assistant2Cost: number;
|
||||
sale: number;
|
||||
material: number;
|
||||
laborAndFees: number;
|
||||
unallocated: number;
|
||||
totalCost: number;
|
||||
profit: number;
|
||||
ownerCost: number;
|
||||
assistantCost: number;
|
||||
}
|
||||
|
||||
export interface LockActivityRow {
|
||||
id: string;
|
||||
price_lock_id: string;
|
||||
date: string;
|
||||
kind: string;
|
||||
amount: number;
|
||||
account?: string;
|
||||
number: string;
|
||||
customer: string;
|
||||
product?: string;
|
||||
actor?: string;
|
||||
created?: string;
|
||||
line_index?: null | number;
|
||||
voided?: number;
|
||||
payer?: string;
|
||||
source?: string;
|
||||
quantity?: number;
|
||||
rate?: number;
|
||||
component?: string;
|
||||
order_id?: string;
|
||||
note?: string;
|
||||
name?: string;
|
||||
excluded?: boolean;
|
||||
calculation?: null;
|
||||
paper_number?: string;
|
||||
}
|
||||
|
||||
export interface LockActivitySummary {
|
||||
receipt: number;
|
||||
refund: number;
|
||||
net: number;
|
||||
ownerOutlay: number;
|
||||
assistantOutlay: number;
|
||||
eventCount: number;
|
||||
}
|
||||
|
||||
export interface ReceiptSummaryChannels {
|
||||
channel: string;
|
||||
name: string;
|
||||
receipt: number;
|
||||
refund: number;
|
||||
net: number;
|
||||
}
|
||||
|
||||
export interface CostSummary {
|
||||
total: number;
|
||||
netReceived: number;
|
||||
directCost: number;
|
||||
goodsCost: number | null;
|
||||
profit: number | null;
|
||||
settlementDue: number | null;
|
||||
}
|
||||
|
||||
export interface InventoryChange {
|
||||
legacyCountNotice?: string;
|
||||
before: InventoryRow[];
|
||||
after: InventoryRow[];
|
||||
changes: InventoryRow[];
|
||||
}
|
||||
|
||||
export interface InventoryRow {
|
||||
stockCount?: number | null;
|
||||
date: string;
|
||||
pocket: string;
|
||||
mg: number;
|
||||
kind?: string;
|
||||
}
|
||||
|
||||
export interface ActionRule {
|
||||
eligible: boolean;
|
||||
reason: string;
|
||||
directToday?: boolean;
|
||||
}
|
||||
|
||||
export interface Refund {
|
||||
amount: number;
|
||||
account: string;
|
||||
payer: string;
|
||||
reference: string;
|
||||
}
|
||||
|
||||
export interface AfterSummary {
|
||||
refundAmount: number;
|
||||
retainedAmount: number;
|
||||
materialReturnedCost: number;
|
||||
laborRestockedCost: number;
|
||||
costLoss: number;
|
||||
directCost: number;
|
||||
profit: number;
|
||||
profitAdjustment: number;
|
||||
}
|
||||
|
||||
export interface AfterSaleLine {
|
||||
lineIndex: number;
|
||||
name: string;
|
||||
code: string;
|
||||
quantity: number;
|
||||
pocket: string;
|
||||
disposition: string;
|
||||
stockCount: null;
|
||||
materialReturnedCost: number;
|
||||
laborRestockedCost: number;
|
||||
laborPayer: string;
|
||||
costLoss: number;
|
||||
}
|
||||
|
||||
export interface LinePoolAllocations {
|
||||
payer: string;
|
||||
amount: number;
|
||||
}
|
||||
|
||||
export interface BookCostCalculation {
|
||||
rate: number;
|
||||
quantity: number;
|
||||
weighted?: boolean;
|
||||
}
|
||||
|
||||
export interface Settlement {
|
||||
bucket: string;
|
||||
id: string;
|
||||
date: string;
|
||||
amount: number;
|
||||
kind: string;
|
||||
note: string;
|
||||
actor: string;
|
||||
}
|
||||
export interface RelatedOrder {
|
||||
id: string;
|
||||
number: string;
|
||||
date: string;
|
||||
customer: string;
|
||||
before: OrderRecord;
|
||||
after: OrderRecord;
|
||||
summary: ChangeSummary;
|
||||
}
|
||||
export interface LockImpact {
|
||||
materialAmount: number | null;
|
||||
usedMaterialAmount?: number | null;
|
||||
leftoverCost?: number | null;
|
||||
allocations: { payer: string; amount: number }[];
|
||||
}
|
||||
export interface RelatedLock {
|
||||
id: string;
|
||||
number: string;
|
||||
date: string;
|
||||
customer: string;
|
||||
before: LockImpact;
|
||||
after: LockImpact;
|
||||
}
|
||||
export interface LockCosts {
|
||||
date?: string;
|
||||
lines?: LockCosts[];
|
||||
lineId?: string;
|
||||
materialSource?: string;
|
||||
buyRate?: number;
|
||||
buyPayer?: string;
|
||||
materialAmount?: number | null;
|
||||
extraRate?: number;
|
||||
extraPayer?: string;
|
||||
}
|
||||
export interface Filters {
|
||||
mode: string;
|
||||
date: string;
|
||||
from: string;
|
||||
to: string;
|
||||
q: string;
|
||||
status: string;
|
||||
member: string;
|
||||
pocket: string;
|
||||
}
|
||||
export interface ReviewList<T> {
|
||||
requests: T[];
|
||||
counts: Record<string, number>;
|
||||
canApprove?: boolean;
|
||||
}
|
||||
export interface DetailEntry<T> {
|
||||
id: string;
|
||||
revision: number;
|
||||
user: string;
|
||||
data?: T;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export type MoneyKey =
|
||||
| 'sale'
|
||||
| 'material'
|
||||
| 'laborAndFees'
|
||||
| 'unallocated'
|
||||
| 'totalCost'
|
||||
| 'profit'
|
||||
| 'ownerCost'
|
||||
| 'assistantCost'
|
||||
| `${string}Cost`;
|
||||
export interface ChangeActionInput {
|
||||
date?: string;
|
||||
amount?: string;
|
||||
account?: string;
|
||||
payer?: string;
|
||||
note?: string;
|
||||
reference?: string;
|
||||
afterSale?: object;
|
||||
returnCounts?: (string | number | null)[];
|
||||
returnPockets?: string[];
|
||||
fee_items?: { note: string; amount: string; payer: string }[];
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { useState, useEffect, useEffectEvent } from 'react';
|
||||
export type Queue = 'change' | 'ownership' | 'cancellation' | 'after-sale';
|
||||
export const queues: readonly (readonly [Queue, string, string, string, string])[] = [
|
||||
['change', '/api/order-changes', '待变更复核', 'open-order-changes', 'order-changes-entry'],
|
||||
['ownership', '/api/order-ownership-changes', '归属复核', 'order-ownership-open-list', 'order-ownership-entry'],
|
||||
['cancellation', '/api/order-cancellations', '待取消复核', 'open-order-cancellations', 'order-cancellations-entry'],
|
||||
['after-sale', '/api/after-sales/changes', '售后修改', 'after-sale-changes-open', 'after-sale-changes-entry'],
|
||||
];
|
||||
|
||||
export function useRead<T>(
|
||||
read: () => Promise<T>,
|
||||
key: string | false | null | undefined,
|
||||
): { value?: T; error?: string } {
|
||||
const [entry, set] = useState<{ key: string; value?: T; error?: string } | null>(null);
|
||||
const task = useEffectEvent(read);
|
||||
useEffect(() => {
|
||||
if (!key) return;
|
||||
let active = true;
|
||||
Promise.resolve()
|
||||
.then(() => task())
|
||||
.then(
|
||||
value => {
|
||||
if (active) set({ key, value });
|
||||
},
|
||||
error => {
|
||||
if (active) set({ key, error: error.message });
|
||||
},
|
||||
);
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [key]);
|
||||
return entry && entry.key === key ? entry : {};
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { OrderContext } from './viewTypes';
|
||||
import { sharedViews } from './views/sharedViews';
|
||||
import { orderBook } from './views/orderBook';
|
||||
import { orderDetail } from './views/orderDetail';
|
||||
import { orderActions } from './views/orderActions';
|
||||
import { orderReviews } from './views/orderReviews';
|
||||
import { afterSales } from './views/afterSales';
|
||||
export function orderViews(context) {
|
||||
export function orderViews(context: OrderContext) {
|
||||
const shared = sharedViews(context);
|
||||
return {
|
||||
...shared,
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { OrderRecord } from './orderData';
|
||||
|
||||
export const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
value !== null && typeof value === 'object';
|
||||
export const errorStatus = (error: unknown) => (isRecord(error) && typeof error.status === 'number' ? error.status : 0);
|
||||
export const errorMessage = (error: unknown) => (error instanceof Error ? error.message : String(error));
|
||||
|
||||
function isOrderDetail(value: Record<string, unknown>): value is Record<string, unknown> & OrderRecord {
|
||||
return (
|
||||
['date', 'number', 'status', 'member'].every(key => typeof value[key] === 'string') &&
|
||||
['revision', 'total', 'balance', 'netReceived'].every(key => Number.isSafeInteger(value[key])) &&
|
||||
['lines', 'payments', 'expenses', 'settlements', 'corrections', 'fee_items', 'pendingFees', 'audit'].every(key =>
|
||||
Array.isArray(value[key]),
|
||||
)
|
||||
);
|
||||
}
|
||||
export function readOrderRecord(value: unknown, id: string): OrderRecord {
|
||||
if (!isRecord(value) || value.id !== id) throw new Error('返回的订单与所选订单不一致,请重试读取。');
|
||||
if (!isOrderDetail(value)) throw new Error('订单详情未完整返回,请重新读取订单。');
|
||||
return value;
|
||||
}
|
||||
+22
-6
@@ -1,13 +1,29 @@
|
||||
import { useCallback, useEffect, useRef } from 'react';
|
||||
|
||||
import type { LedgerState } from '../../shared';
|
||||
|
||||
interface OrderAccess {
|
||||
client: { user: string; busy: boolean; pending: () => unknown; api: (url: string) => Promise<unknown> };
|
||||
state: { user: Pick<LedgerState['user'], 'id' | 'role'> };
|
||||
id: string;
|
||||
watch: boolean;
|
||||
onLost: (message: string) => void;
|
||||
}
|
||||
interface ActiveOrder {
|
||||
user: string;
|
||||
id: string;
|
||||
request: number;
|
||||
}
|
||||
|
||||
export const ownershipNotice = '订单归属或权限已更新,本账号已不能查看这张订单。';
|
||||
export const ownershipNoticeKey = user => 'mm-order-access-notice-' + user;
|
||||
const denied = error => [403, 404].includes(error?.status);
|
||||
export const ownershipNoticeKey = (user: string) => 'mm-order-access-notice-' + user;
|
||||
const denied = (error: unknown) =>
|
||||
!!error && typeof error === 'object' && 'status' in error && (error.status === 403 || error.status === 404);
|
||||
|
||||
// 同一账号可以从“当天直接修改”降为“须申请”。只有订单归属查询也拒绝访问,才清除该账号的该单草稿。
|
||||
export function useOrderAccess({ client, state, id, watch, onLost }) {
|
||||
export function useOrderAccess({ client, state, id, watch, onLost }: OrderAccess) {
|
||||
const user = state.user.id;
|
||||
const scope = useRef(null);
|
||||
const scope = useRef<ActiveOrder | null>(null);
|
||||
const lost = useRef(onLost);
|
||||
useEffect(() => {
|
||||
lost.current = onLost;
|
||||
@@ -20,7 +36,7 @@ export function useOrderAccess({ client, state, id, watch, onLost }) {
|
||||
};
|
||||
}, [user, id]);
|
||||
const revoke = useCallback(
|
||||
(error, current = scope.current) => {
|
||||
(error: unknown, current = scope.current) => {
|
||||
if (state.user.role !== 'assistant' || !denied(error)) return false;
|
||||
if (!current || scope.current !== current || client.user !== current.user) return true;
|
||||
localStorage.removeItem('mm-order-edit-' + user + '-' + id);
|
||||
@@ -45,7 +61,7 @@ export function useOrderAccess({ client, state, id, watch, onLost }) {
|
||||
}
|
||||
return scope.current !== current || client.user !== user || request !== current.request;
|
||||
}, [client, id, state.user.role, user, revoke]);
|
||||
const checkFailure = useCallback(error => (denied(error) ? check() : Promise.resolve(false)), [check]);
|
||||
const checkFailure = useCallback((error: unknown) => (denied(error) ? check() : Promise.resolve(false)), [check]);
|
||||
useEffect(() => {
|
||||
if (!watch || state.user.role !== 'assistant') return;
|
||||
const focus = () => {
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import type { LedgerState, SessionInfo } from '../../shared';
|
||||
import type {
|
||||
CancellationData,
|
||||
ChangeData,
|
||||
DetailEntry,
|
||||
Filters,
|
||||
OrderAfterSale,
|
||||
OrderRecord,
|
||||
OwnershipData,
|
||||
} from './orderData';
|
||||
import type { sharedViews } from './views/sharedViews';
|
||||
|
||||
export type SharedViews = ReturnType<typeof sharedViews>;
|
||||
export type Options = ReadonlyArray<string | readonly [string, string, boolean?]>;
|
||||
export interface OrderUi {
|
||||
action?: string;
|
||||
forceApproval?: boolean;
|
||||
actionBlocked?: boolean;
|
||||
retryBusy?: boolean;
|
||||
retryKey?: string | null;
|
||||
pendingKey?: string;
|
||||
actionError?: string;
|
||||
stale?: boolean;
|
||||
formKey?: string | number;
|
||||
date?: string;
|
||||
lastCardBasis?: string;
|
||||
values?: Record<string, string>;
|
||||
paymentMethod?: string;
|
||||
recipient?: string;
|
||||
afterError?: string;
|
||||
busy?: boolean;
|
||||
approval?: boolean;
|
||||
blocked?: boolean;
|
||||
lines?: { pocket: string; disposition: string }[];
|
||||
reasonRequired?: boolean;
|
||||
retained?: string;
|
||||
previewLoading?: boolean;
|
||||
previewStatus?: string;
|
||||
expenses?: ReactNode;
|
||||
feedback?: ReactNode;
|
||||
verified?: boolean;
|
||||
preview?: { record: OrderAfterSale; signature?: string } | null;
|
||||
}
|
||||
export interface OrderContext {
|
||||
state: LedgerState;
|
||||
session: SessionInfo;
|
||||
currentOrder?: OrderRecord;
|
||||
orderBookFilters?: Filters;
|
||||
detailForm?: ReactNode;
|
||||
navigation?: ReactNode;
|
||||
error?: string;
|
||||
orderChangeDetail?: DetailEntry<ChangeData>;
|
||||
orderCancellationDetail?: DetailEntry<CancellationData>;
|
||||
orderOwnershipDetail?: DetailEntry<OwnershipData>;
|
||||
orderAfterSaleFormEntry?: { id: string; revision: number; user: string; forceApproval?: boolean };
|
||||
ui?: OrderUi;
|
||||
orderChangeListStatus?: string;
|
||||
orderOwnershipListStatus?: string;
|
||||
orderCancellationListStatus?: string;
|
||||
afterSaleChangesStatus?: string;
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
import { useState } from 'react';
|
||||
import { Calc as LedgerCalc } from '../../../shared';
|
||||
import type { OrderLine } from '../orderData';
|
||||
import type { SharedViews } from '../viewTypes';
|
||||
type CostModeKey = 'material' | 'labor';
|
||||
type CostInputs = Record<string, string>;
|
||||
type LineProps = { line: OrderLine; index: number; members: SharedViews['teamMemberOptions']; fallback: string } & Pick<
|
||||
SharedViews,
|
||||
'choice' | 'opts' | 'grams' | 'yuan'
|
||||
>;
|
||||
const asMoney = (value?: number | null) => (value == null ? '' : (value / 100).toFixed(2));
|
||||
const costKeys = Object.keys(LedgerCalc.costLabels);
|
||||
function costBreakdown(
|
||||
line: OrderLine,
|
||||
quantity: string | number,
|
||||
parts: CostInputs,
|
||||
modes: CostInputs,
|
||||
rates: CostInputs,
|
||||
) {
|
||||
const input: {
|
||||
unit: string;
|
||||
quantity: string | number;
|
||||
costParts: CostInputs;
|
||||
costMaterial?: { mode: string; rate?: string };
|
||||
costLabor?: { mode: string; rate?: string };
|
||||
} = { unit: line.unit, quantity, costParts: parts };
|
||||
for (const [key, property] of [
|
||||
['material', 'costMaterial'],
|
||||
['labor', 'costLabor'],
|
||||
] as const) {
|
||||
input[property] = modes[key] === 'gram' ? { mode: 'gram', rate: rates[key] } : { mode: 'total' };
|
||||
}
|
||||
return LedgerCalc.purchaseCosts(input);
|
||||
}
|
||||
export function LegacyCostRow({ line, index, members, fallback, choice, opts, grams, yuan }: LineProps) {
|
||||
const prefix = 'cost-' + index + '-';
|
||||
const quantity = line.unit === 'g' ? (line.quantity / 1000).toFixed(3) : line.quantity;
|
||||
const initialParts = Object.fromEntries(
|
||||
costKeys.map(key => [
|
||||
key,
|
||||
line.costParts ? asMoney(line.costParts[key]) : ['accessories', 'other'].includes(key) ? '0' : '',
|
||||
]),
|
||||
);
|
||||
const originalMode = ['gram', 'total'].includes(line.costMaterial?.mode ?? '')
|
||||
? line.costMaterial!.mode
|
||||
: initialParts.material === ''
|
||||
? 'gram'
|
||||
: 'total';
|
||||
const [parts, setParts] = useState(initialParts);
|
||||
const [modes, setModes] = useState({
|
||||
material: line.unit === 'g' ? originalMode : 'total',
|
||||
labor: line.unit === 'g' ? line.costLabor?.mode || 'total' : 'total',
|
||||
});
|
||||
const [rates, setRates] = useState({
|
||||
material: asMoney(line.costMaterial?.rate),
|
||||
labor: asMoney(line.costLabor?.rate),
|
||||
});
|
||||
const originalTotal = line.unit !== 'g' || originalMode === 'total' ? initialParts.material : '';
|
||||
const changePart = (key: string, value: string) => setParts(old => ({ ...old, [key]: value }));
|
||||
const updateMode = (key: CostModeKey, value: string, computed: string) => {
|
||||
if (value === 'total' && (key === 'labor' || parts.material === '')) changePart(key, computed);
|
||||
setModes(old => ({ ...old, [key]: value }));
|
||||
};
|
||||
const amount = (key: string, title: string, value: string, gram = false) => (
|
||||
<label>
|
||||
{title}
|
||||
<input
|
||||
type="number"
|
||||
name={prefix + key}
|
||||
min="0"
|
||||
step="0.01"
|
||||
placeholder="开单前必填,没有填0"
|
||||
required={!gram}
|
||||
readOnly={gram}
|
||||
value={value}
|
||||
onChange={event => changePart(key, event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
function group(key: CostModeKey) {
|
||||
const material = key === 'material',
|
||||
gram = modes[key] === 'gram';
|
||||
const payer = line.costPayers?.[key] ?? line.payer ?? fallback;
|
||||
let value = parts[key],
|
||||
formula;
|
||||
if (gram) {
|
||||
try {
|
||||
const result = costBreakdown(
|
||||
line,
|
||||
quantity,
|
||||
{ material: '0', labor: '0', accessories: '0', other: '0' },
|
||||
{ material: 'total', labor: 'total', [key]: 'gram' },
|
||||
rates,
|
||||
).parts[key];
|
||||
value = asMoney(result);
|
||||
formula =
|
||||
result == null
|
||||
? material
|
||||
? '填写每克进货料价后,系统自动乘以本行克重。'
|
||||
: '填写每克工费后自动乘以克重。'
|
||||
: quantity + 'g × ' + rates[key] + '元/克 = ' + yuan(result) + '元';
|
||||
} catch (err) {
|
||||
value = '';
|
||||
formula = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
} else {
|
||||
formula = material
|
||||
? line.unit === 'g'
|
||||
? '直接填写本行料费合计,不再乘以克重。'
|
||||
: '按件商品请填写本行料费合计' + (rates.material ? ';每克料价已保留,切回g可恢复' : '') + '。'
|
||||
: '直接填写本行总工费。';
|
||||
}
|
||||
const options = members(false, { selected: payer });
|
||||
return (
|
||||
<div className={'purchase-' + key} data-prefix={prefix} data-mode={modes[key]}>
|
||||
<div className="grid purchase-cost-grid">
|
||||
<label>
|
||||
{material ? '进货料费方式' : '进货工费方式'}
|
||||
<select
|
||||
name={prefix + key + 'Mode'}
|
||||
value={modes[key]}
|
||||
onChange={event => updateMode(key, event.target.value, value)}
|
||||
>
|
||||
<option value="gram" disabled={line.unit !== 'g'}>
|
||||
{material ? '按克料价' : '克工费'}
|
||||
</option>
|
||||
<option value="total">{material ? '直接填总料费' : '总工费'}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label hidden={!gram}>
|
||||
{material ? '进货料价(元/克)' : '进货克工费(元/克)'}
|
||||
<input
|
||||
type="number"
|
||||
name={prefix + key + 'Rate'}
|
||||
min="0"
|
||||
step="0.01"
|
||||
value={rates[key]}
|
||||
placeholder={material ? '填写每克进货料价' : '填写每克工费'}
|
||||
disabled={!gram}
|
||||
required={gram}
|
||||
onChange={event => setRates(old => ({ ...old, [key]: event.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
{amount(key, material ? '料费成本合计(元)' : '进货总工费(元)', value, gram)}
|
||||
<label className="purchase-payer">
|
||||
{material ? '料费付款人' : '进货工费付款人'}
|
||||
<select
|
||||
required
|
||||
name={prefix + key + 'Payer'}
|
||||
defaultValue={options.some(([id]) => id === payer) ? payer : ''}
|
||||
>
|
||||
{options.some(([id]) => id === payer) ? null : (
|
||||
<option value="" disabled>
|
||||
请选择
|
||||
</option>
|
||||
)}
|
||||
{opts(options)}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<p className="purchase-formula small muted" aria-live="polite">
|
||||
{formula}
|
||||
</p>
|
||||
{material && (
|
||||
<p className="purchase-original small muted" hidden={!originalTotal}>
|
||||
{originalTotal &&
|
||||
'已保留原料费合计 ' + originalTotal + '元。原金额不会当成每克料价;切换按克后请填写实际进货料价。'}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
let summary;
|
||||
try {
|
||||
summary = costBreakdown(line, quantity, parts, modes, rates).total;
|
||||
} catch {
|
||||
summary = null;
|
||||
}
|
||||
return (
|
||||
<div className="internal cost-editor">
|
||||
<h3>
|
||||
{line.name} · {line.unit === 'g' ? grams(line.quantity) + 'g' : line.quantity + '件'}
|
||||
</h3>
|
||||
<div className="cost-fallback-payer">
|
||||
{choice('配件及其他成本付款人', 'goodsPayer', members(), line.payer || 'owner')}
|
||||
</div>
|
||||
{!line.costParts && line.cost !== null && (
|
||||
<p className="small">原记录未分项,总额 ¥{yuan(line.cost)};请按凭据拆分,不要把总额再填入每个项目。</p>
|
||||
)}
|
||||
<div className="cost-fields grid">
|
||||
{group('material')}
|
||||
{group('labor')}
|
||||
{amount('accessories', '配件成本(元,本行合计)', parts.accessories)}
|
||||
{amount('other', '其他货品成本(元,本行合计)', parts.other)}
|
||||
</div>
|
||||
<div className="cost-summary small">
|
||||
本行货品成本合计:{summary == null ? '请补齐(没有的项目填0)' : '¥' + yuan(summary)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+134
-77
@@ -1,7 +1,23 @@
|
||||
import type {
|
||||
IndependentDetail,
|
||||
IndependentRecord,
|
||||
IndependentRequest,
|
||||
IndependentValues,
|
||||
OrderRecord,
|
||||
OrderLine,
|
||||
ReviewList,
|
||||
} from '../orderData';
|
||||
import type { OrderContext, SharedViews } from '../viewTypes';
|
||||
import { Children } from 'react';
|
||||
import { Calc as LedgerCalc, Values } from '../../../shared';
|
||||
function object(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
function revision(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
export function afterSales(
|
||||
{ afterSaleChangesStatus, state, ui, orderAfterSaleFormEntry, currentOrder },
|
||||
{ afterSaleChangesStatus, state, ui = {}, orderAfterSaleFormEntry, currentOrder }: OrderContext,
|
||||
{
|
||||
button,
|
||||
validOrderDate,
|
||||
@@ -28,39 +44,47 @@ export function afterSales(
|
||||
activePocketKeys,
|
||||
orderChangeUser,
|
||||
stockCountValue,
|
||||
},
|
||||
}: SharedViews,
|
||||
) {
|
||||
function validateAfterSaleDetail(detail, id) {
|
||||
const record = detail?.record,
|
||||
permissions = detail?.permissions;
|
||||
if (
|
||||
!record ||
|
||||
detail.id !== id ||
|
||||
record.id !== id ||
|
||||
!Number.isSafeInteger(detail.revision) ||
|
||||
detail.revision < 1 ||
|
||||
record.revision !== detail.revision ||
|
||||
!afterSaleValuesValid(record) ||
|
||||
!teamMemberKeys().includes(record.member) ||
|
||||
typeof permissions?.canEdit !== 'boolean' ||
|
||||
typeof permissions.canDirectEdit !== 'boolean' ||
|
||||
typeof permissions.requiresApproval !== 'boolean' ||
|
||||
!Array.isArray(detail.history)
|
||||
)
|
||||
throw new Error('售后记录资料未完整返回,请重新读取后再修改。');
|
||||
if (detail.pending && (validateAfterSaleRequest(detail.pending).afterSaleId !== id || permissions.canEdit))
|
||||
function readAfterSaleDetail(detail: unknown, id: string): detail is IndependentDetail {
|
||||
if (!object(detail) || detail.id !== id || !revision(detail.revision) || !object(detail.record)) return false;
|
||||
const record = detail.record,
|
||||
permissions = detail.permissions;
|
||||
return (
|
||||
record.id === id &&
|
||||
record.revision === detail.revision &&
|
||||
typeof record.actor === 'string' &&
|
||||
typeof record.created === 'string' &&
|
||||
typeof record.member === 'string' &&
|
||||
teamMemberKeys().includes(record.member) &&
|
||||
afterSaleValuesValid(record) &&
|
||||
object(permissions) &&
|
||||
typeof permissions.canEdit === 'boolean' &&
|
||||
typeof permissions.canDirectEdit === 'boolean' &&
|
||||
typeof permissions.requiresApproval === 'boolean' &&
|
||||
typeof permissions.reason === 'string' &&
|
||||
object(detail.values) &&
|
||||
typeof detail.values.amount === 'string' &&
|
||||
Array.isArray(detail.history) &&
|
||||
detail.history.every(request => validateAfterSaleRequest(request)) &&
|
||||
(detail.pending === null || !!validateAfterSaleRequest(detail.pending))
|
||||
);
|
||||
}
|
||||
function validateAfterSaleDetail(detail: unknown, id: string) {
|
||||
if (!readAfterSaleDetail(detail, id)) throw new Error('售后记录资料未完整返回,请重新读取后再修改。');
|
||||
if (detail.pending && (detail.pending.afterSaleId !== id || detail.permissions.canEdit))
|
||||
throw new Error('售后修改状态不一致,请重新读取。');
|
||||
for (const request of detail.history)
|
||||
if (validateAfterSaleRequest(request).afterSaleId !== id) throw new Error('售后修改历史不一致,请重新读取。');
|
||||
if (request.afterSaleId !== id) throw new Error('售后修改历史不一致,请重新读取。');
|
||||
return detail;
|
||||
}
|
||||
function independentReviewForm(kind, request) {
|
||||
function independentReviewForm(kind: string, request: IndependentRequest) {
|
||||
return (
|
||||
<form id="after-sale-review-form" data-id={request.id} data-kind={kind}>
|
||||
<h3>{kind === 'approve' ? '同意售后修改' : '驳回售后修改'}</h3>
|
||||
<label>
|
||||
{kind === 'approve' ? '复核备注(选填)' : '驳回意见'}
|
||||
<textarea disabled={ui.blocked} name="note" rows="2" maxLength="200" required={kind === 'reject'}></textarea>
|
||||
<textarea disabled={ui.blocked} name="note" rows={2} maxLength={200} required={kind === 'reject'}></textarea>
|
||||
</label>
|
||||
{kind === 'approve' ? (
|
||||
<label className="check">
|
||||
@@ -79,7 +103,7 @@ export function afterSales(
|
||||
</form>
|
||||
);
|
||||
}
|
||||
function independentReview(request, kind) {
|
||||
function independentReview(request: IndependentRequest, kind?: string | null) {
|
||||
const canReview = state.user.role === 'owner' && request.status === 'pending';
|
||||
return (
|
||||
<>
|
||||
@@ -144,7 +168,7 @@ export function afterSales(
|
||||
</>
|
||||
);
|
||||
}
|
||||
function afterSaleHistoryHTML(request) {
|
||||
function afterSaleHistoryHTML(request: IndependentRequest) {
|
||||
return (
|
||||
<li>
|
||||
<strong>{afterSaleStatus(request)}</strong>
|
||||
@@ -175,7 +199,7 @@ export function afterSales(
|
||||
</li>
|
||||
);
|
||||
}
|
||||
function afterSaleRecordHTML(record) {
|
||||
function afterSaleRecordHTML(record: IndependentRecord) {
|
||||
return (
|
||||
<dl className="after-sale-facts">
|
||||
{Children.toArray(
|
||||
@@ -196,9 +220,13 @@ export function afterSales(
|
||||
</dl>
|
||||
);
|
||||
}
|
||||
function afterSaleComparisonHTML(raw) {
|
||||
function afterSaleComparisonHTML(raw: IndependentRequest) {
|
||||
const request = validateAfterSaleRequest(raw),
|
||||
pair = (title, key, format = value => value) => {
|
||||
pair = <K extends keyof IndependentValues>(
|
||||
title: string,
|
||||
key: K,
|
||||
format: (value: IndependentValues[K]) => string | number = value => value,
|
||||
) => {
|
||||
const changed = request.before[key] !== request.after[key];
|
||||
return (
|
||||
<tr
|
||||
@@ -231,14 +259,14 @@ export function afterSales(
|
||||
{pair('售后日期', 'date')}
|
||||
{pair('售后项目', 'project')}
|
||||
{pair('客户', 'customer')}
|
||||
{pair('金额', 'amount', value => '¥' + yuan(value))}
|
||||
{pair('金额', 'amount', value => '¥' + yuan(Number(value)))}
|
||||
{pair('谁支付', 'payer', teamMemberName)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function editIndependentSale(detail) {
|
||||
function editIndependentSale(detail: IndependentDetail) {
|
||||
const record = detail.record,
|
||||
request = detail.pending;
|
||||
const pendingHTML = request ? (
|
||||
@@ -274,11 +302,11 @@ export function afterSales(
|
||||
})}
|
||||
{field('售后项目', 'project', record.project, 'text', {
|
||||
required: true,
|
||||
maxLength: '100',
|
||||
maxLength: 100,
|
||||
})}
|
||||
{field('客户', 'customer', record.customer, 'text', {
|
||||
required: true,
|
||||
maxLength: '60',
|
||||
maxLength: 60,
|
||||
})}
|
||||
{moneyField('金额(元)', 'amount', (record.amount / 100).toFixed(2))}
|
||||
{orderMemberField(record.member, true)}
|
||||
@@ -293,7 +321,7 @@ export function afterSales(
|
||||
</div>
|
||||
<label>
|
||||
修改说明(选填)
|
||||
<textarea name="reason" rows="2" maxLength="200" placeholder="例如:售后金额或付款人录错。"></textarea>
|
||||
<textarea name="reason" rows={2} maxLength={200} placeholder="例如:售后金额或付款人录错。"></textarea>
|
||||
</label>
|
||||
</fieldset>
|
||||
<div id="after-sale-edit-error" aria-live="polite">
|
||||
@@ -357,12 +385,12 @@ export function afterSales(
|
||||
})}
|
||||
{field('售后项目', 'project', '', 'text', {
|
||||
required: true,
|
||||
maxLength: '100',
|
||||
maxLength: 100,
|
||||
placeholder: '例如:维修、补寄快递',
|
||||
})}
|
||||
{field('客户', 'customer', '', 'text', {
|
||||
required: true,
|
||||
maxLength: '60',
|
||||
maxLength: 60,
|
||||
placeholder: '客户称呼或代号',
|
||||
})}
|
||||
{moneyField('金额(元)', 'amount', '')}
|
||||
@@ -373,7 +401,7 @@ export function afterSales(
|
||||
<option value="" disabled>
|
||||
请选择
|
||||
</option>
|
||||
{opts(teamMemberOptions(), '')}
|
||||
{opts(teamMemberOptions())}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
@@ -393,16 +421,21 @@ export function afterSales(
|
||||
</>
|
||||
);
|
||||
}
|
||||
function orderAfterSaleAccountPayer(account) {
|
||||
function orderAfterSaleAccountPayer(account: string) {
|
||||
return accountIdentity(account)?.member || currentMember();
|
||||
}
|
||||
const materialPoolMg = Values.positiveMg;
|
||||
function orderAfterSaleInput(form) {
|
||||
function orderAfterSaleInput(form: HTMLFormElement) {
|
||||
const order = currentOrder,
|
||||
entry = orderAfterSaleFormEntry,
|
||||
get = name => String(form.querySelector(`[name="${name}"]`)?.value ?? '').trim();
|
||||
get = (name: string) =>
|
||||
String(
|
||||
form.querySelector<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>(`[name="${name}"]`)?.value ??
|
||||
'',
|
||||
).trim();
|
||||
if (
|
||||
!entry ||
|
||||
!order ||
|
||||
entry.id !== order?.id ||
|
||||
entry.user !== orderChangeUser() ||
|
||||
entry.revision !== order.revision ||
|
||||
@@ -417,7 +450,11 @@ export function afterSales(
|
||||
const rows = [...form.querySelectorAll('[data-after-sale-line]')];
|
||||
if (rows.length !== order.lines.length) throw new Error('请核对全部退回商品后再提交。');
|
||||
const lines = rows.map((row, lineIndex) => {
|
||||
const read = name => String(row.querySelector(`[name="${name}"]`)?.value ?? '').trim(),
|
||||
const read = (name: string) =>
|
||||
String(
|
||||
row.querySelector<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>(`[name="${name}"]`)?.value ??
|
||||
'',
|
||||
).trim(),
|
||||
original = order.lines[lineIndex],
|
||||
quantity = read('return_quantity'),
|
||||
mg = materialPoolMg(quantity),
|
||||
@@ -436,7 +473,12 @@ export function afterSales(
|
||||
title: '商品 ' + (lineIndex + 1) + '实际退回数量(对)',
|
||||
})
|
||||
: null;
|
||||
if (Number.isSafeInteger(original.stockCount) && stockCount > original.stockCount)
|
||||
if (
|
||||
original.stockCount != null &&
|
||||
stockCount != null &&
|
||||
Number.isSafeInteger(original.stockCount) &&
|
||||
stockCount > original.stockCount
|
||||
)
|
||||
throw new Error('商品 ' + (lineIndex + 1) + '实际退回对数不能超过原出库对数。');
|
||||
return {
|
||||
lineIndex,
|
||||
@@ -459,7 +501,11 @@ export function afterSales(
|
||||
const reference = get('refund_reference');
|
||||
if (reference.length > 100) throw new Error('退款凭据备注最多100字。');
|
||||
const expenses = [...form.querySelectorAll('.order-after-sale-expense')].map(row => {
|
||||
const read = name => String(row.querySelector(`[name="${name}"]`)?.value ?? '').trim(),
|
||||
const read = (name: string) =>
|
||||
String(
|
||||
row.querySelector<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>(`[name="${name}"]`)?.value ??
|
||||
'',
|
||||
).trim(),
|
||||
amount = read('expense_amount'),
|
||||
note = read('expense_note'),
|
||||
payer = read('expense_payer');
|
||||
@@ -491,12 +537,12 @@ export function afterSales(
|
||||
},
|
||||
};
|
||||
}
|
||||
function orderAfterSaleExpenseHTML(value = {}) {
|
||||
function orderAfterSaleExpenseHTML(value: Partial<{ amount: string; note: string; payer: string }> = {}) {
|
||||
return (
|
||||
<div className="order-after-sale-expense grid four">
|
||||
{field('售后成本项目', 'expense_note', value.note || '', 'text', {
|
||||
required: true,
|
||||
maxLength: '150',
|
||||
maxLength: 150,
|
||||
placeholder: '如寄件费、重新编绳',
|
||||
})}
|
||||
{moneyField('实际成本(元)', 'expense_amount', value.amount ?? '')}
|
||||
@@ -508,7 +554,7 @@ export function afterSales(
|
||||
function orderAfterSalePocketKeys() {
|
||||
return activePocketKeys().filter(key => state.pocketCatalog?.some(row => row.key === key && row.self === true));
|
||||
}
|
||||
function orderAfterSaleLineHTML(line, index) {
|
||||
function orderAfterSaleLineHTML(line: OrderLine, index: number) {
|
||||
const pockets = orderAfterSalePocketKeys();
|
||||
const pocket = ui.lines?.[index]?.pocket ?? (pockets.includes(line.pocket) ? line.pocket : pockets[0] || '');
|
||||
const disposition = ui.lines?.[index]?.disposition || 'stock';
|
||||
@@ -550,7 +596,7 @@ export function afterSales(
|
||||
pockets.map(key => [key, pocketLabel(key)]),
|
||||
pocket,
|
||||
)}
|
||||
{stockCountField(pocket, line.stockCount, {
|
||||
{stockCountField(pocket, String(line.stockCount ?? ''), {
|
||||
name: 'return_count',
|
||||
visible: disposition === 'stock' && pocketCountsEnabled(pocket),
|
||||
title: '实际退回数量(对)',
|
||||
@@ -576,7 +622,7 @@ export function afterSales(
|
||||
? '本次提交原订单售后申请,店主同意后一次登记退货、退款、费用与利润调整。复核前原账保持原值。'
|
||||
: '核实后一次登记退货、实际退款与售后成本。系统只记账,退款须已在实际账户完成。';
|
||||
}
|
||||
function orderAfterSaleFormHTML(order) {
|
||||
function orderAfterSaleFormHTML(order: OrderRecord) {
|
||||
const receipts = order.payments?.filter(row => row.kind === 'receipt') || [],
|
||||
account =
|
||||
receipts.find(
|
||||
@@ -604,8 +650,8 @@ export function afterSales(
|
||||
售后原因
|
||||
<textarea
|
||||
name="reason"
|
||||
rows="2"
|
||||
maxLength="200"
|
||||
rows={2}
|
||||
maxLength={200}
|
||||
required
|
||||
placeholder="填写客户实际退货退款原因。"
|
||||
></textarea>
|
||||
@@ -623,7 +669,7 @@ export function afterSales(
|
||||
{choice('实际退款付款人', 'refund_payer', teamMemberOptions(), payer)}
|
||||
</div>
|
||||
{field('退款凭据备注(选填)', 'refund_reference', '', 'text', {
|
||||
maxLength: '100',
|
||||
maxLength: 100,
|
||||
})}
|
||||
<div className="order-after-sale-retained">
|
||||
<span>本次扣留客户款(系统计算)</span>
|
||||
@@ -635,8 +681,8 @@ export function afterSales(
|
||||
<textarea
|
||||
name="deduction_reason"
|
||||
required={ui.reasonRequired}
|
||||
rows="2"
|
||||
maxLength="200"
|
||||
rows={2}
|
||||
maxLength={200}
|
||||
placeholder="有扣留款时填写,如约定扣除不可退工费或实际损耗。"
|
||||
></textarea>
|
||||
</label>
|
||||
@@ -687,7 +733,7 @@ export function afterSales(
|
||||
</form>
|
||||
);
|
||||
}
|
||||
function afterSaleStatus(request) {
|
||||
function afterSaleStatus(request: IndependentRequest) {
|
||||
return (
|
||||
{
|
||||
pending: '待店主审批',
|
||||
@@ -696,47 +742,58 @@ export function afterSales(
|
||||
}[request.status] || '状态待确认'
|
||||
);
|
||||
}
|
||||
function afterSaleTime(value) {
|
||||
function afterSaleTime(value: string | null) {
|
||||
return String(value || '未提供')
|
||||
.replace('T', ' ')
|
||||
.replace(/\.\d{3}Z$/, ' UTC')
|
||||
.replace(/Z$/, ' UTC');
|
||||
}
|
||||
function afterSaleValuesValid(record) {
|
||||
function afterSaleValuesValid(record: unknown): record is IndependentValues & { amount: number } {
|
||||
return (
|
||||
record &&
|
||||
object(record) &&
|
||||
validOrderDate(record.date) &&
|
||||
typeof record.project === 'string' &&
|
||||
record.project.trim() &&
|
||||
!!record.project.trim() &&
|
||||
record.project.length <= 100 &&
|
||||
typeof record.customer === 'string' &&
|
||||
record.customer.trim() &&
|
||||
!!record.customer.trim() &&
|
||||
record.customer.length <= 60 &&
|
||||
typeof record.amount === 'number' &&
|
||||
Number.isSafeInteger(record.amount) &&
|
||||
record.amount >= 0 &&
|
||||
typeof record.payer === 'string' &&
|
||||
teamMemberKeys().includes(record.payer)
|
||||
);
|
||||
}
|
||||
function validateAfterSaleRequest(request) {
|
||||
if (
|
||||
!request ||
|
||||
typeof request.id !== 'string' ||
|
||||
!request.id ||
|
||||
typeof request.afterSaleId !== 'string' ||
|
||||
!request.afterSaleId ||
|
||||
!Number.isSafeInteger(request.revision) ||
|
||||
request.revision < 1 ||
|
||||
!Number.isSafeInteger(request.recordRevision) ||
|
||||
request.recordRevision < 1 ||
|
||||
!['pending', 'approved', 'rejected'].includes(request.status) ||
|
||||
!afterSaleValuesValid(request.before) ||
|
||||
!afterSaleValuesValid(request.after) ||
|
||||
typeof request.canApprove !== 'boolean'
|
||||
)
|
||||
throw new Error('售后修改申请资料未完整返回,请重新读取。');
|
||||
function isRequest(request: unknown): request is IndependentRequest {
|
||||
return (
|
||||
object(request) &&
|
||||
typeof request.id === 'string' &&
|
||||
!!request.id &&
|
||||
typeof request.afterSaleId === 'string' &&
|
||||
!!request.afterSaleId &&
|
||||
revision(request.revision) &&
|
||||
revision(request.recordRevision) &&
|
||||
(request.status === 'pending' || request.status === 'approved' || request.status === 'rejected') &&
|
||||
afterSaleValuesValid(request.before) &&
|
||||
afterSaleValuesValid(request.after) &&
|
||||
typeof request.canApprove === 'boolean' &&
|
||||
typeof request.stale === 'boolean' &&
|
||||
typeof request.staleReason === 'string' &&
|
||||
typeof request.member === 'string' &&
|
||||
typeof request.created === 'string' &&
|
||||
typeof request.requesterName === 'string' &&
|
||||
(request.reviewed == null || typeof request.reviewed === 'string') &&
|
||||
(request.reviewerName == null || typeof request.reviewerName === 'string') &&
|
||||
(request.note == null || typeof request.note === 'string') &&
|
||||
typeof request.reason === 'string'
|
||||
);
|
||||
}
|
||||
function validateAfterSaleRequest(request: unknown) {
|
||||
if (!isRequest(request)) throw new Error('售后修改申请资料未完整返回,请重新读取。');
|
||||
return request;
|
||||
}
|
||||
function afterSaleChangeListHTML(data) {
|
||||
function afterSaleChangeListHTML(data: ReviewList<IndependentRequest>) {
|
||||
if (
|
||||
!Array.isArray(data.requests) ||
|
||||
!data.counts ||
|
||||
+92
-251
@@ -1,187 +1,20 @@
|
||||
import { Children, useState } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { LegacyCostRow } from './LegacyCostRow';
|
||||
interface ActionInput extends Record<string, unknown> {
|
||||
date: string;
|
||||
verified: boolean;
|
||||
feesVerified: boolean;
|
||||
account?: string;
|
||||
revision?: number;
|
||||
returnPockets?: string[];
|
||||
returnCounts?: (number | null)[];
|
||||
stockCounts?: Record<number, number | null>;
|
||||
}
|
||||
import type { OrderContext, SharedViews } from '../viewTypes';
|
||||
import { Children } from 'react';
|
||||
import { Cards as CreditCardFees, Calc as LedgerCalc } from '../../../shared';
|
||||
const asMoney = value => (value == null ? '' : (value / 100).toFixed(2));
|
||||
const costKeys = ['material', 'labor', 'accessories', 'other'];
|
||||
function costBreakdown(line, quantity, parts, modes, rates) {
|
||||
const input = { unit: line.unit, quantity, costParts: parts };
|
||||
for (const [key, property] of [
|
||||
['material', 'costMaterial'],
|
||||
['labor', 'costLabor'],
|
||||
]) {
|
||||
input[property] = modes[key] === 'gram' ? { mode: 'gram', rate: rates[key] } : { mode: 'total' };
|
||||
}
|
||||
return LedgerCalc.purchaseCosts(input);
|
||||
}
|
||||
function LegacyCostRow({ line, index, members, fallback, choice, opts, grams, yuan }) {
|
||||
const prefix = 'cost-' + index + '-';
|
||||
const quantity = line.unit === 'g' ? (line.quantity / 1000).toFixed(3) : line.quantity;
|
||||
const initialParts = Object.fromEntries(
|
||||
costKeys.map(key => [
|
||||
key,
|
||||
line.costParts ? asMoney(line.costParts[key]) : ['accessories', 'other'].includes(key) ? '0' : '',
|
||||
]),
|
||||
);
|
||||
const originalMode = ['gram', 'total'].includes(line.costMaterial?.mode)
|
||||
? line.costMaterial.mode
|
||||
: initialParts.material === ''
|
||||
? 'gram'
|
||||
: 'total';
|
||||
const [parts, setParts] = useState(initialParts);
|
||||
const [modes, setModes] = useState({
|
||||
material: line.unit === 'g' ? originalMode : 'total',
|
||||
labor: line.unit === 'g' ? line.costLabor?.mode || 'total' : 'total',
|
||||
});
|
||||
const [rates, setRates] = useState({
|
||||
material: asMoney(line.costMaterial?.rate),
|
||||
labor: asMoney(line.costLabor?.rate),
|
||||
});
|
||||
const originalTotal = line.unit !== 'g' || originalMode === 'total' ? initialParts.material : '';
|
||||
const changePart = (key, value) => setParts(old => ({ ...old, [key]: value }));
|
||||
const updateMode = (key, value, computed) => {
|
||||
if (value === 'total' && (key === 'labor' || parts.material === '')) changePart(key, computed);
|
||||
setModes(old => ({ ...old, [key]: value }));
|
||||
};
|
||||
const amount = (key, title, value, gram = false) => (
|
||||
<label>
|
||||
{title}
|
||||
<input
|
||||
type="number"
|
||||
name={prefix + key}
|
||||
min="0"
|
||||
step="0.01"
|
||||
placeholder="开单前必填,没有填0"
|
||||
required={!gram}
|
||||
readOnly={gram}
|
||||
value={value}
|
||||
onChange={event => changePart(key, event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
function group(key) {
|
||||
const material = key === 'material',
|
||||
gram = modes[key] === 'gram';
|
||||
const payer = line.costPayers?.[key] ?? line.payer ?? fallback;
|
||||
let value = parts[key],
|
||||
formula;
|
||||
if (gram) {
|
||||
try {
|
||||
const result = costBreakdown(
|
||||
line,
|
||||
quantity,
|
||||
{ material: '0', labor: '0', accessories: '0', other: '0' },
|
||||
{ material: 'total', labor: 'total', [key]: 'gram' },
|
||||
rates,
|
||||
).parts[key];
|
||||
value = asMoney(result);
|
||||
formula =
|
||||
result == null
|
||||
? material
|
||||
? '填写每克进货料价后,系统自动乘以本行克重。'
|
||||
: '填写每克工费后自动乘以克重。'
|
||||
: quantity + 'g × ' + rates[key] + '元/克 = ' + yuan(result) + '元';
|
||||
} catch (err) {
|
||||
value = '';
|
||||
formula = err.message;
|
||||
}
|
||||
} else {
|
||||
formula = material
|
||||
? line.unit === 'g'
|
||||
? '直接填写本行料费合计,不再乘以克重。'
|
||||
: '按件商品请填写本行料费合计' + (rates.material ? ';每克料价已保留,切回g可恢复' : '') + '。'
|
||||
: '直接填写本行总工费。';
|
||||
}
|
||||
const options = members(false, { selected: payer });
|
||||
return (
|
||||
<div className={'purchase-' + key} data-prefix={prefix} data-mode={modes[key]}>
|
||||
<div className="grid purchase-cost-grid">
|
||||
<label>
|
||||
{material ? '进货料费方式' : '进货工费方式'}
|
||||
<select
|
||||
name={prefix + key + 'Mode'}
|
||||
value={modes[key]}
|
||||
onChange={event => updateMode(key, event.target.value, value)}
|
||||
>
|
||||
<option value="gram" disabled={line.unit !== 'g'}>
|
||||
{material ? '按克料价' : '克工费'}
|
||||
</option>
|
||||
<option value="total">{material ? '直接填总料费' : '总工费'}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label hidden={!gram}>
|
||||
{material ? '进货料价(元/克)' : '进货克工费(元/克)'}
|
||||
<input
|
||||
type="number"
|
||||
name={prefix + key + 'Rate'}
|
||||
min="0"
|
||||
step="0.01"
|
||||
value={rates[key]}
|
||||
placeholder={material ? '填写每克进货料价' : '填写每克工费'}
|
||||
disabled={!gram}
|
||||
required={gram}
|
||||
onChange={event => setRates(old => ({ ...old, [key]: event.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
{amount(key, material ? '料费成本合计(元)' : '进货总工费(元)', value, gram)}
|
||||
<label className="purchase-payer">
|
||||
{material ? '料费付款人' : '进货工费付款人'}
|
||||
<select
|
||||
required
|
||||
name={prefix + key + 'Payer'}
|
||||
defaultValue={options.some(([id]) => id === payer) ? payer : ''}
|
||||
>
|
||||
{options.some(([id]) => id === payer) ? null : (
|
||||
<option value="" disabled>
|
||||
请选择
|
||||
</option>
|
||||
)}
|
||||
{opts(options)}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<p className="purchase-formula small muted" aria-live="polite">
|
||||
{formula}
|
||||
</p>
|
||||
{material && (
|
||||
<p className="purchase-original small muted" hidden={!originalTotal}>
|
||||
{originalTotal &&
|
||||
'已保留原料费合计 ' + originalTotal + '元。原金额不会当成每克料价;切换按克后请填写实际进货料价。'}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
let summary;
|
||||
try {
|
||||
summary = costBreakdown(line, quantity, parts, modes, rates).total;
|
||||
} catch {
|
||||
summary = null;
|
||||
}
|
||||
return (
|
||||
<div className="internal cost-editor">
|
||||
<h3>
|
||||
{line.name} · {line.unit === 'g' ? grams(line.quantity) + 'g' : line.quantity + '件'}
|
||||
</h3>
|
||||
<div className="cost-fallback-payer">
|
||||
{choice('配件及其他成本付款人', 'goodsPayer', members(), line.payer || 'owner')}
|
||||
</div>
|
||||
{!line.costParts && line.cost !== null && (
|
||||
<p className="small">原记录未分项,总额 ¥{yuan(line.cost)};请按凭据拆分,不要把总额再填入每个项目。</p>
|
||||
)}
|
||||
<div className="cost-fields grid">
|
||||
{group('material')}
|
||||
{group('labor')}
|
||||
{amount('accessories', '配件成本(元,本行合计)', parts.accessories)}
|
||||
{amount('other', '其他货品成本(元,本行合计)', parts.other)}
|
||||
</div>
|
||||
<div className="cost-summary small">
|
||||
本行货品成本合计:{summary == null ? '请补齐(没有的项目填0)' : '¥' + yuan(summary)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function orderActions(
|
||||
{ currentOrder, ui, state },
|
||||
{ currentOrder, ui = {}, state }: OrderContext,
|
||||
{
|
||||
orderActionUsesChangeForm,
|
||||
orderActionRequiresApproval,
|
||||
@@ -213,12 +46,12 @@ export function orderActions(
|
||||
activePocketKeys,
|
||||
pocketLabel,
|
||||
stockCountValue,
|
||||
},
|
||||
}: SharedViews,
|
||||
) {
|
||||
function readReturnCounts(form, pockets) {
|
||||
function readReturnCounts(form: HTMLFormElement, pockets: string[]) {
|
||||
return pockets.map((pocket, index) => {
|
||||
if (!pocketCountsEnabled(pocket)) return null;
|
||||
const count = stockCountValue(form.querySelector('[name="returnCount-' + index + '"]')?.value, {
|
||||
const count = stockCountValue(form.querySelector<HTMLInputElement>('[name="returnCount-' + index + '"]')?.value, {
|
||||
title: '商品 ' + (index + 1) + '实际退回数量(对)',
|
||||
}),
|
||||
original = currentOrder?.lines?.[index]?.stockCount;
|
||||
@@ -227,28 +60,28 @@ export function orderActions(
|
||||
return count;
|
||||
});
|
||||
}
|
||||
function readPaymentAccount(form) {
|
||||
function readPaymentAccount(form: HTMLFormElement) {
|
||||
return normalizePaymentAccount(
|
||||
(form?.querySelector?.('[name="payment_recipient"]')?.value || '') +
|
||||
(form?.querySelector?.('[name="payment_method"]')?.value || ''),
|
||||
(form?.querySelector?.<HTMLInputElement>('[name="payment_recipient"]')?.value || '') +
|
||||
(form?.querySelector?.<HTMLInputElement>('[name="payment_method"]')?.value || ''),
|
||||
);
|
||||
}
|
||||
function actionInput(form) {
|
||||
const data = Object.fromEntries(new FormData(form));
|
||||
const kind = form.dataset.kind;
|
||||
const input = {
|
||||
function actionInput(form: HTMLFormElement) {
|
||||
const data = Object.fromEntries(new FormData(form)) as Record<string, string>;
|
||||
const kind = form.dataset.kind!;
|
||||
const input: ActionInput = {
|
||||
...data,
|
||||
date: data.date || state.today,
|
||||
verified: data.verified === 'on',
|
||||
feesVerified: data.feesVerified === 'on',
|
||||
};
|
||||
if (kind === 'fees') {
|
||||
input.revision = currentOrder.revision;
|
||||
input.fee_items = [...form.querySelectorAll('.fee-verify-row')].map(row => ({
|
||||
...currentOrder.pendingFees.find(f => f.key === row.dataset.key),
|
||||
input.revision = currentOrder!.revision;
|
||||
input.fee_items = [...form.querySelectorAll<HTMLElement>('.fee-verify-row')].map(row => ({
|
||||
...currentOrder!.pendingFees.find(f => f.key === row.dataset.key),
|
||||
status: 'estimated',
|
||||
amount: row.querySelector('[name="verifiedAmount"]').value,
|
||||
payer: row.querySelector('[name="verifiedPayer"]').value,
|
||||
amount: row.querySelector<HTMLInputElement>('[name="verifiedAmount"]')!.value,
|
||||
payer: row.querySelector<HTMLInputElement>('[name="verifiedPayer"]')!.value,
|
||||
}));
|
||||
}
|
||||
if (kind === 'correct') {
|
||||
@@ -257,47 +90,48 @@ export function orderActions(
|
||||
input.target = target;
|
||||
}
|
||||
if (kind === 'cost')
|
||||
input.costs = Array.from(form.querySelectorAll('.cost-editor'), (row, index) => {
|
||||
const get = key => row.querySelector('[name="cost-' + index + '-' + key + '"]').value;
|
||||
const mode = key =>
|
||||
input.costs = Array.from(form.querySelectorAll<HTMLElement>('.cost-editor'), (row, index) => {
|
||||
const get = (key: string) =>
|
||||
row.querySelector<HTMLInputElement>('[name="cost-' + index + '-' + key + '"]')!.value;
|
||||
const mode = (key: string) =>
|
||||
get(key + 'Mode') === 'gram' ? { mode: 'gram', rate: get(key + 'Rate') } : { mode: 'total' };
|
||||
return {
|
||||
parts: Object.fromEntries(costKeys.map(key => [key, get(key)])),
|
||||
parts: Object.fromEntries(Object.keys(LedgerCalc.costLabels).map(key => [key, get(key)])),
|
||||
costMaterial: mode('material'),
|
||||
costLabor: mode('labor'),
|
||||
costPayers: { material: get('materialPayer'), labor: get('laborPayer') },
|
||||
payer: row.querySelector('[name="goodsPayer"]').value,
|
||||
payer: row.querySelector<HTMLInputElement>('[name="goodsPayer"]')!.value,
|
||||
};
|
||||
});
|
||||
if (kind === 'receipt' || kind === 'refund') input.account = readPaymentAccount(form);
|
||||
if (kind === 'correct' && input.account) input.account = normalizePaymentAccount(input.account);
|
||||
if (kind === 'return') {
|
||||
input.returnPockets = currentOrder.lines.map(
|
||||
(_, i) => form.querySelector('[name="return-' + i + '"]')?.value ?? data['return-' + i],
|
||||
input.returnPockets = currentOrder!.lines.map(
|
||||
(_, i) => form.querySelector<HTMLInputElement>('[name="return-' + i + '"]')?.value ?? data['return-' + i],
|
||||
);
|
||||
input.returnCounts = readReturnCounts(form, input.returnPockets);
|
||||
}
|
||||
if (kind === 'complete') {
|
||||
input.stockCounts = {};
|
||||
currentOrder.lines.forEach((line, index) => {
|
||||
currentOrder!.lines.forEach((line, index) => {
|
||||
if (line.unit === 'g' && pocketCountsEnabled(line.pocket) && line.stockCount == null)
|
||||
input.stockCounts[index] = stockCountValue(
|
||||
form.querySelector('[name="completeCount-' + index + '"]')?.value,
|
||||
input.stockCounts![index] = stockCountValue(
|
||||
form.querySelector<HTMLInputElement>('[name="completeCount-' + index + '"]')?.value,
|
||||
{
|
||||
title: '商品 ' + (index + 1) + '实际出库数量(对)',
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
if (['review', 'complete'].includes(kind)) input.revision = currentOrder.revision;
|
||||
if (['review', 'complete'].includes(kind)) input.revision = currentOrder!.revision;
|
||||
return input;
|
||||
}
|
||||
function orderActionModeText(kind, approval) {
|
||||
function orderActionModeText(kind: string, approval: boolean) {
|
||||
return approval
|
||||
? `本次提交${orderChangeActionLabels[kind]}申请。店主同意后才记账;待批期间原订单、收退款、费用、库存和利润均不变。系统不会发起真实付款。`
|
||||
: '原单与本次业务日期均为今天,核实后直接记账,无需店主审批。改为其他业务日期须提交申请。系统不会发起真实付款。';
|
||||
}
|
||||
function orderActionChangeReviewHTML(kind) {
|
||||
function orderActionChangeReviewHTML(kind: string) {
|
||||
const approval = orderActionRequiresApproval(kind, ui.date);
|
||||
return (
|
||||
<>
|
||||
@@ -311,8 +145,8 @@ export function orderActions(
|
||||
<span id="order-action-reason-label">{approval ? '申请原因' : '登记原因'}</span>
|
||||
<textarea
|
||||
name="change_reason"
|
||||
maxLength="200"
|
||||
rows="2"
|
||||
maxLength={200}
|
||||
rows={2}
|
||||
required
|
||||
placeholder="写清本次需要登记或更正的原因。"
|
||||
></textarea>
|
||||
@@ -329,19 +163,19 @@ export function orderActions(
|
||||
</>
|
||||
);
|
||||
}
|
||||
function creditCardPreviewHTML(id, payer = 'owner', basis = '客户付款金额') {
|
||||
function creditCardPreviewHTML(id: string, payer = 'owner', basis = '客户付款金额') {
|
||||
const values = ui.values || {};
|
||||
const original = currentOrder.payment_account;
|
||||
const original = currentOrder!.payment_account;
|
||||
const method = ui.paymentMethod ?? accountIdentity(original)?.channel;
|
||||
const corrected = currentOrder.payments.find(p => p.id === (values.entry || '').split(':')[1]);
|
||||
const corrected = currentOrder!.payments.find(p => p.id === (values.entry || '').split(':')[1]);
|
||||
const correction = ui.action === 'correct';
|
||||
const visible = correction
|
||||
? corrected?.kind === 'receipt' && isCreditCardAccount(values.account)
|
||||
: method === '信用卡' && ui.action === 'receipt';
|
||||
const rate = currentOrder.credit_card_rate_permille ?? state.shopSettings?.creditCardRatePermille;
|
||||
const rate = currentOrder!.credit_card_rate_permille ?? state.shopSettings?.creditCardRatePermille;
|
||||
let amount, formula;
|
||||
if (visible || ui.lastCardBasis !== undefined) {
|
||||
const basisAmount = visible ? (values.amount ?? (currentOrder.balance / 100).toFixed(2)) : ui.lastCardBasis;
|
||||
const basisAmount = visible ? (values.amount ?? (currentOrder!.balance / 100).toFixed(2)) : ui.lastCardBasis;
|
||||
let cents, fee;
|
||||
try {
|
||||
cents = LedgerCalc.cents(basisAmount);
|
||||
@@ -406,12 +240,12 @@ export function orderActions(
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function isAutomaticCardFee(item) {
|
||||
function isAutomaticCardFee(item: { system?: string; key?: string; id?: string }) {
|
||||
return item?.system === 'credit_card' || String(item?.key || '').startsWith('card_fee:');
|
||||
}
|
||||
function pocketOptions(selected = '', historical = false) {
|
||||
const keys = activePocketKeys(),
|
||||
options = keys.map(key => [key, pocketLabel(key)]);
|
||||
options = keys.map((key): [string, string, boolean?] => [key, pocketLabel(key)]);
|
||||
if (selected && !keys.includes(selected))
|
||||
options.push([
|
||||
selected,
|
||||
@@ -420,10 +254,10 @@ export function orderActions(
|
||||
]);
|
||||
return options;
|
||||
}
|
||||
function isCreditCardAccount(account) {
|
||||
function isCreditCardAccount(account: string | undefined) {
|
||||
return typeof CreditCardFees === 'object' && typeof CreditCardFees.isAccount === 'function'
|
||||
? CreditCardFees.isAccount(account)
|
||||
: ['助理信用卡', '助理1信用卡', '麦麦信用卡', '助理2信用卡'].includes(account);
|
||||
? CreditCardFees.isAccount(account ?? '')
|
||||
: ['助理信用卡', '助理1信用卡', '麦麦信用卡', '助理2信用卡'].includes(account ?? '');
|
||||
}
|
||||
const orderFormMember = () => currentOrder?.member || currentMember();
|
||||
function defaultPaymentRecipient() {
|
||||
@@ -433,13 +267,16 @@ export function orderActions(
|
||||
function creditCardAvailable() {
|
||||
return typeof CreditCardFees === 'object' && state?.accounts?.includes('麦麦信用卡');
|
||||
}
|
||||
function accountFields(account) {
|
||||
function accountFields(account: string) {
|
||||
const methods = ['微信', '支付宝', '现金', ...(creditCardAvailable() ? ['信用卡'] : [])];
|
||||
account = normalizePaymentAccount(account || defaultPaymentRecipient() + '微信');
|
||||
const card = ui.paymentMethod ? ui.paymentMethod === '信用卡' : isCreditCardAccount(account),
|
||||
identity = accountIdentity(account),
|
||||
prefix = identity ? memberAccountPrefix(identity.member) : defaultPaymentRecipient();
|
||||
const recipients = teamMemberOptions(!teamMode()).map(([member, name]) => [memberAccountPrefix(member), name]);
|
||||
const recipients = teamMemberOptions(!teamMode()).map(([member, name]): [string, string] => [
|
||||
memberAccountPrefix(member),
|
||||
name,
|
||||
]);
|
||||
if (identity && !teamMemberEnabled(identity.member))
|
||||
recipients.push([prefix, teamMemberName(identity.member) + '(已停用 · 原记录)']);
|
||||
return (
|
||||
@@ -455,7 +292,7 @@ export function orderActions(
|
||||
data-card-locked={card}
|
||||
disabled={card}
|
||||
>
|
||||
{opts(recipients, card ? '麦麦' : prefix)}
|
||||
{opts(recipients)}
|
||||
</select>
|
||||
{creditCardAvailable() ? (
|
||||
<small className="small muted payment-account-note" hidden={!card}>
|
||||
@@ -468,14 +305,14 @@ export function orderActions(
|
||||
</>
|
||||
);
|
||||
}
|
||||
const dateField = (name = 'date', value) =>
|
||||
const dateField = (name = 'date', value?: string) =>
|
||||
field('业务日期', name, value || state.today, 'date', {
|
||||
max: state.today,
|
||||
required: true,
|
||||
});
|
||||
function showAction(action) {
|
||||
const o = currentOrder;
|
||||
let html = '';
|
||||
function showAction(action: string) {
|
||||
const o = currentOrder!;
|
||||
let html: ReactNode = '';
|
||||
const dt = dateField(),
|
||||
changeForm = orderActionUsesChangeForm(action),
|
||||
requiresApproval = orderActionRequiresApproval(action, ui.date);
|
||||
@@ -537,7 +374,7 @@ export function orderActions(
|
||||
)}
|
||||
</div>
|
||||
{field('凭据备注(选填)', 'reference', '', 'text', {
|
||||
maxLength: '100',
|
||||
maxLength: 100,
|
||||
placeholder: '交易凭据末几位或说明',
|
||||
})}
|
||||
<label className="check">
|
||||
@@ -564,7 +401,7 @@ export function orderActions(
|
||||
</div>
|
||||
{field('费用项目与说明', 'note', '', 'text', {
|
||||
required: true,
|
||||
maxLength: '150',
|
||||
maxLength: 150,
|
||||
})}
|
||||
</>
|
||||
);
|
||||
@@ -619,7 +456,7 @@ export function orderActions(
|
||||
{dt}
|
||||
{field('退货原因', 'reason', '', 'text', {
|
||||
required: true,
|
||||
maxLength: '200',
|
||||
maxLength: 200,
|
||||
})}
|
||||
<div className="grid two">
|
||||
{Children.toArray(
|
||||
@@ -630,15 +467,17 @@ export function orderActions(
|
||||
'return-' + i,
|
||||
l.unit === 'g'
|
||||
? [
|
||||
...(l.pocket || l.costMaterial?.mode === 'pool' ? [] : [['', '已退供应商,不留店内']]),
|
||||
...(l.pocket || l.costMaterial?.mode === 'pool'
|
||||
? []
|
||||
: [['', '已退供应商,不留店内'] as const]),
|
||||
...pocketOptions(l.pocket, true),
|
||||
]
|
||||
: [['', '按件商品,不记黄金货盘']],
|
||||
l.pocket || (l.costMaterial?.mode === 'pool' ? state.pockets[0] : ''),
|
||||
l.pocket || (l.costMaterial?.mode === 'pool' ? state.pockets![0] : ''),
|
||||
)}
|
||||
{stockCountField(
|
||||
ui.values?.['return-' + i] ??
|
||||
(l.pocket || (l.costMaterial?.mode === 'pool' ? state.pockets[0] : '')),
|
||||
(l.pocket || (l.costMaterial?.mode === 'pool' ? state.pockets![0] : '')),
|
||||
l.stockCount,
|
||||
{
|
||||
readOnly: Number.isSafeInteger(l.stockCount),
|
||||
@@ -675,7 +514,7 @@ export function orderActions(
|
||||
['toOwner', teamMemberName('assistant') + ' → ' + teamMemberName('owner')],
|
||||
['toAssistant', teamMemberName('owner') + ' → ' + teamMemberName('assistant')],
|
||||
],
|
||||
o.settlementDue < 0 ? 'toAssistant' : 'toOwner',
|
||||
o.settlementDue! < 0 ? 'toAssistant' : 'toOwner',
|
||||
)}
|
||||
{choice(
|
||||
'本笔归属',
|
||||
@@ -691,7 +530,7 @@ export function orderActions(
|
||||
{moneyField('实际转账金额', 'amount')}
|
||||
{field('转账凭据/说明', 'note', '', 'text', {
|
||||
required: true,
|
||||
maxLength: '150',
|
||||
maxLength: 150,
|
||||
})}
|
||||
</div>
|
||||
<p className="small muted">
|
||||
@@ -706,29 +545,31 @@ export function orderActions(
|
||||
</>
|
||||
);
|
||||
if (action === 'correct') {
|
||||
const valid = r =>
|
||||
const valid = (r: { id: string; price_lock_event_id?: string; note?: string; reference?: string }) =>
|
||||
!r.price_lock_event_id &&
|
||||
!o.corrections.some(c => c.target === r.id) &&
|
||||
!String(r.note || r.reference || '').startsWith('更正冲回:');
|
||||
const cardExpenseIds = new Set((o.fee_items || []).filter(isAutomaticCardFee).map(item => item.expense_id));
|
||||
const entries = [
|
||||
...(o.cancellationApproved || orderAfterSaleRecord(o) ? [] : o.payments.filter(valid)).map(r => [
|
||||
'payment:' + r.id,
|
||||
r.date +
|
||||
' ' +
|
||||
(r.kind === 'receipt' ? '客户收款' : '客户退款') +
|
||||
' ' +
|
||||
yuan(r.amount) +
|
||||
'元 ' +
|
||||
accountDisplayName(r.account),
|
||||
]),
|
||||
...(o.cancellationApproved || orderAfterSaleRecord(o) ? [] : o.payments.filter(valid)).map(
|
||||
(r): [string, string] => [
|
||||
'payment:' + r.id,
|
||||
r.date +
|
||||
' ' +
|
||||
(r.kind === 'receipt' ? '客户收款' : '客户退款') +
|
||||
' ' +
|
||||
yuan(r.amount) +
|
||||
'元 ' +
|
||||
accountDisplayName(r.account),
|
||||
],
|
||||
),
|
||||
...(o.cancellationApproved || orderAfterSaleRecord(o)
|
||||
? []
|
||||
: o.expenses.filter(r => valid(r) && !isAutomaticCardFee(r) && !cardExpenseIds.has(r.id))
|
||||
).map(r => ['expense:' + r.id, r.date + ' 直接费用 ' + yuan(r.amount) + '元 ' + r.note]),
|
||||
).map((r): [string, string] => ['expense:' + r.id, r.date + ' 直接费用 ' + yuan(r.amount) + '元 ' + r.note]),
|
||||
...o.settlements
|
||||
.filter(valid)
|
||||
.map(r => [
|
||||
.map((r): [string, string] => [
|
||||
'settlement:' + r.id,
|
||||
r.date +
|
||||
' ' +
|
||||
@@ -778,7 +619,7 @@ export function orderActions(
|
||||
</div>
|
||||
{field('更正原因', 'reason', '', 'text', {
|
||||
required: true,
|
||||
maxLength: '200',
|
||||
maxLength: 200,
|
||||
})}
|
||||
<label className="check">
|
||||
<input type="checkbox" name="verified" required />
|
||||
+44
-39
@@ -1,7 +1,10 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import type { BookData, BookRow, BookSummary, LockActivity, MoneyKey } from '../orderData';
|
||||
import type { OrderContext, SharedViews } from '../viewTypes';
|
||||
import { Children, Fragment } from 'react';
|
||||
import { Values } from '../../../shared';
|
||||
export function orderBook(
|
||||
{ orderBookFilters, state },
|
||||
{ orderBookFilters, state }: OrderContext,
|
||||
{
|
||||
yuan,
|
||||
teamMode,
|
||||
@@ -19,16 +22,16 @@ export function orderBook(
|
||||
activePocketKeys,
|
||||
pocketLabel,
|
||||
accountDisplayName,
|
||||
},
|
||||
}: SharedViews,
|
||||
) {
|
||||
const priceLockPayerName = payer => (payer ? teamMemberName(payer) : '待补');
|
||||
function priceLockActivityRows(activity) {
|
||||
const priceLockPayerName = (payer?: string) => (payer ? teamMemberName(payer) : '待补');
|
||||
function priceLockActivityRows(activity: LockActivity) {
|
||||
if (!activity) return [];
|
||||
return [...(activity.customerCash || []), ...(activity.orderPayments || [])]
|
||||
.map(item => ({
|
||||
...item,
|
||||
activityType: item.kind === 'receipt' ? '客户收款' : '客户退款',
|
||||
who: accountDisplayName(item.account),
|
||||
who: accountDisplayName(item.account!),
|
||||
activityName: item.product || '客户收退款',
|
||||
}))
|
||||
.concat(
|
||||
@@ -36,24 +39,24 @@ export function orderBook(
|
||||
...item,
|
||||
activityType: item.source === 'extra' ? '补重料费付款' : '原锁料费付款',
|
||||
who: priceLockPayerName(item.payer),
|
||||
activityName: (item.product || '黄金') + ' · ' + grams(item.quantity) + 'g × ' + yuan(item.rate) + '元/克',
|
||||
activityName: (item.product || '黄金') + ' · ' + grams(item.quantity!) + 'g × ' + yuan(item.rate) + '元/克',
|
||||
})),
|
||||
(activity.deliveryGoodsOutlays || []).map(item => ({
|
||||
...item,
|
||||
activityType: '交付货品支出',
|
||||
who: priceLockPayerName(item.payer),
|
||||
activityName: item.name,
|
||||
activityName: item.name!,
|
||||
})),
|
||||
(activity.directOutlays || []).map(item => ({
|
||||
...item,
|
||||
activityType: '实际费用',
|
||||
who: priceLockPayerName(item.payer),
|
||||
activityName: item.note,
|
||||
activityName: item.note!,
|
||||
})),
|
||||
)
|
||||
.sort((a, b) => a.date.localeCompare(b.date));
|
||||
}
|
||||
function priceLockActivityHTML(activity) {
|
||||
function priceLockActivityHTML(activity: LockActivity) {
|
||||
if (!activity?.summary?.eventCount) return '';
|
||||
const s = activity.summary,
|
||||
rows = priceLockActivityRows(activity);
|
||||
@@ -136,7 +139,7 @@ export function orderBook(
|
||||
return '销售与利润按开单/交付日期,售后与回收按记录日期筛选。普通订单收款显示当前累计;锁价收退款按实际发生日期计入,待交付不计销售和利润。已取消订单不计本页销售汇总;直接回收付款计入每日购料,不计销售和利润。';
|
||||
}
|
||||
const previousOrderDate = Values.previousDate;
|
||||
const getOrderBookFilters = () => orderBookFilters;
|
||||
const getOrderBookFilters = () => orderBookFilters!;
|
||||
function orderBookRange() {
|
||||
const f = getOrderBookFilters(),
|
||||
today = state.today;
|
||||
@@ -193,7 +196,7 @@ export function orderBook(
|
||||
...historical.map(pocket => [pocket, pocketLabel(pocket) + '(已停用 · 历史)']),
|
||||
];
|
||||
}
|
||||
function orderBookMobileCards(rows, version, showCopy) {
|
||||
function orderBookMobileCards(rows: BookRow[], version: number, showCopy: boolean) {
|
||||
return (
|
||||
<div className="order-mobile-list">
|
||||
{Children.toArray(
|
||||
@@ -218,7 +221,7 @@ export function orderBook(
|
||||
</div>
|
||||
</div>
|
||||
{row.status === 'cancelled' ? <p className="small muted">已取消,未计入汇总</p> : ''}
|
||||
{row.balance < 0 ? <p className="small danger-text">退款待处理</p> : ''}
|
||||
{(row.balance ?? 0) < 0 ? <p className="small danger-text">退款待处理</p> : ''}
|
||||
<details className="order-mobile-breakdown">
|
||||
<summary>成本、利润与备注</summary>
|
||||
<dl>
|
||||
@@ -263,8 +266,8 @@ export function orderBook(
|
||||
) : (
|
||||
''
|
||||
)}
|
||||
{!['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind) ? orderEntryTimeHTML(row) : ''}
|
||||
{showCopy && !['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind)
|
||||
{!['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind ?? '') ? orderEntryTimeHTML(row) : ''}
|
||||
{showCopy && !['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind ?? '')
|
||||
? button('复制新增', 'copy-order', 'order-copy-button', {
|
||||
'data-id': row.id,
|
||||
})
|
||||
@@ -276,7 +279,7 @@ export function orderBook(
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function orderBookSummaryQuantity(summary) {
|
||||
function orderBookSummaryQuantity(summary: BookSummary) {
|
||||
return (
|
||||
<>
|
||||
{grams(summary.mg) + 'g' + (summary.pieces ? ' / ' + summary.pieces + '件' : '')}
|
||||
@@ -284,10 +287,10 @@ export function orderBook(
|
||||
</>
|
||||
);
|
||||
}
|
||||
function afterSalePayerName(row) {
|
||||
function afterSalePayerName(row: BookRow) {
|
||||
return row.costItems?.[0]?.payer ? teamMemberName(row.costItems[0].payer) : '付款人待补';
|
||||
}
|
||||
function orderBookFeeParts(row) {
|
||||
function orderBookFeeParts(row: BookRow) {
|
||||
if (row.kind === 'recovery') return '';
|
||||
if (row.status === 'draft') return '';
|
||||
if (row.kind === 'afterSale')
|
||||
@@ -302,7 +305,7 @@ export function orderBook(
|
||||
<span>原单售后成本调整</span>
|
||||
</div>
|
||||
);
|
||||
const grouped = new Map();
|
||||
const grouped = new Map<string, { name: string; amount: number; missing: boolean }>();
|
||||
for (const item of row.laborAndFeeItems || []) {
|
||||
const key = item.component + ':' + item.name,
|
||||
previous = grouped.get(key);
|
||||
@@ -332,7 +335,7 @@ export function orderBook(
|
||||
''
|
||||
);
|
||||
}
|
||||
function orderBookMoney(row, key) {
|
||||
function orderBookMoney(row: BookRow, key: MoneyKey) {
|
||||
if (row.kind === 'recovery') return <span className="muted">—</span>;
|
||||
if (row.status === 'draft')
|
||||
return (
|
||||
@@ -362,22 +365,22 @@ export function orderBook(
|
||||
</>
|
||||
);
|
||||
}
|
||||
function orderBookQuantity(value) {
|
||||
function orderBookQuantity(value: Pick<BookRow, 'mg' | 'pieces'>) {
|
||||
return (
|
||||
[value.mg ? grams(value.mg) + 'g' : '', value.pieces ? value.pieces + '件' : ''].filter(Boolean).join(' / ') ||
|
||||
'—'
|
||||
);
|
||||
}
|
||||
function orderReviewBadge(row) {
|
||||
function orderReviewBadge(row: BookRow) {
|
||||
return orderIsReviewed(row) ? <span className="order-review-status">已复核</span> : '';
|
||||
}
|
||||
function afterSaleEditButton(row) {
|
||||
function afterSaleEditButton(row: BookRow) {
|
||||
return button('修改', 'after-sale-edit', 'after-sale-edit-button', {
|
||||
'data-id': row.after_sale_id || row.id,
|
||||
'aria-label': '修改 ' + row.customer + ' 的售后记录',
|
||||
});
|
||||
}
|
||||
function orderBookIdentity(row, version) {
|
||||
function orderBookIdentity(row: BookRow, version: number | undefined = undefined) {
|
||||
if (row.kind === 'orderAfterSale')
|
||||
return (
|
||||
<button
|
||||
@@ -462,14 +465,14 @@ export function orderBook(
|
||||
</button>
|
||||
);
|
||||
}
|
||||
const card = (title, value, hint = '', emphasis = false) => (
|
||||
const card = (title: string, value: ReactNode, hint: ReactNode = '', emphasis = false) => (
|
||||
<div className={'stat ' + (emphasis ? 'emphasis' : '')}>
|
||||
<small>{title}</small>
|
||||
<strong>{value}</strong>
|
||||
<div className="hint">{hint}</div>
|
||||
</div>
|
||||
);
|
||||
function orderBookSummaryAmount(summary, key) {
|
||||
function orderBookSummaryAmount(summary: BookSummary, key: MoneyKey) {
|
||||
const missing = summary.unknownCounts?.[key] || 0,
|
||||
known = summary.knownCounts?.[key];
|
||||
if (missing && known === 0 && !summary[key] && !summary.afterSaleCount)
|
||||
@@ -480,7 +483,7 @@ export function orderBook(
|
||||
);
|
||||
return (missing ? '已知 ' : '') + '¥' + yuan(summary[key]);
|
||||
}
|
||||
function validateOrderBook(book) {
|
||||
function validateOrderBook(book: BookData) {
|
||||
const s = book?.summaryWithoutCancelled,
|
||||
r = book?.receiptsWithoutCancelled;
|
||||
const amounts = [
|
||||
@@ -492,7 +495,7 @@ export function orderBook(
|
||||
'profit',
|
||||
'ownerCost',
|
||||
'assistantCost',
|
||||
];
|
||||
] as const;
|
||||
const counts = [
|
||||
'orderCount',
|
||||
'completedCount',
|
||||
@@ -505,7 +508,7 @@ export function orderBook(
|
||||
'unknownCosts',
|
||||
'unknownCostCount',
|
||||
'unknownProfitCount',
|
||||
];
|
||||
] as const;
|
||||
if (
|
||||
!Array.isArray(book?.rows) ||
|
||||
(book.displayRows !== undefined && !Array.isArray(book.displayRows)) ||
|
||||
@@ -525,20 +528,20 @@ export function orderBook(
|
||||
s.unknownCounts[key] >= 0,
|
||||
) ||
|
||||
!counts.every(key => Number.isSafeInteger(s[key]) && s[key] >= 0) ||
|
||||
!['receipt', 'refund', 'net'].every(key => Number.isSafeInteger(r[key])) ||
|
||||
!(['receipt', 'refund', 'net'] as const).every(key => Number.isSafeInteger(r[key])) ||
|
||||
!Array.isArray(r.channels) ||
|
||||
!r.channels.every(
|
||||
channel =>
|
||||
channel &&
|
||||
typeof channel.name === 'string' &&
|
||||
['receipt', 'refund', 'net'].every(key => Number.isSafeInteger(channel[key])),
|
||||
(['receipt', 'refund', 'net'] as const).every(key => Number.isSafeInteger(channel[key])),
|
||||
) ||
|
||||
!['wechat', 'alipay', 'cash'].every(channel => r.channels.some(item => item.channel === channel))
|
||||
!(['wechat', 'alipay', 'cash'] as const).every(channel => r.channels.some(item => item.channel === channel))
|
||||
)
|
||||
throw new Error('订单汇总数据尚未完整返回,请刷新后重新读取。');
|
||||
return book;
|
||||
}
|
||||
function renderOrderBook(book, range) {
|
||||
function renderOrderBook(book: BookData, range: { from: string; date: string; name: string }) {
|
||||
validateOrderBook(book);
|
||||
const s = book.summaryWithoutCancelled,
|
||||
receipts = book.receiptsWithoutCancelled,
|
||||
@@ -598,7 +601,7 @@ export function orderBook(
|
||||
(teamMode() ? teamMemberKeys() : ['owner', 'assistant']).map(member => (
|
||||
<span>
|
||||
<b>{teamMemberName(member)}</b>
|
||||
<span>{orderBookSummaryAmount(s, member + 'Cost')}</span>
|
||||
<span>{orderBookSummaryAmount(s, `${member}Cost`)}</span>
|
||||
</span>
|
||||
)),
|
||||
)}
|
||||
@@ -640,7 +643,7 @@ export function orderBook(
|
||||
{card(range.name + '成本' + (costPartial ? '(已知部分)' : ''), costValue, costDetails)}
|
||||
</>
|
||||
);
|
||||
const count = `${range.name} · 汇总 ${s.orderCount} 单${recoveryCount ? ' · 回收 ' + recoveryCount + ' 笔' : ''}${s.afterSaleCount ? ' · 售后 ' + s.afterSaleCount + ' 笔' : ''}${cancelledCount ? ',另有 ' + cancelledCount + ' 单取消未计' : ''}${orderBookFilters.q || orderBookFilters.status || orderBookFilters.pocket || orderBookFilters.member ? '(已筛选)' : ''}`;
|
||||
const count = `${range.name} · 汇总 ${s.orderCount} 单${recoveryCount ? ' · 回收 ' + recoveryCount + ' 笔' : ''}${s.afterSaleCount ? ' · 售后 ' + s.afterSaleCount + ' 笔' : ''}${cancelledCount ? ',另有 ' + cancelledCount + ' 单取消未计' : ''}${orderBookFilters!.q || orderBookFilters!.status || orderBookFilters!.pocket || orderBookFilters!.member ? '(已筛选)' : ''}`;
|
||||
const rows = book.displayRows ?? book.rows;
|
||||
if (!rows.length) {
|
||||
const list = (
|
||||
@@ -677,7 +680,7 @@ export function orderBook(
|
||||
rows.map((row, i) => (
|
||||
<tr
|
||||
className={
|
||||
['afterSale', 'orderAfterSale'].includes(row.kind)
|
||||
['afterSale', 'orderAfterSale'].includes(row.kind ?? '')
|
||||
? 'order-after-sale'
|
||||
: row.kind === 'recovery'
|
||||
? 'order-recovery'
|
||||
@@ -696,8 +699,10 @@ export function orderBook(
|
||||
{row.kind === 'recovery' ? <span className="order-status muted">已记录</span> : badge(row)}
|
||||
{orderReviewBadge(row)}
|
||||
</div>
|
||||
{!['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind) ? orderEntryTimeHTML(row) : ''}
|
||||
{showOrderCopyEntry && !['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind)
|
||||
{!['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind ?? '')
|
||||
? orderEntryTimeHTML(row)
|
||||
: ''}
|
||||
{showOrderCopyEntry && !['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind ?? '')
|
||||
? button(
|
||||
<>
|
||||
<span aria-hidden="true">+</span>复制新增
|
||||
@@ -711,7 +716,7 @@ export function orderBook(
|
||||
)
|
||||
: ''}
|
||||
{row.status === 'cancelled' ? <div className="small muted">未计入汇总</div> : ''}
|
||||
{row.balance < 0 ? <div className="small danger-text">退款待处理</div> : ''}
|
||||
{(row.balance ?? 0) < 0 ? <div className="small danger-text">退款待处理</div> : ''}
|
||||
</td>
|
||||
<td className="order-type">
|
||||
{row.types.map(e).map((part, i) => (
|
||||
@@ -758,7 +763,7 @@ export function orderBook(
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<td colSpan="2">
|
||||
<td colSpan={2}>
|
||||
汇总 {s.orderCount} 单
|
||||
{recoveryCount ? (
|
||||
<>
|
||||
+66
-56
@@ -1,7 +1,13 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import type { OrderRecord, OrderLine, OwnershipRequest, ChangeRequest, CancellationRequest } from '../orderData';
|
||||
type CostRow = ReturnType<typeof import('../../../../../public/calculations.js').orderCosts>['rows'][number] & {
|
||||
allocations?: { payer: string; amount: number | null }[];
|
||||
};
|
||||
import type { OrderContext, SharedViews } from '../viewTypes';
|
||||
import { Children, Fragment } from 'react';
|
||||
import { Calc as LedgerCalc } from '../../../shared';
|
||||
export function orderDetail(
|
||||
{ currentOrder, state, detailForm, error, navigation },
|
||||
{ currentOrder, state, detailForm, error, navigation }: OrderContext,
|
||||
{
|
||||
orderCancellationPending,
|
||||
orderChangePending,
|
||||
@@ -41,9 +47,9 @@ export function orderDetail(
|
||||
stockCountText,
|
||||
pocketCountsEnabled,
|
||||
teamMemberKeys,
|
||||
},
|
||||
}: SharedViews,
|
||||
) {
|
||||
function transactionTable(o) {
|
||||
function transactionTable(o: OrderRecord) {
|
||||
const rows = [
|
||||
...o.payments.map(p => ({
|
||||
date: p.date,
|
||||
@@ -107,7 +113,7 @@ export function orderDetail(
|
||||
<p className="muted">还没有收退款、费用或交款记录。</p>
|
||||
);
|
||||
}
|
||||
function priceLockInventoryCreditHTML(order) {
|
||||
function priceLockInventoryCreditHTML(order: OrderRecord) {
|
||||
if (!order.assistantInventoryCredit) return '';
|
||||
return (
|
||||
<div className="note">
|
||||
@@ -125,7 +131,7 @@ export function orderDetail(
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function orderTeamFundsHTML(order) {
|
||||
function orderTeamFundsHTML(order: OrderRecord) {
|
||||
return (
|
||||
<section className="panel">
|
||||
<h2>{teamMemberName(order.member)}的经营订单</h2>
|
||||
@@ -134,7 +140,7 @@ export function orderDetail(
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function orderProductTraceHTML(o) {
|
||||
function orderProductTraceHTML(o: OrderRecord) {
|
||||
return (
|
||||
<details className="panel detail-product-trace">
|
||||
<summary>商品来源与原始说明</summary>
|
||||
@@ -158,8 +164,8 @@ export function orderDetail(
|
||||
</details>
|
||||
);
|
||||
}
|
||||
function orderAfterSaleProfitHTML(order) {
|
||||
const summary = orderAfterSaleRecord(order).summary,
|
||||
function orderAfterSaleProfitHTML(order: OrderRecord) {
|
||||
const summary = orderAfterSaleRecord(order)!.summary,
|
||||
direct = Number.isSafeInteger(summary.directCost) ? summary.directCost : order.directCost;
|
||||
return (
|
||||
<section className="panel detail-profit detail-profit-known" aria-label="售后最终利润">
|
||||
@@ -177,7 +183,11 @@ export function orderDetail(
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function orderProfitHTML(o, summary, { voided = false } = {}) {
|
||||
function orderProfitHTML(
|
||||
o: OrderRecord,
|
||||
summary: ReturnType<typeof orderDetailCostSummary>,
|
||||
{ voided = false } = {},
|
||||
) {
|
||||
if (orderAfterSaleRecord(o)) return orderAfterSaleProfitHTML(o);
|
||||
const { total, missing } = summary,
|
||||
done = ['delivered', 'returned', 'cancelled'].includes(o.status),
|
||||
@@ -197,7 +207,7 @@ export function orderDetail(
|
||||
: !known
|
||||
? `成交金额 ¥${yuan(o.total)} − 完整成本待补,利润暂不确认。`
|
||||
: `${historical ? '销售净额' : '成交金额'} ¥${yuan(sale)} − ${historical ? '保留成本' : '成本合计'} ¥${yuan(total)} = ${title} ¥${yuan(o.profit)}`;
|
||||
if (known && sale - total !== o.profit)
|
||||
if (known && sale - total! !== o.profit)
|
||||
equation = `${historical ? '销售净额' : '成交金额'} ¥${yuan(sale)};成本合计 ¥${yuan(total)}。利润沿用已记账金额,历史差异请核对下方流水。`;
|
||||
return (
|
||||
<section className={'panel detail-profit' + (known ? ' detail-profit-known' : '')} aria-label={title}>
|
||||
@@ -210,7 +220,7 @@ export function orderDetail(
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function orderCostRowsHTML(rows, label) {
|
||||
function orderCostRowsHTML(rows: CostRow[], label: string) {
|
||||
const names = Object.fromEntries(teamMemberKeys().map(member => [member, teamMemberName(member)]));
|
||||
return (
|
||||
<div className="table-wrap">
|
||||
@@ -229,8 +239,8 @@ export function orderDetail(
|
||||
weighted = calculation?.weighted;
|
||||
const formula = calculation
|
||||
? weighted
|
||||
? `耗用 ${grams(calculation.quantity)}g${calculation.rate == null ? '' : ' · 加权均价约 ' + yuan(calculation.rate) + '元/克'};按实际购料分摊`
|
||||
: `${grams(calculation.quantity)}g × ${calculation.rate == null ? '单价待补' : yuan(calculation.rate) + '元/克'}`
|
||||
? `耗用 ${grams(calculation.quantity!)}g${calculation.rate == null ? '' : ' · 加权均价约 ' + yuan(calculation.rate) + '元/克'};按实际购料分摊`
|
||||
: `${grams(calculation.quantity!)}g × ${calculation.rate == null ? '单价待补' : yuan(calculation.rate) + '元/克'}`
|
||||
: '';
|
||||
const payer = row.poolPending
|
||||
? '待补采购后分摊'
|
||||
@@ -278,9 +288,9 @@ export function orderDetail(
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function orderAfterSaleCostsHTML(order) {
|
||||
function orderAfterSaleCostsHTML(order: OrderRecord) {
|
||||
const record = orderAfterSaleRecord(order),
|
||||
summary = record.summary,
|
||||
summary = record!.summary,
|
||||
direct = Number.isSafeInteger(summary.directCost) ? summary.directCost : order.directCost,
|
||||
total = summary.costLoss + direct;
|
||||
return (
|
||||
@@ -312,13 +322,13 @@ export function orderDetail(
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function orderCostsHTML(o, summary = orderDetailCostSummary(o), { voided = false } = {}) {
|
||||
function orderCostsHTML(o: OrderRecord, summary = orderDetailCostSummary(o), { voided = false } = {}) {
|
||||
if (orderAfterSaleRecord(o)) return orderAfterSaleCostsHTML(o);
|
||||
const { costs, rows, knownTotal, missing, knownGoods, paidFees } = summary;
|
||||
const actual = rows.filter(row => !row.excluded && row.kind !== 'pending' && row.amount !== 0),
|
||||
pending = rows.filter(row => row.kind === 'pending' && row.amount !== 0),
|
||||
historical = rows.filter(row => row.excluded && row.amount !== 0);
|
||||
const numbers = actual.filter(row => row.amount != null).map(row => row.amount),
|
||||
const numbers = actual.filter(row => row.amount != null).map(row => row.amount!),
|
||||
rowTotal = numbers.reduce((sum, amount) => sum + amount, 0);
|
||||
const terms = rowTotal === knownTotal ? numbers : [knownGoods, paidFees].filter(amount => amount !== 0);
|
||||
const equation = (terms.length ? terms : [0]).map(amount => '¥' + yuan(amount)).join(' + ');
|
||||
@@ -395,7 +405,7 @@ export function orderDetail(
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function orderAmount(value, mode) {
|
||||
function orderAmount(value: number | null, mode: string) {
|
||||
return value == null
|
||||
? '待补'
|
||||
: '¥' +
|
||||
@@ -406,7 +416,7 @@ export function orderDetail(
|
||||
})
|
||||
: yuan(value));
|
||||
}
|
||||
function orderLinePocketHTML(order, line) {
|
||||
function orderLinePocketHTML(order: OrderRecord, line: OrderLine) {
|
||||
const pocket = pocketLabel(String(line.pocket || '').trim()) || '配货';
|
||||
const title =
|
||||
order.status === 'delivered'
|
||||
@@ -429,7 +439,7 @@ export function orderDetail(
|
||||
</span>
|
||||
);
|
||||
}
|
||||
function orderSalesHTML(o, { voided = false } = {}) {
|
||||
function orderSalesHTML(o: OrderRecord, { voided = false } = {}) {
|
||||
const historical = voided || ['returned', 'cancelled'].includes(o.status),
|
||||
unbooked = ['draft', 'confirmed'].includes(o.status);
|
||||
const subtotal = o.lines.reduce((sum, line) => sum + line.sale, 0),
|
||||
@@ -461,8 +471,8 @@ export function orderDetail(
|
||||
line.unit === 'g' &&
|
||||
Number.isSafeInteger(line.goldPrice) &&
|
||||
Number.isSafeInteger(line.laborRate) &&
|
||||
['gram', 'piece'].includes(line.laborMode) &&
|
||||
(line.laborMode !== 'piece' || (Number.isSafeInteger(line.pieces) && line.pieces > 0));
|
||||
['gram', 'piece'].includes(line.laborMode ?? '') &&
|
||||
(line.laborMode !== 'piece' || (Number.isSafeInteger(line.pieces) && line.pieces! > 0));
|
||||
const quantity = line.unit === 'g' ? grams(line.quantity) + 'g' : line.quantity + '件';
|
||||
const formula = auto
|
||||
? line.laborMode === 'gram'
|
||||
@@ -553,7 +563,7 @@ export function orderDetail(
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function orderAfterSaleDetailHTML(order) {
|
||||
function orderAfterSaleDetailHTML(order: OrderRecord) {
|
||||
const record = orderAfterSaleRecord(order);
|
||||
if (!record) return '';
|
||||
try {
|
||||
@@ -611,7 +621,7 @@ export function orderDetail(
|
||||
return (
|
||||
<section className="panel">
|
||||
<h2>已处理售后</h2>
|
||||
<p className="danger-text">{err.message}</p>
|
||||
<p className="danger-text">{err instanceof Error ? err.message : String(err)}</p>
|
||||
{button('重新读取订单', 'reload-order-change', '', {
|
||||
'data-id': order.id,
|
||||
})}
|
||||
@@ -619,7 +629,7 @@ export function orderDetail(
|
||||
);
|
||||
}
|
||||
}
|
||||
function orderOwnershipHistoryHTML(request) {
|
||||
function orderOwnershipHistoryHTML(request: OwnershipRequest) {
|
||||
return (
|
||||
<li>
|
||||
<div className="change-record-title">
|
||||
@@ -651,7 +661,7 @@ export function orderDetail(
|
||||
</li>
|
||||
);
|
||||
}
|
||||
function orderOwnershipDetailHTML(order) {
|
||||
function orderOwnershipDetailHTML(order: OrderRecord) {
|
||||
const entry = currentOrderOwnership(order),
|
||||
data = entry?.data,
|
||||
request = orderOwnershipPending(order);
|
||||
@@ -730,14 +740,14 @@ export function orderDetail(
|
||||
) : (
|
||||
''
|
||||
)}
|
||||
<details open={request}>
|
||||
<details open={!!request}>
|
||||
<summary>归属修改与复核记录({data.requests.length})</summary>
|
||||
<ul className="timeline change-history">{Children.toArray(data.requests.map(orderOwnershipHistoryHTML))}</ul>
|
||||
</details>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function orderChangeHistoryHTML(request) {
|
||||
function orderChangeHistoryHTML(request: ChangeRequest) {
|
||||
return (
|
||||
<li>
|
||||
<div className="change-record-title">
|
||||
@@ -771,7 +781,7 @@ export function orderDetail(
|
||||
</li>
|
||||
);
|
||||
}
|
||||
function orderChangeDetailHTML(order) {
|
||||
function orderChangeDetailHTML(order: OrderRecord) {
|
||||
const entry = currentOrderChange(order),
|
||||
data = entry?.data,
|
||||
request = orderChangePending(order);
|
||||
@@ -826,14 +836,14 @@ export function orderDetail(
|
||||
) : (
|
||||
''
|
||||
)}
|
||||
<details open={request}>
|
||||
<details open={!!request}>
|
||||
<summary>变更申请与复核记录({data.requests.length})</summary>
|
||||
<ul className="timeline change-history">{Children.toArray(data.requests.map(orderChangeHistoryHTML))}</ul>
|
||||
</details>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function orderCancellationHistoryHTML(request) {
|
||||
function orderCancellationHistoryHTML(request: CancellationRequest) {
|
||||
if (request.direct === true)
|
||||
return (
|
||||
<li>
|
||||
@@ -875,7 +885,7 @@ export function orderDetail(
|
||||
</li>
|
||||
);
|
||||
}
|
||||
function orderCancellationDetailHTML(order) {
|
||||
function orderCancellationDetailHTML(order: OrderRecord) {
|
||||
if (order.price_lock_id) return '';
|
||||
const entry = currentOrderCancellation(order),
|
||||
data = entry?.data,
|
||||
@@ -939,7 +949,7 @@ export function orderDetail(
|
||||
) : (
|
||||
''
|
||||
)}
|
||||
<details open={request}>
|
||||
<details open={!!request}>
|
||||
<summary>取消申请与处理记录({data.requests.length})</summary>
|
||||
<ul className="timeline cancellation-history">
|
||||
{Children.toArray(data.requests.map(orderCancellationHistoryHTML))}
|
||||
@@ -948,7 +958,7 @@ export function orderDetail(
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function printStatusControls(value) {
|
||||
function printStatusControls(value: OrderRecord) {
|
||||
return (
|
||||
<div className="document-print-controls">
|
||||
{printStatusBadge(value)}
|
||||
@@ -956,7 +966,7 @@ export function orderDetail(
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function recoveryLinkedOrderNoticeHTML(order) {
|
||||
function recoveryLinkedOrderNoticeHTML(order: OrderRecord) {
|
||||
return order.recovery_id ? (
|
||||
<div className="note">
|
||||
这张销售单由置换结算自动生成。重量、抵扣与收付款请在关联置换单核对;修改或取消请从关联置换单进入,整套收付款、购料与库存一起更正。
|
||||
@@ -965,10 +975,10 @@ export function orderDetail(
|
||||
''
|
||||
);
|
||||
}
|
||||
function materialPoolOrderNoticeHTML(order) {
|
||||
function materialPoolOrderNoticeHTML(order: OrderRecord) {
|
||||
if (!order.materialCostPending) return '';
|
||||
const dates = [
|
||||
...new Set(order.lines.filter(line => line.costMaterial?.mode === 'pool').map(line => line.costMaterial.poolId)),
|
||||
...new Set(order.lines.filter(line => line.costMaterial?.mode === 'pool').map(line => line.costMaterial!.poolId)),
|
||||
];
|
||||
return (
|
||||
<div className="note material-order-pending">
|
||||
@@ -978,10 +988,10 @@ export function orderDetail(
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function orderOwnershipOtherPending(order) {
|
||||
function orderOwnershipOtherPending(order: OrderRecord) {
|
||||
return orderChangePending(order) || orderCancellationPending(order);
|
||||
}
|
||||
function orderOwnershipActionHTML(order) {
|
||||
function orderOwnershipActionHTML(order: OrderRecord) {
|
||||
const data = currentOrderOwnership(order)?.data;
|
||||
if (!data?.eligible || data.pending || orderOwnershipPending(order) || orderOwnershipOtherPending(order)) return '';
|
||||
const direct = state.user.role === 'owner' && data.canDirect;
|
||||
@@ -989,7 +999,7 @@ export function orderDetail(
|
||||
'data-id': order.id,
|
||||
});
|
||||
}
|
||||
function orderInternalNoteHTML(order) {
|
||||
function orderInternalNoteHTML(order: OrderRecord) {
|
||||
return (
|
||||
<aside className="detail-internal-note" aria-label="内部备注(客户不可见)">
|
||||
<span className="detail-internal-note-label">内部备注 · 客户不可见</span>
|
||||
@@ -1008,16 +1018,16 @@ export function orderDetail(
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
function orderDetailCostSummary(o) {
|
||||
function orderDetailCostSummary(o: OrderRecord) {
|
||||
const costs = LedgerCalc.orderCosts(o),
|
||||
rows = [],
|
||||
pools = new Map();
|
||||
rows: CostRow[] = [],
|
||||
pools = new Map<string, CostRow & { allocations: { payer: string; amount: number | null }[] }>();
|
||||
for (const row of costs.rows) {
|
||||
if ((row.materialPoolId || row.priceLockSource) && row.calculation?.weighted) {
|
||||
const key = row.source,
|
||||
existing = pools.get(key);
|
||||
if (existing) {
|
||||
existing.amount += row.amount;
|
||||
existing.amount = Number(existing.amount) + Number(row.amount);
|
||||
existing.allocations.push({
|
||||
payer: row.payer,
|
||||
amount: row.amount,
|
||||
@@ -1051,7 +1061,7 @@ export function orderDetail(
|
||||
knownGoods = costs.goodsExcluded
|
||||
? 0
|
||||
: Number.isSafeInteger(goods)
|
||||
? goods
|
||||
? goods!
|
||||
: Number.isSafeInteger(o.knownGoodsCost)
|
||||
? o.knownGoodsCost
|
||||
: costs.total.goods;
|
||||
@@ -1070,7 +1080,7 @@ export function orderDetail(
|
||||
total: missing ? null : knownGoods + paidFees,
|
||||
};
|
||||
}
|
||||
function recoveryLinkedOrderActionsHTML(order, { reviewAllowed = false } = {}) {
|
||||
function recoveryLinkedOrderActionsHTML(order: OrderRecord, { reviewAllowed = false } = {}) {
|
||||
return (
|
||||
<>
|
||||
{button('查看置换结算单', 'recovery-open', 'primary', {
|
||||
@@ -1083,7 +1093,7 @@ export function orderDetail(
|
||||
</>
|
||||
);
|
||||
}
|
||||
function orderAfterSaleLegacyActionHTML(order, needsApproval) {
|
||||
function orderAfterSaleLegacyActionHTML(order: OrderRecord, needsApproval: boolean) {
|
||||
if (order.lines.some(line => line.priceLockPool)) return '';
|
||||
const action = button(needsApproval ? '申请整单退货' : '整单退货', 'show-return', 'quiet', {
|
||||
title: '旧入口:仅登记退货,实际退款另行登记',
|
||||
@@ -1099,7 +1109,7 @@ export function orderDetail(
|
||||
</details>
|
||||
);
|
||||
}
|
||||
function orderAfterSaleActionHTML(order, { blocked = false } = {}) {
|
||||
function orderAfterSaleActionHTML(order: OrderRecord, { blocked = false } = {}) {
|
||||
if (
|
||||
order.status !== 'delivered' ||
|
||||
blocked ||
|
||||
@@ -1112,7 +1122,7 @@ export function orderDetail(
|
||||
'data-id': order.id,
|
||||
});
|
||||
}
|
||||
function orderCancellationActionHTML(order) {
|
||||
function orderCancellationActionHTML(order: OrderRecord) {
|
||||
const entry = currentOrderCancellation(order),
|
||||
data = entry?.data;
|
||||
if (orderOwnershipPending(order)) return '';
|
||||
@@ -1128,7 +1138,7 @@ export function orderDetail(
|
||||
'data-id': order.id,
|
||||
});
|
||||
}
|
||||
function orderCancellationApproved(order) {
|
||||
function orderCancellationApproved(order: OrderRecord) {
|
||||
return (
|
||||
order.cancellationApproved ||
|
||||
currentOrderCancellation(order)?.data?.requests.find(request => request.status === 'approved') ||
|
||||
@@ -1136,17 +1146,17 @@ export function orderDetail(
|
||||
);
|
||||
}
|
||||
function renderDetail() {
|
||||
const o = currentOrder,
|
||||
const o = currentOrder!,
|
||||
done = ['delivered', 'returned', 'cancelled'].includes(o.status);
|
||||
const cancellationPending = orderCancellationPending(o),
|
||||
changePending = orderChangePending(o),
|
||||
ownershipPending = orderOwnershipPending(o),
|
||||
approvalPending = !!cancellationPending || !!changePending || !!ownershipPending,
|
||||
afterSaleDone = !!orderAfterSaleRecord(o),
|
||||
voided = orderCancellationApproved(o),
|
||||
voided = !!orderCancellationApproved(o),
|
||||
financialBlocked = approvalPending || !!voided || afterSaleDone,
|
||||
owner = state.user.role === 'owner';
|
||||
let actions = (
|
||||
let actions: ReactNode = (
|
||||
<>
|
||||
{button('客户预览/打印', 'print', 'primary', {
|
||||
'data-id': o.id,
|
||||
@@ -1176,7 +1186,7 @@ export function orderDetail(
|
||||
);
|
||||
if (o.status === 'draft' && owner && !financialBlocked)
|
||||
actions = Children.toArray([actions, button('继续填写并开单', 'edit')]);
|
||||
const needsApproval = kind => orderActionRequiresApproval(kind);
|
||||
const needsApproval = (kind: string) => orderActionRequiresApproval(kind);
|
||||
if (o.status === 'confirmed' && !financialBlocked) {
|
||||
if (o.pendingFees.length)
|
||||
actions = Children.toArray([
|
||||
@@ -1335,7 +1345,7 @@ export function orderDetail(
|
||||
<small className="muted">实际已交净额 ¥{yuan(o.profitTransferred)}</small>
|
||||
</div>
|
||||
<div>
|
||||
{o.settlementDue < 0
|
||||
{Number(o.settlementDue) < 0
|
||||
? teamMemberName('owner') + '待转回' + teamMemberName('assistant')
|
||||
: teamMemberName('assistant') + '待交' + teamMemberName('owner')}{' '}
|
||||
<strong>{o.settlementDue == null ? '料费待补' : '¥' + yuan(Math.abs(o.settlementDue))}</strong>
|
||||
@@ -1386,7 +1396,7 @@ export function orderDetail(
|
||||
<summary>操作记录</summary>
|
||||
<ul className="timeline">
|
||||
{Children.toArray(
|
||||
o.audit.map(a => (
|
||||
o.audit!.map(a => (
|
||||
<li>
|
||||
{actionName[a.action] || a.action} · {a.actor}
|
||||
<small>{new Date(a.created).toLocaleString('zh-CN')}</small>
|
||||
+49
-42
@@ -1,3 +1,5 @@
|
||||
import type { CancellationRequest, OwnershipRequest, ChangeRequest, ReviewList, CancelSummary } from '../orderData';
|
||||
import type { OrderContext, SharedViews } from '../viewTypes';
|
||||
import { Children } from 'react';
|
||||
export function orderReviews(
|
||||
{
|
||||
@@ -9,7 +11,7 @@ export function orderReviews(
|
||||
orderChangeListStatus,
|
||||
orderOwnershipListStatus,
|
||||
orderCancellationListStatus,
|
||||
},
|
||||
}: OrderContext,
|
||||
{
|
||||
orderChangeActionLabel,
|
||||
orderChangeTime,
|
||||
@@ -34,12 +36,12 @@ export function orderReviews(
|
||||
orderOwnershipStatus,
|
||||
validateOrderChangeRequest,
|
||||
validateOrderOwnershipRequest,
|
||||
},
|
||||
}: SharedViews,
|
||||
) {
|
||||
function orderCancellationRecordStatus(request) {
|
||||
function orderCancellationRecordStatus(request: CancellationRequest) {
|
||||
return request.direct === true ? '当天直接取消' : orderCancellationStatus[request.status];
|
||||
}
|
||||
function orderCancellationListHTML(result) {
|
||||
function orderCancellationListHTML(result: ReviewList<CancellationRequest>) {
|
||||
const owner = state.user.role === 'owner' && result.canApprove;
|
||||
return (
|
||||
<>
|
||||
@@ -130,7 +132,7 @@ export function orderReviews(
|
||||
</>
|
||||
);
|
||||
}
|
||||
function orderOwnershipListHTML(result) {
|
||||
function orderOwnershipListHTML(result: ReviewList<OwnershipRequest>) {
|
||||
const owner = state.user.role === 'owner' && result.canApprove;
|
||||
return (
|
||||
<>
|
||||
@@ -222,7 +224,7 @@ export function orderReviews(
|
||||
</>
|
||||
);
|
||||
}
|
||||
function orderChangeListHTML(result) {
|
||||
function orderChangeListHTML(result: ReviewList<ChangeRequest>) {
|
||||
const owner = state.user.role === 'owner' && result.canApprove;
|
||||
return (
|
||||
<>
|
||||
@@ -318,7 +320,9 @@ export function orderReviews(
|
||||
</>
|
||||
);
|
||||
}
|
||||
function legacyCountConfirmationHTML(value) {
|
||||
function legacyCountConfirmationHTML(
|
||||
value: { requiresLegacyCountVerified?: boolean; legacyCountNotice?: string } | undefined,
|
||||
) {
|
||||
return value?.requiresLegacyCountVerified ? (
|
||||
<>
|
||||
<div className="note">
|
||||
@@ -334,9 +338,9 @@ export function orderReviews(
|
||||
''
|
||||
);
|
||||
}
|
||||
function validateOrderCancellationRequest(request, orderId) {
|
||||
function validateOrderCancellationRequest(request: CancellationRequest, orderId: string | undefined = undefined) {
|
||||
const summary = request?.summary,
|
||||
nullable = value => value === null || Number.isSafeInteger(value);
|
||||
nullable = (value: unknown) => value === null || Number.isSafeInteger(value);
|
||||
if (
|
||||
!request ||
|
||||
typeof request.id !== 'string' ||
|
||||
@@ -351,8 +355,8 @@ export function orderReviews(
|
||||
typeof request.stale !== 'boolean' ||
|
||||
typeof request.canApprove !== 'boolean' ||
|
||||
!summary ||
|
||||
!['total', 'netReceived', 'directCost'].every(key => Number.isSafeInteger(summary[key])) ||
|
||||
!['goodsCost', 'profit', 'settlementDue'].every(key => nullable(summary[key])) ||
|
||||
!(['total', 'netReceived', 'directCost'] as const).every(key => Number.isSafeInteger(summary[key])) ||
|
||||
!(['goodsCost', 'profit', 'settlementDue'] as const).every(key => nullable(summary[key])) ||
|
||||
!Array.isArray(summary.inventory) ||
|
||||
!summary.inventory.every(
|
||||
item => typeof item.date === 'string' && typeof item.pocket === 'string' && Number.isSafeInteger(item.mg),
|
||||
@@ -361,12 +365,12 @@ export function orderReviews(
|
||||
throw new Error('取消申请资料未完整返回,请重新读取订单后复核。');
|
||||
return request;
|
||||
}
|
||||
function orderCancellationSummaryHTML(request) {
|
||||
function orderCancellationSummaryHTML(request: CancellationRequest) {
|
||||
return orderCancellationSummaryDataHTML(validateOrderCancellationRequest(request).summary);
|
||||
}
|
||||
function orderCancellationSummaryDataHTML(value) {
|
||||
function orderCancellationSummaryDataHTML(value: CancelSummary | undefined) {
|
||||
const summary = validateOrderCancellationSummary(value),
|
||||
amount = value => (value === null ? '待补齐' : '¥' + yuan(value));
|
||||
amount = (value: number | null) => (value === null ? '待补齐' : '¥' + yuan(value));
|
||||
return (
|
||||
<>
|
||||
<div className="note">本次按“录错作废”撤销本单记账,不是实际退货退款。原单和冲回明细保留,不会向客户付款。</div>
|
||||
@@ -437,12 +441,12 @@ export function orderReviews(
|
||||
);
|
||||
}
|
||||
const requireOrderCancellationDetail = () => ({
|
||||
order: currentOrder,
|
||||
data: orderCancellationDetail.data,
|
||||
order: currentOrder!,
|
||||
data: orderCancellationDetail!.data!,
|
||||
});
|
||||
function showOrderCancellationForm(kind) {
|
||||
function showOrderCancellationForm(kind: string) {
|
||||
const { order, data } = requireOrderCancellationDetail(),
|
||||
request = data.pending;
|
||||
request = data.pending!;
|
||||
if (kind === 'request' && orderCancellationCanDirect(order)) kind = 'direct';
|
||||
if (
|
||||
['request', 'direct'].includes(kind) &&
|
||||
@@ -473,9 +477,9 @@ export function orderReviews(
|
||||
取消原因
|
||||
<textarea
|
||||
name="reason"
|
||||
rows="3"
|
||||
rows={3}
|
||||
required
|
||||
maxLength="200"
|
||||
maxLength={200}
|
||||
placeholder="写清这张单录错的原因,例如:同一笔销售重复录入。"
|
||||
></textarea>
|
||||
</label>
|
||||
@@ -498,9 +502,9 @@ export function orderReviews(
|
||||
取消原因
|
||||
<textarea
|
||||
name="reason"
|
||||
rows="3"
|
||||
rows={3}
|
||||
required
|
||||
maxLength="200"
|
||||
maxLength={200}
|
||||
placeholder="写清这张单录错的原因,例如:同一笔销售重复录入。"
|
||||
></textarea>
|
||||
</label>
|
||||
@@ -517,7 +521,7 @@ export function orderReviews(
|
||||
<p className="cancellation-reason">取消原因:{request.reason}</p>
|
||||
{orderCancellationSummaryHTML(request)}
|
||||
<label>
|
||||
复核备注(选填)<textarea name="note" maxLength="200" rows="2"></textarea>
|
||||
复核备注(选填)<textarea name="note" maxLength={200} rows={2}></textarea>
|
||||
</label>
|
||||
<label className="check">
|
||||
<input type="checkbox" name="verified" required />
|
||||
@@ -536,9 +540,9 @@ export function orderReviews(
|
||||
驳回意见
|
||||
<textarea
|
||||
name="note"
|
||||
rows="3"
|
||||
rows={3}
|
||||
required
|
||||
maxLength="200"
|
||||
maxLength={200}
|
||||
placeholder="写清需要补充或重新核对的地方。"
|
||||
></textarea>
|
||||
</label>
|
||||
@@ -573,12 +577,12 @@ export function orderReviews(
|
||||
);
|
||||
}
|
||||
const requireOrderOwnershipDetail = () => ({
|
||||
order: currentOrder,
|
||||
data: orderOwnershipDetail.data,
|
||||
order: currentOrder!,
|
||||
data: orderOwnershipDetail!.data!,
|
||||
});
|
||||
function showOrderOwnershipForm(kind = 'request') {
|
||||
const { order, data } = requireOrderOwnershipDetail(),
|
||||
request = data.pending;
|
||||
request = data.pending!;
|
||||
if (!['request', 'approve', 'reject'].includes(kind)) throw new Error('归属修改操作无效,请重新读取。');
|
||||
if (kind === 'request' && (!data.eligible || request)) throw new Error(data.reason || '本单当前不能重复修改归属。');
|
||||
if (kind !== 'request' && (state.user.role !== 'owner' || !data.canApprove || request?.status !== 'pending'))
|
||||
@@ -592,7 +596,7 @@ export function orderReviews(
|
||||
if (kind === 'request') {
|
||||
title = direct ? '修改订单归属' : '申请修改订单归属';
|
||||
submit = direct ? '确认修改归属' : '提交归属申请';
|
||||
const before = data.members.find(member => member.member === data.member),
|
||||
const before = data.members.find(member => member.member === data.member)!,
|
||||
members = data.members.filter(
|
||||
member => member.member !== data.member && member.enabled !== false && teamMemberEnabled(member.member),
|
||||
);
|
||||
@@ -609,7 +613,10 @@ export function orderReviews(
|
||||
<label>
|
||||
修改为
|
||||
<select name="member" required defaultValue="">
|
||||
{opts([['', '请选择新归属'], ...members.map(member => [member.member, member.label])])}
|
||||
{opts([
|
||||
['', '请选择新归属'],
|
||||
...members.map((member): [string, string] => [member.member, member.label]),
|
||||
])}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
@@ -622,8 +629,8 @@ export function orderReviews(
|
||||
<textarea
|
||||
name="reason"
|
||||
required
|
||||
maxLength="200"
|
||||
rows="3"
|
||||
maxLength={200}
|
||||
rows={3}
|
||||
placeholder="写清原归属录错的原因及正确归属。"
|
||||
></textarea>
|
||||
</label>
|
||||
@@ -647,7 +654,7 @@ export function orderReviews(
|
||||
<>
|
||||
{orderOwnershipEffectHTML(request.before.member)}
|
||||
<label>
|
||||
复核备注(选填)<textarea name="note" maxLength="200" rows="2"></textarea>
|
||||
复核备注(选填)<textarea name="note" maxLength={200} rows={2}></textarea>
|
||||
</label>
|
||||
<label className="check">
|
||||
<input type="checkbox" name="verified" required />
|
||||
@@ -662,8 +669,8 @@ export function orderReviews(
|
||||
<textarea
|
||||
name="note"
|
||||
required
|
||||
maxLength="200"
|
||||
rows="3"
|
||||
maxLength={200}
|
||||
rows={3}
|
||||
placeholder="写清需要重新核对的地方。"
|
||||
></textarea>
|
||||
</label>
|
||||
@@ -687,12 +694,12 @@ export function orderReviews(
|
||||
);
|
||||
}
|
||||
const requireOrderChangeDetail = () => ({
|
||||
order: currentOrder,
|
||||
data: orderChangeDetail.data,
|
||||
order: currentOrder!,
|
||||
data: orderChangeDetail!.data!,
|
||||
});
|
||||
function showOrderChangeForm(kind) {
|
||||
function showOrderChangeForm(kind: string) {
|
||||
const { order, data } = requireOrderChangeDetail(),
|
||||
request = data.pending;
|
||||
request = data.pending!;
|
||||
if (!['approve', 'reject'].includes(kind)) throw new Error('修改复核操作无效,请重新读取订单。');
|
||||
if (state.user.role !== 'owner' || !data.canApprove || request?.status !== 'pending')
|
||||
throw new Error('修改申请由店主账号复核。');
|
||||
@@ -716,7 +723,7 @@ export function orderReviews(
|
||||
{orderChangeActionSummaryHTML(request)}
|
||||
{orderChangeComparisonHTML(request)}
|
||||
<label>
|
||||
复核备注(选填)<textarea name="note" maxLength="200" rows="2"></textarea>
|
||||
复核备注(选填)<textarea name="note" maxLength={200} rows={2}></textarea>
|
||||
</label>
|
||||
<label className="check">
|
||||
<input type="checkbox" name="verified" required />
|
||||
@@ -732,8 +739,8 @@ export function orderReviews(
|
||||
<textarea
|
||||
name="note"
|
||||
required
|
||||
maxLength="200"
|
||||
rows="3"
|
||||
maxLength={200}
|
||||
rows={3}
|
||||
placeholder="写清需要重新核对或补充的地方。"
|
||||
></textarea>
|
||||
</label>
|
||||
+182
-136
@@ -1,3 +1,21 @@
|
||||
import type { ReactNode, ButtonHTMLAttributes, InputHTMLAttributes } from 'react';
|
||||
import type { OrderContext, Options } from '../viewTypes';
|
||||
import type {
|
||||
OrderRecord,
|
||||
OrderLine,
|
||||
OwnershipRequest,
|
||||
ChangeRequest,
|
||||
CancelSummary,
|
||||
Member,
|
||||
RelatedLock,
|
||||
LockImpact,
|
||||
InventoryRow,
|
||||
InventoryChange,
|
||||
LockCosts,
|
||||
OrderAfterSale,
|
||||
BookRow,
|
||||
PrintStatus,
|
||||
} from '../orderData';
|
||||
import { Children, Fragment } from 'react';
|
||||
import { Calc as LedgerCalc, Cards as CreditCardFees, Values } from '../../../shared';
|
||||
export function sharedViews({
|
||||
@@ -8,8 +26,11 @@ export function sharedViews({
|
||||
orderOwnershipDetail,
|
||||
orderCancellationDetail,
|
||||
ui = {},
|
||||
}) {
|
||||
function stockCountValue(value, { zero = false, optional = false, signed = false, title = '库存数量(对)' } = {}) {
|
||||
}: OrderContext) {
|
||||
function stockCountValue(
|
||||
value: unknown,
|
||||
{ zero = false, optional = false, signed = false, title = '库存数量(对)' } = {},
|
||||
) {
|
||||
const text = String(value ?? '').trim();
|
||||
if (!text && optional) return null;
|
||||
if (signed) {
|
||||
@@ -44,8 +65,8 @@ export function sharedViews({
|
||||
return Array.isArray(state?.pockets) ? state.pockets : defaultPocketKeys;
|
||||
}
|
||||
function stockCountField(
|
||||
pocket,
|
||||
value = '',
|
||||
pocket: string,
|
||||
value: string | number | null | undefined = '',
|
||||
{
|
||||
name = 'stockCount',
|
||||
title = '出库数量(对)',
|
||||
@@ -53,7 +74,7 @@ export function sharedViews({
|
||||
readOnly = false,
|
||||
visible = pocketCountsEnabled(pocket),
|
||||
help,
|
||||
} = {},
|
||||
}: { name?: string; title?: string; optional?: boolean; readOnly?: boolean; visible?: boolean; help?: string } = {},
|
||||
) {
|
||||
const hint = help ?? (optional ? '历史未记录对数,可保留空白;与计工费件数分别填写。' : '与计工费件数分别填写。');
|
||||
return (
|
||||
@@ -79,7 +100,7 @@ export function sharedViews({
|
||||
function currentMember() {
|
||||
return state?.user?.member || session?.user?.member || (state?.user?.role === 'owner' ? 'owner' : 'assistant');
|
||||
}
|
||||
function normalizePaymentAccount(account) {
|
||||
function normalizePaymentAccount(account: string) {
|
||||
return typeof CreditCardFees === 'object' && typeof CreditCardFees.normalizeAccount === 'function'
|
||||
? CreditCardFees.normalizeAccount(account)
|
||||
: ['助理信用卡', '助理1信用卡', '助理2信用卡', '麦麦信用卡'].includes(account)
|
||||
@@ -95,7 +116,7 @@ export function sharedViews({
|
||||
);
|
||||
if (assistantFirst)
|
||||
keys = [...keys.filter(member => member !== 'owner'), ...keys.filter(member => member === 'owner')];
|
||||
const options = keys.map(member => [
|
||||
const options = keys.map((member): [string, string] => [
|
||||
member,
|
||||
teamMemberName(member) + (historical && !teamMemberEnabled(member) ? '(已停用)' : ''),
|
||||
]);
|
||||
@@ -103,7 +124,7 @@ export function sharedViews({
|
||||
options.push([selected, teamMemberName(selected) + '(已停用 · 原记录)']);
|
||||
return options;
|
||||
}
|
||||
const choice = (title, name, values, selected) => {
|
||||
const choice = (title: string, name: string, values: Options, selected?: string) => {
|
||||
if (
|
||||
selected &&
|
||||
teamMemberKeys().includes(selected) &&
|
||||
@@ -121,19 +142,25 @@ export function sharedViews({
|
||||
</label>
|
||||
);
|
||||
};
|
||||
const moneyField = (title, name, value = '') =>
|
||||
const moneyField = (title: string, name: string, value: string | number = '') =>
|
||||
field(title, name, value, 'number', {
|
||||
min: '0',
|
||||
step: '0.01',
|
||||
required: true,
|
||||
});
|
||||
const field = (title, name, value = '', type = 'text', props = {}) => (
|
||||
const field = (
|
||||
title: string,
|
||||
name: string,
|
||||
value: string | number = '',
|
||||
type = 'text',
|
||||
props: InputHTMLAttributes<HTMLInputElement> = {},
|
||||
) => (
|
||||
<label>
|
||||
{title}
|
||||
<input type={type} name={name} defaultValue={value} {...props} />
|
||||
</label>
|
||||
);
|
||||
const opts = values =>
|
||||
const opts = (values: Options) =>
|
||||
values.map(v => {
|
||||
const [value, name, disabled] = Array.isArray(v) ? v : [v, v];
|
||||
return (
|
||||
@@ -142,10 +169,7 @@ export function sharedViews({
|
||||
</option>
|
||||
);
|
||||
});
|
||||
function teamMemberEnabled(member) {
|
||||
return Values.memberEnabled(state, member);
|
||||
}
|
||||
const actionName = {
|
||||
const actionName: Record<string, string> = {
|
||||
confirm: '确认订单',
|
||||
receipt: '登记收款',
|
||||
refund: '登记退款',
|
||||
@@ -161,7 +185,7 @@ export function sharedViews({
|
||||
correct: '更正流水',
|
||||
ownership: '修改订单归属',
|
||||
};
|
||||
function orderOwnershipEffectHTML(before) {
|
||||
function orderOwnershipEffectHTML(before: string) {
|
||||
return (
|
||||
<>
|
||||
<p className="small muted">
|
||||
@@ -177,11 +201,11 @@ export function sharedViews({
|
||||
</>
|
||||
);
|
||||
}
|
||||
function orderOwnershipTime(value) {
|
||||
const date = new Date(value);
|
||||
function orderOwnershipTime(value: string | null) {
|
||||
const date = new Date(value!);
|
||||
return Number.isNaN(date.getTime()) ? '时间未提供' : date.toLocaleString('zh-CN');
|
||||
}
|
||||
function validOrderOwnershipMember(value) {
|
||||
function validOrderOwnershipMember(value: Member) {
|
||||
return value && teamMemberKeys().includes(value.member) && typeof value.label === 'string' && !!value.label;
|
||||
}
|
||||
const orderOwnershipStatus = {
|
||||
@@ -189,7 +213,7 @@ export function sharedViews({
|
||||
approved: '已修改归属',
|
||||
rejected: '已驳回',
|
||||
};
|
||||
function validateOrderOwnershipRequest(request, orderId) {
|
||||
function validateOrderOwnershipRequest(request: OwnershipRequest, orderId: string | undefined = undefined) {
|
||||
if (
|
||||
!request ||
|
||||
typeof request.id !== 'string' ||
|
||||
@@ -211,7 +235,7 @@ export function sharedViews({
|
||||
throw new Error('归属修改资料未完整返回,请重新读取订单后复核。');
|
||||
return request;
|
||||
}
|
||||
function orderOwnershipPairHTML(request) {
|
||||
function orderOwnershipPairHTML(request: OwnershipRequest) {
|
||||
validateOrderOwnershipRequest(request);
|
||||
return (
|
||||
<div className="order-ownership-pair" aria-label="订单归属原值与新值">
|
||||
@@ -227,17 +251,17 @@ export function sharedViews({
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function relatedPriceLocksHTML(items) {
|
||||
function relatedPriceLocksHTML(items: RelatedLock[] | undefined) {
|
||||
const locks = validateRelatedPriceLocks(items);
|
||||
if (!locks.length) return '';
|
||||
const money = value => (value === null ? '待补齐' : '¥' + yuan(value)),
|
||||
sources = value =>
|
||||
const money = (value?: number | null) => (value === null ? '待补齐' : '¥' + yuan(value)),
|
||||
sources = (value: LockImpact) =>
|
||||
value.allocations.length
|
||||
? value.allocations.map(part => teamMemberName(part.payer) + ' ' + money(part.amount)).join(';')
|
||||
: value.materialAmount === null
|
||||
? '待补齐后分摊'
|
||||
: '无分摊金额';
|
||||
const pair = (name, before, after) => (
|
||||
const pair = (name: string, before: ReactNode, after: ReactNode) => (
|
||||
<tr>
|
||||
<th scope="row">{name}</th>
|
||||
<td>{before}</td>
|
||||
@@ -266,7 +290,7 @@ export function sharedViews({
|
||||
</thead>
|
||||
<tbody>
|
||||
{pair('原锁预留料费', money(lock.before.materialAmount), money(lock.after.materialAmount))}
|
||||
{['before', 'after'].some(side => Object.hasOwn(lock[side], 'usedMaterialAmount'))
|
||||
{(['before', 'after'] as const).some(side => Object.hasOwn(lock[side], 'usedMaterialAmount'))
|
||||
? pair(
|
||||
'交付耗用原锁料费',
|
||||
Object.hasOwn(lock.before, 'usedMaterialAmount')
|
||||
@@ -277,7 +301,7 @@ export function sharedViews({
|
||||
: '未交付',
|
||||
)
|
||||
: ''}
|
||||
{['before', 'after'].some(side => Object.hasOwn(lock[side], 'leftoverCost'))
|
||||
{(['before', 'after'] as const).some(side => Object.hasOwn(lock[side], 'leftoverCost'))
|
||||
? pair(
|
||||
'少重回池成本',
|
||||
Object.hasOwn(lock.before, 'leftoverCost') ? money(lock.before.leftoverCost) : '未交付',
|
||||
@@ -294,7 +318,7 @@ export function sharedViews({
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function inventoryCountHTML(item, { signed = false } = {}) {
|
||||
function inventoryCountHTML(item: InventoryRow, { signed = false } = {}) {
|
||||
return Number.isSafeInteger(item?.stockCount) ? (
|
||||
<div className="small stock-count-number">
|
||||
{stockCountText(item.stockCount, {
|
||||
@@ -307,9 +331,9 @@ export function sharedViews({
|
||||
''
|
||||
);
|
||||
}
|
||||
function orderChangeInventoryHTML(inventory) {
|
||||
function orderChangeInventoryHTML(inventory: InventoryChange | undefined) {
|
||||
if (!inventory) return '';
|
||||
const table = (title, rows, changes = false) => (
|
||||
const table = (title: string, rows: InventoryRow[], changes = false) => (
|
||||
<>
|
||||
<h3>{title}</h3>
|
||||
{rows.length ? (
|
||||
@@ -361,11 +385,11 @@ export function sharedViews({
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function orderChangeEffectiveExpenses(order) {
|
||||
function orderChangeEffectiveExpenses(order: OrderRecord) {
|
||||
const corrected = new Set((order.corrections || []).filter(row => row.type === 'expense').map(row => row.target));
|
||||
return order.expenses.filter(row => row.amount > 0 && !corrected.has(row.id));
|
||||
}
|
||||
function orderChangeExpensesValue(order) {
|
||||
function orderChangeExpensesValue(order: OrderRecord) {
|
||||
return (
|
||||
orderChangeEffectiveExpenses(order)
|
||||
.map(
|
||||
@@ -375,7 +399,7 @@ export function sharedViews({
|
||||
.join('\n\n') || '无已记费用'
|
||||
);
|
||||
}
|
||||
function orderChangePaymentsValue(order) {
|
||||
function orderChangePaymentsValue(order: OrderRecord) {
|
||||
const corrected = new Set((order.corrections || []).filter(row => row.type === 'payment').map(row => row.target));
|
||||
return (
|
||||
order.payments
|
||||
@@ -387,12 +411,16 @@ export function sharedViews({
|
||||
.join('\n\n') || '无有效收退款'
|
||||
);
|
||||
}
|
||||
function orderChangePriceLockCostsHTML(before, after, title = '锁价购料成本') {
|
||||
function orderChangePriceLockCostsHTML(
|
||||
before: { priceLockCosts?: LockCosts },
|
||||
after: { priceLockCosts?: LockCosts },
|
||||
title = '锁价购料成本',
|
||||
): ReactNode {
|
||||
if (!before.priceLockCosts && !after.priceLockCosts) return '';
|
||||
if (before.priceLockCosts?.lines || after.priceLockCosts?.lines) {
|
||||
const a = before.priceLockCosts || {},
|
||||
b = after.priceLockCosts || {},
|
||||
rows = a.lines || b.lines;
|
||||
rows = a.lines || b.lines!;
|
||||
return Children.toArray(
|
||||
rows.map((row, index) => {
|
||||
const left = a.lines?.find(item => item.lineId === row.lineId) || {},
|
||||
@@ -417,11 +445,11 @@ export function sharedViews({
|
||||
}
|
||||
const a = before.priceLockCosts || {},
|
||||
b = after.priceLockCosts || {},
|
||||
source = value => (value === 'pool' ? '原锁料池' : value === 'manual' ? '手填原锁料价' : '未提供');
|
||||
source = (value?: string) => (value === 'pool' ? '原锁料池' : value === 'manual' ? '手填原锁料价' : '未提供');
|
||||
return (
|
||||
<>
|
||||
<tr className="change-section-row">
|
||||
<th colSpan="3" scope="colgroup">
|
||||
<th colSpan={3} scope="colgroup">
|
||||
{title}
|
||||
</th>
|
||||
</tr>
|
||||
@@ -443,7 +471,7 @@ export function sharedViews({
|
||||
</>
|
||||
);
|
||||
}
|
||||
function orderChangeLineValue(line, kind) {
|
||||
function orderChangeLineValue(line: OrderLine | undefined, kind: string) {
|
||||
if (!line) return '无此商品';
|
||||
const money = orderChangeMoney;
|
||||
if (kind === 'name') return `${line.name || '未填写'}${line.priceNote ? '\n' + line.priceNote : ''}`;
|
||||
@@ -480,7 +508,7 @@ export function sharedViews({
|
||||
return `料费:${line.costMaterial?.mode === 'pool' ? line.materialPool?.allocations?.map(item => orderChangePayer(item.payer) + ' ' + money(item.amount)).join(';') || '按真实采购分摊' : orderChangePayer(line.costPayers?.material ?? line.payer)}\n进货工费:${orderChangePayer(line.costPayers?.labor ?? line.payer)}\n配件及其他:${orderChangePayer(line.payer)}`;
|
||||
return '';
|
||||
}
|
||||
function orderChangePair(title, before, after) {
|
||||
function orderChangePair(title: string, before: ReactNode, after: ReactNode) {
|
||||
const changed = String(before ?? '') !== String(after ?? '');
|
||||
return (
|
||||
<tr
|
||||
@@ -499,13 +527,15 @@ export function sharedViews({
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
function validateRelatedPriceLocks(items) {
|
||||
function validateRelatedPriceLocks(items: RelatedLock[] | undefined) {
|
||||
if (items === undefined) return [];
|
||||
const amount = value => value === null || (Number.isSafeInteger(value) && value >= 0);
|
||||
const snapshot = value =>
|
||||
const amount = (value?: number | null) => value === null || (Number.isSafeInteger(value) && value! >= 0);
|
||||
const snapshot = (value: LockImpact) =>
|
||||
value &&
|
||||
amount(value.materialAmount) &&
|
||||
['usedMaterialAmount', 'leftoverCost'].every(key => !Object.hasOwn(value, key) || amount(value[key])) &&
|
||||
(['usedMaterialAmount', 'leftoverCost'] as const).every(
|
||||
key => !Object.hasOwn(value, key) || amount(value[key]),
|
||||
) &&
|
||||
Array.isArray(value.allocations) &&
|
||||
value.allocations.every(
|
||||
part => teamMemberKeys().includes(part.payer) && Number.isSafeInteger(part.amount) && part.amount >= 0,
|
||||
@@ -527,15 +557,15 @@ export function sharedViews({
|
||||
throw new Error('关联锁价单的成本影响未完整返回,请重新读取后复核。');
|
||||
return items;
|
||||
}
|
||||
function validateOrderChangeRequest(request, orderId) {
|
||||
const validSnapshot = order =>
|
||||
function validateOrderChangeRequest(request: ChangeRequest, orderId: string | undefined = undefined) {
|
||||
const validSnapshot = (order: OrderRecord) =>
|
||||
order &&
|
||||
order.id === request.order_id &&
|
||||
Number.isSafeInteger(order.total) &&
|
||||
Array.isArray(order.lines) &&
|
||||
Array.isArray(order.expenses) &&
|
||||
Array.isArray(order.payments);
|
||||
const nullable = value => value === null || Number.isSafeInteger(value);
|
||||
const nullable = (value?: number | null) => value === null || Number.isSafeInteger(value);
|
||||
if (
|
||||
!request ||
|
||||
typeof request.id !== 'string' ||
|
||||
@@ -551,11 +581,13 @@ export function sharedViews({
|
||||
typeof request.canApprove !== 'boolean' ||
|
||||
!validSnapshot(request.before) ||
|
||||
!validSnapshot(request.after) ||
|
||||
!['before', 'after'].every(
|
||||
!(['before', 'after'] as const).every(
|
||||
side =>
|
||||
request.summary?.[side] &&
|
||||
['total', 'netReceived', 'directCost'].every(key => Number.isSafeInteger(request.summary[side][key])) &&
|
||||
['goodsCost', 'profit', 'settlementDue'].every(key => nullable(request.summary[side][key])),
|
||||
(['total', 'netReceived', 'directCost'] as const).every(key =>
|
||||
Number.isSafeInteger(request.summary[side][key]),
|
||||
) &&
|
||||
(['goodsCost', 'profit', 'settlementDue'] as const).every(key => nullable(request.summary[side][key])),
|
||||
)
|
||||
)
|
||||
throw new Error('修改申请资料未完整返回,请重新读取订单后复核。');
|
||||
@@ -579,7 +611,7 @@ export function sharedViews({
|
||||
if (
|
||||
inventory !== undefined &&
|
||||
(!inventory ||
|
||||
!['before', 'after', 'changes'].every(
|
||||
!(['before', 'after', 'changes'] as const).every(
|
||||
key =>
|
||||
Array.isArray(inventory[key]) &&
|
||||
inventory[key].every(
|
||||
@@ -590,7 +622,7 @@ export function sharedViews({
|
||||
throw new Error('变更申请库存摘要未完整返回,请重新读取后复核。');
|
||||
return request;
|
||||
}
|
||||
function orderChangeComparisonHTML(raw) {
|
||||
function orderChangeComparisonHTML(raw: ChangeRequest) {
|
||||
const request = validateOrderChangeRequest(raw),
|
||||
before = request.before,
|
||||
after = request.after;
|
||||
@@ -601,14 +633,16 @@ export function sharedViews({
|
||||
{
|
||||
<>
|
||||
{Children.toArray(
|
||||
[
|
||||
['业务日期', 'date'],
|
||||
['客户称呼/代号', 'customer'],
|
||||
['开单人', 'salesperson'],
|
||||
['收款方式与收款人', 'payment_account'],
|
||||
['客户单备注', 'note'],
|
||||
['内部备注(客户不可见)', 'internal_note'],
|
||||
].map(([title, key]) =>
|
||||
(
|
||||
[
|
||||
['业务日期', 'date'],
|
||||
['客户称呼/代号', 'customer'],
|
||||
['开单人', 'salesperson'],
|
||||
['收款方式与收款人', 'payment_account'],
|
||||
['客户单备注', 'note'],
|
||||
['内部备注(客户不可见)', 'internal_note'],
|
||||
] as const
|
||||
).map(([title, key]) =>
|
||||
orderChangePair(
|
||||
title,
|
||||
key === 'payment_account' ? accountDisplayName(before[key]) : before[key],
|
||||
@@ -630,14 +664,16 @@ export function sharedViews({
|
||||
</>
|
||||
);
|
||||
const summary = Children.toArray(
|
||||
[
|
||||
['成交金额', 'total'],
|
||||
['收款净额', 'netReceived'],
|
||||
['货品成本', 'goodsCost'],
|
||||
['实际费用合计', 'directCost'],
|
||||
['利润', 'profit'],
|
||||
['双方待结净额', 'settlementDue'],
|
||||
].map(([title, key]) =>
|
||||
(
|
||||
[
|
||||
['成交金额', 'total'],
|
||||
['收款净额', 'netReceived'],
|
||||
['货品成本', 'goodsCost'],
|
||||
['实际费用合计', 'directCost'],
|
||||
['利润', 'profit'],
|
||||
['双方待结净额', 'settlementDue'],
|
||||
] as const
|
||||
).map(([title, key]) =>
|
||||
orderChangePair(
|
||||
title,
|
||||
orderChangeMoney(request.summary.before[key]),
|
||||
@@ -653,7 +689,7 @@ export function sharedViews({
|
||||
(_, index) => (
|
||||
<>
|
||||
<tr className="change-section-row">
|
||||
<th colSpan="3" scope="colgroup">
|
||||
<th colSpan={3} scope="colgroup">
|
||||
商品 {index + 1}
|
||||
</th>
|
||||
</tr>
|
||||
@@ -726,7 +762,7 @@ export function sharedViews({
|
||||
{summary}
|
||||
{lines}
|
||||
<tr className="change-section-row">
|
||||
<th colSpan="3" scope="colgroup">
|
||||
<th colSpan={3} scope="colgroup">
|
||||
逐笔收退款与实际费用
|
||||
</th>
|
||||
</tr>
|
||||
@@ -752,7 +788,7 @@ export function sharedViews({
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function orderChangeCell(value) {
|
||||
function orderChangeCell(value: ReactNode) {
|
||||
return String(value == null || value === '' ? '未填写' : value)
|
||||
.split('\n')
|
||||
.map((line, index) => (
|
||||
@@ -762,58 +798,60 @@ export function sharedViews({
|
||||
</Fragment>
|
||||
));
|
||||
}
|
||||
function orderChangePayer(value) {
|
||||
function orderChangePayer(value: string | undefined) {
|
||||
return value ? teamMemberName(value) : '待补齐';
|
||||
}
|
||||
function orderChangeMoney(value) {
|
||||
function orderChangeMoney(value: number | null | undefined) {
|
||||
return value == null ? '待补齐' : '¥' + yuan(value);
|
||||
}
|
||||
function orderChangeInputMoney(value) {
|
||||
function orderChangeInputMoney(value: unknown) {
|
||||
try {
|
||||
return orderChangeMoney(LedgerCalc.cents(value));
|
||||
} catch {
|
||||
return '金额未提供';
|
||||
}
|
||||
}
|
||||
function stockCountText(value, { signed = false, unknown = '未记录对数' } = {}) {
|
||||
return Number.isSafeInteger(value) ? (signed && value > 0 ? '+' : '') + value + '对' : unknown;
|
||||
function stockCountText(value: unknown, { signed = false, unknown = '未记录对数' } = {}) {
|
||||
return Number.isSafeInteger(value) ? (signed && Number(value) > 0 ? '+' : '') + value + '对' : unknown;
|
||||
}
|
||||
function pocketCountsEnabled(key) {
|
||||
function pocketCountsEnabled(key: string) {
|
||||
return !!key && state?.pocketCatalog?.some(row => row.key === key && row.countUnit === 'pair') === true;
|
||||
}
|
||||
function pocketLabel(key) {
|
||||
function pocketLabel(key: string) {
|
||||
return state?.pocketCatalog?.find(row => row.key === key)?.name || String(key ?? '');
|
||||
}
|
||||
function validateOrderAfterSaleRecord(record) {
|
||||
function validateOrderAfterSaleRecord(record: OrderAfterSale | null) {
|
||||
if (
|
||||
!record ||
|
||||
!Array.isArray(record.lines) ||
|
||||
!record.lines.length ||
|
||||
!record.lines.every(line =>
|
||||
['quantity', 'materialReturnedCost', 'laborRestockedCost', 'costLoss'].every(key =>
|
||||
(['quantity', 'materialReturnedCost', 'laborRestockedCost', 'costLoss'] as const).every(key =>
|
||||
Number.isSafeInteger(line[key]),
|
||||
),
|
||||
) ||
|
||||
!record.summary ||
|
||||
![
|
||||
'refundAmount',
|
||||
'retainedAmount',
|
||||
'materialReturnedCost',
|
||||
'laborRestockedCost',
|
||||
'costLoss',
|
||||
'directCost',
|
||||
'profit',
|
||||
'profitAdjustment',
|
||||
].every(key => Number.isSafeInteger(record.summary[key]))
|
||||
!(
|
||||
[
|
||||
'refundAmount',
|
||||
'retainedAmount',
|
||||
'materialReturnedCost',
|
||||
'laborRestockedCost',
|
||||
'costLoss',
|
||||
'directCost',
|
||||
'profit',
|
||||
'profitAdjustment',
|
||||
] as const
|
||||
).every(key => Number.isSafeInteger(record.summary[key]))
|
||||
)
|
||||
throw new Error('售后核算资料未完整返回,请重新读取订单。');
|
||||
return record;
|
||||
}
|
||||
function orderAfterSaleSummaryHTML(raw, { preview = false } = {}) {
|
||||
function orderAfterSaleSummaryHTML(raw: OrderAfterSale | null, { preview = false } = {}) {
|
||||
const record = validateOrderAfterSaleRecord(raw),
|
||||
summary = record.summary,
|
||||
money = value => '¥' + yuan(value),
|
||||
facts = [
|
||||
money = (value: number) => '¥' + yuan(value),
|
||||
facts: [string, number][] = [
|
||||
['实际退款', summary.refundAmount],
|
||||
['扣留客户款', summary.retainedAmount],
|
||||
['回料池原料成本', summary.materialReturnedCost],
|
||||
@@ -893,7 +931,7 @@ export function sharedViews({
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function orderChangeActionSummaryHTML(request) {
|
||||
function orderChangeActionSummaryHTML(request: ChangeRequest) {
|
||||
const action = request.action || 'edit',
|
||||
input = request.action_input || request.action_details || {};
|
||||
if (action === 'edit') return '';
|
||||
@@ -964,8 +1002,8 @@ export function sharedViews({
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function orderChangeTime(value) {
|
||||
const date = new Date(value);
|
||||
function orderChangeTime(value: string | null) {
|
||||
const date = new Date(value!);
|
||||
return Number.isNaN(date.getTime()) ? '时间未提供' : date.toLocaleString('zh-CN');
|
||||
}
|
||||
const orderChangeStatus = {
|
||||
@@ -973,7 +1011,7 @@ export function sharedViews({
|
||||
approved: '已同意变更',
|
||||
rejected: '已驳回',
|
||||
};
|
||||
const orderChangeActionLabels = {
|
||||
const orderChangeActionLabels: Record<string, string> = {
|
||||
edit: '修改订单',
|
||||
expense: '费用补记',
|
||||
fees: '旧费用核实',
|
||||
@@ -981,7 +1019,7 @@ export function sharedViews({
|
||||
return: '退货',
|
||||
cost: '成本补录',
|
||||
};
|
||||
function orderChangeActionLabel(request) {
|
||||
function orderChangeActionLabel(request: ChangeRequest) {
|
||||
if ((request.action_input || request.action_details)?.afterSale) return '处理订单售后';
|
||||
return request.action_label || orderChangeActionLabels[request.action || 'edit'] || '订单变更';
|
||||
}
|
||||
@@ -990,20 +1028,20 @@ export function sharedViews({
|
||||
approved: '已同意取消',
|
||||
rejected: '已驳回',
|
||||
};
|
||||
function orderCancellationTime(value) {
|
||||
const date = new Date(value);
|
||||
function orderCancellationTime(value: string | null) {
|
||||
const date = new Date(value!);
|
||||
return Number.isNaN(date.getTime()) ? '时间未提供' : date.toLocaleString('zh-CN');
|
||||
}
|
||||
const accountIdentity = value => Values.accountIdentity(teamMemberKeys(), value);
|
||||
function accountDisplayName(value) {
|
||||
const accountIdentity = (value: string) => Values.accountIdentity(teamMemberKeys(), value);
|
||||
function accountDisplayName(value: string) {
|
||||
const account = accountIdentity(value);
|
||||
return account ? teamMemberName(account.member) + account.channel : value;
|
||||
}
|
||||
function validateOrderCancellationSummary(summary) {
|
||||
function validateOrderCancellationSummary(summary: CancelSummary | undefined) {
|
||||
if (
|
||||
!summary ||
|
||||
!['total', 'netReceived', 'directCost'].every(key => Number.isSafeInteger(summary[key])) ||
|
||||
!['goodsCost', 'profit', 'settlementDue'].every(
|
||||
!(['total', 'netReceived', 'directCost'] as const).every(key => Number.isSafeInteger(summary[key])) ||
|
||||
!(['goodsCost', 'profit', 'settlementDue'] as const).every(
|
||||
key => summary[key] === null || Number.isSafeInteger(summary[key]),
|
||||
) ||
|
||||
!Array.isArray(summary.inventory) ||
|
||||
@@ -1021,9 +1059,9 @@ export function sharedViews({
|
||||
data.pending ||
|
||||
data.directToday !== true ||
|
||||
!/^\d{4}-\d{2}-\d{2}$/.test(data.directActionDate || '') ||
|
||||
order.date !== data.directActionDate ||
|
||||
order.price_lock_id ||
|
||||
!['draft', 'confirmed', 'delivered'].includes(order.status)
|
||||
order?.date !== data.directActionDate ||
|
||||
order?.price_lock_id ||
|
||||
!['draft', 'confirmed', 'delivered'].includes(order?.status || '')
|
||||
)
|
||||
return false;
|
||||
try {
|
||||
@@ -1033,7 +1071,7 @@ export function sharedViews({
|
||||
return false;
|
||||
}
|
||||
}
|
||||
function orderActionCanDirect(kind, date = state.today, order = currentOrder) {
|
||||
function orderActionCanDirect(kind: string, date = state.today, order = currentOrder) {
|
||||
const data = currentOrderChange(order)?.data;
|
||||
return (
|
||||
['expense', 'fees', 'refund', 'return'].includes(kind) &&
|
||||
@@ -1041,18 +1079,18 @@ export function sharedViews({
|
||||
!data.pending &&
|
||||
/^\d{4}-\d{2}-\d{2}$/.test(data.directActionDate || '') &&
|
||||
data.actions?.[kind]?.directToday === true &&
|
||||
order.date === data.directActionDate &&
|
||||
order?.date === data.directActionDate &&
|
||||
date === data.directActionDate &&
|
||||
!(ui.action === kind && ui.forceApproval)
|
||||
);
|
||||
}
|
||||
function orderActionUsesChangeForm(kind) {
|
||||
function orderActionUsesChangeForm(kind: string) {
|
||||
return state.user.role === 'assistant' && ['expense', 'fees', 'refund', 'return', 'cost'].includes(kind);
|
||||
}
|
||||
function orderActionRequiresApproval(kind, date = state.today) {
|
||||
function orderActionRequiresApproval(kind: string, date = state.today) {
|
||||
return orderActionUsesChangeForm(kind) && !orderActionCanDirect(kind, date);
|
||||
}
|
||||
function orderAfterSaleRecord(order) {
|
||||
function orderAfterSaleRecord(order: OrderRecord | undefined) {
|
||||
return order?.orderAfterSale || null;
|
||||
}
|
||||
function orderOwnershipUser() {
|
||||
@@ -1080,7 +1118,7 @@ export function sharedViews({
|
||||
? orderChangeDetail
|
||||
: null;
|
||||
}
|
||||
function orderChangePending(order) {
|
||||
function orderChangePending(order: OrderRecord) {
|
||||
return currentOrderChange(order)?.data?.pending || order?.changePending || null;
|
||||
}
|
||||
function orderCancellationUser() {
|
||||
@@ -1094,11 +1132,11 @@ export function sharedViews({
|
||||
? orderCancellationDetail
|
||||
: null;
|
||||
}
|
||||
function orderCancellationPending(order) {
|
||||
function orderCancellationPending(order: OrderRecord) {
|
||||
return currentOrderCancellation(order)?.data?.pending || order.cancellationPending || null;
|
||||
}
|
||||
function printStatusBadge(value) {
|
||||
if (['afterSale', 'orderAfterSale'].includes(value.kind)) return '';
|
||||
function printStatusBadge(value: { id: string; kind?: string; printStatus?: PrintStatus }) {
|
||||
if (['afterSale', 'orderAfterSale'].includes(value.kind ?? '')) return '';
|
||||
const printed = value.printStatus?.printed;
|
||||
return (
|
||||
<span
|
||||
@@ -1112,7 +1150,7 @@ export function sharedViews({
|
||||
);
|
||||
}
|
||||
const grams = Values.grams;
|
||||
const e = value => String(value ?? '');
|
||||
const e = (value: unknown) => String(value ?? '');
|
||||
const showOrderCopyEntry = false;
|
||||
const orderEntryTimeFormatter = new Intl.DateTimeFormat('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
@@ -1124,7 +1162,7 @@ export function sharedViews({
|
||||
hourCycle: 'h23',
|
||||
});
|
||||
const validOrderDate = Values.validDate;
|
||||
function orderEntryTime(value) {
|
||||
function orderEntryTime(value: unknown) {
|
||||
if (
|
||||
typeof value !== 'string' ||
|
||||
!/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,3})?)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.test(
|
||||
@@ -1133,23 +1171,23 @@ export function sharedViews({
|
||||
!validOrderDate(value.slice(0, 10))
|
||||
)
|
||||
return '未记录';
|
||||
const date = new Date(value);
|
||||
const date = new Date(value!);
|
||||
if (Number.isNaN(date.getTime())) return '未记录';
|
||||
const parts = Object.fromEntries(orderEntryTimeFormatter.formatToParts(date).map(part => [part.type, part.value]));
|
||||
return `${parts.year}-${parts.month}-${parts.day} ${parts.hour}:${parts.minute}`;
|
||||
}
|
||||
function orderEntryTimeHTML(order) {
|
||||
function orderEntryTimeHTML(order: { created: string }) {
|
||||
return <div className="small muted order-entry-time">录入时间(北京时间):{orderEntryTime(order.created)}</div>;
|
||||
}
|
||||
function orderIsReviewed(row) {
|
||||
function orderIsReviewed(row: Pick<BookRow, 'kind' | 'revision' | 'reviewed_revision'>) {
|
||||
return (
|
||||
!['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind) &&
|
||||
!['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind ?? '') &&
|
||||
Number.isSafeInteger(row.revision) &&
|
||||
row.revision > 0 &&
|
||||
row.revision! > 0 &&
|
||||
row.reviewed_revision === row.revision
|
||||
);
|
||||
}
|
||||
const label = {
|
||||
const label: Record<string, string> = {
|
||||
draft: '旧草稿',
|
||||
confirmed: '旧单待补齐',
|
||||
delivered: '已完成',
|
||||
@@ -1158,36 +1196,44 @@ export function sharedViews({
|
||||
after_sale: '售后',
|
||||
recovery: '回收',
|
||||
};
|
||||
const badge = o => (
|
||||
const badge = (o: { status: string }) => (
|
||||
<span className={'order-status ' + (['draft', 'confirmed'].includes(o.status) ? 'danger-text' : 'muted')}>
|
||||
{label[o.status] || o.status}
|
||||
</span>
|
||||
);
|
||||
const button = (text, action, cls = '', props = {}) => (
|
||||
const button = (
|
||||
text: ReactNode,
|
||||
action: string,
|
||||
cls = '',
|
||||
props: ButtonHTMLAttributes<HTMLButtonElement> & {
|
||||
[key: `data-${string}`]: string | number | boolean | undefined;
|
||||
} = {},
|
||||
) => (
|
||||
<button type="button" data-action={action} className={cls} {...props}>
|
||||
{text}
|
||||
</button>
|
||||
);
|
||||
function teamMemberName(member) {
|
||||
function teamMemberName(member: string | undefined) {
|
||||
return (
|
||||
state?.shopSettings?.members?.find(row => row.member === member)?.label ||
|
||||
state?.members?.find(row => row.member === member)?.label ||
|
||||
session?.loginOptions?.find(row => row.member === member)?.label ||
|
||||
{
|
||||
owner: '麦麦',
|
||||
assistant: '娜娜',
|
||||
assistant2: '小昊',
|
||||
}[member] ||
|
||||
(
|
||||
{
|
||||
owner: '麦麦',
|
||||
assistant: '娜娜',
|
||||
assistant2: '小昊',
|
||||
} as Record<string, string>
|
||||
)[member ?? ''] ||
|
||||
'待确认'
|
||||
);
|
||||
}
|
||||
function teamMemberKeys() {
|
||||
return Values.memberKeys(state);
|
||||
}
|
||||
const teamMemberKeys = () => Values.memberKeys(state);
|
||||
const teamMemberEnabled = (member: string) => Values.memberEnabled(state, member);
|
||||
function teamMode() {
|
||||
return !!(state?.user?.member || state?.members?.some(member => member.member === 'assistant2'));
|
||||
}
|
||||
const yuan = n => (n == null ? '待补' : Values.yuan(n));
|
||||
const yuan = (n?: number | null) => (n == null ? '待补' : Values.yuan(n));
|
||||
return {
|
||||
yuan,
|
||||
teamMode,
|
||||
Reference in new issue
Block a user