第5项:按页面管理导航、历史草稿与操作回执
This commit is contained in:
1 parent
f570929cfe
commit
ff8b05973a
48 files changed
+1577
-574
No files matched your search
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Alert, App as AntApp, Button, Popconfirm, Spin, Typography } from 'antd';
|
||||
import { ClearOutlined } from '@ant-design/icons';
|
||||
import type { ApiError, LedgerClient, PendingJob } from '../../lib/api';
|
||||
import { clearDraft, clearIssuedDraft, loadDraft, saveDraft } from '../../lib/drafts';
|
||||
import { clearDraft, clearIssuedDraft, loadDraft, saveDraft } from './drafts';
|
||||
import { navigate, pathFor, searchParam } from '../../lib/router';
|
||||
import { useClientSnapshot } from '../../lib/useClient';
|
||||
import { Model } from '../../shared';
|
||||
@@ -175,7 +175,7 @@ function CreateOrderForm({
|
||||
throw new Error('已有草稿由店主继续填写并开单;无单号的新开单流程照常使用。');
|
||||
awaitingIssue.current = true;
|
||||
const result = await client.mutate<{ id: string }>('/api/orders/issue', draft);
|
||||
clearIssuedDraft(window.localStorage, state.user.id, draft);
|
||||
clearIssuedDraft(window.localStorage, state.user.id, { data: draft });
|
||||
await finishIssued(draft.customer, result);
|
||||
} catch (err) {
|
||||
awaitingIssue.current = false;
|
||||
@@ -189,7 +189,7 @@ function CreateOrderForm({
|
||||
awaitingIssue.current = true;
|
||||
const recovered = await client.retryPending<{ id?: string }>();
|
||||
if (recovered?.result.id && job.url === '/api/orders/issue') {
|
||||
clearIssuedDraft(window.localStorage, state.user.id, recovered.job.data);
|
||||
clearIssuedDraft(window.localStorage, state.user.id, recovered.job);
|
||||
return await finishIssued((recovered.job.data as OrderDraft).customer, { id: recovered.result.id });
|
||||
}
|
||||
awaitingIssue.current = false;
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import type { PendingJob } from '../../lib/api';
|
||||
import {
|
||||
clearRecovered,
|
||||
detailTarget,
|
||||
matchesLegacyDraft,
|
||||
record,
|
||||
type ReceiptHandler,
|
||||
type StorageLike,
|
||||
} from '../../lib/receipt';
|
||||
export const draftKey = (user: string) => 'mm-next-draft-' + user;
|
||||
const oldKey = (user: string) => 'mm-draft-' + user;
|
||||
const importedKey = (user: string) => 'mm-next-draft-imported-' + user;
|
||||
function readOrder(raw: string | null): Record<string, unknown> | null {
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const draft: unknown = JSON.parse(raw);
|
||||
return record(draft) && Array.isArray(draft.lines) ? draft : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
export function loadDraft(storage: StorageLike, user: string) {
|
||||
try {
|
||||
const current = storage.getItem(draftKey(user));
|
||||
if (current !== null) return readOrder(current);
|
||||
const legacy = storage.getItem(oldKey(user));
|
||||
if (!legacy || legacy === storage.getItem(importedKey(user))) return null;
|
||||
const draft = readOrder(legacy);
|
||||
if (draft) {
|
||||
storage.setItem(draftKey(user), legacy);
|
||||
storage.setItem(importedKey(user), legacy);
|
||||
}
|
||||
return draft;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
export function saveDraft(storage: StorageLike, user: string, draft: unknown) {
|
||||
try {
|
||||
storage.setItem(draftKey(user), JSON.stringify(draft));
|
||||
} catch {
|
||||
/* 存储空间不足时仍可开单。 */
|
||||
}
|
||||
}
|
||||
export function clearDraft(storage: StorageLike, user: string) {
|
||||
try {
|
||||
storage.removeItem(draftKey(user));
|
||||
} catch {
|
||||
/* 存储被浏览器禁用时仍可开始下一单。 */
|
||||
}
|
||||
}
|
||||
function identityInput(draft: Record<string, unknown>) {
|
||||
if (!Array.isArray(draft.lines)) return;
|
||||
const input = { ...draft };
|
||||
for (const k of ['customer', 'salesperson', 'internal_note'])
|
||||
if (typeof input[k] === 'string') input[k] = input[k].trim();
|
||||
return input;
|
||||
}
|
||||
export function clearIssuedDraft(storage: StorageLike, user: string, job: Pick<PendingJob, 'data' | 'draft'>) {
|
||||
clearRecovered(storage, draftKey(user), job, identityInput);
|
||||
// 旧版提交可能尚未在新版打开。已确认的原草稿不应被下一次打开自动导入。
|
||||
const legacy = storage.getItem(oldKey(user));
|
||||
if (legacy && matchesLegacyDraft(legacy, job.data, identityInput)) storage.setItem(importedKey(user), legacy);
|
||||
}
|
||||
export const issueReceipt: ReceiptHandler = {
|
||||
accepts: url => url === '/api/orders/issue',
|
||||
finish: ({ job, result, state, storage }) => {
|
||||
const target = detailTarget('orders', 'order', result.order_id || result.id);
|
||||
if (target.route) clearIssuedDraft(storage, state.user.id, job);
|
||||
return target;
|
||||
},
|
||||
};
|
||||
|
||||
export const templateReceipt: ReceiptHandler = {
|
||||
accepts: url => /^\/api\/order-templates(?:\/[^/]+\/(?:update|delete))?$/.test(url),
|
||||
finish: ({ job }) => ({
|
||||
message: job.url.endsWith('/delete') ? '模板已删除,当前开单内容保留' : '模板已保存,当前开单内容保留',
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
import { record, type ReceiptHandler } from '../../lib/receipt';
|
||||
export const inventoryReceipt: ReceiptHandler = {
|
||||
accepts: url =>
|
||||
/^\/api\/inventory\/(?:movements\/[^/]+\/(?:update|delete)|changes\/[^/]+\/(?:approve|reject))$/.test(url),
|
||||
finish: ({ job, result }) => ({
|
||||
route: 'stock',
|
||||
message: job.url.endsWith('/reject')
|
||||
? '库存申请已驳回,库存未改变'
|
||||
: result.pending && !result.applied
|
||||
? '库存申请已提交,等待店主审批;库存未改变'
|
||||
: job.url.endsWith('/delete') || (record(result.request) && result.request.action === 'delete')
|
||||
? '库存记录已删除'
|
||||
: '库存记录已修改',
|
||||
}),
|
||||
};
|
||||
@@ -1,3 +1,5 @@
|
||||
import { saveWithDraft, record } from '../../lib/receipt';
|
||||
import { purchaseDraftKey, materialReceipt, materialMessage } from './receipts';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { type LedgerClient, type ApiError } from '../../lib/api';
|
||||
import { useClientSnapshot } from '../../lib/useClient';
|
||||
@@ -7,7 +9,6 @@ import { PoolList, RollingSummary } from './PoolTables';
|
||||
import { PurchaseForm, PurchaseChange, Settlement } from './PurchaseForms';
|
||||
import { ChangePanel, EnableForm, ReviewForm } from './Review';
|
||||
import {
|
||||
draftKey,
|
||||
validatePools,
|
||||
validatePurchaseResponse,
|
||||
validateEnable,
|
||||
@@ -304,24 +305,12 @@ export function MaterialPoolsPage({ client, state, onState, onRecoverOther }: Pr
|
||||
const create = url === '/api/material-purchases',
|
||||
action = url.split('/').at(-1),
|
||||
settlement = action === 'settlement';
|
||||
if (create) localStorage.removeItem(draftKey(state));
|
||||
if (!mounted.current) return;
|
||||
if (create) resetDraft(n => n + 1);
|
||||
if (create || action === 'edit' || action === 'delete')
|
||||
setOpenDate(result.poolId || result.previousPoolId || String(input.date || ''));
|
||||
if (settlement) setOpenDate(decodeURIComponent(url.split('/')[3]));
|
||||
const title = create
|
||||
? '购料已保存'
|
||||
: settlement
|
||||
? '本批料款交款已保存'
|
||||
: {
|
||||
edit: '购料修改已保存',
|
||||
delete: '购料已删除',
|
||||
change: '购料更正申请已提交',
|
||||
'rolling-enable': '跨日结转已启用',
|
||||
approve: '购料更正已批准',
|
||||
reject: '购料更正申请已驳回',
|
||||
}[action || ''] || '原操作已确认';
|
||||
const title = materialMessage(url);
|
||||
setSaved(title);
|
||||
setNotice('');
|
||||
setSavedFailure(false);
|
||||
@@ -339,19 +328,29 @@ export function MaterialPoolsPage({ client, state, onState, onRecoverOther }: Pr
|
||||
}
|
||||
}
|
||||
const save: Save = async (url, input) => {
|
||||
const result = await client.mutate<WriteResult>(url, input);
|
||||
const result =
|
||||
url === '/api/material-purchases'
|
||||
? await saveWithDraft<WriteResult>(client, url, input, {
|
||||
key: purchaseDraftKey(state.user.id),
|
||||
value: JSON.stringify(input),
|
||||
})
|
||||
: await client.mutate<WriteResult>(url, input);
|
||||
await confirmed(url, input, result);
|
||||
};
|
||||
async function retry() {
|
||||
const job = client.pending();
|
||||
if (
|
||||
job &&
|
||||
!/^\/api\/(?:material-purchases|material-pools|material-purchase-changes)(?:\/|$)/.test(job.url) &&
|
||||
onRecoverOther
|
||||
)
|
||||
return onRecoverOther();
|
||||
if (job && !materialReceipt.accepts(job.url) && onRecoverOther) return onRecoverOther();
|
||||
const recovered = await client.retryPending<WriteResult>();
|
||||
if (recovered) await confirmed(recovered.job.url, recovered.job.data as Record<string, unknown>, recovered.result);
|
||||
if (recovered && record(recovered.job.data)) {
|
||||
materialReceipt.finish({
|
||||
client,
|
||||
state,
|
||||
storage: localStorage,
|
||||
job: recovered.job,
|
||||
result: { ...recovered.result },
|
||||
});
|
||||
await confirmed(recovered.job.url, recovered.job.data, recovered.result);
|
||||
}
|
||||
}
|
||||
function open(spec: DialogSpec) {
|
||||
if (client.pending() || client.busy) {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { purchaseDraftKey } from './receipts';
|
||||
import { useState } from 'react';
|
||||
import type { FormEvent, ReactNode } from 'react';
|
||||
import { Calc, Model, type LedgerState } from '../../shared';
|
||||
import { grams, yuan } from '../../lib/format';
|
||||
import {
|
||||
draftKey,
|
||||
money,
|
||||
purchaseInput,
|
||||
validatePurchaseInput,
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
function initialDraft(state: LedgerState) {
|
||||
let saved: Record<string, unknown> | null;
|
||||
try {
|
||||
saved = JSON.parse(localStorage.getItem(draftKey(state)) || 'null');
|
||||
saved = JSON.parse(localStorage.getItem(purchaseDraftKey(state.user.id)) || 'null');
|
||||
} catch {
|
||||
saved = null;
|
||||
}
|
||||
@@ -110,7 +110,10 @@ export function PurchaseForm({
|
||||
const [draft] = useState(() => initialDraft(state)),
|
||||
[error, setError] = useState('');
|
||||
function remember(form: HTMLFormElement) {
|
||||
localStorage.setItem(draftKey(state), JSON.stringify(purchaseInput(Object.fromEntries(new FormData(form)))));
|
||||
localStorage.setItem(
|
||||
purchaseDraftKey(state.user.id),
|
||||
JSON.stringify(purchaseInput(Object.fromEntries(new FormData(form)))),
|
||||
);
|
||||
}
|
||||
async function submit(e: FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -317,7 +317,3 @@ export interface WriteResult {
|
||||
previousPoolId?: string;
|
||||
}
|
||||
export type Save = (url: string, data: Record<string, unknown>) => Promise<void>;
|
||||
|
||||
export function draftKey(state: LedgerState) {
|
||||
return 'mm-material-purchase-' + state.user.id;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { clearRecovered, detailTarget, record, type ReceiptHandler } from '../../lib/receipt';
|
||||
import { purchaseInput } from './model';
|
||||
export const purchaseDraftKey = (user: string) => 'mm-material-purchase-' + user;
|
||||
export const materialReceipt: ReceiptHandler = {
|
||||
accepts: url => /^\/api\/(?:material-purchases|material-pools|material-purchase-changes)(?:\/|$)/.test(url),
|
||||
finish: ({ job, result, state, storage }) => {
|
||||
const action = job.url.split('/').at(-1),
|
||||
data = record(job.data) ? job.data : {};
|
||||
if (job.url === '/api/material-purchases')
|
||||
clearRecovered(storage, purchaseDraftKey(state.user.id), job, purchaseInput);
|
||||
const day =
|
||||
action === 'settlement'
|
||||
? decodeURIComponent(job.url.split('/')[3])
|
||||
: result.poolId || result.previousPoolId || data.date;
|
||||
return {
|
||||
route: 'material-pools',
|
||||
...detailTarget('material-pools', 'pool', day),
|
||||
message: materialMessage(job.url),
|
||||
};
|
||||
},
|
||||
};
|
||||
export function materialMessage(url: string) {
|
||||
const messages: Record<string, string> = {
|
||||
settlement: '本批料款交款已保存',
|
||||
edit: '购料修改已保存',
|
||||
delete: '购料已删除',
|
||||
change: '购料更正申请已提交',
|
||||
'rolling-enable': '跨日结转已启用',
|
||||
approve: '购料更正已批准',
|
||||
reject: '购料更正申请已驳回',
|
||||
};
|
||||
return url === '/api/material-purchases' ? '购料已保存' : messages[url.split('/').at(-1) || ''] || '原操作已确认';
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { activeOrderEditKey, orderEditKey } from './receipts';
|
||||
import { saveWithDraft } from '../../lib/receipt';
|
||||
import { useOrderAccess, ownershipNoticeKey } from './useOrderAccess';
|
||||
import { useCallback, useEffect, useEffectEvent, useRef, useState } from 'react';
|
||||
import type { ReactNode, FormEvent, ComponentType } from 'react';
|
||||
@@ -204,9 +206,9 @@ function ConflictPanel({
|
||||
}
|
||||
|
||||
export function OrderEditPage({ client, state, session, refreshState, registerLeaveGuard, LockEditor }: PageProps) {
|
||||
const activeKey = 'mm-order-edit-active-' + state.user.id;
|
||||
const activeKey = activeOrderEditKey(state.user.id);
|
||||
const id = searchParam('order') || searchParam('id') || localStorage.getItem(activeKey) || '';
|
||||
const key = 'mm-order-edit-' + state.user.id + '-' + id;
|
||||
const key = orderEditKey(state.user.id, id);
|
||||
const [entry, setEntry] = useState<EditEntry | null>(null),
|
||||
[epoch, reset] = useState(0),
|
||||
[error, setError] = useState(''),
|
||||
@@ -214,10 +216,12 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
||||
[reading, setReading] = useState(false);
|
||||
const live = useRef(false),
|
||||
generation = useRef(0);
|
||||
const ownDraft = useRef<string | undefined>(undefined);
|
||||
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 }));
|
||||
ownDraft.current = JSON.stringify({ id, revision: inputs.revision, inputs, reason, verified });
|
||||
localStorage.setItem(key, ownDraft.current);
|
||||
localStorage.setItem(activeKey, id);
|
||||
},
|
||||
[id, key, activeKey, client, state.user.id],
|
||||
@@ -281,9 +285,10 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
||||
return () => {
|
||||
disposed = true;
|
||||
cancelRead();
|
||||
if (localStorage.getItem(activeKey) === id) localStorage.removeItem(activeKey);
|
||||
if (localStorage.getItem(activeKey) === id && localStorage.getItem(key) === ownDraft.current)
|
||||
localStorage.removeItem(activeKey);
|
||||
};
|
||||
}, [id, activeKey]);
|
||||
}, [id, activeKey, key]);
|
||||
const go = () => navigate('orders', { search: '?order=' + encodeURIComponent(id) });
|
||||
async function save(inputs: EditPayload, reason: string, verified: boolean, approval: boolean) {
|
||||
if (!entry) return;
|
||||
@@ -291,12 +296,15 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
||||
if (entry.conflicted) throw new Error('订单已有新记录,请先读取最新订单并核对,填写内容已经保留。');
|
||||
if (!reason.trim() || reason.trim().length > 200) throw new Error('请填写1~200字的修改原因。');
|
||||
if (!verified) throw new Error('请先核实本次资料更正,并勾选确认。');
|
||||
await client.mutate('/api/orders/' + encodeURIComponent(id) + (approval ? '/change' : '/edit'), {
|
||||
const url = '/api/orders/' + encodeURIComponent(id) + (approval ? '/change' : '/edit');
|
||||
const payload = {
|
||||
...inputs,
|
||||
revision: entry.revision,
|
||||
reason: reason.trim(),
|
||||
verified: true,
|
||||
});
|
||||
};
|
||||
if (ownDraft.current !== undefined) await saveWithDraft(client, url, payload, { key, value: ownDraft.current });
|
||||
else await client.mutate(url, payload);
|
||||
} catch (err) {
|
||||
if (!active() || (await checkFailure(err)) || !active()) return;
|
||||
let message = errorMessage(err).replace('不要重新开单', '不要重复保存修改');
|
||||
@@ -322,8 +330,8 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
|
||||
}
|
||||
if (!active()) return;
|
||||
live.current = false;
|
||||
localStorage.removeItem(key);
|
||||
localStorage.removeItem(activeKey);
|
||||
if (localStorage.getItem(key) === null && localStorage.getItem(activeKey) === id)
|
||||
localStorage.removeItem(activeKey);
|
||||
if (approval) navigate('orders', { search: '?order=' + encodeURIComponent(id), fromPage: true });
|
||||
else {
|
||||
setSuccess(true);
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { clearRecovered, detailTarget, record, type ReceiptHandler } from '../../lib/receipt';
|
||||
export const orderEditKey = (user: string, id: string) => `mm-order-edit-${user}-${id}`;
|
||||
export const activeOrderEditKey = (user: string) => 'mm-order-edit-active-' + user;
|
||||
export const orderReceipt: ReceiptHandler = {
|
||||
accepts: url =>
|
||||
/^\/api\/(?:orders\/[^/]+\/|order-(?:changes|cancellations|ownership-changes)\/)/.test(url) &&
|
||||
!url.endsWith('/issue'),
|
||||
finish: ({ job, result, state, storage }) => {
|
||||
const path = job.url.split('/'),
|
||||
direct = path[2] === 'orders',
|
||||
id = direct
|
||||
? decodeURIComponent(path[3])
|
||||
: result.order_id || (record(result.order) && result.order.id) || result.id;
|
||||
const data = record(job.data) ? job.data : {};
|
||||
if (typeof id === 'string' && direct && (path[4] === 'edit' || (path[4] === 'change' && !data.action))) {
|
||||
const cleared = clearRecovered(storage, orderEditKey(state.user.id, id), job, d =>
|
||||
d.id === id && record(d.inputs)
|
||||
? {
|
||||
...d.inputs,
|
||||
revision: d.revision,
|
||||
reason: typeof d.reason === 'string' ? d.reason.trim() : d.reason,
|
||||
verified: true,
|
||||
}
|
||||
: undefined,
|
||||
);
|
||||
const active = activeOrderEditKey(state.user.id);
|
||||
if (cleared && storage.getItem(active) === id) storage.removeItem(active);
|
||||
}
|
||||
return detailTarget('orders', 'order', id);
|
||||
},
|
||||
};
|
||||
|
||||
export const afterSaleReceipt: ReceiptHandler = {
|
||||
accepts: url => /^\/api\/after-sales(?:\/|$)/.test(url),
|
||||
finish: ({ job, result }) => {
|
||||
const action = job.url.split('/').at(-1),
|
||||
data = record(job.data) ? job.data : {};
|
||||
if (action === 'update')
|
||||
return { message: result.applied === true ? '售后修改已保存' : '售后修改申请已提交,待店主审批' };
|
||||
if (action === 'approve' || action === 'reject')
|
||||
return { message: action === 'approve' ? '已同意售后修改' : '已驳回售后修改申请' };
|
||||
return {
|
||||
message: typeof data.date === 'string' ? '售后已保存,已计入 ' + data.date + ' 的费用与利润' : '售后已保存',
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -1,3 +1,4 @@
|
||||
import { activeOrderEditKey, orderEditKey } from './receipts';
|
||||
import { useCallback, useEffect, useRef } from 'react';
|
||||
|
||||
import type { LedgerState } from '../../shared';
|
||||
@@ -39,8 +40,8 @@ export function useOrderAccess({ client, state, id, watch, onLost }: OrderAccess
|
||||
(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);
|
||||
const active = 'mm-order-edit-active-' + user;
|
||||
localStorage.removeItem(orderEditKey(user, id));
|
||||
const active = activeOrderEditKey(user);
|
||||
if (localStorage.getItem(active) === id) localStorage.removeItem(active);
|
||||
scope.current = null;
|
||||
lost.current(ownershipNotice);
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { PageContext } from './registry';
|
||||
import { OrdersPage } from './Orders/OrdersPage';
|
||||
import { createContext, useContext, useState, type ReactNode } from 'react';
|
||||
// 独立售后的列表筛选由同次登录的各订单页共用,重新登录后复位。
|
||||
const filter = createContext<{ saleListStatus: string; setSaleListStatus: (value: string) => void } | null>(null);
|
||||
export function PageSession({ children }: { children: ReactNode }) {
|
||||
const [saleListStatus, setSaleListStatus] = useState('pending');
|
||||
return <filter.Provider value={{ saleListStatus, setSaleListStatus }}>{children}</filter.Provider>;
|
||||
}
|
||||
export function OrdersRoute(c: PageContext) {
|
||||
const current = useContext(filter);
|
||||
if (!current) throw new Error('订单页面会话尚未初始化');
|
||||
return <OrdersPage {...c} {...current} />;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { savedCreate } from './draftInput';
|
||||
import { lockEditKey, lockDraftKey } from './receipts';
|
||||
import type { FormEvent } from 'react';
|
||||
import type { LedgerState, SessionInfo } from '../../shared';
|
||||
import type { LockPayment } from './formParts';
|
||||
@@ -180,9 +181,7 @@ export function LockCreate({
|
||||
blocked,
|
||||
reset,
|
||||
}: LockProps & { views: LockViews; edit: LockEdit | null; save: SaveLock; blocked: boolean; reset: () => void }) {
|
||||
const key = edit
|
||||
? 'mm-price-lock-edit-' + state.user.id + '-' + edit.lock.id
|
||||
: 'mm-price-lock-draft-' + state.user.id;
|
||||
const key = edit ? lockEditKey(state.user.id, edit.lock.id) : lockDraftKey(state.user.id);
|
||||
const [d, set] = useState(() => initial(state, session, edit, key)),
|
||||
[verified, setVerified] = useState(false),
|
||||
[error, setError] = useState('');
|
||||
@@ -293,7 +292,7 @@ export function LockCreate({
|
||||
...(approval ? { action: 'edit' } : {}),
|
||||
});
|
||||
}
|
||||
await save(url, input);
|
||||
await save(url, input, { key, value: stored });
|
||||
} catch (err) {
|
||||
if (edit && err instanceof Error && 'status' in err && err.status === 409) {
|
||||
set(prev => ({ ...prev, conflicted: true }));
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { savedDelivery } from './draftInput';
|
||||
import { lockDeliveryKey } from './receipts';
|
||||
import type { FormEvent } from 'react';
|
||||
import type { OrderForm, SyncContext } from '../../shared';
|
||||
import type { LockRecord, LockProps, LockViews, SaveLock, DeliveryCost } from './types';
|
||||
@@ -88,7 +89,7 @@ export function LockDelivery({
|
||||
save,
|
||||
blocked,
|
||||
}: LockProps & { views: LockViews; lock: LockRecord; save: SaveLock; blocked: boolean }) {
|
||||
const key = 'mm-price-lock-delivery-' + state.user.id + '-' + lock.id,
|
||||
const key = lockDeliveryKey(state.user.id, lock.id),
|
||||
ctx = { st: state, session, uuid };
|
||||
const [d, set] = useState(() => initialize(lock, views, ctx, key)),
|
||||
[error, setError] = useState('');
|
||||
@@ -252,7 +253,7 @@ export function LockDelivery({
|
||||
verified: true,
|
||||
lines: actual,
|
||||
};
|
||||
await save('/api/price-locks/' + encodeURIComponent(lock.id) + '/deliver', input);
|
||||
await save('/api/price-locks/' + encodeURIComponent(lock.id) + '/deliver', input, { key, value: snapshot });
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { clearMatching, type DraftSubmission } from '../../lib/receipt';
|
||||
import { lockReceipt } from './receipts';
|
||||
import { useEffect, useMemo, useRef, useState, type FormEvent, type MouseEvent, type ReactNode } from 'react';
|
||||
import type { LedgerClient } from '../../lib/api';
|
||||
import type { LedgerState } from '../../shared';
|
||||
@@ -334,7 +336,7 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
|
||||
break;
|
||||
}
|
||||
}
|
||||
async function confirmed(url: string, data: unknown, result: unknown) {
|
||||
async function confirmed(url: string, data: unknown, result: unknown, draft?: DraftSubmission) {
|
||||
if (!object(result) || !object(data)) throw new Error('锁价操作回执未完整返回,请重新读取后核对。');
|
||||
const request = object(result.request) ? result.request : {},
|
||||
saved = object(result.lock) ? result.lock : {};
|
||||
@@ -346,7 +348,7 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
|
||||
(url === '/api/price-locks' ? result.id : url.split('/')[3]);
|
||||
if (typeof lockId !== 'string' || !lockId) throw new Error('锁价操作回执未完整返回,请重新读取后核对。');
|
||||
if (url === '/api/price-locks') {
|
||||
localStorage.removeItem('mm-price-lock-draft-' + state.user.id);
|
||||
if (draft) clearMatching(localStorage, draft.key, draft.value);
|
||||
reset();
|
||||
navigate('price-locks', { search: '?lock=' + encodeURIComponent(lockId) });
|
||||
setMessage('锁价已保存到待交付,尚未出入库、不计利润');
|
||||
@@ -354,7 +356,7 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
|
||||
const orderId = result.order_id || result.id;
|
||||
if (typeof orderId !== 'string' || !orderId || typeof data.date !== 'string')
|
||||
throw new Error('交付回执未完整返回,请重新读取后核对。');
|
||||
localStorage.removeItem('mm-price-lock-delivery-' + state.user.id + '-' + url.split('/')[3]);
|
||||
if (draft) clearMatching(localStorage, draft.key, draft.value);
|
||||
const filterKey = 'mm-order-book-' + state.user.id;
|
||||
const filters = readDraftFilters(filterKey);
|
||||
sessionStorage.setItem(
|
||||
@@ -363,9 +365,8 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
|
||||
);
|
||||
navigate('orders', { search: '?order=' + encodeURIComponent(orderId) });
|
||||
} else {
|
||||
if (draft) clearMatching(localStorage, draft.key, draft.value);
|
||||
setSavedLockId(lockId);
|
||||
if (suffix === 'edit' || suffix === 'cancel' || (suffix === 'change-requests' && data.action === 'edit'))
|
||||
localStorage.removeItem('mm-price-lock-edit-' + state.user.id + '-' + lockId);
|
||||
reset();
|
||||
navigate('price-locks');
|
||||
setMessage(
|
||||
@@ -388,17 +389,19 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
|
||||
setMessage('操作已保存,最新记录暂未读到。请重新读取,不要重复提交。');
|
||||
}
|
||||
}
|
||||
async function save(url: string, data: Record<string, unknown>) {
|
||||
const result = await client.mutate(url, data);
|
||||
await confirmed(url, data, result);
|
||||
async function save(url: string, data: Record<string, unknown>, draft?: DraftSubmission) {
|
||||
const result = await client.mutate(url, data, undefined, draft?.value);
|
||||
await confirmed(url, data, result, draft);
|
||||
}
|
||||
async function retry() {
|
||||
try {
|
||||
const job = client.pending();
|
||||
if (job && !/^\/api\/(?:price-locks|price-lock-changes)(?:\/|$)/.test(job.url) && onRecoverOther)
|
||||
return await onRecoverOther();
|
||||
if (job && !lockReceipt.accepts(job.url) && onRecoverOther) return await onRecoverOther();
|
||||
const r = await client.retryPending();
|
||||
if (r) await confirmed(r.job.url, r.job.data, r.result);
|
||||
if (r && object(r.result)) {
|
||||
lockReceipt.finish({ client, state, job: r.job, result: r.result, storage: localStorage });
|
||||
await confirmed(r.job.url, r.job.data, r.result);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(errorText(err));
|
||||
if (err instanceof Error && 'status' in err && err.status === 409) setStale(true);
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { clearRecovered, detailTarget, record, type ReceiptHandler } from '../../lib/receipt';
|
||||
export const lockDraftKey = (user: string) => 'mm-price-lock-draft-' + user;
|
||||
export const lockEditKey = (user: string, id: string) => `mm-price-lock-edit-${user}-${id}`;
|
||||
export const lockDeliveryKey = (user: string, id: string) => `mm-price-lock-delivery-${user}-${id}`;
|
||||
// 池料草稿额外保存切回手动模式时的值,提交时只包含实际计价来源。
|
||||
function lockInput(d: Record<string, unknown>) {
|
||||
const input = { ...d };
|
||||
for (const k of ['customer', 'salesperson']) if (typeof input[k] === 'string') input[k] = input[k].trim();
|
||||
if (Array.isArray(input.lines))
|
||||
input.lines = input.lines.map(line => {
|
||||
if (!record(line) || !record(line.material) || line.material.source !== 'pool') return line;
|
||||
const material = { ...line.material };
|
||||
delete material.manual;
|
||||
return { ...line, material };
|
||||
});
|
||||
return input;
|
||||
}
|
||||
export const lockReceipt: ReceiptHandler = {
|
||||
accepts: url => /^\/api\/(?:price-locks|price-lock-changes)(?:\/|$)/.test(url),
|
||||
finish: ({ job, result, state, storage }) => {
|
||||
const path = job.url.split('/'),
|
||||
action = path[4],
|
||||
user = state.user.id,
|
||||
data = record(job.data) ? job.data : {};
|
||||
const id =
|
||||
result.price_lock_id ||
|
||||
(record(result.request) && result.request.price_lock_id) ||
|
||||
(record(result.lock) && result.lock.id) ||
|
||||
(path[2] === 'price-locks' && path[3] ? decodeURIComponent(path[3]) : result.id);
|
||||
if (typeof id !== 'string' || !id) return {};
|
||||
if (!action) clearRecovered(storage, lockDraftKey(user), job, lockInput);
|
||||
else if (action === 'deliver') {
|
||||
clearRecovered(storage, lockDeliveryKey(user, id), job, draft => draft);
|
||||
return detailTarget('orders', 'order', result.order_id || result.id);
|
||||
} else if (action === 'edit' || (action === 'change-requests' && data.action === 'edit')) {
|
||||
clearRecovered(storage, lockEditKey(user, id), job, d =>
|
||||
d.id === id && record(d.inputs)
|
||||
? {
|
||||
...lockInput(d.inputs),
|
||||
revision: d.revision,
|
||||
reason: typeof d.reason === 'string' ? d.reason.trim() : d.reason,
|
||||
verified: true,
|
||||
...(action === 'change-requests' ? { action: 'edit' } : {}),
|
||||
}
|
||||
: undefined,
|
||||
);
|
||||
}
|
||||
return detailTarget('price-locks', 'lock', id);
|
||||
},
|
||||
};
|
||||
@@ -11,7 +11,11 @@ export interface LockProps {
|
||||
session: SessionInfo;
|
||||
}
|
||||
export type LockViews = ReturnType<typeof lockViews>;
|
||||
export type SaveLock = (url: string, input: Record<string, unknown>) => Promise<void>;
|
||||
export type SaveLock = (
|
||||
url: string,
|
||||
input: Record<string, unknown>,
|
||||
draft?: import('../../lib/receipt').DraftSubmission,
|
||||
) => Promise<void>;
|
||||
export interface PreviewRow extends QuoteEntry {
|
||||
amount: number | null;
|
||||
allocations: Allocation[];
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { ReceiptHandler } from '../../lib/receipt';
|
||||
import { peopleUrl } from './data';
|
||||
export const peopleReceipt: ReceiptHandler = {
|
||||
accepts: url => url === peopleUrl,
|
||||
finish: () => ({ message: '原人数操作已确认' }),
|
||||
};
|
||||
@@ -1,8 +1,10 @@
|
||||
import { readStored, saveStored, depositDraft, unreadableDraft } from './localDraft';
|
||||
import { clearMatching } from '../../lib/receipt';
|
||||
import { depositDraftKey } from './receipts';
|
||||
import type { FormEvent } from 'react';
|
||||
import type { PageProps, RecoveryModel, DepositListData } from './types';
|
||||
import { useState } from 'react';
|
||||
import { grams } from '../../lib/format';
|
||||
import { loadDraft } from './controls';
|
||||
export function validateDeposits(r: DepositListData) {
|
||||
if (
|
||||
!Array.isArray(r.rows) ||
|
||||
@@ -104,16 +106,15 @@ export function DepositList({
|
||||
);
|
||||
}
|
||||
export function DepositForm({ client, state, model, saved }: PageProps & { model: RecoveryModel; saved(): void }) {
|
||||
const key = 'mm-customer-material-' + state.user.id,
|
||||
[draft, setDraft] = useState(
|
||||
() => loadDraft<Partial<Record<'date' | 'grams' | 'memo' | 'verified', string>>>(key) || {},
|
||||
),
|
||||
const key = depositDraftKey(state.user.id),
|
||||
[local] = useState(() => readStored(key, depositDraft)),
|
||||
[draft, setDraft] = useState(local.value || {}),
|
||||
[error, setError] = useState('');
|
||||
const change = (e: FormEvent<HTMLFormElement>) => {
|
||||
const form = e.currentTarget,
|
||||
next = Object.fromEntries(Array.from(new FormData(form), ([key, value]) => [key, String(value)]));
|
||||
setDraft(next);
|
||||
localStorage.setItem(key, JSON.stringify(next));
|
||||
saveStored(key, JSON.stringify(next), local.invalid);
|
||||
};
|
||||
async function submit(e: FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
@@ -127,9 +128,10 @@ export function DepositForm({ client, state, model, saved }: PageProps & { model
|
||||
try {
|
||||
model.units(input.grams, 3, '寄存克重', { zero: false });
|
||||
if (!input.memo) throw new Error('请填写备忘');
|
||||
const result = await client.mutate<{ id: string }>('/api/customer-materials', input);
|
||||
const snapshot = JSON.stringify(draft);
|
||||
const result = await client.mutate<{ id: string }>('/api/customer-materials', input, undefined, snapshot);
|
||||
if (!result.id) throw new Error('寄存保存结果未完整返回,请核对后再操作');
|
||||
localStorage.removeItem(key);
|
||||
clearMatching(localStorage, key, snapshot);
|
||||
saved();
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
@@ -137,6 +139,7 @@ export function DepositForm({ client, state, model, saved }: PageProps & { model
|
||||
}
|
||||
return (
|
||||
<form id="customer-material-form" className="panel" onChange={change} onSubmit={submit}>
|
||||
{local.invalid !== null && <p role="alert">{unreadableDraft}</p>}
|
||||
<div className="recovery-row">
|
||||
<label>
|
||||
寄存日期
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { recoveryDraftKey } from './receipts';
|
||||
import type { LedgerClient } from '../../lib/api';
|
||||
import type { ChangeList, EditDetail, Filters, Input, PageProps, Saved, Selection } from './types';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
@@ -20,7 +21,7 @@ export function RecoveriesPage({ client, state, search = window.location.search
|
||||
[previousDeep, setPreviousDeep] = useState(deep),
|
||||
[selection, select] = useState<Selection | null>(null),
|
||||
[edit, setEdit] = useState<EditDetail | null>(null),
|
||||
[page, setPage] = useState('new'),
|
||||
[page, setPage] = useState(() => (new URLSearchParams(search).get('deposit') === '1' ? 'deposit' : 'new')),
|
||||
[version, reload] = useState(0),
|
||||
[result, setResult] = useState<{ payload: Input; r: Saved } | null>(null),
|
||||
[notice, setNotice] = useState(''),
|
||||
@@ -106,7 +107,7 @@ export function RecoveriesPage({ client, state, search = window.location.search
|
||||
}
|
||||
function newForm() {
|
||||
if (result) {
|
||||
localStorage.setItem('mm-recovery-draft-' + state.user.id, JSON.stringify(model.defaults(result.payload.mode)));
|
||||
localStorage.setItem(recoveryDraftKey(state.user.id), JSON.stringify(model.defaults(result.payload.mode)));
|
||||
}
|
||||
setPage('new');
|
||||
setResult(null);
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { readStored, saveStored, recoverDraft, editDraft, unreadableDraft } from './localDraft';
|
||||
import { saveWithDraft } from '../../lib/receipt';
|
||||
import { recoveryDraftKey, recoveryEditKey } from './receipts';
|
||||
import { derive } from './derive';
|
||||
import type { ChangeEvent, FormEvent, InputHTMLAttributes, SelectHTMLAttributes } from 'react';
|
||||
import type { ApiError } from '../../lib/api';
|
||||
import type { Choice } from './controls';
|
||||
import type {
|
||||
EditDetail,
|
||||
Draft,
|
||||
RecoveryModel,
|
||||
Derived,
|
||||
TextField,
|
||||
PageProps,
|
||||
Deposit,
|
||||
@@ -22,143 +24,11 @@ import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Model, Cards } from '../../shared';
|
||||
import { grams } from '../../lib/format';
|
||||
import { memberAccountPrefix, recoveryModel } from './model';
|
||||
import { LegacyCount, Settlement, loadDraft, money, options, pocketOptions, rowLabel } from './controls';
|
||||
import { LegacyCount, Settlement, money, options, pocketOptions, rowLabel } from './controls';
|
||||
import { IndependentItems } from './IndependentItems';
|
||||
import { localMaterialNote, quotedMaterialNote } from './materialPreview';
|
||||
import { useRead } from '../Inventory/data';
|
||||
|
||||
function normalize(draft: Draft) {
|
||||
const result = { ...draft, customer_type: draft.mode === 'direct' ? '' : draft.customer_type };
|
||||
for (const [key, value] of Object.entries(result))
|
||||
if (typeof value === 'string') Object.assign(result, { [key]: value.trim() });
|
||||
if (draft.old_lines?.length)
|
||||
result.old_lines = [
|
||||
{
|
||||
...draft.old_lines[0],
|
||||
name: draft.old_name,
|
||||
incoming_weight: draft.incoming_weight,
|
||||
melted_weight: draft.melted_weight,
|
||||
purity: draft.purity,
|
||||
},
|
||||
...draft.old_lines.slice(1),
|
||||
];
|
||||
if (draft.charges)
|
||||
result.charges = [
|
||||
...(draft.charges.length || Number(draft.charge_amount) > 0
|
||||
? [{ name: draft.charge_name, amount: draft.charge_amount }]
|
||||
: []),
|
||||
...draft.charges.slice(1),
|
||||
];
|
||||
if (draft.fee_items)
|
||||
result.fee_items = [
|
||||
...(draft.fee_items.length || Number(draft.fee_amount) > 0
|
||||
? [
|
||||
{
|
||||
...draft.fee_items[0],
|
||||
key: draft.fee_items[0]?.key || 'other',
|
||||
note: draft.fee_note,
|
||||
amount: draft.fee_amount,
|
||||
payer: draft.fee_payer,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...draft.fee_items.slice(1),
|
||||
];
|
||||
return result;
|
||||
}
|
||||
function derive(model: RecoveryModel, raw: Draft): Derived {
|
||||
if (raw.independent_products && raw.mode === 'exchange') {
|
||||
const parts = [raw, ...(raw.extra_products || [])].map((item, index) =>
|
||||
derive(model, {
|
||||
...raw,
|
||||
...item,
|
||||
cost_payer: index === 0 ? raw.cost_payer : item.labor_payer,
|
||||
independent_products: false,
|
||||
extra_products: [],
|
||||
charges: [],
|
||||
fee_items: [],
|
||||
charge_amount: '0',
|
||||
fee_amount: '0',
|
||||
rounding_mode: 'cent',
|
||||
discount: '0',
|
||||
}),
|
||||
);
|
||||
const draft = {
|
||||
...raw,
|
||||
...parts[0].draft,
|
||||
charge_amount: raw.charge_amount,
|
||||
fee_amount: raw.fee_amount,
|
||||
charges: raw.charges,
|
||||
fee_items: raw.fee_items,
|
||||
rounding_mode: raw.rounding_mode,
|
||||
discount: raw.discount,
|
||||
independent_products: true,
|
||||
extra_products: parts.slice(1).map(x => x.draft),
|
||||
};
|
||||
try {
|
||||
const input = model.input(draft, { quote: true });
|
||||
return { draft, parts, input, q: model.calculate(input), error: '' };
|
||||
} catch (error) {
|
||||
return { draft, parts, input: null, q: null, error: (error as Error).message };
|
||||
}
|
||||
}
|
||||
|
||||
let draft = normalize(raw),
|
||||
old = null,
|
||||
newMg = null,
|
||||
q = null,
|
||||
input = null,
|
||||
error;
|
||||
try {
|
||||
old = model.calculate(
|
||||
model.input(
|
||||
{
|
||||
...draft,
|
||||
mode: 'direct',
|
||||
buy_rate: '1',
|
||||
buy_total: '1',
|
||||
buy_total_manual: true,
|
||||
...(draft.mode === 'exchange' && draft.old_source === 'deposit'
|
||||
? {
|
||||
old_lines: [
|
||||
{
|
||||
name: '客户寄存料',
|
||||
incoming_weight: draft.deposit_weight,
|
||||
melted_weight: draft.deposit_weight,
|
||||
purity: '100',
|
||||
},
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
{ quote: true },
|
||||
),
|
||||
);
|
||||
} catch {
|
||||
// 草稿可以缺少旧料行;下方完整试算会显示对应的输入错误。
|
||||
}
|
||||
if (draft.mode === 'exchange') {
|
||||
try {
|
||||
newMg = model.newWeight(draft);
|
||||
} catch {
|
||||
// 新料未填全时保留空的克重预览,下方完整试算给出提示。
|
||||
}
|
||||
}
|
||||
if (old && newMg !== null && !draft.depreciation_manual)
|
||||
draft = { ...draft, depreciation_weight: grams(Math.min(old.oldMg, newMg)) };
|
||||
const hasBuy = draft.mode !== 'exchange' || !!(old && newMg !== null && old.oldMg > newMg),
|
||||
diff = draft.mode === 'exchange' && !!(old && newMg !== null && newMg > old.oldMg);
|
||||
if (!hasBuy) draft = { ...draft, buy_total_manual: false, buy_total: '0.00' };
|
||||
try {
|
||||
input = model.input(draft, { quote: true });
|
||||
q = model.calculate(input);
|
||||
error = '';
|
||||
if (!draft.buy_total_manual) draft = { ...draft, buy_total: (q.defaultPurchaseAmount / 100).toFixed(2) };
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
return { draft, old, newMg, q, input, error, hasBuy, diff };
|
||||
}
|
||||
function RecoveryCardFee({ state, edit, net }: { state: PageProps['state']; edit: EditDetail | null; net: number }) {
|
||||
const rate = edit ? edit.record.credit_card_rate_permille : state.shopSettings?.creditCardRatePermille;
|
||||
const unavailable = <p role="status">信用卡手续费率未能确认,请重新读取后核对。</p>;
|
||||
@@ -196,25 +66,40 @@ export function RecoveryForm({
|
||||
refreshEdit(): Promise<EditDetail>;
|
||||
}) {
|
||||
const model = useMemo(() => recoveryModel(state, edit), [state, edit]),
|
||||
key = 'mm-recovery-draft-' + state.user.id;
|
||||
const editKey = edit ? 'mm-recovery-edit-' + state.user.id + '-' + edit.id : null;
|
||||
const existing = useMemo(() => {
|
||||
const v = editKey ? loadDraft<{ id: string; draft: Draft; revision: number; reason?: string }>(editKey) : null;
|
||||
return v?.id === edit?.id && v?.draft?.mode === edit?.inputs?.mode && v?.draft?.member === edit?.inputs?.member
|
||||
? v
|
||||
: null;
|
||||
}, [edit, editKey]);
|
||||
key = recoveryDraftKey(state.user.id);
|
||||
const editKey = edit ? recoveryEditKey(state.user.id, edit.id) : null;
|
||||
const local = useMemo(() => {
|
||||
if (edit && editKey) {
|
||||
const base = model.forEdit(edit.inputs);
|
||||
const saved = readStored(editKey, value => editDraft(value, edit, base));
|
||||
return { draft: saved.value?.draft ?? base, existing: saved.value, invalid: saved.invalid };
|
||||
}
|
||||
const base = model.defaults(),
|
||||
saved = readStored(key, value => recoverDraft(value, base));
|
||||
return { draft: saved.value ?? base, existing: null, invalid: saved.invalid };
|
||||
}, [model, edit, editKey, key]);
|
||||
const existing = local.existing;
|
||||
const [raw, setRaw] = useState<Draft>(() => {
|
||||
if (edit)
|
||||
if (edit && editKey) {
|
||||
let draft = local.draft;
|
||||
if (existing?.draft.independent_products && (edit.inputs.exchange?.items?.length ?? 0) <= 1) {
|
||||
const source = localStorage.getItem(editKey);
|
||||
if (source && !localStorage.getItem(editKey + '-before-shared-old'))
|
||||
localStorage.setItem(editKey + '-before-shared-old', source);
|
||||
draft = model.sharedDraft(draft);
|
||||
}
|
||||
return {
|
||||
...(existing?.draft || model.forEdit(edit.inputs)),
|
||||
...draft,
|
||||
customer_type: existing?.draft?.customer_type || '',
|
||||
change_reason: existing?.reason || '',
|
||||
verified: false,
|
||||
};
|
||||
const stored = loadDraft<Partial<Draft>>(key);
|
||||
if (stored?.independent_products && !localStorage.getItem(key + '-before-shared-old'))
|
||||
localStorage.setItem(key + '-before-shared-old', JSON.stringify(stored));
|
||||
}
|
||||
const stored = local.draft;
|
||||
if (stored.independent_products && !localStorage.getItem(key + '-before-shared-old')) {
|
||||
const source = localStorage.getItem(key);
|
||||
if (source) localStorage.setItem(key + '-before-shared-old', source);
|
||||
}
|
||||
const d = model.sharedDraft({
|
||||
...model.defaults(),
|
||||
shared_old_notice: '',
|
||||
@@ -239,18 +124,15 @@ export function RecoveryForm({
|
||||
card = net > 0 && d.payment_method === '信用卡';
|
||||
const signature = input && q ? JSON.stringify(edit ? { ...input, revision } : input) : '',
|
||||
live = useRef<Draft | null>(raw);
|
||||
const stored = JSON.stringify(edit ? { id: edit.id, revision, draft: raw, reason: raw.change_reason || '' } : raw);
|
||||
const initial = useRef(raw);
|
||||
useEffect(() => {
|
||||
live.current = raw;
|
||||
if (edit)
|
||||
localStorage.setItem(
|
||||
editKey!,
|
||||
JSON.stringify({ id: edit.id, revision, draft: raw, reason: raw.change_reason || '' }),
|
||||
);
|
||||
else localStorage.setItem(key, JSON.stringify(raw));
|
||||
if (local.invalid === null || raw !== initial.current) saveStored(editKey || key, stored, local.invalid);
|
||||
return () => {
|
||||
live.current = null;
|
||||
};
|
||||
}, [edit, editKey, key, raw, revision]);
|
||||
}, [editKey, key, raw, stored, local.invalid]);
|
||||
const quoteUrl = edit ? '/api/recoveries/' + encodeURIComponent(edit.id) + '/quote' : '/api/recoveries/quote',
|
||||
expected = q?.netSettlement,
|
||||
differenceMg = q?.differenceMg;
|
||||
@@ -528,11 +410,12 @@ export function RecoveryForm({
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
const result = await client.mutate<Saved>(
|
||||
const result = await saveWithDraft<Saved>(
|
||||
client,
|
||||
edit ? '/api/recoveries/' + encodeURIComponent(edit.id) + '/update' : '/api/recoveries',
|
||||
payload,
|
||||
{ key: editKey || key, value: stored },
|
||||
);
|
||||
localStorage.removeItem(editKey || key);
|
||||
saved(payload, result);
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
@@ -619,6 +502,7 @@ export function RecoveryForm({
|
||||
}
|
||||
return (
|
||||
<form id="recovery-form" data-recovery-edit={edit ? 'true' : undefined} onSubmit={submit}>
|
||||
{local.invalid !== null && <p role="alert">{unreadableDraft}</p>}
|
||||
<input type="hidden" name="mode" value={d.mode} />
|
||||
<input type="hidden" name="shared_old_notice" value={d.shared_old_notice || ''} />
|
||||
{!edit && (
|
||||
|
||||
@@ -168,13 +168,6 @@ export function pocketOptions(state: LedgerState, key: string, historical: boole
|
||||
]);
|
||||
return blank ? [['', blank], ...result] : result;
|
||||
}
|
||||
export function loadDraft<T>(key: string): T | null {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(key) || 'null');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
export function LegacyCount({ value }: { value?: Permission }) {
|
||||
return value?.requiresLegacyCountVerified ? (
|
||||
<>
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import { grams } from '../../lib/format';
|
||||
import type { Draft, RecoveryModel, Derived } from './types';
|
||||
function normalize(draft: Draft) {
|
||||
const result = { ...draft, customer_type: draft.mode === 'direct' ? '' : draft.customer_type };
|
||||
for (const [key, value] of Object.entries(result))
|
||||
if (typeof value === 'string') Object.assign(result, { [key]: value.trim() });
|
||||
if (draft.old_lines?.length)
|
||||
result.old_lines = [
|
||||
{
|
||||
...draft.old_lines[0],
|
||||
name: draft.old_name,
|
||||
incoming_weight: draft.incoming_weight,
|
||||
melted_weight: draft.melted_weight,
|
||||
purity: draft.purity,
|
||||
},
|
||||
...draft.old_lines.slice(1),
|
||||
];
|
||||
if (draft.charges)
|
||||
result.charges = [
|
||||
...(draft.charges.length || Number(draft.charge_amount) > 0
|
||||
? [{ name: draft.charge_name, amount: draft.charge_amount }]
|
||||
: []),
|
||||
...draft.charges.slice(1),
|
||||
];
|
||||
if (draft.fee_items)
|
||||
result.fee_items = [
|
||||
...(draft.fee_items.length || Number(draft.fee_amount) > 0
|
||||
? [
|
||||
{
|
||||
...draft.fee_items[0],
|
||||
key: draft.fee_items[0]?.key || 'other',
|
||||
note: draft.fee_note,
|
||||
amount: draft.fee_amount,
|
||||
payer: draft.fee_payer,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...draft.fee_items.slice(1),
|
||||
];
|
||||
return result;
|
||||
}
|
||||
export function derive(model: RecoveryModel, raw: Draft): Derived {
|
||||
if (raw.independent_products && raw.mode === 'exchange') {
|
||||
const parts = [raw, ...(raw.extra_products || [])].map((item, index) =>
|
||||
derive(model, {
|
||||
...raw,
|
||||
...item,
|
||||
cost_payer: index === 0 ? raw.cost_payer : item.labor_payer,
|
||||
independent_products: false,
|
||||
extra_products: [],
|
||||
charges: [],
|
||||
fee_items: [],
|
||||
charge_amount: '0',
|
||||
fee_amount: '0',
|
||||
rounding_mode: 'cent',
|
||||
discount: '0',
|
||||
}),
|
||||
);
|
||||
const draft = {
|
||||
...raw,
|
||||
...parts[0].draft,
|
||||
charge_amount: raw.charge_amount,
|
||||
fee_amount: raw.fee_amount,
|
||||
charges: raw.charges,
|
||||
fee_items: raw.fee_items,
|
||||
rounding_mode: raw.rounding_mode,
|
||||
discount: raw.discount,
|
||||
independent_products: true,
|
||||
extra_products: parts.slice(1).map(x => x.draft),
|
||||
};
|
||||
try {
|
||||
const input = model.input(draft, { quote: true });
|
||||
return { draft, parts, input, q: model.calculate(input), error: '' };
|
||||
} catch (error) {
|
||||
return { draft, parts, input: null, q: null, error: (error as Error).message };
|
||||
}
|
||||
}
|
||||
|
||||
let draft = normalize(raw),
|
||||
old = null,
|
||||
newMg = null,
|
||||
q = null,
|
||||
input = null,
|
||||
error;
|
||||
try {
|
||||
old = model.calculate(
|
||||
model.input(
|
||||
{
|
||||
...draft,
|
||||
mode: 'direct',
|
||||
buy_rate: '1',
|
||||
buy_total: '1',
|
||||
buy_total_manual: true,
|
||||
...(draft.mode === 'exchange' && draft.old_source === 'deposit'
|
||||
? {
|
||||
old_lines: [
|
||||
{
|
||||
name: '客户寄存料',
|
||||
incoming_weight: draft.deposit_weight,
|
||||
melted_weight: draft.deposit_weight,
|
||||
purity: '100',
|
||||
},
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
{ quote: true },
|
||||
),
|
||||
);
|
||||
} catch {
|
||||
// 草稿可以缺少旧料行;下方完整试算会显示对应的输入错误。
|
||||
}
|
||||
if (draft.mode === 'exchange') {
|
||||
try {
|
||||
newMg = model.newWeight(draft);
|
||||
} catch {
|
||||
// 新料未填全时保留空的克重预览,下方完整试算给出提示。
|
||||
}
|
||||
}
|
||||
if (old && newMg !== null && !draft.depreciation_manual)
|
||||
draft = { ...draft, depreciation_weight: grams(Math.min(old.oldMg, newMg)) };
|
||||
const hasBuy = draft.mode !== 'exchange' || !!(old && newMg !== null && old.oldMg > newMg),
|
||||
diff = draft.mode === 'exchange' && !!(old && newMg !== null && newMg > old.oldMg);
|
||||
if (!hasBuy) draft = { ...draft, buy_total_manual: false, buy_total: '0.00' };
|
||||
try {
|
||||
input = model.input(draft, { quote: true });
|
||||
q = model.calculate(input);
|
||||
error = '';
|
||||
if (!draft.buy_total_manual) draft = { ...draft, buy_total: (q.defaultPurchaseAmount / 100).toFixed(2) };
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
return { draft, old, newMg, q, input, error, hasBuy, diff };
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
import { record } from '../../lib/receipt';
|
||||
import type { Draft, EditDetail, Fee, OldLine, Charge, ProductDraft } from './types';
|
||||
|
||||
type Stored<T> = { value: T | null; invalid: string | null };
|
||||
export const unreadableDraft = '本机草稿格式异常,原文已保留。请核对当前表单后继续填写。';
|
||||
|
||||
export function readStored<T>(key: string, decode: (value: unknown) => T | null): Stored<T> {
|
||||
const text = localStorage.getItem(key);
|
||||
if (text === null) return { value: null, invalid: null };
|
||||
let raw: unknown;
|
||||
try {
|
||||
raw = JSON.parse(text);
|
||||
} catch (error) {
|
||||
if (!(error instanceof SyntaxError)) throw error;
|
||||
return { value: null, invalid: text };
|
||||
}
|
||||
if (raw === null) return { value: null, invalid: null };
|
||||
const value = decode(raw);
|
||||
return { value, invalid: value === null ? text : null };
|
||||
}
|
||||
|
||||
export function saveStored(key: string, text: string, invalid: string | null) {
|
||||
if (invalid !== null && localStorage.getItem(key) === invalid)
|
||||
localStorage.setItem(key + '-unreadable-' + crypto.randomUUID(), invalid);
|
||||
localStorage.setItem(key, text);
|
||||
}
|
||||
|
||||
const numericText = new Set([
|
||||
'incoming_weight',
|
||||
'melted_weight',
|
||||
'purity',
|
||||
'deposit_weight',
|
||||
'buy_rate',
|
||||
'buy_total',
|
||||
'new_quantity',
|
||||
'gold_price',
|
||||
'labor_rate',
|
||||
'depreciation_weight',
|
||||
'depreciation_rate',
|
||||
'discount',
|
||||
'material_rate',
|
||||
'cost_labor_value',
|
||||
'fee_amount',
|
||||
'charge_amount',
|
||||
'folded_weight',
|
||||
]);
|
||||
const flagNames = new Set([
|
||||
'independent_products',
|
||||
'buy_total_manual',
|
||||
'depreciation_manual',
|
||||
'melted_manual',
|
||||
'verified',
|
||||
]);
|
||||
const optionalText = new Set(['customer_type', 'change_reason', 'shared_old_notice', 'folded_weight', 'cost_payer']);
|
||||
|
||||
function oldLine(v: unknown): v is OldLine {
|
||||
return (
|
||||
record(v) &&
|
||||
typeof v.name === 'string' &&
|
||||
typeof v.incoming_weight === 'string' &&
|
||||
typeof v.melted_weight === 'string' &&
|
||||
typeof v.purity === 'string'
|
||||
);
|
||||
}
|
||||
function charge(v: unknown): v is Charge {
|
||||
return record(v) && typeof v.name === 'string' && typeof v.amount === 'string';
|
||||
}
|
||||
function fee(v: unknown): v is Fee {
|
||||
return (
|
||||
record(v) &&
|
||||
typeof v.key === 'string' &&
|
||||
typeof v.note === 'string' &&
|
||||
typeof v.amount === 'string' &&
|
||||
typeof v.payer === 'string'
|
||||
);
|
||||
}
|
||||
function list<T>(v: unknown, valid: (entry: unknown) => entry is T): v is T[] {
|
||||
return Array.isArray(v) && v.every(valid);
|
||||
}
|
||||
|
||||
// 草稿允许缺项和未完成的数字;只有数据结构在恢复时校验,业务有效性仍由提交时的原规则判断。
|
||||
function fields(value: unknown, base: Draft, product = false): Partial<Draft> | null {
|
||||
if (!record(value)) return null;
|
||||
const result: Partial<Draft> = {};
|
||||
for (const [key, v] of Object.entries(value)) {
|
||||
if (key === 'mode') {
|
||||
if (v !== 'direct' && v !== 'exchange') return null;
|
||||
result.mode = v;
|
||||
} else if (key === 'old_lines') {
|
||||
if (!list(v, oldLine)) return null;
|
||||
result.old_lines = v;
|
||||
} else if (key === 'charges') {
|
||||
if (!list(v, charge)) return null;
|
||||
result.charges = v;
|
||||
} else if (key === 'fee_items') {
|
||||
if (!list(v, fee)) return null;
|
||||
result.fee_items = v;
|
||||
} else if (key === 'extra_products') {
|
||||
if (!Array.isArray(v) || (product && v.length)) return null;
|
||||
const products: ProductDraft[] = [];
|
||||
for (const [i, item] of v.entries()) {
|
||||
const row = fields(item, base, true);
|
||||
if (!row) return null;
|
||||
// 历史逐件草稿可以带自己的旧料资料;缺少的商品输入沿用该行原值。
|
||||
const defaults = base.extra_products?.[i] || base;
|
||||
products.push({
|
||||
new_name: defaults.new_name,
|
||||
new_quantity: defaults.new_quantity,
|
||||
pocket: defaults.pocket,
|
||||
stockCount: defaults.stockCount,
|
||||
labor_mode: defaults.labor_mode,
|
||||
labor_rate: defaults.labor_rate,
|
||||
cost_labor_mode: defaults.cost_labor_mode,
|
||||
cost_labor_value: defaults.cost_labor_value,
|
||||
labor_payer: defaults.labor_payer,
|
||||
...row,
|
||||
});
|
||||
}
|
||||
result.extra_products = products;
|
||||
} else if (flagNames.has(key)) {
|
||||
if (typeof v !== 'boolean') return null;
|
||||
Object.assign(result, { [key]: v });
|
||||
} else if (key === 'stockCount' || key === 'old_stock_count') {
|
||||
if (typeof v !== 'string' && !(typeof v === 'number' && Number.isFinite(v))) return null;
|
||||
result[key] = v;
|
||||
} else if (Object.hasOwn(base, key) || optionalText.has(key)) {
|
||||
if (typeof v !== 'string' && !(typeof v === 'number' && Number.isFinite(v) && numericText.has(key))) return null;
|
||||
Object.assign(result, { [key]: String(v) });
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export function recoverDraft(value: unknown, base: Draft): Draft | null {
|
||||
const decoded = fields(value, base);
|
||||
return decoded && { ...base, ...decoded };
|
||||
}
|
||||
export function editDraft(value: unknown, edit: EditDetail, base: Draft) {
|
||||
if (
|
||||
!record(value) ||
|
||||
value.id !== edit.id ||
|
||||
typeof value.revision !== 'number' ||
|
||||
!Number.isSafeInteger(value.revision) ||
|
||||
value.revision < 1 ||
|
||||
(value.reason !== undefined && typeof value.reason !== 'string') ||
|
||||
!record(value.draft) ||
|
||||
value.draft.mode !== edit.inputs.mode ||
|
||||
value.draft.member !== edit.inputs.member
|
||||
)
|
||||
return null;
|
||||
const draft = recoverDraft(value.draft, base);
|
||||
return draft && { draft, revision: value.revision, reason: value.reason };
|
||||
}
|
||||
export type DepositDraft = Partial<Record<'date' | 'memo' | 'grams', string>> & { verified?: boolean | 'on' | '' };
|
||||
export function depositDraft(v: unknown): DepositDraft | null {
|
||||
if (!record(v)) return null;
|
||||
const { date, memo, grams, verified } = v;
|
||||
if (
|
||||
(date !== undefined && typeof date !== 'string') ||
|
||||
(memo !== undefined && typeof memo !== 'string') ||
|
||||
(grams !== undefined && typeof grams !== 'string' && !(typeof grams === 'number' && Number.isFinite(grams))) ||
|
||||
(verified !== undefined && verified !== true && verified !== false && verified !== 'on' && verified !== '')
|
||||
)
|
||||
return null;
|
||||
return { date, memo, ...(grams === undefined ? {} : { grams: String(grams) }), verified };
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { derive } from './derive';
|
||||
import { recoveryModel } from './model';
|
||||
import { clearRecovered, detailTarget, record, type ReceiptHandler } from '../../lib/receipt';
|
||||
export const recoveryDraftKey = (user: string) => 'mm-recovery-draft-' + user;
|
||||
export const recoveryEditKey = (user: string, id: string) => `mm-recovery-edit-${user}-${id}`;
|
||||
export const depositDraftKey = (user: string) => 'mm-customer-material-' + user;
|
||||
export const recoveryReceipt: ReceiptHandler = {
|
||||
accepts: url =>
|
||||
url === '/api/customer-materials' || url === '/api/recoveries' || /^\/api\/recoveries\/[^/]+\/update$/.test(url),
|
||||
finish: ({ job, result, state, storage }) => {
|
||||
if (job.url === '/api/customer-materials') {
|
||||
clearRecovered(storage, depositDraftKey(state.user.id), job, d => ({
|
||||
date: d.date,
|
||||
grams: d.grams,
|
||||
memo: typeof d.memo === 'string' ? d.memo.trim() : d.memo,
|
||||
verified: !!d.verified,
|
||||
}));
|
||||
return { route: 'recoveries', search: '?deposit=1', message: '寄存记录已保存,未生成购料或收付款' };
|
||||
}
|
||||
const edit = job.url.split('/')[3];
|
||||
const id = edit ? decodeURIComponent(edit) : result.id;
|
||||
if (typeof id !== 'string' || !id) return {};
|
||||
clearRecovered(storage, edit ? recoveryEditKey(state.user.id, id) : recoveryDraftKey(state.user.id), job, d => {
|
||||
const raw = edit ? d.draft : d;
|
||||
if (!record(raw) || (raw.mode !== 'direct' && raw.mode !== 'exchange') || (edit && d.id !== id)) return;
|
||||
const model = recoveryModel(state);
|
||||
try {
|
||||
const draft = derive(model, { ...model.defaults(raw.mode), ...raw }).draft;
|
||||
const input = model.validate(model.input(draft));
|
||||
const submitted = record(job.data) ? job.data : {};
|
||||
return edit
|
||||
? {
|
||||
...input,
|
||||
revision: d.revision,
|
||||
reason: typeof d.reason === 'string' ? d.reason.trim() : d.reason,
|
||||
verified: true,
|
||||
...(submitted.legacyCountVerified ? { legacyCountVerified: true } : {}),
|
||||
}
|
||||
: input;
|
||||
} catch {
|
||||
return; /* 无法按当前配置复原旧提交时,保留本地草稿。 */
|
||||
}
|
||||
});
|
||||
return detailTarget('recoveries', 'recovery', id);
|
||||
},
|
||||
};
|
||||
@@ -1,16 +1,8 @@
|
||||
import { draftsFor, receiptFor, finishReportDraft, type DraftItem, type FormKind, type ReportResult } from './drafts';
|
||||
import type { FormEvent, RefObject } from 'react';
|
||||
import type { LedgerClient } from '../../lib/api';
|
||||
import type { LedgerState } from '../../shared';
|
||||
import type {
|
||||
DailyFunds,
|
||||
ReportQuery,
|
||||
Range,
|
||||
ReportAction,
|
||||
ReimbursementList,
|
||||
Reimbursement,
|
||||
ReimbursementItem,
|
||||
Confirmation,
|
||||
} from './contracts';
|
||||
import type { DailyFunds, ReportQuery, Range, ReportAction, ReimbursementList, Reimbursement } from './contracts';
|
||||
import type { reportPresentation } from './presentation';
|
||||
import { useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { Calc, Model } from '../../shared';
|
||||
@@ -18,37 +10,6 @@ import { Button, Choice, Dialog, Field } from '../Settings/controls';
|
||||
import { errorText } from '../Settings/settingsModel';
|
||||
|
||||
type View = ReturnType<typeof reportPresentation>;
|
||||
type DraftItem = Omit<ReimbursementItem, 'amount'> & { amount: string };
|
||||
interface Draft {
|
||||
id: string;
|
||||
revision?: number;
|
||||
date: string;
|
||||
items: DraftItem[];
|
||||
payer?: string;
|
||||
note: string;
|
||||
}
|
||||
interface Review {
|
||||
id: string;
|
||||
revision: number;
|
||||
kind: 'approve' | 'reject';
|
||||
note: string;
|
||||
verified: boolean;
|
||||
}
|
||||
interface Outlay {
|
||||
amount: string;
|
||||
note: string;
|
||||
verified: boolean;
|
||||
editing: boolean;
|
||||
revision: number;
|
||||
sourceRevision: string;
|
||||
}
|
||||
interface Drafts {
|
||||
user: string;
|
||||
forms: Map<string, Draft>;
|
||||
editors: Map<string, string>;
|
||||
reviews: Map<string, Review>;
|
||||
outlays: Map<string, Outlay>;
|
||||
}
|
||||
interface Props {
|
||||
client: LedgerClient;
|
||||
state: LedgerState;
|
||||
@@ -65,16 +26,7 @@ interface PageReply {
|
||||
list?: ReimbursementList;
|
||||
error?: string;
|
||||
}
|
||||
type FormKind = 'outlay' | 'draft' | 'review';
|
||||
type FormError = { kind: FormKind; text: string; conflict?: boolean };
|
||||
const draftsByClient = new WeakMap<LedgerClient, Drafts>();
|
||||
function draftsFor(client: LedgerClient, user: string) {
|
||||
const current = draftsByClient.get(client);
|
||||
if (current?.user === user) return current;
|
||||
const drafts: Drafts = { user, forms: new Map(), editors: new Map(), reviews: new Map(), outlays: new Map() };
|
||||
draftsByClient.set(client, drafts);
|
||||
return drafts;
|
||||
}
|
||||
type FormError = { kind: FormKind; text: string; conflict?: boolean; operation?: string };
|
||||
function newItem(team: boolean): DraftItem {
|
||||
return {
|
||||
name: '',
|
||||
@@ -401,35 +353,16 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
|
||||
: '报销已批准,已计入报销日期的应转合计';
|
||||
}
|
||||
setError(null);
|
||||
const result = await client.mutate<{
|
||||
confirmation?: Pick<Confirmation, 'revision' | 'sourceRevision'>;
|
||||
reimbursement?: { date: string };
|
||||
date?: string;
|
||||
}>(url, input);
|
||||
if (kind === 'draft' && formKey) {
|
||||
cache.forms.delete(formKey);
|
||||
cache.editors.delete(key);
|
||||
}
|
||||
if (kind === 'review') cache.reviews.delete(key);
|
||||
if (kind === 'outlay' && out) {
|
||||
if (
|
||||
!result.confirmation ||
|
||||
!Number.isSafeInteger(result.confirmation.revision) ||
|
||||
typeof result.confirmation.sourceRevision !== 'string'
|
||||
)
|
||||
throw new Error('实际支出已提交,确认回执未完整返回,请重新读取后核对。');
|
||||
out.editing = false;
|
||||
out.verified = false;
|
||||
out.revision = result.confirmation.revision;
|
||||
out.sourceRevision = result.confirmation.sourceRevision;
|
||||
}
|
||||
const snapshot = receiptFor(cache, key, kind);
|
||||
const result = await client.mutate<ReportResult>(url, input, undefined, snapshot);
|
||||
finishReportDraft(cache, snapshot, result);
|
||||
reload();
|
||||
const date = result.reimbursement?.date || result.date || input.date;
|
||||
notify(notice + (date && date !== query.date ? '(' + date + ')' : ''));
|
||||
} catch (err) {
|
||||
if (currentView.current !== key) return;
|
||||
const conflict = err instanceof Error && 'status' in err && err.status === 409;
|
||||
setError({ kind, text: errorText(err), conflict });
|
||||
setError({ kind, text: errorText(err), conflict, operation: client.pending()?.key });
|
||||
notify(errorText(err), true);
|
||||
if (conflict) {
|
||||
if (review) review.verified = false;
|
||||
@@ -442,17 +375,15 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
|
||||
{error?.kind === kind && (
|
||||
<div className="error">
|
||||
{error.text}
|
||||
{client.pending() ? (
|
||||
{error.operation && client.pending()?.key === error.operation ? (
|
||||
<Button
|
||||
action="retry"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await client.retryPending();
|
||||
if (kind === 'draft' && formKey) {
|
||||
cache.forms.delete(formKey);
|
||||
cache.editors.delete(key);
|
||||
}
|
||||
if (kind === 'review') cache.reviews.delete(key);
|
||||
const job = client.pending();
|
||||
if (!job || job.key !== error.operation) return;
|
||||
const restored = await client.retryPending<ReportResult>();
|
||||
if (restored) finishReportDraft(cache, restored.job.draft, restored.result);
|
||||
setError(null);
|
||||
reload();
|
||||
} catch (err) {
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import type { LedgerClient } from '../../lib/api';
|
||||
import { record } from '../../lib/receipt';
|
||||
import type { ReimbursementItem, Confirmation } from './contracts';
|
||||
export type DraftItem = Omit<ReimbursementItem, 'amount'> & { amount: string };
|
||||
export interface Draft {
|
||||
id: string;
|
||||
revision?: number;
|
||||
date: string;
|
||||
items: DraftItem[];
|
||||
payer?: string;
|
||||
note: string;
|
||||
}
|
||||
export interface Review {
|
||||
id: string;
|
||||
revision: number;
|
||||
kind: 'approve' | 'reject';
|
||||
note: string;
|
||||
verified: boolean;
|
||||
}
|
||||
interface Outlay {
|
||||
amount: string;
|
||||
note: string;
|
||||
verified: boolean;
|
||||
editing: boolean;
|
||||
revision: number;
|
||||
sourceRevision: string;
|
||||
}
|
||||
interface Drafts {
|
||||
user: string;
|
||||
forms: Map<string, Draft>;
|
||||
editors: Map<string, string>;
|
||||
reviews: Map<string, Review>;
|
||||
outlays: Map<string, Outlay>;
|
||||
}
|
||||
const draftsByClient = new WeakMap<LedgerClient, Drafts>();
|
||||
export function draftsFor(client: LedgerClient, user: string) {
|
||||
const current = draftsByClient.get(client);
|
||||
if (current?.user === user) return current;
|
||||
const drafts: Drafts = { user, forms: new Map(), editors: new Map(), reviews: new Map(), outlays: new Map() };
|
||||
draftsByClient.set(client, drafts);
|
||||
return drafts;
|
||||
}
|
||||
|
||||
export type FormKind = 'draft' | 'review' | 'outlay';
|
||||
export interface ReportResult {
|
||||
confirmation?: Pick<Confirmation, 'revision' | 'sourceRevision'>;
|
||||
reimbursement?: { date: string };
|
||||
date?: string;
|
||||
}
|
||||
export function receiptFor(cache: Drafts, key: string, kind: FormKind) {
|
||||
const formKey = kind === 'draft' ? cache.editors.get(key) : undefined;
|
||||
const value =
|
||||
kind === 'draft'
|
||||
? cache.forms.get(formKey || '')
|
||||
: kind === 'review'
|
||||
? cache.reviews.get(key)
|
||||
: cache.outlays.get(key);
|
||||
return value ? JSON.stringify({ key, kind, formKey, value }) : undefined;
|
||||
}
|
||||
export function finishReportDraft(cache: Drafts, snapshot: string | undefined, result: ReportResult) {
|
||||
if (!snapshot) return;
|
||||
let data: unknown;
|
||||
try {
|
||||
data = JSON.parse(snapshot);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!record(data) || typeof data.key !== 'string' || !data.key.startsWith(cache.user + '|')) return;
|
||||
const { key, kind } = data;
|
||||
if (kind !== 'draft' && kind !== 'review' && kind !== 'outlay') return;
|
||||
if (kind === 'draft') {
|
||||
if (
|
||||
typeof data.formKey !== 'string' ||
|
||||
JSON.stringify(cache.forms.get(data.formKey)) !== JSON.stringify(data.value)
|
||||
)
|
||||
return;
|
||||
cache.forms.delete(data.formKey);
|
||||
if (cache.editors.get(key) === data.formKey) cache.editors.delete(key);
|
||||
return;
|
||||
}
|
||||
if (snapshot !== receiptFor(cache, key, kind)) return;
|
||||
if (kind === 'review') cache.reviews.delete(key);
|
||||
if (kind === 'outlay') {
|
||||
const out = cache.outlays.get(key),
|
||||
r = result.confirmation;
|
||||
if (!r || !Number.isSafeInteger(r.revision) || typeof r.sourceRevision !== 'string')
|
||||
throw new Error('实际支出已提交,确认回执未完整返回,请重新读取后核对。');
|
||||
if (out)
|
||||
Object.assign(out, { editing: false, verified: false, revision: r.revision, sourceRevision: r.sourceRevision });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { ReceiptHandler } from '../../lib/receipt';
|
||||
import { record } from '../../lib/receipt';
|
||||
import { Model } from '../../shared';
|
||||
import { draftsFor, finishReportDraft } from './drafts';
|
||||
export const reportReceipt: ReceiptHandler = {
|
||||
accepts: url => url === '/api/daily-funds/confirm' || /^\/api\/reimbursements(?:\/|$)/.test(url),
|
||||
finish: ({ client, state, job, result }) => {
|
||||
const confirmation = result.confirmation;
|
||||
const validated =
|
||||
record(confirmation) &&
|
||||
typeof confirmation.revision === 'number' &&
|
||||
typeof confirmation.sourceRevision === 'string'
|
||||
? { revision: confirmation.revision, sourceRevision: confirmation.sourceRevision }
|
||||
: undefined;
|
||||
finishReportDraft(draftsFor(client, state.user.id), job.draft, { confirmation: validated });
|
||||
const action = job.url.split('/').at(-1);
|
||||
return {
|
||||
message:
|
||||
action === 'confirm'
|
||||
? '当天完整支出已确认'
|
||||
: action === 'reject'
|
||||
? '报销已驳回,原原因保留'
|
||||
: action === 'approve'
|
||||
? Model.teamMode(state)
|
||||
? '报销已批准,成员往来已更新'
|
||||
: '报销已批准,已计入报销日期的应转合计'
|
||||
: '报销单已提交,等待店主复核',
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { ReceiptHandler } from '../../lib/receipt';
|
||||
const settingsMessages: Record<string, string> = {
|
||||
'/api/shop-settings': '店铺配置已保存',
|
||||
'/api/printing': '打印设置已保存,预览和后续打印使用新设置',
|
||||
};
|
||||
export const settingsReceipt: ReceiptHandler = {
|
||||
accepts: url => Object.hasOwn(settingsMessages, url),
|
||||
finish: ({ job }) => ({ message: settingsMessages[job.url] }),
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { ReceiptHandler } from '../../lib/receipt';
|
||||
// 两条历史路径的确认提示不同。单数路径没有附带可打开的销售单据。
|
||||
export const teamTransferReceipt: ReceiptHandler = {
|
||||
accepts: url => url === '/api/team-funds/transfers',
|
||||
finish: () => ({ route: 'team-funds', message: '实际转账已保存,待转金额已重新核对' }),
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
import { accountChangedError, type LedgerClient } from '../lib/api';
|
||||
import { record, type ReceiptHandler, type StorageLike } from '../lib/receipt';
|
||||
import type { LedgerState } from '../shared';
|
||||
import { issueReceipt, templateReceipt } from './CreateOrder/drafts';
|
||||
import { orderReceipt, afterSaleReceipt } from './Orders/receipts';
|
||||
import { materialReceipt } from './MaterialPools/receipts';
|
||||
import { lockReceipt } from './PriceLocks/receipts';
|
||||
import { recoveryReceipt } from './Recoveries/receipts';
|
||||
import { teamTransferReceipt } from './TeamFunds/receipts';
|
||||
import { reportReceipt } from './Report/receipts';
|
||||
import { inventoryReceipt } from './Inventory/receipts';
|
||||
import { settingsReceipt } from './Settings/receipts';
|
||||
import { peopleReceipt } from './PrivateOperations/receipts';
|
||||
const handlers: ReceiptHandler[] = [
|
||||
issueReceipt,
|
||||
orderReceipt,
|
||||
materialReceipt,
|
||||
lockReceipt,
|
||||
recoveryReceipt,
|
||||
teamTransferReceipt,
|
||||
reportReceipt,
|
||||
templateReceipt,
|
||||
afterSaleReceipt,
|
||||
inventoryReceipt,
|
||||
settingsReceipt,
|
||||
peopleReceipt,
|
||||
];
|
||||
export async function recoverPending(client: LedgerClient, state: LedgerState, storage: StorageLike) {
|
||||
const user = state.user.id;
|
||||
if (client.user !== user) throw accountChangedError();
|
||||
const recovered = await client.retryPending();
|
||||
if (!recovered) return null;
|
||||
if (client.user !== user) throw accountChangedError();
|
||||
const { job, result } = recovered;
|
||||
const handler = handlers.find(h => h.accepts(job.url));
|
||||
return handler?.finish({ client, job, result: record(result) ? result : {}, state, storage }) || {};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import type { LedgerClient, PendingJob } from '../lib/api';
|
||||
import type { Route } from '../lib/router';
|
||||
import type { LedgerState, SessionInfo } from '../shared';
|
||||
import { CreateOrderPage } from './CreateOrder/CreateOrderPage';
|
||||
import { PriceLocksPage } from './PriceLocks/PriceLocksPage';
|
||||
import { MaterialPoolsPage } from './MaterialPools/MaterialPoolsPage';
|
||||
import { RecoveriesPage } from './Recoveries/RecoveriesPage';
|
||||
import { OrderEditPage } from './Orders/OrderEditPage';
|
||||
import { LockOrderEditor } from './Orders/LockOrderEditor';
|
||||
import { InventoryPage } from './Inventory/InventoryPage';
|
||||
import { ReportPage } from './Report/ReportPage';
|
||||
import { TeamFundsPage } from './TeamFunds/TeamFundsPage';
|
||||
import { PrivateOperationsPage } from './PrivateOperations/PrivateOperationsPage';
|
||||
import { SettingsPage } from './Settings/SettingsPage';
|
||||
import { OrdersRoute } from './PageSession';
|
||||
import { peopleReceipt } from './PrivateOperations/receipts';
|
||||
export interface PageContext {
|
||||
route: Route;
|
||||
client: LedgerClient;
|
||||
state: LedgerState;
|
||||
session: SessionInfo;
|
||||
location: string;
|
||||
refreshState: () => Promise<LedgerState>;
|
||||
stateChanged: (state: LedgerState) => void;
|
||||
init: () => void;
|
||||
registerLeaveGuard: (check: () => boolean) => () => void;
|
||||
recover: () => Promise<void>;
|
||||
}
|
||||
interface PageRegistration {
|
||||
Page: (ctx: PageContext) => ReactNode;
|
||||
ownsRecovery?: (job: PendingJob) => boolean;
|
||||
}
|
||||
const locallyHandled = () => true;
|
||||
const locks: PageRegistration = {
|
||||
Page: c => (
|
||||
<PriceLocksPage
|
||||
{...c}
|
||||
route={c.route === 'price-lock-create' ? 'price-lock-create' : 'price-locks'}
|
||||
onState={c.stateChanged}
|
||||
onRecoverOther={c.recover}
|
||||
/>
|
||||
),
|
||||
ownsRecovery: locallyHandled,
|
||||
};
|
||||
const privateOps: PageRegistration = {
|
||||
Page: c => <PrivateOperationsPage {...c} />,
|
||||
ownsRecovery: job => peopleReceipt.accepts(job.url),
|
||||
};
|
||||
export const pages: Record<Exclude<Route, 'login'>, PageRegistration> = {
|
||||
create: {
|
||||
Page: c => <CreateOrderPage key={c.location} {...c} onAccountChanged={c.init} onRecoverOther={c.recover} />,
|
||||
ownsRecovery: locallyHandled,
|
||||
},
|
||||
'price-locks': locks,
|
||||
'price-lock-create': locks,
|
||||
'material-pools': {
|
||||
Page: c => <MaterialPoolsPage {...c} onState={c.stateChanged} onRecoverOther={c.recover} />,
|
||||
ownsRecovery: locallyHandled,
|
||||
},
|
||||
recoveries: { Page: c => <RecoveriesPage {...c} search={window.location.search} /> },
|
||||
'order-edit': { Page: c => <OrderEditPage key={c.location} {...c} LockEditor={LockOrderEditor} /> },
|
||||
orders: { Page: c => <OrdersRoute key={c.location} {...c} /> },
|
||||
stock: { Page: c => <InventoryPage {...c} /> },
|
||||
report: { Page: c => <ReportPage {...c} /> },
|
||||
'team-funds': { Page: c => <TeamFundsPage {...c} /> },
|
||||
'private-operations': privateOps,
|
||||
'people-entry': privateOps,
|
||||
settings: { Page: c => <SettingsPage {...c} onAccountChanged={c.init} /> },
|
||||
};
|
||||
Reference in new issue
Block a user