新版界面(React + TypeScript + Vite + Ant Design):登录页与开单页
共用计算经构建插件直接导入 public/ 下的 UMD 源文件;请求客户端沿用旧界面的重试、 同一操作号自动确认、恢复原操作与账号切换约定;附 vitest 单元与组件测试。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
bdffbcab85
commit
ec5889075f
39 files changed
+8772
No files matched your search
@@ -0,0 +1,96 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { Button, Result, Spin } from 'antd';
|
||||
import type { LedgerClient } from './lib/api';
|
||||
import { loadSession, loadState } from './lib/session';
|
||||
import { navigate, useRoute } from './lib/router';
|
||||
import type { LedgerState, SessionInfo } from './shared';
|
||||
import { LoginPage } from './pages/Login/LoginPage';
|
||||
import { CreateOrderPage } from './pages/CreateOrder/CreateOrderPage';
|
||||
import { TopBar } from './components/TopBar';
|
||||
import { RequestStatus } from './components/RequestStatus';
|
||||
|
||||
export function App({ client }: { client: LedgerClient }) {
|
||||
const [session, setSession] = useState<SessionInfo | null>(null);
|
||||
const [state, setState] = useState<LedgerState | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
const route = useRoute();
|
||||
|
||||
// 重新读取登录状态:登录、退出、账号切换后调用。
|
||||
const [initRequest, setInitRequest] = useState(0);
|
||||
const init = useCallback(() => setInitRequest(value => value + 1), []);
|
||||
useEffect(() => {
|
||||
let current = true;
|
||||
loadSession(client)
|
||||
.then(async latest => {
|
||||
if (!current) return;
|
||||
setError('');
|
||||
setSession(latest);
|
||||
if (!latest.user) {
|
||||
setState(null);
|
||||
navigate('login', { keepSearch: true });
|
||||
return;
|
||||
}
|
||||
const next = await loadState(client);
|
||||
if (!current) return;
|
||||
setState(next);
|
||||
navigate('create', { keepSearch: true });
|
||||
})
|
||||
.catch(err => current && setError((err as Error).message));
|
||||
return () => {
|
||||
current = false;
|
||||
};
|
||||
}, [client, initRequest]);
|
||||
const refreshState = useCallback(async () => {
|
||||
const latest = await loadState(client);
|
||||
setState(latest);
|
||||
return latest;
|
||||
}, [client]);
|
||||
|
||||
if (error)
|
||||
return (
|
||||
<Result
|
||||
status="warning"
|
||||
title="系统暂时没有连接上"
|
||||
subTitle={error + ' 请保持启动窗口打开,再刷新页面。'}
|
||||
extra={
|
||||
<Button type="primary" onClick={init}>
|
||||
重新连接
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
);
|
||||
if (!session)
|
||||
return (
|
||||
<div className="page-loading">
|
||||
<Spin tip="正在读取登录状态…" size="large">
|
||||
<div style={{ height: 80 }} />
|
||||
</Spin>
|
||||
</div>
|
||||
);
|
||||
if (!session.user || route === 'login' && !state)
|
||||
return <LoginPage client={client} session={session} onLoggedIn={init} />;
|
||||
if (!state)
|
||||
return (
|
||||
<div className="page-loading">
|
||||
<Spin tip="正在读取店铺资料…" size="large">
|
||||
<div style={{ height: 80 }} />
|
||||
</Spin>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className="shell">
|
||||
<TopBar client={client} state={state} session={session} onLoggedOut={init} />
|
||||
<RequestStatus client={client} />
|
||||
<main className="main">
|
||||
<CreateOrderPage
|
||||
key={state.user.id}
|
||||
client={client}
|
||||
state={state}
|
||||
session={session}
|
||||
refreshState={refreshState}
|
||||
onAccountChanged={init}
|
||||
/>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Alert } from 'antd';
|
||||
import type { LedgerClient } from '../lib/api';
|
||||
import { useClientSnapshot } from '../lib/useClient';
|
||||
|
||||
// 与旧界面 #request-status 相同:显示“正在保存”“正在自动确认(1/2)”等进度。
|
||||
export function RequestStatus({ client }: { client: LedgerClient }) {
|
||||
useClientSnapshot(client);
|
||||
if (!client.progressText) return null;
|
||||
return <Alert className="request-status" type="info" showIcon role="status" message={client.progressText} />;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { useState } from 'react';
|
||||
import { App as AntApp, Button, Tag } from 'antd';
|
||||
import type { LedgerClient } from '../lib/api';
|
||||
import { logout, shopName } from '../lib/session';
|
||||
import { modeLabel } from '../lib/format';
|
||||
import { useClientSnapshot } from '../lib/useClient';
|
||||
import type { LedgerState, SessionInfo } from '../shared';
|
||||
|
||||
export function TopBar({
|
||||
client,
|
||||
state,
|
||||
session,
|
||||
onLoggedOut,
|
||||
}: {
|
||||
client: LedgerClient;
|
||||
state: LedgerState;
|
||||
session: SessionInfo;
|
||||
onLoggedOut: () => void;
|
||||
}) {
|
||||
const { message } = AntApp.useApp();
|
||||
const [leaving, setLeaving] = useState(false);
|
||||
useClientSnapshot(client);
|
||||
const name = shopName(state, session);
|
||||
return (
|
||||
<header className="topbar">
|
||||
<div className="topbar-brand">
|
||||
<span className="brand-mark" aria-hidden="true">
|
||||
{Array.from(name)[0] || '店'}
|
||||
</span>
|
||||
<div>
|
||||
<strong data-testid="store-name">{name}</strong>
|
||||
<small>新版界面 · 开单</small>
|
||||
</div>
|
||||
</div>
|
||||
<div className="topbar-right">
|
||||
<Tag className="mode-tag">{modeLabel(state.mode)}</Tag>
|
||||
<span className="identity" data-testid="identity">
|
||||
{state.user.label || state.user.name}
|
||||
</span>
|
||||
<a className="old-ui-link" href="/">
|
||||
返回旧版界面
|
||||
</a>
|
||||
<Button
|
||||
size="small"
|
||||
loading={leaving}
|
||||
disabled={client.busy}
|
||||
onClick={async () => {
|
||||
setLeaving(true);
|
||||
try {
|
||||
await logout(client);
|
||||
onLoggedOut();
|
||||
} catch (err) {
|
||||
message.error((err as Error).message);
|
||||
} finally {
|
||||
setLeaving(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
退出
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
// 请求客户端:逐条沿用旧界面 public/app.js 中 api()、mutate()、pending() 的约定。
|
||||
// - 读请求:408/502/503/504、网络中断、超时(25 秒)、正文不完整时,按 400ms、1200ms 退避最多重试 2 次。
|
||||
// - 写请求:只有 mutate() 发起、且在幂等白名单内、操作号合法的写入才自动确认(同一 Idempotency-Key、同一请求体)。
|
||||
// - 每次写入前把完整请求存入 localStorage 的 mm-pending-<用户>(与旧界面同一个键),结果未确认时保留,
|
||||
// 由“恢复原操作”原样重发;已确认的 400/403/404/409/413 或已完成的请求才清除。
|
||||
// - 受保护接口带 X-Ledger-User;本页账号与 cookie 不一致时服务端返回 409 ACCOUNT_CHANGED,本端也在重试前核对。
|
||||
|
||||
export interface ApiError extends Error {
|
||||
status?: number;
|
||||
code?: string;
|
||||
confirmed?: boolean;
|
||||
retryable?: boolean;
|
||||
completed?: boolean;
|
||||
}
|
||||
export interface PendingJob {
|
||||
url: string;
|
||||
data: unknown;
|
||||
key: string;
|
||||
userId?: string;
|
||||
}
|
||||
interface StorageLike {
|
||||
getItem(key: string): string | null;
|
||||
setItem(key: string, value: string): void;
|
||||
removeItem(key: string): void;
|
||||
}
|
||||
export interface ClientEnv {
|
||||
fetch: (url: string, init: RequestInit) => Promise<Response>;
|
||||
storage: StorageLike;
|
||||
setTimeout: (fn: () => void, ms: number) => unknown;
|
||||
clearTimeout: (id: unknown) => void;
|
||||
randomUUID: () => string;
|
||||
}
|
||||
const MUTATION_RETRY = Symbol('mutationRetry');
|
||||
export const requestBackoffs = [400, 1200];
|
||||
export const REQUEST_TIMEOUT = 25000;
|
||||
const PUBLIC_ROUTES = ['/api/session', '/api/login', '/api/setup', '/api/demo-login'];
|
||||
|
||||
// 只有服务端事务幂等入口可自动确认;密码、备份、同步及新未知接口不在这里(与旧界面相同的白名单)。
|
||||
export function retryableMutation(url: string): boolean {
|
||||
return (
|
||||
/^\/api\/print-status\/(order|recovery)\/[a-f0-9-]{36}$/.test(url) ||
|
||||
[
|
||||
'/api/orders',
|
||||
'/api/orders/issue',
|
||||
'/api/people-count',
|
||||
'/api/after-sales',
|
||||
'/api/recoveries',
|
||||
'/api/customer-materials',
|
||||
'/api/material-purchases',
|
||||
'/api/material-pools/rolling-enable',
|
||||
'/api/price-locks',
|
||||
'/api/order-templates',
|
||||
'/api/reimbursements',
|
||||
'/api/daily-funds/confirm',
|
||||
'/api/team-funds/transfers',
|
||||
'/api/team-funds/transfer',
|
||||
'/api/stock',
|
||||
'/api/inventory/review',
|
||||
'/api/pockets',
|
||||
'/api/close',
|
||||
'/api/printing',
|
||||
'/api/shop-settings',
|
||||
'/api/employees',
|
||||
].includes(url) ||
|
||||
[
|
||||
/^\/api\/pockets\/[^/]+\/update$/,
|
||||
/^\/api\/employees\/[^/]+\/(?:update|deactivate|reactivate|delete)$/,
|
||||
/^\/api\/orders\/[^/]+\/(?:edit|ownership|change|cancellation|canceltoday|confirm|receipt|refund|expense|fees|cost|deliver|complete|cancel|return|settlement|review|correct|print)$/,
|
||||
/^\/api\/(?:order-templates\/[^/]+\/(?:update|delete)|reimbursements\/[^/]+\/(?:update|approve|reject)|price-locks\/[^/]+\/(?:deliver|edit|cancel|change-requests)|price-lock-changes\/[^/]+\/(?:approve|reject)|material-purchases\/[^/]+\/(?:edit|delete|change)|material-pools\/\d{4}-\d{2}-\d{2}\/settlement|after-sales\/[^/]+\/update|after-sales\/changes\/[^/]+\/(?:approve|reject)|(?:order-changes|order-ownership-changes|order-cancellations|material-purchase-changes)\/[^/]+\/(?:approve|reject)|inventory\/movements\/[^/]+\/(?:update|delete)|inventory\/changes\/[^/]+\/(?:approve|reject))$/,
|
||||
].some(pattern => pattern.test(url))
|
||||
);
|
||||
}
|
||||
export function accountChangedError(): ApiError {
|
||||
return Object.assign(new Error('登录账号已切换,请刷新后继续;原操作已暂停。'), {
|
||||
status: 409,
|
||||
code: 'ACCOUNT_CHANGED',
|
||||
});
|
||||
}
|
||||
interface RetryContext {
|
||||
permission?: symbol;
|
||||
user?: string;
|
||||
}
|
||||
type Token = { user: string; write: boolean };
|
||||
|
||||
export class LedgerClient {
|
||||
private env: ClientEnv;
|
||||
private currentUser = '';
|
||||
private progress = new Map<Token, string>();
|
||||
private listeners = new Set<() => void>();
|
||||
busy = false;
|
||||
progressText = '';
|
||||
|
||||
constructor(env: ClientEnv) {
|
||||
this.env = env;
|
||||
}
|
||||
/** 本页记住的登录账号(旧界面 requestUser())。 */
|
||||
get user() {
|
||||
return this.currentUser;
|
||||
}
|
||||
setUser(id: string) {
|
||||
this.currentUser = id || '';
|
||||
this.emit();
|
||||
}
|
||||
subscribe(listener: () => void) {
|
||||
this.listeners.add(listener);
|
||||
return () => this.listeners.delete(listener);
|
||||
}
|
||||
private emit() {
|
||||
for (const listener of this.listeners) listener();
|
||||
}
|
||||
private showProgress(token: Token, message = '') {
|
||||
if (message) this.progress.set(token, message);
|
||||
else this.progress.delete(token);
|
||||
this.progressText =
|
||||
[...this.progress]
|
||||
.filter(([key]) => key.user === this.currentUser)
|
||||
.sort(([a], [b]) => Number(a.write) - Number(b.write))
|
||||
.at(-1)?.[1] || '';
|
||||
this.emit();
|
||||
}
|
||||
|
||||
async api<T = unknown>(url: string, data?: unknown, operation?: string, retryContext?: RetryContext): Promise<T> {
|
||||
const write = !!data,
|
||||
body = write ? JSON.stringify(data) : undefined;
|
||||
const protectedRequest = url.startsWith('/api/') && !PUBLIC_ROUTES.includes(url),
|
||||
user = protectedRequest ? retryContext?.user || this.currentUser : '';
|
||||
const retry =
|
||||
!write ||
|
||||
(retryContext?.permission === MUTATION_RETRY &&
|
||||
retryableMutation(url) &&
|
||||
/^[a-zA-Z0-9_-]{16,100}$/.test(operation || ''));
|
||||
const token: Token = { user: user || this.currentUser, write },
|
||||
active = () => !user || this.currentUser === user;
|
||||
if (write && retryContext) this.showProgress(token, '正在保存,请稍候…');
|
||||
try {
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
if (!active()) throw accountChangedError();
|
||||
const controller = new AbortController(),
|
||||
timer = this.env.setTimeout(() => controller.abort(), REQUEST_TIMEOUT);
|
||||
try {
|
||||
const r = await this.env.fetch(url, {
|
||||
method: write ? 'POST' : 'GET',
|
||||
headers: {
|
||||
...(write
|
||||
? {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Requested-With': 'maimai-ledger',
|
||||
...(operation ? { 'Idempotency-Key': operation } : {}),
|
||||
}
|
||||
: {}),
|
||||
...(user ? { 'X-Ledger-User': user } : {}),
|
||||
},
|
||||
...(write ? { body } : {}),
|
||||
signal: controller.signal,
|
||||
});
|
||||
// 网关可能返回 HTML,先按状态识别,不能让 JSON 解析失败掩盖 502 等。
|
||||
if ([408, 502, 503, 504].includes(r.status))
|
||||
throw Object.assign(new Error('服务器暂时没有响应(' + r.status + ')'), {
|
||||
status: r.status,
|
||||
retryable: true,
|
||||
});
|
||||
let result: unknown;
|
||||
try {
|
||||
result = await r.json();
|
||||
} catch (error) {
|
||||
if (r.ok) {
|
||||
(error as ApiError).retryable = true;
|
||||
throw error;
|
||||
}
|
||||
result = null;
|
||||
}
|
||||
if (!r.ok) {
|
||||
const payload = result as { error?: unknown; code?: string } | null;
|
||||
const confirmed = !!payload && typeof payload.error === 'string';
|
||||
throw Object.assign(
|
||||
new Error(
|
||||
confirmed ? (payload!.error as string) : '请求被拒绝(' + r.status + '),服务器未返回可确认的业务结果。',
|
||||
),
|
||||
{ confirmed, status: r.status, ...(payload?.code ? { code: payload.code } : {}) },
|
||||
);
|
||||
}
|
||||
if (!active()) throw Object.assign(accountChangedError(), { completed: true });
|
||||
return result as T;
|
||||
} catch (caught) {
|
||||
const err = caught as ApiError;
|
||||
if (!active() && err.code !== 'ACCOUNT_CHANGED') throw accountChangedError();
|
||||
const transient =
|
||||
err.retryable || (!err.status && ['TypeError', 'AbortError', 'TimeoutError'].includes(err.name));
|
||||
if (!retry || !transient || attempt >= requestBackoffs.length) throw err;
|
||||
this.showProgress(
|
||||
token,
|
||||
'连接暂时中断,正在自动' + (write ? '确认' : '重连') + '(' + (attempt + 1) + '/2)…',
|
||||
);
|
||||
await new Promise<void>(resolve => this.env.setTimeout(resolve, requestBackoffs[attempt]));
|
||||
} finally {
|
||||
this.env.clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this.showProgress(token);
|
||||
}
|
||||
}
|
||||
|
||||
pendingKey(user = this.currentUser) {
|
||||
return `mm-pending-${user}`;
|
||||
}
|
||||
pending(): PendingJob | null {
|
||||
try {
|
||||
return JSON.parse(this.env.storage.getItem(this.pendingKey()) || 'null');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
private clearPendingJob(storageKey: string, job: PendingJob) {
|
||||
try {
|
||||
if (JSON.parse(this.env.storage.getItem(storageKey) || 'null')?.key === job.key)
|
||||
this.env.storage.removeItem(storageKey);
|
||||
} catch {
|
||||
/* 本地存储不可用时保留原状 */
|
||||
}
|
||||
}
|
||||
|
||||
/** 写入:先保存完整请求,再以同一操作号发送;existing 为“恢复原操作”时的原请求。 */
|
||||
async mutate<T = unknown>(url: string, data: unknown, existing?: PendingJob): Promise<T> {
|
||||
if (this.busy) throw new Error('正在保存,请稍候');
|
||||
if (this.pending() && !existing) throw new Error('请先点击顶部“恢复原操作”,确认上次提交结果');
|
||||
const user = this.currentUser;
|
||||
if (!user) throw new Error('请先登录后再保存');
|
||||
// 首次发送前复制完整请求,表单继续变动也不能改变自动重试的内容。
|
||||
const job: PendingJob = JSON.parse(
|
||||
JSON.stringify(existing || { url, data, key: this.env.randomUUID(), userId: user }),
|
||||
);
|
||||
const storageKey = this.pendingKey();
|
||||
if (existing && ((job.userId && job.userId !== user) || JSON.stringify(this.pending()) !== JSON.stringify(existing)))
|
||||
throw new Error('待恢复操作与当前账号不匹配,请刷新后核对。');
|
||||
this.busy = true;
|
||||
try {
|
||||
this.env.storage.setItem(storageKey, JSON.stringify(job));
|
||||
this.emit();
|
||||
const r = await this.api<T>(job.url, job.data, job.key, { permission: MUTATION_RETRY, user });
|
||||
this.clearPendingJob(storageKey, job);
|
||||
return r;
|
||||
} catch (caught) {
|
||||
const err = caught as ApiError;
|
||||
if (
|
||||
err.completed ||
|
||||
(err.code !== 'ACCOUNT_CHANGED' && err.confirmed && [400, 403, 404, 409, 413].includes(err.status ?? 0))
|
||||
)
|
||||
this.clearPendingJob(storageKey, job);
|
||||
if (err.code !== 'ACCOUNT_CHANGED') {
|
||||
if (err.status === 401) err.message = '登录已过期,请刷新并登录,再恢复原操作。';
|
||||
else if (!err.confirmed && (!err.status || err.retryable))
|
||||
err.message = '连接中断,提交结果待确认。请点“恢复原操作”,不要重新开单。';
|
||||
else if (!err.confirmed) err.message += ' 提交结果仍待确认,请保留原操作。';
|
||||
}
|
||||
throw err;
|
||||
} finally {
|
||||
this.busy = false;
|
||||
this.emit();
|
||||
}
|
||||
}
|
||||
|
||||
/** “恢复原操作”:原样重发本账号保存的请求(同一请求体、同一操作号)。 */
|
||||
async retryPending<T = unknown>(): Promise<{ job: PendingJob; result: T } | null> {
|
||||
const job = this.pending();
|
||||
if (!job) return null;
|
||||
const result = await this.mutate<T>(job.url, job.data, job);
|
||||
return { job, result };
|
||||
}
|
||||
}
|
||||
|
||||
export function browserClient(): LedgerClient {
|
||||
return new LedgerClient({
|
||||
fetch: (url, init) => window.fetch(url, init),
|
||||
storage: window.localStorage,
|
||||
setTimeout: (fn, ms) => window.setTimeout(fn, ms),
|
||||
clearTimeout: id => window.clearTimeout(id as number),
|
||||
randomUUID: () => window.crypto.randomUUID(),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// 开单内容在浏览器本地暂存(按账号分开),刷新或回到页面后继续填写。
|
||||
// 使用独立的 mm-next-draft-<账号> 键,不覆盖旧界面的 mm-draft-<账号>;内容与旧界面草稿结构相同。
|
||||
interface StorageLike {
|
||||
getItem(key: string): string | null;
|
||||
setItem(key: string, value: string): void;
|
||||
removeItem(key: string): void;
|
||||
}
|
||||
export const draftKey = (userId: string) => `mm-next-draft-${userId}`;
|
||||
export function loadDraft(storage: StorageLike, userId: string): Record<string, unknown> | null {
|
||||
try {
|
||||
const value = JSON.parse(storage.getItem(draftKey(userId)) || 'null');
|
||||
return value && typeof value === 'object' && Array.isArray(value.lines) ? value : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
export function saveDraft(storage: StorageLike, userId: string, draft: unknown) {
|
||||
try {
|
||||
storage.setItem(draftKey(userId), JSON.stringify(draft));
|
||||
} catch {
|
||||
/* 空间不足等情况下放弃暂存,不影响开单 */
|
||||
}
|
||||
}
|
||||
export function clearDraft(storage: StorageLike, userId: string) {
|
||||
try {
|
||||
storage.removeItem(draftKey(userId));
|
||||
} catch {
|
||||
/* 同上 */
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// 显示格式:金额、克重、日期。金额格式与旧界面共用 order-entry-model 中的实现。
|
||||
import dayjs from 'dayjs';
|
||||
import { Model } from '../shared';
|
||||
|
||||
export const yuan = (cents: number | null | undefined) => Model.yuan(cents);
|
||||
export const orderAmount = (cents: number | null, mode: string) => Model.orderAmount(cents, mode);
|
||||
export const grams = (mg: number) => Model.grams(mg);
|
||||
export const longDate = (date: string) => (dayjs(date).isValid() ? dayjs(date).format('YYYY年M月D日') : date);
|
||||
export const modeLabel = (mode?: string) =>
|
||||
mode === 'demo' ? '团队功能预览 · 虚构数据' : mode === 'production' ? '云端系统' : '本机试用';
|
||||
@@ -0,0 +1,29 @@
|
||||
// 极简路由:/next/login 与 /next/(开单),基础路径 /next。只用 History API,不引入路由库。
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export const BASE = '/next';
|
||||
export type Route = 'login' | 'create';
|
||||
export function routeOf(pathname: string): Route {
|
||||
return pathname.replace(/\/+$/, '') === BASE + '/login' ? 'login' : 'create';
|
||||
}
|
||||
export function navigate(route: Route, { keepSearch = false } = {}) {
|
||||
const target = (route === 'login' ? BASE + '/login' : BASE + '/') + (keepSearch ? window.location.search : '');
|
||||
if (window.location.pathname + window.location.search !== target) window.history.pushState(null, '', target);
|
||||
window.dispatchEvent(new Event('next-route'));
|
||||
}
|
||||
export function useRoute(): Route {
|
||||
const [route, setRoute] = useState<Route>(() => routeOf(window.location.pathname));
|
||||
useEffect(() => {
|
||||
const update = () => setRoute(routeOf(window.location.pathname));
|
||||
window.addEventListener('popstate', update);
|
||||
window.addEventListener('next-route', update);
|
||||
return () => {
|
||||
window.removeEventListener('popstate', update);
|
||||
window.removeEventListener('next-route', update);
|
||||
};
|
||||
}, []);
|
||||
return route;
|
||||
}
|
||||
export function searchParam(name: string) {
|
||||
return new URLSearchParams(window.location.search).get(name) || '';
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// 登录状态:会话(登录前)与 /api/state(登录后)读取,以及登录、演示登录、试用初始化与退出。
|
||||
// 登录类接口与旧界面相同:不带操作号、不自动重试;成功后由服务端设置共用的 mm_session cookie(Path=/)。
|
||||
import type { LedgerClient } from './api';
|
||||
import type { LedgerState, SessionInfo } from '../shared';
|
||||
|
||||
export async function loadSession(client: LedgerClient): Promise<SessionInfo> {
|
||||
const session = await client.api<SessionInfo>('/api/session');
|
||||
client.setUser(session.user?.id || '');
|
||||
return session;
|
||||
}
|
||||
export async function loadState(client: LedgerClient): Promise<LedgerState> {
|
||||
return client.api<LedgerState>('/api/state');
|
||||
}
|
||||
export async function login(client: LedgerClient, member: string, password: string) {
|
||||
if (!member) throw new Error('请选择登录账号');
|
||||
if (!password) throw new Error('请输入密码');
|
||||
return client.api('/api/login', { member, password });
|
||||
}
|
||||
export async function demoLogin(client: LedgerClient, member: string) {
|
||||
return client.api('/api/demo-login', { member });
|
||||
}
|
||||
export interface SetupInput {
|
||||
storeName: string;
|
||||
ownerLabel: string;
|
||||
ownerLoginName: string;
|
||||
ownerPassword: string;
|
||||
}
|
||||
export function validateSetup(input: SetupInput): SetupInput {
|
||||
const value = {
|
||||
storeName: input.storeName.trim(),
|
||||
ownerLabel: input.ownerLabel.trim(),
|
||||
ownerLoginName: input.ownerLoginName.trim(),
|
||||
ownerPassword: input.ownerPassword,
|
||||
};
|
||||
if (!value.storeName || value.storeName.length > 80) throw new Error('店铺名称请填写1~80字');
|
||||
if (!value.ownerLabel || value.ownerLabel.length > 30) throw new Error('店主显示名请填写1~30字');
|
||||
if (!value.ownerLoginName || value.ownerLoginName.length > 60) throw new Error('店主登录名请填写1~60字');
|
||||
if (value.ownerPassword.length < 12) throw new Error('店主密码至少12个字符');
|
||||
return value;
|
||||
}
|
||||
export async function setup(client: LedgerClient, input: SetupInput) {
|
||||
// 与旧界面一致:表单原样提交(密码不去空格),校验只拦明显的空白与长度。
|
||||
validateSetup(input);
|
||||
return client.api('/api/setup', input);
|
||||
}
|
||||
export async function logout(client: LedgerClient) {
|
||||
if (client.pending()) throw new Error('请先恢复上次未确认的操作,再退出');
|
||||
await client.api('/api/logout', {});
|
||||
client.setUser('');
|
||||
}
|
||||
export function shopName(state?: LedgerState | null, session?: SessionInfo | null) {
|
||||
return state?.shopSettings?.storeName || state?.printing?.store || session?.brand?.storeName || '珠宝台账';
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { useSyncExternalStore } from 'react';
|
||||
import type { LedgerClient } from './api';
|
||||
|
||||
// 订阅客户端的忙碌、进度与待恢复状态;返回快照字符串用于触发重新渲染。
|
||||
export function useClientSnapshot(client: LedgerClient) {
|
||||
return useSyncExternalStore(
|
||||
listener => {
|
||||
const unsubscribe = client.subscribe(listener);
|
||||
return () => void unsubscribe();
|
||||
},
|
||||
() => [client.busy, client.progressText, client.user, client.pending()?.key || ''].join('\u0000'),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { App as AntApp, ConfigProvider } from 'antd';
|
||||
import zhCN from 'antd/locale/zh_CN';
|
||||
import dayjs from 'dayjs';
|
||||
import 'dayjs/locale/zh-cn';
|
||||
import { App } from './App';
|
||||
import { browserClient } from './lib/api';
|
||||
import './styles.css';
|
||||
|
||||
dayjs.locale('zh-cn');
|
||||
const client = browserClient();
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<ConfigProvider
|
||||
locale={zhCN}
|
||||
theme={{ token: { colorPrimary: '#9a6a2f', borderRadius: 8, fontSize: 15 } }}
|
||||
componentSize="middle"
|
||||
>
|
||||
<AntApp>
|
||||
<App client={client} />
|
||||
</AntApp>
|
||||
</ConfigProvider>
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,97 @@
|
||||
import { Button } from 'antd';
|
||||
import { Model } from '../../shared';
|
||||
import type { ChargeState, LineState, OrderForm } from '../../shared';
|
||||
import { uuid } from './useOrderForm';
|
||||
import { ChoiceField, TextField } from './fields';
|
||||
|
||||
type Update = (change: (form: OrderForm) => OrderForm) => void;
|
||||
|
||||
// 工费附加项目:新选择按店铺报价预填(编绳55、证书10、包装10、快递8),手改金额、填0或清空都原样保留;
|
||||
// 切换类目时记住每个类目各自填过的金额。
|
||||
export function ChargeList({ index, line, update }: { index: number; line: LineState; update: Update }) {
|
||||
const setCharge = (j: number, change: (charge: ChargeState) => ChargeState) =>
|
||||
update(form => {
|
||||
const current = form.lines[index];
|
||||
return Model.updateLine(form, index, {
|
||||
...current,
|
||||
charges: current.charges.map((charge, k) => (k === j ? change(charge) : charge)),
|
||||
});
|
||||
});
|
||||
return (
|
||||
<div className="sale-charges">
|
||||
<div className="panel-title">
|
||||
<strong>工费附加项目(选填)</strong>
|
||||
<Button
|
||||
size="small"
|
||||
data-action="add-charge"
|
||||
onClick={() => update(form => Model.addCharge(form, index, uuid))}
|
||||
>
|
||||
+ 添加附加项目
|
||||
</Button>
|
||||
</div>
|
||||
<p className="small muted">
|
||||
向客户收费预填:编绳55元、证书10元、包装10元、快递8元,均可修改;按填写金额自动加进本行销售额。
|
||||
</p>
|
||||
<div className="charge-list">
|
||||
{line.charges.map((charge, j) => (
|
||||
<div className="charge-row" key={charge.id} data-charge={j}>
|
||||
<ChoiceField
|
||||
label="附加项目"
|
||||
field="chargeType"
|
||||
value={charge.type}
|
||||
options={[...Model.chargeNames, '其他'].map(name => [name, name] as [string, string])}
|
||||
onChange={type => setCharge(j, c => Model.changeChargeType(c, type))}
|
||||
/>
|
||||
<TextField
|
||||
label="附加项目名称"
|
||||
field="chargeName"
|
||||
hidden={charge.type !== '其他'}
|
||||
value={charge.customName}
|
||||
maxLength={40}
|
||||
onChange={value => setCharge(j, c => ({ ...c, customName: value }))}
|
||||
/>
|
||||
<TextField
|
||||
label="附加金额(元)"
|
||||
field="chargeAmount"
|
||||
numeric
|
||||
value={charge.amount}
|
||||
placeholder="没有收费填0,可修改金额"
|
||||
onChange={value => setCharge(j, c => Model.setChargeAmount(c, value))}
|
||||
/>
|
||||
<div className="charge-actions">
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
data-action="remove-charge"
|
||||
onClick={() =>
|
||||
update(form => {
|
||||
const current = form.lines[index];
|
||||
return Model.updateLine(form, index, {
|
||||
...current,
|
||||
charges: current.charges.filter((_, k) => k !== j),
|
||||
});
|
||||
})
|
||||
}
|
||||
>
|
||||
移除附加项
|
||||
</Button>
|
||||
{charge.costRemoved && (
|
||||
<small className="muted">
|
||||
内部成本已移除{' '}
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
data-action="restore-charge-cost"
|
||||
onClick={() => update(form => Model.restoreChargeCost(form, index, j))}
|
||||
>
|
||||
恢复内部成本
|
||||
</Button>
|
||||
</small>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Alert, App as AntApp, Button, Spin, Typography } from 'antd';
|
||||
import type { ApiError, LedgerClient, PendingJob } from '../../lib/api';
|
||||
import { clearDraft, loadDraft } from '../../lib/drafts';
|
||||
import { searchParam } from '../../lib/router';
|
||||
import { useClientSnapshot } from '../../lib/useClient';
|
||||
import { Model } from '../../shared';
|
||||
import type { LedgerState, OrderDraft, SessionInfo } from '../../shared';
|
||||
import { useOrderForm } from './useOrderForm';
|
||||
import { CustomerSection } from './CustomerSection';
|
||||
import { LineItems } from './LineItems';
|
||||
import { FeeCosts } from './FeeCosts';
|
||||
import { SummarySection } from './SummarySection';
|
||||
import { EntryTools } from './EntryTools';
|
||||
import { IssuedResult, type IssuedOrder } from './IssuedResult';
|
||||
|
||||
interface Props {
|
||||
client: LedgerClient;
|
||||
state: LedgerState;
|
||||
session: SessionInfo;
|
||||
refreshState: () => Promise<LedgerState>;
|
||||
onAccountChanged: () => void;
|
||||
}
|
||||
|
||||
// 开单页:先确定初始草稿(地址中的旧草稿订单 ?draft=<订单号>,或本机暂存),再进入表单。
|
||||
export function CreateOrderPage(props: Props) {
|
||||
const { client, state } = props;
|
||||
const draftId = searchParam('draft');
|
||||
const [initial, setInitial] = useState<{ draft: Record<string, unknown> | null; note: string } | null>(
|
||||
draftId ? null : { draft: loadDraft(window.localStorage, state.user.id), note: '' },
|
||||
);
|
||||
useEffect(() => {
|
||||
if (!draftId) return;
|
||||
let current = true;
|
||||
(async () => {
|
||||
try {
|
||||
if (state.user.role !== 'owner') throw new Error('已有草稿由店主继续填写并开单;无单号的新开单流程照常使用。');
|
||||
const order = await client.api<{ status: string } & Record<string, unknown>>(
|
||||
'/api/orders/' + encodeURIComponent(draftId),
|
||||
);
|
||||
if (order.status !== 'draft') throw new Error('这张订单不是未开单的旧草稿,请在旧版界面查看。');
|
||||
if (current) setInitial({ draft: Model.draftInputs(order), note: '正在继续填写旧草稿,生成销售单据后完成记账。' });
|
||||
} catch (err) {
|
||||
if (current)
|
||||
setInitial({ draft: loadDraft(window.localStorage, state.user.id), note: '旧草稿未能打开:' + (err as Error).message });
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
current = false;
|
||||
};
|
||||
}, [client, draftId, state.user.id, state.user.role]);
|
||||
if (!initial)
|
||||
return (
|
||||
<div className="page-loading">
|
||||
<Spin tip="正在读取旧草稿…">
|
||||
<div style={{ height: 60 }} />
|
||||
</Spin>
|
||||
</div>
|
||||
);
|
||||
return <CreateOrderForm {...props} initialDraft={initial.draft} initialNote={initial.note} />;
|
||||
}
|
||||
|
||||
function CreateOrderForm({
|
||||
client,
|
||||
state,
|
||||
session,
|
||||
refreshState,
|
||||
onAccountChanged,
|
||||
initialDraft,
|
||||
initialNote,
|
||||
}: Props & { initialDraft: Record<string, unknown> | null; initialNote: string }) {
|
||||
const { message } = AntApp.useApp();
|
||||
useClientSnapshot(client);
|
||||
const { store, update, reset, ctx, poolError, loadPools } = useOrderForm({ client, state, session, initialDraft });
|
||||
const { form, summary } = store;
|
||||
const [error, setError] = useState('');
|
||||
const [accountChanged, setAccountChanged] = useState(false);
|
||||
const [issued, setIssued] = useState<{ order: IssuedOrder; error: string } | null>(null);
|
||||
const [tags, setTags] = useState<string[]>([]);
|
||||
const [tagsStatus, setTagsStatus] = useState('正在读取快捷标签…');
|
||||
const busy = client.busy;
|
||||
const pending = client.pending();
|
||||
|
||||
// 纸单号预览(旧页面 updatePaperNumber):旧草稿沿用原号(换日期时替换日期段),新单读取预计号码。
|
||||
const [preview, setPreview] = useState<{ date: string; number: string } | null>(null);
|
||||
const paperNumber = useMemo(() => {
|
||||
if (form.paper_number) {
|
||||
const match = form.paper_date && form.paper_number.match(/^\d{8}-?(\d+)$/);
|
||||
return match ? form.date.replaceAll('-', '') + match[1] : form.paper_number;
|
||||
}
|
||||
return preview?.date === form.date ? preview.number + '(预计)' : '保存时分配';
|
||||
}, [form.paper_number, form.paper_date, form.date, preview]);
|
||||
useEffect(() => {
|
||||
if (form.paper_number) return;
|
||||
let current = true;
|
||||
const date = form.date;
|
||||
client
|
||||
.api<{ number: string }>('/api/paper-number?date=' + encodeURIComponent(date))
|
||||
.then(r => current && setPreview({ date, number: r.number }))
|
||||
.catch(() => {
|
||||
/* 日期校验由表单和服务端提示 */
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
};
|
||||
}, [client, form.date, form.paper_number]);
|
||||
// 内部备注快捷标签。
|
||||
useEffect(() => {
|
||||
let current = true;
|
||||
client
|
||||
.api<{ tags?: unknown[] }>('/api/order-note-tags')
|
||||
.then(result => {
|
||||
if (!current) return;
|
||||
setTags(Array.isArray(result.tags) ? result.tags.filter((tag): tag is string => typeof tag === 'string') : []);
|
||||
setTagsStatus('');
|
||||
})
|
||||
.catch(() => current && setTagsStatus('快捷标签暂未读取成功,可直接填写备注。'));
|
||||
return () => {
|
||||
current = false;
|
||||
};
|
||||
}, [client]);
|
||||
|
||||
const showError = useCallback(
|
||||
(err: unknown) => {
|
||||
const e = err as ApiError;
|
||||
if (e.code === 'ACCOUNT_CHANGED') setAccountChanged(true);
|
||||
setError(e.message);
|
||||
message.error(e.message);
|
||||
},
|
||||
[message],
|
||||
);
|
||||
const finishIssued = useCallback(
|
||||
async (input: OrderDraft, result: { id: string }) => {
|
||||
clearDraft(window.localStorage, state.user.id);
|
||||
setIssued({ order: { id: result.id }, error: '' });
|
||||
try {
|
||||
const order = await client.api<IssuedOrder>('/api/orders/' + encodeURIComponent(result.id));
|
||||
setIssued({ order: { ...order, id: result.id }, error: '' });
|
||||
message.success(
|
||||
order.materialCostPending
|
||||
? '销售单据已生成;料费待补,补足购料后自动核算利润'
|
||||
: '销售单据已生成,收款、费用、出库和利润已记账',
|
||||
);
|
||||
void refreshState().catch(() => {});
|
||||
} catch {
|
||||
setIssued({
|
||||
order: { id: result.id, customer: input.customer },
|
||||
error: '销售单据已经生成,最新订单暂未读到。请重新读取或查看已生成销售单;不要重复开单。',
|
||||
});
|
||||
}
|
||||
},
|
||||
[client, message, refreshState, state.user.id],
|
||||
);
|
||||
|
||||
async function submit() {
|
||||
setError('');
|
||||
try {
|
||||
Model.validateFormFields(form, state);
|
||||
const draft = Model.validateIssueDraft(Model.collectDraft(form, state), state);
|
||||
if (draft.id && state.user.role !== 'owner')
|
||||
throw new Error('已有草稿由店主继续填写并开单;无单号的新开单流程照常使用。');
|
||||
const result = await client.mutate<{ id: string }>('/api/orders/issue', draft);
|
||||
await finishIssued(draft, result);
|
||||
} catch (err) {
|
||||
showError(err);
|
||||
}
|
||||
}
|
||||
async function recover(job: PendingJob) {
|
||||
setError('');
|
||||
try {
|
||||
const recovered = await client.retryPending<{ id?: string }>();
|
||||
if (!recovered) return;
|
||||
if (job.url === '/api/orders/issue' && recovered.result.id)
|
||||
return await finishIssued(job.data as OrderDraft, recovered.result as { id: string });
|
||||
message.success('原操作已确认,不会重复记账');
|
||||
} catch (err) {
|
||||
showError(err);
|
||||
}
|
||||
}
|
||||
function startNew() {
|
||||
clearDraft(window.localStorage, state.user.id);
|
||||
if (window.location.search) window.history.replaceState(null, '', window.location.pathname);
|
||||
setIssued(null);
|
||||
setError('');
|
||||
reset(null);
|
||||
}
|
||||
|
||||
if (issued)
|
||||
return (
|
||||
<IssuedResult
|
||||
order={issued.order}
|
||||
error={issued.error}
|
||||
onRetry={() => void finishIssued({ customer: issued.order.customer } as OrderDraft, { id: issued.order.id })}
|
||||
onNew={startNew}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<div className="create-page">
|
||||
<div className="page-heading">
|
||||
<div>
|
||||
<div className="eyebrow">NEW ORDER · 新版界面</div>
|
||||
<Typography.Title level={2}>开一张新单</Typography.Title>
|
||||
<Typography.Paragraph type="secondary">
|
||||
开单即交付,一次记录全额收款、实际费用、出库和利润。订单列表、报表等其他功能请
|
||||
<a href="/">返回旧版界面</a>。
|
||||
</Typography.Paragraph>
|
||||
</div>
|
||||
<Button data-action="clear-draft" disabled={busy} onClick={startNew}>
|
||||
清空表单
|
||||
</Button>
|
||||
</div>
|
||||
{pending && (
|
||||
<Alert
|
||||
className="pending"
|
||||
type="warning"
|
||||
showIcon
|
||||
data-testid="pending"
|
||||
message="上次提交结果尚未确认,请先恢复原操作。重试会使用同一个操作号。"
|
||||
action={
|
||||
<Button danger size="small" disabled={busy} data-action="retry" onClick={() => void recover(pending)}>
|
||||
恢复原操作
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{accountChanged && (
|
||||
<Alert
|
||||
type="error"
|
||||
showIcon
|
||||
message="登录账号已在其他页面切换,原操作已暂停。"
|
||||
action={
|
||||
<Button size="small" onClick={onAccountChanged}>
|
||||
重新读取登录状态
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{initialNote && <Alert type="info" showIcon message={initialNote} />}
|
||||
{form.copy_kind && <Alert type="info" showIcon message="已复制为未保存的新订单,客户称呼已留空。" />}
|
||||
{poolError && <Alert type="warning" showIcon message={poolError} />}
|
||||
<EntryTools
|
||||
client={client}
|
||||
state={state}
|
||||
session={session}
|
||||
form={form}
|
||||
ctx={ctx}
|
||||
update={update}
|
||||
reset={draft => reset(draft)}
|
||||
/>
|
||||
<form
|
||||
id="order-form"
|
||||
className="order-form"
|
||||
noValidate
|
||||
onSubmit={event => {
|
||||
event.preventDefault();
|
||||
if (!busy) void submit();
|
||||
}}
|
||||
>
|
||||
<fieldset disabled={busy} className="form-fieldset">
|
||||
<CustomerSection form={form} state={state} paperNumber={paperNumber} update={update} />
|
||||
<LineItems
|
||||
form={form}
|
||||
state={state}
|
||||
update={update}
|
||||
onError={text => message.error(text)}
|
||||
onReloadPools={() => void loadPools()}
|
||||
/>
|
||||
<FeeCosts form={form} state={state} summary={summary} update={update} />
|
||||
<SummarySection
|
||||
form={form}
|
||||
summary={summary}
|
||||
tags={tags}
|
||||
tagsStatus={tagsStatus}
|
||||
busy={busy}
|
||||
error={error}
|
||||
update={update}
|
||||
onError={text => message.error(text)}
|
||||
/>
|
||||
</fieldset>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { Card, Typography } from 'antd';
|
||||
import { Model } from '../../shared';
|
||||
import type { LedgerState, OrderForm } from '../../shared';
|
||||
import { ChoiceField, RadioField, TextField } from './fields';
|
||||
|
||||
// 客户与单据:业务日期、纸单号、客户、客户类型、开单人、订单归属、收款方式与收款人。
|
||||
export function CustomerSection({
|
||||
form,
|
||||
state,
|
||||
paperNumber,
|
||||
update,
|
||||
}: {
|
||||
form: OrderForm;
|
||||
state: LedgerState;
|
||||
paperNumber: string;
|
||||
update: (change: (form: OrderForm) => OrderForm) => void;
|
||||
}) {
|
||||
const set = (key: keyof OrderForm) => (value: string) => update(f => ({ ...f, [key]: value }));
|
||||
const team = Model.teamMode(state);
|
||||
const card = form.payment.method === '信用卡';
|
||||
return (
|
||||
<Card
|
||||
className="panel"
|
||||
title="客户与单据"
|
||||
extra={
|
||||
<span className="small muted">
|
||||
{form.id ? '补齐原草稿,生成销售单据后完成记账' : '填写内容自动暂存,生成单据即完成记账'}
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<div className="grid four">
|
||||
<TextField label="业务日期" field="date" type="date" value={form.date} onChange={set('date')} />
|
||||
<TextField label="纸单编号(自动)" field="paper_number" value={paperNumber} readOnly />
|
||||
<TextField
|
||||
label="客户称呼/代号(必填)"
|
||||
field="customer"
|
||||
value={form.customer}
|
||||
maxLength={60}
|
||||
placeholder="方便找回订单即可"
|
||||
onChange={set('customer')}
|
||||
/>
|
||||
<RadioField
|
||||
label={'客户类型' + (form.customerTypeRequired ? '(必选)' : '')}
|
||||
field="customer_type"
|
||||
value={form.customer_type}
|
||||
options={[
|
||||
['new', '新客户'],
|
||||
['returning', '老客户'],
|
||||
]}
|
||||
onChange={set('customer_type')}
|
||||
/>
|
||||
<TextField
|
||||
label="开单人(必填)"
|
||||
field="salesperson"
|
||||
value={form.salesperson}
|
||||
maxLength={30}
|
||||
onChange={set('salesperson')}
|
||||
/>
|
||||
{team &&
|
||||
(form.memberLocked ? (
|
||||
<TextField label="订单归属(经营款与业绩)" field="member" value={Model.memberName(state, form.member)} readOnly />
|
||||
) : (
|
||||
<ChoiceField
|
||||
label="订单归属(经营款与业绩)"
|
||||
field="member"
|
||||
value={form.member}
|
||||
options={Model.memberOptions(state)}
|
||||
onChange={member => update(f => Model.changeMember(f, member, state))}
|
||||
/>
|
||||
))}
|
||||
<RadioField
|
||||
label="收款方式"
|
||||
field="payment_method"
|
||||
value={form.payment.method}
|
||||
options={Model.paymentMethods(state).map(method => [method, method] as [string, string])}
|
||||
onChange={method => update(f => ({ ...f, payment: { ...f.payment, method } }))}
|
||||
/>
|
||||
<ChoiceField
|
||||
label="收款人"
|
||||
field="payment_recipient"
|
||||
value={form.payment.recipient}
|
||||
disabled={card}
|
||||
options={Model.recipientOptions(state, form.payment)}
|
||||
hint={card && Model.creditCardAvailable(state) ? `信用卡统一由${Model.memberName(state, 'owner')}收款。` : undefined}
|
||||
onChange={recipient => update(f => ({ ...f, payment: { ...f.payment, recipient } }))}
|
||||
/>
|
||||
</div>
|
||||
<Typography.Paragraph type="secondary" className="small section-note">
|
||||
纸单号前半段为业务日期,后半段序号持续累计,中间不加横线,换日期不归零;生成时分配。生成单据即按成交合计记录全额收款,同时按所选货盘扣减黄金库存并计入实际利润。请核对商品已交付,选择实际收款方式与收款人;业务日期作为收款和出库日期。
|
||||
</Typography.Paragraph>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { Alert, App as AntApp, Button, Collapse, Input, Modal, Select, Space } from 'antd';
|
||||
import type { LedgerClient } from '../../lib/api';
|
||||
import { Copy, Formula, Model, Templates } from '../../shared';
|
||||
import type { LedgerState, OrderForm, SessionInfo, SyncContext } from '../../shared';
|
||||
import { uuid } from './useOrderForm';
|
||||
|
||||
type Update = (change: (form: OrderForm) => OrderForm) => void;
|
||||
interface TemplateRow {
|
||||
id: string;
|
||||
name: string;
|
||||
revision: number;
|
||||
}
|
||||
|
||||
// 开单模板与公式快速开单。模板接口与旧界面相同;公式识别使用共用的 order-formula.js。
|
||||
export function EntryTools({
|
||||
client,
|
||||
state,
|
||||
session,
|
||||
form,
|
||||
ctx,
|
||||
update,
|
||||
reset,
|
||||
}: {
|
||||
client: LedgerClient;
|
||||
state: LedgerState;
|
||||
session: SessionInfo;
|
||||
form: OrderForm;
|
||||
ctx: SyncContext;
|
||||
update: Update;
|
||||
reset: (draft: Record<string, unknown>) => void;
|
||||
}) {
|
||||
return (
|
||||
<Collapse
|
||||
className="entry-tools"
|
||||
items={[
|
||||
{
|
||||
key: 'templates',
|
||||
label: (
|
||||
<span>
|
||||
开单模板 <span className="small muted">选择或保存常用模板</span>
|
||||
</span>
|
||||
),
|
||||
children: <TemplatePanel client={client} state={state} session={session} form={form} reset={reset} />,
|
||||
},
|
||||
...(!form.id
|
||||
? [
|
||||
{
|
||||
key: 'formula',
|
||||
label: (
|
||||
<span>
|
||||
公式快速开单 <span className="small muted">粘贴公式,自动填入商品</span>
|
||||
</span>
|
||||
),
|
||||
children: <FormulaPanel form={form} ctx={ctx} update={update} />,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TemplatePanel({
|
||||
client,
|
||||
state,
|
||||
session,
|
||||
form,
|
||||
reset,
|
||||
}: {
|
||||
client: LedgerClient;
|
||||
state: LedgerState;
|
||||
session: SessionInfo;
|
||||
form: OrderForm;
|
||||
reset: (draft: Record<string, unknown>) => void;
|
||||
}) {
|
||||
const { message, modal } = AntApp.useApp();
|
||||
const [rows, setRows] = useState<TemplateRow[] | null>(null);
|
||||
const [selected, setSelected] = useState('');
|
||||
const [status, setStatus] = useState<{ text: string; error?: boolean }>({ text: '' });
|
||||
const [dialog, setDialog] = useState<null | { kind: 'new' | 'update'; name: string; error: string }>(null);
|
||||
const member = form.member || Model.currentMember(state);
|
||||
const team = Model.teamMode(state);
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const query = team && state.user.role === 'owner' ? '?' + new URLSearchParams({ member }) : '';
|
||||
const result = await client.api<{ rows: TemplateRow[] }>('/api/order-templates' + query);
|
||||
if (!Array.isArray(result.rows)) throw new Error('模板列表未完整返回,请重试。');
|
||||
setRows(result.rows);
|
||||
setSelected(current => (result.rows.some(row => row.id === current) ? current : ''));
|
||||
return true;
|
||||
} catch (err) {
|
||||
setStatus({ text: '模板尚未读到:' + (err as Error).message, error: true });
|
||||
return false;
|
||||
}
|
||||
}, [client, member, team, state.user.role]);
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
const salesperson = Model.defaultSalesperson(state, session);
|
||||
async function apply(id: string) {
|
||||
if (client.busy) throw new Error('正在处理订单,请稍候再套用模板。');
|
||||
if (client.pending()) throw new Error('请先恢复上次未确认的操作,再套用模板。');
|
||||
const user = state.user.id;
|
||||
const [template, latest] = await Promise.all([
|
||||
client.api<{ preset: { lines?: { pocket?: string }[] }; member?: string; name: string }>(
|
||||
'/api/order-templates/' + encodeURIComponent(id),
|
||||
),
|
||||
client.api<SessionInfo>('/api/session'),
|
||||
]);
|
||||
if (latest.user?.id !== user) throw new Error('登录账号已变化,请刷新后再套用模板。');
|
||||
const draft = Templates.apply(template.preset, {
|
||||
today: latest.today,
|
||||
salesperson,
|
||||
pocketKeys: [
|
||||
...new Set([
|
||||
...Model.activePocketKeys(state),
|
||||
...(template.preset.lines || []).map(line => line.pocket || '').filter(Boolean),
|
||||
]),
|
||||
],
|
||||
});
|
||||
draft.salesperson = salesperson;
|
||||
if (team) draft.member = template.member || member;
|
||||
const current = Model.collectDraft(form, state);
|
||||
const hasContent =
|
||||
Copy.hasDraftContent(current, { today: latest.today, salesperson }) ||
|
||||
!!selected ||
|
||||
current.lines.some(
|
||||
line =>
|
||||
line.pricingMode === 'manual' ||
|
||||
(line.laborMode && line.laborMode !== 'gram') ||
|
||||
(line.pieces != null && String(line.pieces) !== '1') ||
|
||||
(line.costLabor as { mode?: string })?.mode === 'gram' ||
|
||||
(line.costMaterial as { mode?: string })?.mode === 'total',
|
||||
);
|
||||
const proceed =
|
||||
!hasContent ||
|
||||
(await modal.confirm({
|
||||
title: '套用模板',
|
||||
content: '当前还有未保存的开单内容。套用模板会替换这份草稿,客户称呼将留空、日期改为今天,是否继续?',
|
||||
okText: '继续',
|
||||
cancelText: '取消',
|
||||
}));
|
||||
if (!proceed) return;
|
||||
reset(draft);
|
||||
setSelected(id);
|
||||
setStatus({ text: '已套用「' + template.name + '」,请核对本次克重、报价和费用后生成单据。' });
|
||||
message.success('模板已填入,生成销售单据后才记账');
|
||||
}
|
||||
async function save() {
|
||||
if (!dialog) return;
|
||||
const name = dialog.name.trim();
|
||||
try {
|
||||
if (!name || name.length > 60) throw new Error('模板名称请填写1~60字。');
|
||||
const row = dialog.kind === 'update' ? rows?.find(value => value.id === selected) : null;
|
||||
const input = {
|
||||
...(team ? { member } : {}),
|
||||
name,
|
||||
preset: Templates.fromDraft(Model.collectDraft(form, state), {
|
||||
pocketKeys: Model.activePocketKeys(state),
|
||||
newId: uuid,
|
||||
}),
|
||||
...(row ? { revision: row.revision } : {}),
|
||||
};
|
||||
const url = '/api/order-templates' + (row ? '/' + encodeURIComponent(row.id) + '/update' : '');
|
||||
const result = await client.mutate<{ id: string; name?: string }>(url, input);
|
||||
setDialog(null);
|
||||
setSelected(result.id);
|
||||
const loaded = await load();
|
||||
setStatus({
|
||||
text:
|
||||
'已保存模板「' + (result.name || name) + '」' + (loaded ? '。' : ';列表暂未读到,可重新读取,当前表单已保留。'),
|
||||
});
|
||||
message.success('模板已保存,当前开单内容保留');
|
||||
} catch (err) {
|
||||
setDialog(current => current && { ...current, error: (err as Error).message.replace('不要重新开单', '不要重复保存模板') });
|
||||
}
|
||||
}
|
||||
async function remove() {
|
||||
const row = rows?.find(value => value.id === selected);
|
||||
if (!row) return;
|
||||
const ok = await modal.confirm({
|
||||
title: '删除模板',
|
||||
content: '删除模板「' + row.name + '」?当前开单内容和已保存订单会保留。',
|
||||
okText: '删除',
|
||||
cancelText: '取消',
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
await client.mutate('/api/order-templates/' + encodeURIComponent(row.id) + '/delete', { revision: row.revision });
|
||||
setSelected('');
|
||||
await load();
|
||||
setStatus({ text: '模板已删除。' });
|
||||
} catch (err) {
|
||||
setStatus({ text: (err as Error).message, error: true });
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div className="template-panel">
|
||||
<Space wrap>
|
||||
<Select
|
||||
aria-label="选择模板"
|
||||
data-testid="template-select"
|
||||
style={{ minWidth: 220 }}
|
||||
value={selected || undefined}
|
||||
placeholder={rows ? '选择后自动填入预设' : '正在读取模板…'}
|
||||
disabled={!rows}
|
||||
options={(rows || []).map(row => ({ value: row.id, label: row.name }))}
|
||||
onChange={id => apply(id).catch(err => setStatus({ text: (err as Error).message, error: true }))}
|
||||
/>
|
||||
<Button onClick={() => setDialog({ kind: 'new', name: '', error: '' })}>保存为新模板</Button>
|
||||
<Button
|
||||
disabled={!selected}
|
||||
onClick={() =>
|
||||
setDialog({ kind: 'update', name: rows?.find(row => row.id === selected)?.name || '', error: '' })
|
||||
}
|
||||
>
|
||||
更新所选模板
|
||||
</Button>
|
||||
<Button disabled={!selected} onClick={() => void remove()}>
|
||||
删除模板
|
||||
</Button>
|
||||
</Space>
|
||||
<p className="small muted">
|
||||
用于普通开单,可以保存未填完的表单。客户称呼和内部备注不存入模板,套用时留空;业务日期和费用日期用今天;每日料价随本次订单日期读取。
|
||||
</p>
|
||||
{status.text && <p className={'small ' + (status.error ? 'danger-text' : 'muted')}>{status.text}</p>}
|
||||
<Modal
|
||||
open={!!dialog}
|
||||
title={dialog?.kind === 'update' ? '更新模板' : '保存为新模板'}
|
||||
okText={dialog?.kind === 'update' ? '保存更新' : '保存模板'}
|
||||
cancelText="取消"
|
||||
onOk={() => void save()}
|
||||
onCancel={() => setDialog(null)}
|
||||
confirmLoading={client.busy}
|
||||
>
|
||||
<p className="small muted">
|
||||
将当前普通开单表单保存为预设,允许金额和克重留空。客户、内部备注、日期及订单编号不存入模板;本次正在填写的内容会保留。
|
||||
</p>
|
||||
<Input
|
||||
aria-label="模板名称"
|
||||
maxLength={60}
|
||||
placeholder="例如:足金手链常用报价"
|
||||
value={dialog?.name || ''}
|
||||
onChange={event => setDialog(current => current && { ...current, name: event.target.value })}
|
||||
/>
|
||||
{dialog?.error && <Alert type="error" showIcon message={dialog.error} style={{ marginTop: 12 }} />}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface FormulaResult {
|
||||
kind: 'note' | 'warning' | 'error';
|
||||
lines: string[];
|
||||
title?: string;
|
||||
pending?: string;
|
||||
}
|
||||
function FormulaPanel({ form, ctx, update }: { form: OrderForm; ctx: SyncContext; update: Update }) {
|
||||
const [text, setText] = useState('');
|
||||
const [result, setResult] = useState<FormulaResult | null>(null);
|
||||
function fill(acceptCalculated: boolean) {
|
||||
try {
|
||||
const parsed = Formula.parseBatch(text, { roundingMode: form.rounding_mode });
|
||||
const summaries = parsed.items.map((item, index) => {
|
||||
const line = item.line,
|
||||
base =
|
||||
line.laborMode === 'gram'
|
||||
? `${line.quantity}克 ×(金价 ${line.goldPrice} + 克工费 ${line.laborRate})`
|
||||
: `${line.quantity}克 × 金价 ${line.goldPrice} + 1件 × 件工费 ${line.laborRate}`;
|
||||
return `本次第 ${index + 1} 件:${base}${line.charges.map(c => ' + 附加费 ' + c.amount).join('')} = ${Model.yuan(item.subtotal)}元`;
|
||||
});
|
||||
summaries.push(
|
||||
`本次商品合计 ${Model.yuan(parsed.subtotal)}元${parsed.roundingMode === 'yuan' ? ',整单取整为 ' + Model.yuan(parsed.total) + '元' : ''}。`,
|
||||
);
|
||||
if (parsed.mismatch && !acceptCalculated) {
|
||||
setResult({
|
||||
kind: 'warning',
|
||||
title: '公式金额与计算结果不一致',
|
||||
lines: [...summaries, ...parsed.warnings, '请修改公式,或按计算结果预填。'],
|
||||
pending: text,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (acceptCalculated && result?.pending !== text) throw new Error('公式已改变,请重新点击“识别并预填”核对');
|
||||
const applied = Model.applyFormulaLines(form, parsed.lines, ctx),
|
||||
filled = applied.filled;
|
||||
update(() => applied.form);
|
||||
setResult({
|
||||
kind: 'note',
|
||||
title: `已预填商品 ${filled.join('、')},共 ${filled.length} 件`,
|
||||
lines: [
|
||||
...summaries,
|
||||
...(parsed.mismatch ? ['已采用左侧公式计算金额,未采用不一致的手写金额。'] : []),
|
||||
(parsed.lines.some(line => line.charges.length)
|
||||
? '附加费已填金额,未判断编绳、烤漆等类目,可自行改名;内部成本请另行核对。'
|
||||
: '') + '已有商品、优惠和客户资料保留,尚未生成订单。',
|
||||
],
|
||||
});
|
||||
setText('');
|
||||
} catch (err) {
|
||||
setResult({ kind: 'error', lines: [(err as Error).message] });
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div className="formula-panel">
|
||||
<Input.TextArea
|
||||
aria-label="粘贴销售公式"
|
||||
rows={4}
|
||||
maxLength={18000}
|
||||
autoComplete="off"
|
||||
placeholder={'0.79×822+120=769\n0.58×(822+45)+55=558\n769+558=1327'}
|
||||
value={text}
|
||||
onChange={event => setText(event.target.value)}
|
||||
/>
|
||||
<Space style={{ marginTop: 8 }}>
|
||||
<Button type="primary" onClick={() => fill(false)}>
|
||||
识别并预填
|
||||
</Button>
|
||||
{result?.kind === 'warning' && <Button onClick={() => fill(true)}>按计算金额预填</Button>}
|
||||
</Space>
|
||||
<p className="small muted">
|
||||
括号内是克工费;金价乘克重后加的是一件工费,再加的金额记为附加费。合计行只校验,不增加商品。客户、货盘及内部成本仍按实际填写。
|
||||
</p>
|
||||
{result && (
|
||||
<Alert
|
||||
role="status"
|
||||
type={result.kind === 'note' ? 'success' : result.kind}
|
||||
message={result.title || (result.kind === 'error' ? result.lines[0] : '')}
|
||||
description={
|
||||
result.kind === 'error' ? undefined : (
|
||||
<div>
|
||||
{result.lines.filter(Boolean).map((line, i) => (
|
||||
<p key={i}>{line}</p>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import { Button, Card, Checkbox, Input } from 'antd';
|
||||
import { Model } from '../../shared';
|
||||
import type { FormSummary, LedgerState, OrderForm } from '../../shared';
|
||||
import { uuid } from './useOrderForm';
|
||||
import { ChoiceField, Field, TextField } from './fields';
|
||||
|
||||
type Update = (change: (form: OrderForm) => OrderForm) => void;
|
||||
|
||||
// 实际费用(内部):费用支付日期、常用成本勾选、附加项目带入的成本行、其他成本、信用卡手续费预览与费用合计。
|
||||
export function FeeCosts({
|
||||
form,
|
||||
state,
|
||||
summary,
|
||||
update,
|
||||
}: {
|
||||
form: OrderForm;
|
||||
state: LedgerState;
|
||||
summary: FormSummary;
|
||||
update: Update;
|
||||
}) {
|
||||
const presets = form.presets;
|
||||
const catalog = Model.presetCatalogView(form, state);
|
||||
const defaults = { certificate: '4', packaging: '3', shipping: '6', ...state.shopSettings?.feeDefaults };
|
||||
return (
|
||||
<Card
|
||||
className="panel internal"
|
||||
title="实际费用(内部)"
|
||||
extra={
|
||||
<Button size="small" data-action="add-fee" onClick={() => update(f => Model.addManualFee(f, state, uuid))}>
|
||||
+ 添加其他成本
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<p className="small muted">
|
||||
{presets
|
||||
? '按实际发生勾选,快递最多选一项;盒子按配置单价和数量计费。取消勾选不记成本,客户收费不受影响。'
|
||||
: form.feeCostMode === 'checkboxes'
|
||||
? '沿用本单已有费用、付款人与支付日期。普通费用按凭据核对;信用卡手续费金额和日期自动维护。'
|
||||
: `上方附加项目自动带入成本。证书默认${defaults.certificate}元、包装${defaults.packaging}元;快递按整单默认${defaults.shipping}元,均可修改。请填写实际已付金额,没有成本填0;不需要的整单费用可移除。开单时记录费用和付款人。`}{' '}
|
||||
客户单据不显示。
|
||||
</p>
|
||||
<div className="grid four">
|
||||
<TextField
|
||||
label="费用实际支付日期"
|
||||
field="fees_date"
|
||||
type="date"
|
||||
value={form.fees_date}
|
||||
onChange={value => update(f => ({ ...f, fees_date: value }))}
|
||||
/>
|
||||
</div>
|
||||
{presets && (
|
||||
<fieldset className="order-cost-presets" data-testid="cost-presets">
|
||||
<legend>常用成本 · 按实际发生勾选</legend>
|
||||
<p className="small muted">快递二选一,也可不选;取消勾选不记成本。</p>
|
||||
<div className="order-cost-options">
|
||||
{catalog.length === 0 && <p>暂无启用的勾选成本,可在店铺配置中添加。</p>}
|
||||
{catalog.map(item => (
|
||||
<div className="order-cost-option" key={item.kind} data-preset={item.kind}>
|
||||
<Checkbox
|
||||
checked={!!presets.checked[item.kind]}
|
||||
onChange={event => update(f => Model.togglePreset(f, item.kind, event.target.checked, state, uuid))}
|
||||
>
|
||||
<strong>{item.name}</strong> <span className="order-cost-price">{item.price}</span>
|
||||
<small className="muted"> {item.kind === 'yt' && !presets.configured ? summary.presetNotes.ytPayer : item.payer}</small>
|
||||
</Checkbox>
|
||||
{item.byQuantity && (
|
||||
<Field label="数量(个)" field={'cost_' + item.kind + '_quantity'} hint={summary.presetNotes[item.kind]}>
|
||||
<Input
|
||||
name={'cost_' + item.kind + '_quantity'}
|
||||
inputMode="numeric"
|
||||
value={presets.quantity[item.kind] ?? '1'}
|
||||
disabled={!presets.checked[item.kind]}
|
||||
onChange={event => update(f => Model.setPresetQuantity(f, item.kind, event.target.value))}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
)}
|
||||
<div className="fee-grid">
|
||||
{form.feeRows.map((row, index) => {
|
||||
const manual = row.key.startsWith('manual:');
|
||||
return (
|
||||
<div className="fee-row" key={row.key} data-fee={row.key} data-fee-index={index}>
|
||||
<div className="fee-title">
|
||||
{manual ? (
|
||||
<TextField
|
||||
label="费用项目名称"
|
||||
field="feeNote"
|
||||
value={row.note}
|
||||
maxLength={150}
|
||||
onChange={value => update(f => Model.editFeeRow(f, index, 'note', value))}
|
||||
/>
|
||||
) : (
|
||||
<strong className="fee-name">{row.note}</strong>
|
||||
)}
|
||||
<span className="small muted fee-source">{Model.feeSourceText(row)}</span>
|
||||
</div>
|
||||
<TextField
|
||||
label="实际成本(元)"
|
||||
field="feeAmount"
|
||||
numeric
|
||||
value={row.amount}
|
||||
placeholder="没有成本填0"
|
||||
onChange={value => update(f => Model.editFeeRow(f, index, 'amount', value))}
|
||||
/>
|
||||
<ChoiceField
|
||||
label="费用付款人"
|
||||
field="feePayer"
|
||||
value={row.payer}
|
||||
options={Model.memberOptions(state, true, { selected: row.payer })}
|
||||
onChange={value => update(f => Model.editFeeRow(f, index, 'payer', value))}
|
||||
/>
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
data-action="remove-fee"
|
||||
onClick={() => update(f => Model.removeFeeRow(f, index))}
|
||||
>
|
||||
移除费用
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{summary.card && (
|
||||
<div className="credit-card-preview" data-testid="credit-card-preview">
|
||||
<div className="credit-card-heading">
|
||||
<strong>信用卡手续费(内部)</strong>
|
||||
<span className="small muted">自动计算 · 客户单据不显示</span>
|
||||
</div>
|
||||
<div className="grid two">
|
||||
<TextField label="手续费(元,自动)" field="credit_card_fee" value={summary.card.amountText} readOnly />
|
||||
<ChoiceField
|
||||
label="手续费付款人"
|
||||
field="credit_card_fee_payer"
|
||||
value={form.credit_card_fee_payer}
|
||||
options={Model.memberOptions(state)}
|
||||
onChange={value => update(f => ({ ...f, credit_card_fee_payer: value }))}
|
||||
/>
|
||||
</div>
|
||||
<p className="small muted" aria-live="polite">
|
||||
{summary.card.formula}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<div className="small fees-total" data-testid="fees-total">
|
||||
{summary.feesText}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
import { Button } from 'antd';
|
||||
import { Model } from '../../shared';
|
||||
import type { LedgerState, LineState, OrderForm } from '../../shared';
|
||||
import { ChoiceField, RadioField, TextField } from './fields';
|
||||
|
||||
type Update = (change: (form: OrderForm) => OrderForm) => void;
|
||||
|
||||
// 内部成本(客户单据不显示):出库货盘、对数、料费(按克料价/总料费/当日加权料价)、进货工费(克工费/总工费)、付款人。
|
||||
export function InternalCosts({
|
||||
index,
|
||||
line,
|
||||
state,
|
||||
update,
|
||||
onReloadPools,
|
||||
}: {
|
||||
index: number;
|
||||
line: LineState;
|
||||
state: LedgerState;
|
||||
update: Update;
|
||||
onReloadPools: () => void;
|
||||
}) {
|
||||
const v = Model.lineVisibility(line, state);
|
||||
const setLine = (change: (line: LineState) => LineState) =>
|
||||
update(form => Model.updateLine(form, index, change(form.lines[index])));
|
||||
const setPurchase = (field: string) => (value: string) => setLine(l => Model.setPurchaseField(l, field, value));
|
||||
const payers = Model.memberOptions(state);
|
||||
const p = line.purchase;
|
||||
const pooled = line.pool?.source === 'pool';
|
||||
const payerOptions = (value: string): [string, string][] =>
|
||||
Model.memberKeys(state).includes(value) ? Model.memberOptions(state, false, { selected: value }) : payers;
|
||||
return (
|
||||
<div className="internal">
|
||||
<div className="internal-title">内部成本 · 客户单据不显示</div>
|
||||
<div className="grid two cost-source-fields">
|
||||
<ChoiceField
|
||||
label="出库货盘(仅黄金)"
|
||||
field="pocket"
|
||||
value={line.pocket}
|
||||
options={Model.pocketOptions(state, line.pocket, line.historicalPocket)}
|
||||
onChange={value => setLine(l => Model.setLineField(l, 'pocket', value))}
|
||||
/>
|
||||
<TextField
|
||||
label="出库数量(对)"
|
||||
field="stockCount"
|
||||
numeric
|
||||
hidden={!v.stockCount}
|
||||
value={line.stockCount}
|
||||
placeholder="一对填1"
|
||||
hint={v.stockCountOptional ? '历史未记录对数,可保留空白;与计工费件数分别填写。' : '与计工费件数分别填写。'}
|
||||
onChange={value => setLine(l => Model.setLineField(l, 'stockCount', value))}
|
||||
/>
|
||||
</div>
|
||||
{line.legacy ? (
|
||||
<TextField label="原单货品成本(旧版未分项)" field="cost" value={line.cost} readOnly />
|
||||
) : (
|
||||
p && (
|
||||
<div className="cost-fields">
|
||||
{line.pool && (
|
||||
<div className="material-source">
|
||||
<div className="grid three">
|
||||
<RadioField
|
||||
label="料费成本来源"
|
||||
field="materialSource"
|
||||
value={line.pool.source}
|
||||
options={[
|
||||
['manual', '手动填写成本'],
|
||||
['pool', '当日加权料价', !v.poolAllowed],
|
||||
]}
|
||||
onChange={value => setLine(l => Model.setPoolSource(l, value as 'manual' | 'pool'))}
|
||||
/>
|
||||
{pooled && (
|
||||
<ChoiceField
|
||||
label="料价日期"
|
||||
field="materialPoolId"
|
||||
value={line.pool.poolId}
|
||||
options={line.pool.options.map(option => [option.value, option.label] as [string, string])}
|
||||
onChange={value =>
|
||||
setLine(l => ({ ...l, pool: l.pool ? { ...l.pool, poolId: value } : l.pool }))
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{pooled && (
|
||||
<div className="field">
|
||||
<label className="field-label"> </label>
|
||||
<Button size="small" data-action="reload-material-choices" onClick={onReloadPools}>
|
||||
刷新料价
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<p className="small muted">{line.pool.help}</p>
|
||||
{pooled && line.view.poolNote && (
|
||||
<p className="small material-pool-note" aria-live="polite" data-testid="pool-note">
|
||||
{line.view.poolNote}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="grid four purchase-cost-grid">
|
||||
{v.materialMode && (
|
||||
<RadioField
|
||||
label="进货料费方式"
|
||||
field="cost-materialMode"
|
||||
value={p.materialMode}
|
||||
options={[
|
||||
['gram', '按克料价', line.unit !== 'g'],
|
||||
['total', '直接填总料费'],
|
||||
]}
|
||||
onChange={setPurchase('materialMode')}
|
||||
/>
|
||||
)}
|
||||
<TextField
|
||||
label={pooled ? '加权进货料价(元/克,自动)' : '进货料价(元/克)'}
|
||||
field="cost-materialRate"
|
||||
numeric
|
||||
hidden={!v.materialRate}
|
||||
readOnly={pooled}
|
||||
value={p.materialRate}
|
||||
placeholder={pooled ? '待核算' : '填写每克进货料价'}
|
||||
onChange={setPurchase('materialRate')}
|
||||
/>
|
||||
<TextField
|
||||
label={pooled ? '耗用料费合计(元,自动)' : '料费成本合计(元)'}
|
||||
field="cost-material"
|
||||
numeric
|
||||
readOnly={v.materialReadOnly}
|
||||
value={p.material}
|
||||
placeholder={pooled ? '待核算' : '开单前必填,没有填0'}
|
||||
onChange={setPurchase('material')}
|
||||
/>
|
||||
{v.materialPayer ? (
|
||||
<ChoiceField
|
||||
label="料费付款人"
|
||||
field="cost-materialPayer"
|
||||
value={p.materialPayer}
|
||||
placeholder="请选择"
|
||||
options={payerOptions(p.materialPayer)}
|
||||
onChange={setPurchase('materialPayer')}
|
||||
/>
|
||||
) : (
|
||||
<TextField
|
||||
label={line.pool?.personal ? '材料原付款人' : '本批购料付款人'}
|
||||
field="cost-materialPoolPayer"
|
||||
value={line.pool?.payerText || ''}
|
||||
readOnly
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<p className="purchase-formula small muted" aria-live="polite">
|
||||
{line.view.materialFormula}
|
||||
</p>
|
||||
{line.view.materialOriginal && <p className="small muted">{line.view.materialOriginal}</p>}
|
||||
<div className="grid four purchase-cost-grid">
|
||||
<RadioField
|
||||
label="进货工费方式"
|
||||
field="cost-laborMode"
|
||||
value={p.laborMode}
|
||||
options={[
|
||||
['gram', '克工费', line.unit !== 'g'],
|
||||
['total', '总工费'],
|
||||
]}
|
||||
onChange={setPurchase('laborMode')}
|
||||
/>
|
||||
<TextField
|
||||
label="进货克工费(元/克)"
|
||||
field="cost-laborRate"
|
||||
numeric
|
||||
hidden={!v.laborRateInput}
|
||||
value={p.laborRate}
|
||||
placeholder="填写每克工费"
|
||||
onChange={setPurchase('laborRate')}
|
||||
/>
|
||||
<TextField
|
||||
label="进货总工费(元)"
|
||||
field="cost-labor"
|
||||
numeric
|
||||
readOnly={v.laborReadOnly}
|
||||
value={p.labor}
|
||||
placeholder="开单前必填,没有填0"
|
||||
onChange={setPurchase('labor')}
|
||||
/>
|
||||
<ChoiceField
|
||||
label="进货工费付款人"
|
||||
field="cost-laborPayer"
|
||||
value={p.laborPayer}
|
||||
placeholder="请选择"
|
||||
options={payerOptions(p.laborPayer)}
|
||||
onChange={setPurchase('laborPayer')}
|
||||
/>
|
||||
</div>
|
||||
<p className="purchase-formula small muted" aria-live="polite">
|
||||
{line.view.laborFormula}
|
||||
</p>
|
||||
{v.extraCosts && (
|
||||
<div className="legacy-extra-costs">
|
||||
<p className="small muted">这里保留原来填写的货品成本,不要在下方实际费用重复登记。</p>
|
||||
<div className="grid three">
|
||||
<TextField
|
||||
label="配件成本(元,本行合计)"
|
||||
field="cost-accessories"
|
||||
numeric
|
||||
value={p.accessories}
|
||||
onChange={setPurchase('accessories')}
|
||||
/>
|
||||
<TextField
|
||||
label="其他货品成本(元,本行合计)"
|
||||
field="cost-other"
|
||||
numeric
|
||||
value={p.other}
|
||||
onChange={setPurchase('other')}
|
||||
/>
|
||||
<ChoiceField
|
||||
label="原有配件及其他成本付款人"
|
||||
field="payer"
|
||||
value={line.payer}
|
||||
options={payers}
|
||||
onChange={value => setLine(l => ({ ...l, payer: value }))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<p className="cost-summary small">
|
||||
本行货品成本合计:
|
||||
{line.view.purchase?.total == null
|
||||
? pooled
|
||||
? '料费待核算'
|
||||
: '请补齐(没有的项目填0)'
|
||||
: '¥' + Model.yuan(line.view.purchase.total)}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { Button, Result, Space, Typography } from 'antd';
|
||||
import { orderAmount } from '../../lib/format';
|
||||
|
||||
export interface IssuedOrder {
|
||||
id: string;
|
||||
paper_number?: string;
|
||||
number?: string;
|
||||
total?: number;
|
||||
rounding_mode?: string;
|
||||
customer?: string;
|
||||
materialCostPending?: boolean;
|
||||
}
|
||||
|
||||
// 开单成功:显示纸单号与成交合计,可打开服务端打印预览 /print/<订单号>,或开始下一张单。
|
||||
export function IssuedResult({
|
||||
order,
|
||||
error,
|
||||
onRetry,
|
||||
onNew,
|
||||
}: {
|
||||
order: IssuedOrder;
|
||||
error: string;
|
||||
onRetry: () => void;
|
||||
onNew: () => void;
|
||||
}) {
|
||||
const loaded = order.total !== undefined;
|
||||
return (
|
||||
<Result
|
||||
status="success"
|
||||
title="销售单据已生成"
|
||||
subTitle={
|
||||
loaded
|
||||
? order.materialCostPending
|
||||
? '收款、费用和出库已记账;料费待补,补足购料后自动核算利润。'
|
||||
: '收款、费用、出库和利润已记账。'
|
||||
: error || '正在读取已生成的销售单…'
|
||||
}
|
||||
extra={
|
||||
<Space direction="vertical" size="large" style={{ width: '100%' }}>
|
||||
{loaded && (
|
||||
<div className="issued-summary" data-testid="issued-summary">
|
||||
<div>
|
||||
<Typography.Text type="secondary">纸单号</Typography.Text>
|
||||
<div className="issued-value" data-testid="issued-paper-number">
|
||||
{order.paper_number || '未分配'}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Typography.Text type="secondary">成交合计</Typography.Text>
|
||||
<div className="issued-value" data-testid="issued-total">
|
||||
{orderAmount(order.total ?? null, order.rounding_mode || 'cent')}
|
||||
</div>
|
||||
</div>
|
||||
{order.customer && (
|
||||
<div>
|
||||
<Typography.Text type="secondary">客户</Typography.Text>
|
||||
<div className="issued-value small">{order.customer}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<Space wrap className="issued-actions">
|
||||
<Button
|
||||
type="primary"
|
||||
size="large"
|
||||
href={'/print/' + encodeURIComponent(order.id)}
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
data-action="print-preview"
|
||||
>
|
||||
打开打印预览
|
||||
</Button>
|
||||
<Button size="large" onClick={onNew} data-action="new-order">
|
||||
开始新的一单
|
||||
</Button>
|
||||
{!loaded && <Button onClick={onRetry}>重新读取订单</Button>}
|
||||
<Button size="large" href="/" type="link">
|
||||
到旧版界面查看订单
|
||||
</Button>
|
||||
</Space>
|
||||
</Space>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
import { Button, Card, Typography } from 'antd';
|
||||
import { Model } from '../../shared';
|
||||
import type { LedgerState, LineState, OrderForm } from '../../shared';
|
||||
import { uuid } from './useOrderForm';
|
||||
import { ChoiceField, RadioField, TextField } from './fields';
|
||||
import { ChargeList } from './ChargeList';
|
||||
import { InternalCosts } from './InternalCosts';
|
||||
|
||||
type Update = (change: (form: OrderForm) => OrderForm) => void;
|
||||
|
||||
// 商品明细:每行商品的名称、计价方式、克重、金价与工费或直接金额、附加项目、本行销售额与内部成本。
|
||||
export function LineItems({
|
||||
form,
|
||||
state,
|
||||
update,
|
||||
onError,
|
||||
onReloadPools,
|
||||
}: {
|
||||
form: OrderForm;
|
||||
state: LedgerState;
|
||||
update: Update;
|
||||
onError: (message: string) => void;
|
||||
onReloadPools: () => void;
|
||||
}) {
|
||||
const guarded = (change: (form: OrderForm) => OrderForm) => {
|
||||
try {
|
||||
update(change);
|
||||
} catch (err) {
|
||||
onError((err as Error).message);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Card className="panel" title="商品明细" extra={<span className="small muted">金价与工费分开填写</span>}>
|
||||
{form.lines.map((line, index) => (
|
||||
<LineCard
|
||||
key={index}
|
||||
index={index}
|
||||
line={line}
|
||||
state={state}
|
||||
canRemove={form.lines.length > 1}
|
||||
update={update}
|
||||
onRemove={() => {
|
||||
if (form.lines.length <= 1) return onError('请至少保留一行商品');
|
||||
guarded(f => Model.removeLine(f, index));
|
||||
}}
|
||||
onReloadPools={onReloadPools}
|
||||
/>
|
||||
))}
|
||||
<div className="form-actions">
|
||||
<Button data-action="add-line" onClick={() => guarded(f => Model.addLine(f, { st: state, uuid }))}>
|
||||
+ 添加商品
|
||||
</Button>
|
||||
<span className="small muted">银饰不扣黄金货盘;外配使用店内金料时,选实际出库货盘。</span>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function LineCard({
|
||||
index,
|
||||
line,
|
||||
state,
|
||||
canRemove,
|
||||
update,
|
||||
onRemove,
|
||||
onReloadPools,
|
||||
}: {
|
||||
index: number;
|
||||
line: LineState;
|
||||
state: LedgerState;
|
||||
canRemove: boolean;
|
||||
update: Update;
|
||||
onRemove: () => void;
|
||||
onReloadPools: () => void;
|
||||
}) {
|
||||
const v = Model.lineVisibility(line, state);
|
||||
const setLine = (change: (line: LineState) => LineState) =>
|
||||
update(form => Model.updateLine(form, index, change(form.lines[index])));
|
||||
const set = (field: string) => (value: string) => setLine(l => Model.setLineField(l, field, value));
|
||||
return (
|
||||
<section className="line-item" data-line={index} aria-label={'商品 ' + (index + 1)}>
|
||||
<div className="line-top">
|
||||
<strong>商品 {String(index + 1).padStart(2, '0')}</strong>
|
||||
<Button type="text" size="small" data-action="remove-line" disabled={!canRemove} onClick={onRemove}>
|
||||
移除
|
||||
</Button>
|
||||
</div>
|
||||
<div className="grid four">
|
||||
<ChoiceField
|
||||
label="商品名称"
|
||||
field="nameType"
|
||||
value={line.nameType}
|
||||
options={[...Model.productNames, '其他'].map(name => [name, name] as [string, string])}
|
||||
onChange={set('nameType')}
|
||||
/>
|
||||
<TextField
|
||||
label="其他商品名称"
|
||||
field="customName"
|
||||
hidden={!v.customName}
|
||||
value={line.customName}
|
||||
maxLength={60}
|
||||
onChange={set('customName')}
|
||||
/>
|
||||
<RadioField
|
||||
label="计价方式"
|
||||
field="pricingMode"
|
||||
value={line.pricingMode}
|
||||
options={[
|
||||
['auto', '按金价与工费计算'],
|
||||
['manual', '直接填写金额'],
|
||||
]}
|
||||
onChange={set('pricingMode')}
|
||||
/>
|
||||
<RadioField
|
||||
label="单位"
|
||||
field="unit"
|
||||
value={line.unit}
|
||||
options={[
|
||||
['g', 'g'],
|
||||
['件', '件'],
|
||||
]}
|
||||
onChange={set('unit')}
|
||||
/>
|
||||
<TextField label="克重/数量" field="quantity" numeric value={line.quantity} onChange={set('quantity')} />
|
||||
</div>
|
||||
<div className="grid four sale-inputs">
|
||||
<TextField
|
||||
label="金价/银价(元/克)"
|
||||
field="goldPrice"
|
||||
numeric
|
||||
hidden={!v.goldPrice}
|
||||
value={line.goldPrice}
|
||||
onChange={set('goldPrice')}
|
||||
/>
|
||||
<RadioField
|
||||
label="销售工费方式"
|
||||
field="laborMode"
|
||||
hidden={!v.laborMode}
|
||||
value={line.laborMode}
|
||||
options={[
|
||||
['gram', '克工费'],
|
||||
['piece', '件工费'],
|
||||
]}
|
||||
onChange={set('laborMode')}
|
||||
/>
|
||||
<TextField
|
||||
label="销售工费"
|
||||
field="laborRate"
|
||||
numeric
|
||||
hidden={!v.laborRate}
|
||||
value={line.laborRate}
|
||||
onChange={set('laborRate')}
|
||||
/>
|
||||
<TextField
|
||||
label="计工费件数"
|
||||
field="pieces"
|
||||
numeric
|
||||
hidden={!v.pieces}
|
||||
value={line.pieces}
|
||||
onChange={set('pieces')}
|
||||
/>
|
||||
<TextField
|
||||
label="销售单价说明(客户可见)"
|
||||
field="priceNote"
|
||||
hidden={!v.priceNote}
|
||||
value={line.priceNote}
|
||||
maxLength={100}
|
||||
onChange={set('priceNote')}
|
||||
/>
|
||||
<TextField
|
||||
label="商品基础金额(不含附加项目)"
|
||||
field="baseSale"
|
||||
numeric
|
||||
hidden={!v.baseSale}
|
||||
value={line.baseSale}
|
||||
onChange={set('baseSale')}
|
||||
/>
|
||||
</div>
|
||||
<ChargeList index={index} line={line} update={update} />
|
||||
<div className="grid two sale-result">
|
||||
<TextField label="本行销售额(元,含附加项目)" field="sale" value={line.sale} readOnly />
|
||||
<Typography.Paragraph className="calculation small" aria-live="polite" data-testid="line-calculation">
|
||||
{line.view.calculation}
|
||||
</Typography.Paragraph>
|
||||
</div>
|
||||
<InternalCosts index={index} line={line} state={state} update={update} onReloadPools={onReloadPools} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { Alert, Button, Card, Input } from 'antd';
|
||||
import { Model } from '../../shared';
|
||||
import type { FormSummary, OrderForm } from '../../shared';
|
||||
import { TextField, Field } from './fields';
|
||||
|
||||
type Update = (change: (form: OrderForm) => OrderForm) => void;
|
||||
|
||||
// 整单优惠、客户单备注、内部备注(快捷标签)、成交合计与提交。
|
||||
export function SummarySection({
|
||||
form,
|
||||
summary,
|
||||
tags,
|
||||
tagsStatus,
|
||||
busy,
|
||||
error,
|
||||
update,
|
||||
onError,
|
||||
}: {
|
||||
form: OrderForm;
|
||||
summary: FormSummary;
|
||||
tags: string[];
|
||||
tagsStatus: string;
|
||||
busy: boolean;
|
||||
error: string;
|
||||
update: Update;
|
||||
onError: (message: string) => void;
|
||||
}) {
|
||||
const shown = Model.filterNoteTags(tags, form.internal_note);
|
||||
const query = /(?:^|[\s,。;、])#([\p{L}\p{N}_-]*)$/u.test(form.internal_note);
|
||||
return (
|
||||
<Card className="panel">
|
||||
<div className="grid two">
|
||||
<TextField
|
||||
label="整单优惠/抹零(元)"
|
||||
field="discount"
|
||||
numeric
|
||||
value={form.discount}
|
||||
onChange={value => update(f => ({ ...f, discount: value }))}
|
||||
/>
|
||||
<Field label="客户单备注" field="note">
|
||||
<Input.TextArea
|
||||
name="note"
|
||||
aria-label="客户单备注"
|
||||
maxLength={240}
|
||||
rows={2}
|
||||
placeholder="只写可让客户看到的内容"
|
||||
value={form.note}
|
||||
onChange={event => update(f => ({ ...f, note: event.target.value }))}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
<Field
|
||||
label={
|
||||
<>
|
||||
内部备注(客户不可见)<span className="small muted">必填,至少3个字符(含#号),最多500字</span>
|
||||
</>
|
||||
}
|
||||
field="internal_note"
|
||||
>
|
||||
<Input.TextArea
|
||||
name="internal_note"
|
||||
aria-label="内部备注"
|
||||
maxLength={500}
|
||||
rows={3}
|
||||
placeholder="仅供内部跟进,不会出现在客户销售单或打印件中"
|
||||
value={form.internal_note}
|
||||
onChange={event => update(f => ({ ...f, internal_note: event.target.value }))}
|
||||
/>
|
||||
</Field>
|
||||
<div className="order-note-tags">
|
||||
<p className="small muted">
|
||||
输入 #词语 添加标签,例如 #补货、#客户自提。保存订单后可复用,点击下方标签即可填入。
|
||||
</p>
|
||||
<div className="order-note-tag-options" aria-label="内部备注快捷标签" data-testid="note-tags">
|
||||
{tagsStatus ? (
|
||||
<span className="small muted">{tagsStatus}</span>
|
||||
) : shown.length ? (
|
||||
shown.map(tag => (
|
||||
<Button
|
||||
key={tag}
|
||||
size="small"
|
||||
data-note-tag={tag}
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
try {
|
||||
const next = Model.insertNoteTag(form.internal_note, tag);
|
||||
update(f => ({ ...f, internal_note: next }));
|
||||
} catch (err) {
|
||||
onError((err as Error).message);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{tag}
|
||||
</Button>
|
||||
))
|
||||
) : (
|
||||
<span className="small muted">
|
||||
{query ? '没有匹配标签,可继续输入新标签。' : '暂无已保存标签,填写 #词语 并保存订单后即可复用。'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="create-submit-bar">
|
||||
<div>
|
||||
<span className="small muted">成交合计</span>
|
||||
<div className="summary-amount" data-testid="create-total">
|
||||
{summary.totalText}
|
||||
</div>
|
||||
<div className="small muted" aria-live="polite" data-testid="rounding-note">
|
||||
{summary.roundingHint}
|
||||
</div>
|
||||
</div>
|
||||
<Button type="primary" htmlType="submit" size="large" loading={busy} data-action="issue">
|
||||
生成销售单据
|
||||
</Button>
|
||||
</div>
|
||||
{error && (
|
||||
<Alert type="error" showIcon message={error} className="order-error" role="alert" data-testid="order-error" />
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
// 表单小部件:带标签的文本、数字、选择与单选。每个字段外层带 data-field,便于核对与自动化操作。
|
||||
import type { ReactNode } from 'react';
|
||||
import { Input, Radio, Select } from 'antd';
|
||||
|
||||
interface Base {
|
||||
label: ReactNode;
|
||||
field: string;
|
||||
hint?: ReactNode;
|
||||
hidden?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
export function Field({ label, field, hint, hidden, className, children }: Base & { children: ReactNode }) {
|
||||
if (hidden) return null;
|
||||
return (
|
||||
<div className={'field ' + (className || '')} data-field={field}>
|
||||
<label className="field-label">{label}</label>
|
||||
{children}
|
||||
{hint ? <div className="field-hint">{hint}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function TextField({
|
||||
value,
|
||||
onChange,
|
||||
numeric,
|
||||
readOnly,
|
||||
disabled,
|
||||
placeholder,
|
||||
maxLength,
|
||||
type,
|
||||
...base
|
||||
}: Base & {
|
||||
value: string;
|
||||
onChange?: (value: string) => void;
|
||||
numeric?: boolean;
|
||||
readOnly?: boolean;
|
||||
disabled?: boolean;
|
||||
placeholder?: string;
|
||||
maxLength?: number;
|
||||
type?: string;
|
||||
}) {
|
||||
return (
|
||||
<Field {...base}>
|
||||
<Input
|
||||
name={base.field}
|
||||
aria-label={typeof base.label === 'string' ? base.label : base.field}
|
||||
value={value}
|
||||
type={type}
|
||||
inputMode={numeric ? 'decimal' : undefined}
|
||||
autoComplete="off"
|
||||
readOnly={readOnly}
|
||||
disabled={disabled}
|
||||
placeholder={placeholder}
|
||||
maxLength={maxLength}
|
||||
className={readOnly ? 'readonly-input' : undefined}
|
||||
onChange={event => onChange?.(event.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
export function ChoiceField({
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
disabled,
|
||||
placeholder,
|
||||
...base
|
||||
}: Base & {
|
||||
value: string;
|
||||
options: [string, string, boolean?][];
|
||||
onChange: (value: string) => void;
|
||||
disabled?: boolean;
|
||||
placeholder?: string;
|
||||
}) {
|
||||
return (
|
||||
<Field {...base}>
|
||||
<Select
|
||||
aria-label={typeof base.label === 'string' ? base.label : base.field}
|
||||
value={value === '' && placeholder ? undefined : value}
|
||||
placeholder={placeholder}
|
||||
disabled={disabled}
|
||||
popupMatchSelectWidth={false}
|
||||
options={options.map(([v, label, off]) => ({ value: v, label, disabled: !!off, title: label }))}
|
||||
onChange={onChange}
|
||||
getPopupContainer={() => document.body}
|
||||
/>
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
export function RadioField({
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
disabled,
|
||||
...base
|
||||
}: Base & {
|
||||
value: string;
|
||||
options: [string, string, boolean?][];
|
||||
onChange: (value: string) => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Field {...base}>
|
||||
<Radio.Group
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
optionType="button"
|
||||
buttonStyle="solid"
|
||||
size="middle"
|
||||
onChange={event => onChange(event.target.value)}
|
||||
options={options.map(([v, label, off]) => ({ value: v, label, disabled: !!off }))}
|
||||
/>
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
// 开单表单状态:每次修改都经共用模型 syncForm 重新同步(等同旧页面每次输入后的 updateTotal)。
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { LedgerClient } from '../../lib/api';
|
||||
import { saveDraft } from '../../lib/drafts';
|
||||
import { Model } from '../../shared';
|
||||
import type {
|
||||
FormSummary,
|
||||
LedgerState,
|
||||
MaterialPools,
|
||||
OrderDraft,
|
||||
OrderForm,
|
||||
QuoteState,
|
||||
SessionInfo,
|
||||
SyncContext,
|
||||
} from '../../shared';
|
||||
|
||||
export interface FormStore {
|
||||
form: OrderForm;
|
||||
draft: OrderDraft;
|
||||
summary: FormSummary;
|
||||
}
|
||||
export const uuid = () => window.crypto.randomUUID();
|
||||
|
||||
export function useOrderForm({
|
||||
client,
|
||||
state,
|
||||
session,
|
||||
initialDraft,
|
||||
}: {
|
||||
client: LedgerClient;
|
||||
state: LedgerState;
|
||||
session: SessionInfo;
|
||||
initialDraft: Record<string, unknown> | null;
|
||||
}) {
|
||||
const [pools, setPools] = useState<MaterialPools | null>(null);
|
||||
const [poolError, setPoolError] = useState('');
|
||||
const [quote, setQuote] = useState<QuoteState | null>(null);
|
||||
const ctx = useMemo<SyncContext>(
|
||||
() => ({ st: state, session, uuid, materialPools: pools, quote }),
|
||||
[state, session, pools, quote],
|
||||
);
|
||||
const ctxRef = useRef(ctx);
|
||||
const [store, setStore] = useState<FormStore>(() =>
|
||||
Model.syncForm(Model.newForm({ st: state, session, uuid }, initialDraft || undefined), {
|
||||
st: state,
|
||||
session,
|
||||
uuid,
|
||||
}),
|
||||
);
|
||||
// 同步计算并立即生效:模型抛出的提示(如“请至少保留一行商品”)直接返回给调用方。
|
||||
const storeRef = useRef(store);
|
||||
const commit = useCallback((next: FormStore) => {
|
||||
storeRef.current = next;
|
||||
setStore(next);
|
||||
}, []);
|
||||
const update = useCallback(
|
||||
(change: (form: OrderForm) => OrderForm) => commit(Model.syncForm(change(storeRef.current.form), ctxRef.current)),
|
||||
[commit],
|
||||
);
|
||||
const reset = useCallback(
|
||||
(draft?: Record<string, unknown> | null) =>
|
||||
commit(Model.syncForm(Model.newForm(ctxRef.current, draft || undefined), ctxRef.current)),
|
||||
[commit],
|
||||
);
|
||||
// 每日料价或分来源报价读到后重新同步(旧页面在读取完成后调用 updateTotal)。
|
||||
useEffect(() => {
|
||||
ctxRef.current = ctx;
|
||||
commit(Model.syncForm(storeRef.current.form, ctx));
|
||||
}, [ctx, commit]);
|
||||
// 填写内容自动暂存。
|
||||
useEffect(() => {
|
||||
saveDraft(window.localStorage, state.user.id, store.draft);
|
||||
}, [store.draft, state.user.id]);
|
||||
|
||||
const [poolsRequest, setPoolsRequest] = useState(0);
|
||||
const loadPools = useCallback(() => setPoolsRequest(value => value + 1), []);
|
||||
useEffect(() => {
|
||||
let current = true;
|
||||
client
|
||||
.api<MaterialPools>('/api/material-pools')
|
||||
.then(result => {
|
||||
if (!Array.isArray(result.rows)) throw new Error('每日料价记录未完整返回,请重新读取。');
|
||||
if (!current) return;
|
||||
setPools(result);
|
||||
setPoolError('');
|
||||
})
|
||||
.catch(err => {
|
||||
if (current)
|
||||
setPoolError(
|
||||
'每日料价尚未读到:' +
|
||||
((err as Error).name === 'AbortError' ? '读取超时,请点击“刷新料价”。' : (err as Error).message),
|
||||
);
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
};
|
||||
}, [client, poolsRequest]);
|
||||
|
||||
// 个人回收料需要服务端分来源报价(旧页面 materialQuoteFor,180ms 去抖)。
|
||||
const quoteInput = useMemo(() => {
|
||||
const input = Model.poolQuoteInput(store.form, ctx);
|
||||
const rows = (pools?.rows || []) as { id: string; personalPools?: unknown }[];
|
||||
const personal = input.entries.some(entry =>
|
||||
rows.some(row => row.id === (entry as { poolId: string }).poolId && row.personalPools !== undefined),
|
||||
);
|
||||
return personal ? JSON.stringify(input) : '';
|
||||
}, [store.form, ctx, pools]);
|
||||
useEffect(() => {
|
||||
if (!quoteInput || (quote && JSON.stringify(quote.input) === quoteInput)) return;
|
||||
let current = true;
|
||||
const timer = window.setTimeout(async () => {
|
||||
const input = JSON.parse(quoteInput);
|
||||
try {
|
||||
const result = await client.api('/api/material-pools/quote', input);
|
||||
if (current) setQuote({ input, result, error: '' });
|
||||
} catch (err) {
|
||||
if (current) setQuote({ input, result: null, error: (err as Error).message });
|
||||
}
|
||||
}, 180);
|
||||
return () => {
|
||||
current = false;
|
||||
window.clearTimeout(timer);
|
||||
};
|
||||
}, [quoteInput, quote, client]);
|
||||
|
||||
return { store, update, reset, ctx, pools, poolError, loadPools };
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import { useState } from 'react';
|
||||
import { Alert, Button, Card, Form, Input, Select, Space, Typography } from 'antd';
|
||||
import type { LedgerClient } from '../../lib/api';
|
||||
import { demoLogin, login, setup, shopName, type SetupInput } from '../../lib/session';
|
||||
import type { SessionInfo } from '../../shared';
|
||||
|
||||
// 登录页:与旧界面相同的三种入口——演示模式一键进入、试用空库初始化、员工下拉加密码登录。
|
||||
export function LoginPage({
|
||||
client,
|
||||
session,
|
||||
onLoggedIn,
|
||||
}: {
|
||||
client: LedgerClient;
|
||||
session: SessionInfo;
|
||||
onLoggedIn: () => void | Promise<void>;
|
||||
}) {
|
||||
const [error, setError] = useState('');
|
||||
const [working, setWorking] = useState('');
|
||||
const name = shopName(null, session);
|
||||
const options = session.loginOptions || [];
|
||||
const intro =
|
||||
session.mode === 'demo'
|
||||
? '用虚构订单练习完整流程,演示数据与新账隔离。'
|
||||
: '先设置账号。当前是本机试用,正式云端开账另行配置。';
|
||||
async function run(key: string, action: () => Promise<unknown>) {
|
||||
setError('');
|
||||
setWorking(key);
|
||||
try {
|
||||
await action();
|
||||
await onLoggedIn();
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
} finally {
|
||||
setWorking('');
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div className="login-wrap">
|
||||
<Card className="login-card">
|
||||
<div className="brand-mark large" aria-hidden="true">
|
||||
{Array.from(name)[0] || '店'}
|
||||
</div>
|
||||
<Typography.Title level={3}>{name} · 新账系统</Typography.Title>
|
||||
<Typography.Paragraph type="secondary">
|
||||
{session.setup || session.mode === 'demo' ? intro : '录入、收款与复核,从同一张订单开始。'}
|
||||
</Typography.Paragraph>
|
||||
<Typography.Paragraph type="secondary" className="small">
|
||||
新版界面(对照试用)·{' '}
|
||||
<a href="/" className="old-ui-link">
|
||||
返回旧版界面
|
||||
</a>
|
||||
</Typography.Paragraph>
|
||||
{error && <Alert type="error" showIcon message={error} className="login-error" role="alert" />}
|
||||
{session.mode === 'demo' ? (
|
||||
<Space direction="vertical" style={{ width: '100%' }}>
|
||||
{options.map(row => (
|
||||
<Button
|
||||
key={row.member}
|
||||
block
|
||||
size="large"
|
||||
type={row.member === 'owner' ? 'primary' : 'default'}
|
||||
loading={working === row.member}
|
||||
disabled={!!working && working !== row.member}
|
||||
onClick={() => run(row.member, () => demoLogin(client, row.member))}
|
||||
>
|
||||
{'以' + row.label + '身份进入演示'}
|
||||
</Button>
|
||||
))}
|
||||
</Space>
|
||||
) : session.setup ? (
|
||||
<SetupForm working={working === 'setup'} onSubmit={input => run('setup', () => setup(client, input))} />
|
||||
) : (
|
||||
<LoginForm
|
||||
options={options}
|
||||
working={working === 'login'}
|
||||
onSubmit={(member, password) => run('login', () => login(client, member, password))}
|
||||
/>
|
||||
)}
|
||||
<Typography.Paragraph type="secondary" className="small login-foot">
|
||||
云端数据库和飞书同步的真实状态,会在系统内显示。
|
||||
</Typography.Paragraph>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LoginForm({
|
||||
options,
|
||||
working,
|
||||
onSubmit,
|
||||
}: {
|
||||
options: { member: string; label: string }[];
|
||||
working: boolean;
|
||||
onSubmit: (member: string, password: string) => void;
|
||||
}) {
|
||||
const [member, setMember] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
return (
|
||||
<form
|
||||
className="login-form"
|
||||
onSubmit={event => {
|
||||
event.preventDefault();
|
||||
onSubmit(member, password);
|
||||
}}
|
||||
>
|
||||
<Form layout="vertical" component={false}>
|
||||
<Form.Item label="登录账号" required>
|
||||
<Select
|
||||
aria-label="登录账号"
|
||||
data-testid="login-member"
|
||||
value={member || undefined}
|
||||
placeholder="请选择账号"
|
||||
options={options.map(row => ({ value: row.member, label: row.label }))}
|
||||
onChange={setMember}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label="密码" required>
|
||||
<Input.Password
|
||||
name="password"
|
||||
aria-label="密码"
|
||||
autoComplete="current-password"
|
||||
value={password}
|
||||
onChange={event => setPassword(event.target.value)}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Button type="primary" htmlType="submit" block size="large" loading={working}>
|
||||
登录
|
||||
</Button>
|
||||
</Form>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function SetupForm({ working, onSubmit }: { working: boolean; onSubmit: (input: SetupInput) => void }) {
|
||||
const [value, setValue] = useState<SetupInput>({
|
||||
storeName: '',
|
||||
ownerLabel: '店主',
|
||||
ownerLoginName: 'owner',
|
||||
ownerPassword: '',
|
||||
});
|
||||
const field = (key: keyof SetupInput) => ({
|
||||
value: value[key],
|
||||
onChange: (event: React.ChangeEvent<HTMLInputElement>) => setValue({ ...value, [key]: event.target.value }),
|
||||
});
|
||||
return (
|
||||
<form
|
||||
className="setup-form"
|
||||
onSubmit={event => {
|
||||
event.preventDefault();
|
||||
onSubmit(value);
|
||||
}}
|
||||
>
|
||||
<Form layout="vertical" component={false}>
|
||||
<Form.Item label="店铺名称" required>
|
||||
<Input name="storeName" aria-label="店铺名称" maxLength={80} {...field('storeName')} />
|
||||
</Form.Item>
|
||||
<Form.Item label="店主显示名" required>
|
||||
<Input name="ownerLabel" aria-label="店主显示名" maxLength={30} {...field('ownerLabel')} />
|
||||
</Form.Item>
|
||||
<Form.Item label="店主登录名" required>
|
||||
<Input name="ownerLoginName" aria-label="店主登录名" maxLength={60} {...field('ownerLoginName')} />
|
||||
</Form.Item>
|
||||
<Form.Item label="店主密码(至少12个字符)" required>
|
||||
<Input.Password
|
||||
name="ownerPassword"
|
||||
aria-label="店主密码"
|
||||
autoComplete="new-password"
|
||||
{...field('ownerPassword')}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Typography.Paragraph type="secondary">进入系统后,在设置 → 员工管理中添加员工。</Typography.Paragraph>
|
||||
<Button type="primary" htmlType="submit" block size="large" loading={working}>
|
||||
建立试用账号
|
||||
</Button>
|
||||
</Form>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// 共用计算模块的唯一入口:与旧界面、服务端读取同一份源文件(../public/*.js),不复制业务算法。
|
||||
import LedgerCalc from '@public/calculations.js';
|
||||
import CreditCardFees from '@public/credit-card-fees.js';
|
||||
import FeeEstimates from '@public/fee-estimates.js';
|
||||
import OrderFormula from '@public/order-formula.js';
|
||||
import OrderTemplates from '@public/order-templates.js';
|
||||
import OrderCopy from '@public/order-copy.js';
|
||||
import OrderEntryModel from '@public/order-entry-model.js';
|
||||
|
||||
export const Calc = LedgerCalc;
|
||||
export const Cards = CreditCardFees;
|
||||
export const Fees = FeeEstimates;
|
||||
export const Formula = OrderFormula;
|
||||
export const Templates = OrderTemplates;
|
||||
export const Copy = OrderCopy;
|
||||
export const Model = OrderEntryModel;
|
||||
export type * from './types';
|
||||
@@ -0,0 +1,340 @@
|
||||
// 共用 UMD 模块(../public/*.js)与服务端接口的类型描述。只描述新版界面用到的部分。
|
||||
|
||||
export interface MemberRow {
|
||||
member: string;
|
||||
label: string;
|
||||
enabled?: boolean;
|
||||
operatorName?: string;
|
||||
}
|
||||
export interface SessionUser {
|
||||
id: string;
|
||||
name: string;
|
||||
role: 'owner' | 'assistant';
|
||||
member: string;
|
||||
operatorName?: string;
|
||||
label?: string;
|
||||
}
|
||||
export interface SessionInfo {
|
||||
user: SessionUser | null;
|
||||
setup: boolean;
|
||||
mode: 'trial' | 'demo' | 'production';
|
||||
today: string;
|
||||
brand?: { storeName?: string };
|
||||
loginOptions?: { member: string; label: string }[];
|
||||
}
|
||||
export interface PocketRow {
|
||||
key: string;
|
||||
name?: string;
|
||||
countUnit?: 'pair' | null;
|
||||
active?: boolean;
|
||||
}
|
||||
export interface LedgerState {
|
||||
today: string;
|
||||
mode: string;
|
||||
user: SessionUser;
|
||||
members?: MemberRow[];
|
||||
shopSettings?: {
|
||||
storeName?: string;
|
||||
members?: MemberRow[];
|
||||
feeDefaults?: Record<string, string>;
|
||||
costPresets?: Record<string, unknown>;
|
||||
creditCardRatePermille?: number;
|
||||
};
|
||||
pockets?: string[];
|
||||
pocketCatalog?: PocketRow[];
|
||||
accounts?: string[];
|
||||
printing?: { store?: string };
|
||||
}
|
||||
|
||||
export interface ChargeState {
|
||||
id: string;
|
||||
type: string;
|
||||
customName: string;
|
||||
amount: string;
|
||||
prices: Record<string, string>;
|
||||
costRemoved?: boolean;
|
||||
}
|
||||
export interface PurchaseState {
|
||||
materialMode: 'gram' | 'total';
|
||||
materialRate: string;
|
||||
material: string;
|
||||
materialPayer: string;
|
||||
laborMode: 'gram' | 'total';
|
||||
laborRate: string;
|
||||
labor: string;
|
||||
laborPayer: string;
|
||||
accessories: string;
|
||||
other: string;
|
||||
dataMode: string;
|
||||
preferredMode: string;
|
||||
dataUnit: string;
|
||||
total: string;
|
||||
originalTotal: string;
|
||||
}
|
||||
export interface PoolState {
|
||||
source: 'manual' | 'pool';
|
||||
poolId: string;
|
||||
dataPoolId: string;
|
||||
dataSource: string;
|
||||
preferredSource: string;
|
||||
defaultDate: boolean;
|
||||
allowed: boolean;
|
||||
options: { value: string; label: string }[];
|
||||
help?: string;
|
||||
payerText?: string;
|
||||
personal?: boolean;
|
||||
preview: { amount: number | null } | null;
|
||||
}
|
||||
export interface LineView {
|
||||
calculation: string;
|
||||
materialFormula: string;
|
||||
laborFormula: string;
|
||||
materialOriginal: string;
|
||||
poolNote: string;
|
||||
saleCents?: number | null;
|
||||
purchase?: { total: number | null; parts: Record<string, number | null> } | null;
|
||||
}
|
||||
export interface LineState {
|
||||
legacy: boolean;
|
||||
historicalPocket: boolean;
|
||||
nameType: string;
|
||||
customName: string;
|
||||
pricingMode: 'auto' | 'manual';
|
||||
unit: 'g' | '件';
|
||||
quantity: string;
|
||||
goldPrice: string;
|
||||
laborMode: 'gram' | 'piece';
|
||||
laborRate: string;
|
||||
pieces: string;
|
||||
priceNote: string;
|
||||
baseSale: string;
|
||||
sale: string;
|
||||
pocket: string;
|
||||
stockCount: string;
|
||||
payer: string;
|
||||
cost: string;
|
||||
charges: ChargeState[];
|
||||
purchase: PurchaseState | null;
|
||||
pool: PoolState | null;
|
||||
view: LineView;
|
||||
}
|
||||
export interface FeeRowState {
|
||||
key: string;
|
||||
note: string;
|
||||
amount: string;
|
||||
payer: string;
|
||||
sourceName: string;
|
||||
edited: boolean;
|
||||
status: string;
|
||||
lineNumber?: number;
|
||||
automatic?: unknown;
|
||||
}
|
||||
export interface PresetState {
|
||||
configured: boolean;
|
||||
checked: Record<string, boolean>;
|
||||
quantity: Record<string, string>;
|
||||
}
|
||||
export interface PaymentState {
|
||||
method: string;
|
||||
recipient: string;
|
||||
nonCardRecipient: string;
|
||||
cardLocked: boolean;
|
||||
}
|
||||
export interface OrderForm {
|
||||
copy_kind: string;
|
||||
id: string;
|
||||
revision: string | number;
|
||||
paper_date: string;
|
||||
paper_number: string;
|
||||
rounding_mode: 'yuan' | 'cent';
|
||||
memberLocked: boolean;
|
||||
member: string;
|
||||
date: string;
|
||||
customer: string;
|
||||
customer_type: '' | 'new' | 'returning';
|
||||
customerTypeRequired: boolean;
|
||||
salesperson: string;
|
||||
payment: PaymentState;
|
||||
credit_card_fee_payer: string;
|
||||
fees_date: string;
|
||||
feeCostMode: string;
|
||||
discount: string;
|
||||
note: string;
|
||||
internal_note: string;
|
||||
presets: PresetState | null;
|
||||
feeRows: FeeRowState[];
|
||||
lines: LineState[];
|
||||
}
|
||||
/** 与旧页面 collectDraft() 相同结构,即 /api/orders/issue 的请求体。 */
|
||||
export interface OrderDraft {
|
||||
id?: string;
|
||||
revision?: number;
|
||||
date: string;
|
||||
customer: string;
|
||||
salesperson: string;
|
||||
internal_note: string;
|
||||
payment_account: string;
|
||||
rounding_mode: 'yuan' | 'cent';
|
||||
discount: string;
|
||||
lines: Record<string, unknown>[];
|
||||
fee_items: Record<string, unknown>[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
export interface FormSummary {
|
||||
total: number | null;
|
||||
totalText: string;
|
||||
roundingHint: string;
|
||||
card: { rate: number; amount: number | null; amountText: string; formula: string } | null;
|
||||
feesText: string;
|
||||
presetNotes: Record<string, string>;
|
||||
}
|
||||
export interface MaterialPools {
|
||||
rows: unknown[];
|
||||
rolling?: { enabled?: boolean; cutover?: string };
|
||||
current?: unknown;
|
||||
}
|
||||
export interface QuoteState {
|
||||
input: unknown;
|
||||
result: unknown;
|
||||
error: string;
|
||||
}
|
||||
export interface SyncContext {
|
||||
st: LedgerState;
|
||||
session?: SessionInfo | null;
|
||||
uuid: () => string;
|
||||
materialPools?: MaterialPools | null;
|
||||
quote?: QuoteState | null;
|
||||
}
|
||||
export interface LineVisibility {
|
||||
customName: boolean;
|
||||
goldPrice: boolean;
|
||||
laborMode: boolean;
|
||||
laborRate: boolean;
|
||||
pieces: boolean;
|
||||
priceNote: boolean;
|
||||
baseSale: boolean;
|
||||
stockCount: boolean;
|
||||
stockCountOptional: boolean;
|
||||
materialRate: boolean;
|
||||
materialMode: boolean;
|
||||
materialPayer: boolean;
|
||||
materialReadOnly: boolean;
|
||||
laborRateInput: boolean;
|
||||
laborReadOnly: boolean;
|
||||
poolAllowed: boolean;
|
||||
extraCosts: boolean;
|
||||
}
|
||||
export interface PresetCatalogItem {
|
||||
kind: string;
|
||||
name: string;
|
||||
price: string;
|
||||
payer: string;
|
||||
byQuantity?: boolean;
|
||||
shipping?: boolean;
|
||||
}
|
||||
|
||||
export interface LedgerCalcApi {
|
||||
cents(value: unknown, name?: string): number;
|
||||
isSilver(name: string): boolean;
|
||||
sale(line: unknown): { sale: number; baseSale: number; chargesTotal: number; charges: unknown[] };
|
||||
orderTotal(
|
||||
lines: number[],
|
||||
discount?: number,
|
||||
mode?: 'yuan' | 'cent',
|
||||
): { total: number; unroundedTotal: number; rounding_adjustment: number; rounding_mode: string; subtotal: number };
|
||||
purchaseCosts(line: unknown): { total: number | null; parts: Record<string, number | null> };
|
||||
costLabels: Record<string, string>;
|
||||
}
|
||||
export interface CreditCardFeesApi {
|
||||
isAccount(account: string): boolean;
|
||||
amount(cents: number, rate?: number): number;
|
||||
normalizeAccount(account: string): string;
|
||||
ratePermille: number;
|
||||
}
|
||||
export interface FeeEstimatesApi {
|
||||
presets(values?: unknown): Record<string, { amount: string; payer: string }>;
|
||||
checkboxCategory(name: string): string;
|
||||
normalize(name: string): string;
|
||||
}
|
||||
export interface OrderFormulaApi {
|
||||
parseBatch(
|
||||
input: string,
|
||||
options: { roundingMode: string },
|
||||
): {
|
||||
items: { line: Record<string, string> & { charges: { amount: string }[] }; subtotal: number }[];
|
||||
lines: (Record<string, string> & { charges: { name: string; amount: string }[] })[];
|
||||
subtotal: number;
|
||||
total: number;
|
||||
roundingMode: string;
|
||||
mismatch: boolean;
|
||||
warnings: string[];
|
||||
};
|
||||
}
|
||||
export interface OrderTemplatesApi {
|
||||
fromDraft(draft: unknown, options: { pocketKeys: string[]; newId?: () => string }): unknown;
|
||||
apply(
|
||||
preset: unknown,
|
||||
options: { today: string; salesperson: string; pocketKeys: string[]; newId?: () => string },
|
||||
): Record<string, unknown> & { member?: string; salesperson?: string };
|
||||
}
|
||||
export interface OrderEntryModelApi {
|
||||
productNames: string[];
|
||||
chargeNames: string[];
|
||||
yuan(cents: number | null | undefined): string;
|
||||
grams(mg: number): string;
|
||||
orderAmount(value: number | null, mode: string): string;
|
||||
teamMode(st: LedgerState): boolean;
|
||||
currentMember(st: LedgerState, session?: SessionInfo | null): string;
|
||||
memberKeys(st: LedgerState): string[];
|
||||
memberName(st: LedgerState, member: string): string;
|
||||
memberOptions(st: LedgerState, assistantFirst?: boolean, options?: { selected?: string }): [string, string][];
|
||||
defaultSalesperson(st: LedgerState, session?: SessionInfo | null): string;
|
||||
activePocketKeys(st: LedgerState): string[];
|
||||
pocketOptions(st: LedgerState, selected?: string, historical?: boolean): [string, string, boolean?][];
|
||||
pocketCountsEnabled(st: LedgerState, key: string): boolean;
|
||||
creditCardAvailable(st: LedgerState): boolean;
|
||||
newCharge(c: Record<string, unknown>, uuid: () => string): ChargeState;
|
||||
changeChargeType(charge: ChargeState, type: string): ChargeState;
|
||||
setChargeAmount(charge: ChargeState, amount: string): ChargeState;
|
||||
setLineField(line: LineState, field: string, value: string): LineState;
|
||||
setPurchaseField(line: LineState, field: string, value: string): LineState;
|
||||
setPoolSource(line: LineState, source: 'manual' | 'pool'): LineState;
|
||||
lineVisibility(line: LineState, st: LedgerState): LineVisibility;
|
||||
poolQuoteInput(form: OrderForm, ctx: SyncContext): { date: string; member: string; entries: unknown[] };
|
||||
feeSourceText(row: FeeRowState): string;
|
||||
editFeeRow(form: OrderForm, index: number, field: 'amount' | 'payer' | 'note', value: string): OrderForm;
|
||||
addManualFee(form: OrderForm, st: LedgerState, uuid: () => string): OrderForm;
|
||||
removeFeeRow(form: OrderForm, index: number): OrderForm;
|
||||
restoreChargeCost(form: OrderForm, lineIndex: number, chargeIndex: number): OrderForm;
|
||||
togglePreset(form: OrderForm, kind: string, checked: boolean, st: LedgerState, uuid: () => string): OrderForm;
|
||||
setPresetQuantity(form: OrderForm, kind: string, value: string): OrderForm;
|
||||
presetCatalogView(form: OrderForm, st: LedgerState): PresetCatalogItem[];
|
||||
paymentMethods(st: LedgerState): string[];
|
||||
recipientOptions(st: LedgerState, payment: PaymentState): [string, string][];
|
||||
readPaymentAccount(form: OrderForm): string;
|
||||
changeMember(form: OrderForm, member: string, st: LedgerState): OrderForm;
|
||||
isBlankDraft(draft: unknown): boolean;
|
||||
newForm(ctx: SyncContext, draft?: unknown): OrderForm;
|
||||
addLine(form: OrderForm, ctx: SyncContext): OrderForm;
|
||||
removeLine(form: OrderForm, index: number): OrderForm;
|
||||
addCharge(form: OrderForm, lineIndex: number, uuid: () => string): OrderForm;
|
||||
updateLine(form: OrderForm, index: number, line: LineState): OrderForm;
|
||||
collectDraft(form: OrderForm, st: LedgerState): OrderDraft;
|
||||
syncForm(form: OrderForm, ctx: SyncContext): { form: OrderForm; draft: OrderDraft; summary: FormSummary };
|
||||
validateFormFields(form: OrderForm, st: LedgerState): void;
|
||||
validateIssueDraft(draft: OrderDraft, st: LedgerState): OrderDraft;
|
||||
draftInputs(order: unknown): Record<string, unknown>;
|
||||
filterNoteTags(tags: string[], text: string): string[];
|
||||
insertNoteTag(text: string, tag: string): string;
|
||||
}
|
||||
export interface OrderEntryModelApi {
|
||||
isFormulaBlank(line: LineState): boolean;
|
||||
applyFormulaLines(
|
||||
form: OrderForm,
|
||||
lines: Record<string, unknown>[],
|
||||
ctx: SyncContext,
|
||||
): { form: OrderForm; filled: number[] };
|
||||
}
|
||||
export interface OrderCopyApi {
|
||||
hasDraftContent(draft: unknown, options: { today: string; salesperson: string }): boolean;
|
||||
}
|
||||
Vendored
+29
@@ -0,0 +1,29 @@
|
||||
// ../public/ 下的共用 UMD 文件经 vite.config.ts 的 sharedUmd 插件变为 ES 默认导出。
|
||||
declare module '@public/calculations.js' {
|
||||
const api: import('./types').LedgerCalcApi;
|
||||
export default api;
|
||||
}
|
||||
declare module '@public/credit-card-fees.js' {
|
||||
const api: import('./types').CreditCardFeesApi;
|
||||
export default api;
|
||||
}
|
||||
declare module '@public/fee-estimates.js' {
|
||||
const api: import('./types').FeeEstimatesApi;
|
||||
export default api;
|
||||
}
|
||||
declare module '@public/order-formula.js' {
|
||||
const api: import('./types').OrderFormulaApi;
|
||||
export default api;
|
||||
}
|
||||
declare module '@public/order-templates.js' {
|
||||
const api: import('./types').OrderTemplatesApi;
|
||||
export default api;
|
||||
}
|
||||
declare module '@public/order-entry-model.js' {
|
||||
const api: import('./types').OrderEntryModelApi;
|
||||
export default api;
|
||||
}
|
||||
declare module '@public/order-copy.js' {
|
||||
const api: import('./types').OrderCopyApi;
|
||||
export default api;
|
||||
}
|
||||
@@ -0,0 +1,426 @@
|
||||
:root {
|
||||
--gold: #9a6a2f;
|
||||
--ink: #2b2620;
|
||||
--muted: #7a7064;
|
||||
--paper: #faf7f2;
|
||||
--line: #e8e0d4;
|
||||
--internal: #f4f1fb;
|
||||
}
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
font-family:
|
||||
-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Segoe UI', sans-serif;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
}
|
||||
.small {
|
||||
font-size: 13px;
|
||||
}
|
||||
.muted {
|
||||
color: var(--muted);
|
||||
}
|
||||
.danger-text {
|
||||
color: #c0392b;
|
||||
}
|
||||
.page-loading {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: 120px 16px;
|
||||
}
|
||||
|
||||
/* 顶栏 */
|
||||
.topbar {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 10px 20px;
|
||||
background: #fff;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.topbar-brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
}
|
||||
.topbar-brand strong {
|
||||
display: block;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.topbar-brand small {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
.topbar-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.brand-mark {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
flex: none;
|
||||
border-radius: 10px;
|
||||
background: var(--gold);
|
||||
color: #fff;
|
||||
font-weight: 700;
|
||||
}
|
||||
.brand-mark.large {
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
font-size: 26px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.identity {
|
||||
font-weight: 600;
|
||||
}
|
||||
.old-ui-link {
|
||||
white-space: nowrap;
|
||||
}
|
||||
.request-status {
|
||||
margin: 8px 20px 0;
|
||||
}
|
||||
|
||||
/* 主体 */
|
||||
.main {
|
||||
max-width: 1180px;
|
||||
margin: 0 auto;
|
||||
padding: 16px 20px 80px;
|
||||
}
|
||||
.page-heading {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: 16px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.page-heading h2 {
|
||||
margin: 0 0 4px;
|
||||
}
|
||||
.eyebrow {
|
||||
color: var(--gold);
|
||||
font-size: 12px;
|
||||
letter-spacing: 0.08em;
|
||||
font-weight: 600;
|
||||
}
|
||||
.create-page > .ant-alert,
|
||||
.entry-tools {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.form-fieldset {
|
||||
border: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
.panel {
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.panel.internal,
|
||||
.internal {
|
||||
background: var(--internal);
|
||||
}
|
||||
.panel-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.section-note {
|
||||
margin: 12px 0 0;
|
||||
}
|
||||
|
||||
/* 网格:桌面四列,平板两列,手机一列 */
|
||||
.grid {
|
||||
display: grid;
|
||||
gap: 12px 16px;
|
||||
align-items: start;
|
||||
}
|
||||
.grid.four {
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
}
|
||||
.grid.three {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
.grid.two {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
.field-label {
|
||||
font-size: 13px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.field-hint {
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.field .ant-radio-group {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.readonly-input {
|
||||
background: #f5f2ec;
|
||||
}
|
||||
|
||||
/* 商品行 */
|
||||
.line-item {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
padding: 14px;
|
||||
margin-bottom: 14px;
|
||||
background: #fff;
|
||||
}
|
||||
.line-top {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.sale-inputs,
|
||||
.sale-result {
|
||||
margin-top: 12px;
|
||||
}
|
||||
.sale-charges {
|
||||
margin-top: 12px;
|
||||
padding: 10px;
|
||||
border: 1px dashed var(--line);
|
||||
border-radius: 8px;
|
||||
}
|
||||
.charge-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr)) auto;
|
||||
gap: 8px 12px;
|
||||
align-items: end;
|
||||
padding: 8px 0;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
.calculation {
|
||||
margin: 26px 0 0;
|
||||
color: var(--gold);
|
||||
}
|
||||
.internal {
|
||||
margin-top: 14px;
|
||||
padding: 12px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.internal-title {
|
||||
font-weight: 600;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.material-source,
|
||||
.purchase-cost-grid {
|
||||
margin-top: 10px;
|
||||
}
|
||||
.purchase-formula,
|
||||
.material-pool-note {
|
||||
margin: 6px 0 0;
|
||||
}
|
||||
.cost-summary {
|
||||
margin: 10px 0 0;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* 费用 */
|
||||
.order-cost-presets {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
margin: 12px 0;
|
||||
background: #fff;
|
||||
}
|
||||
.order-cost-presets legend {
|
||||
padding: 0 6px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.order-cost-options {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
.order-cost-option {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
.fee-grid {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.fee-row {
|
||||
display: grid;
|
||||
grid-template-columns: 1.4fr 1fr 1fr auto;
|
||||
gap: 8px 12px;
|
||||
align-items: end;
|
||||
padding: 10px;
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.fee-title {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
.credit-card-preview {
|
||||
margin-top: 12px;
|
||||
padding: 10px;
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #d9c9ef;
|
||||
}
|
||||
.credit-card-heading {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.fees-total {
|
||||
margin-top: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* 合计与提交 */
|
||||
.order-note-tags {
|
||||
margin-top: 8px;
|
||||
}
|
||||
.order-note-tag-options {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.create-submit-bar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
margin-top: 16px;
|
||||
padding-top: 14px;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
.summary-amount {
|
||||
font-size: 30px;
|
||||
font-weight: 700;
|
||||
color: var(--gold);
|
||||
}
|
||||
.order-error {
|
||||
margin-top: 12px;
|
||||
}
|
||||
.form-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.issued-summary {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 32px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.issued-value {
|
||||
font-size: 26px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.issued-value.small {
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
/* 登录 */
|
||||
.login-wrap {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: 48px 16px;
|
||||
}
|
||||
.login-card {
|
||||
width: 100%;
|
||||
max-width: 440px;
|
||||
}
|
||||
.login-error {
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.login-foot {
|
||||
margin-top: 22px;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.grid.four {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
.fee-row {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
.charge-row {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
@media (max-width: 560px) {
|
||||
.main {
|
||||
padding: 10px 10px 70px;
|
||||
}
|
||||
.topbar {
|
||||
padding: 8px 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.topbar-brand small,
|
||||
.mode-tag {
|
||||
display: none;
|
||||
}
|
||||
.grid.four,
|
||||
.grid.three,
|
||||
.grid.two,
|
||||
.fee-row,
|
||||
.charge-row {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
.page-heading {
|
||||
flex-direction: column;
|
||||
}
|
||||
.calculation {
|
||||
margin-top: 0;
|
||||
}
|
||||
.line-item {
|
||||
padding: 10px;
|
||||
}
|
||||
.create-submit-bar {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
background: #fff;
|
||||
margin: 16px -24px -24px;
|
||||
padding: 10px 14px;
|
||||
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
|
||||
z-index: 5;
|
||||
}
|
||||
.summary-amount {
|
||||
font-size: 24px;
|
||||
}
|
||||
.ant-card .ant-card-body {
|
||||
padding: 14px;
|
||||
}
|
||||
.ant-card .ant-card-head {
|
||||
padding: 0 14px;
|
||||
}
|
||||
}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
Reference in new issue
Block a user