393 lines
14 KiB
TypeScript
393 lines
14 KiB
TypeScript
import { useState } from 'react';
|
||
import type { FormEvent, ReactNode } from 'react';
|
||
import { Calc, Model, type LedgerState } from '../../shared';
|
||
import { grams, yuan } from '../../lib/format';
|
||
import {
|
||
draftKey,
|
||
money,
|
||
purchaseInput,
|
||
validatePurchaseInput,
|
||
payerOf,
|
||
needsReview,
|
||
type Pool,
|
||
type Purchase,
|
||
type PurchaseInput,
|
||
type Save,
|
||
} from './model';
|
||
|
||
function initialDraft(state: LedgerState) {
|
||
let saved: Record<string, unknown> | null;
|
||
try {
|
||
saved = JSON.parse(localStorage.getItem(draftKey(state)) || 'null');
|
||
} catch {
|
||
saved = null;
|
||
}
|
||
const draft = purchaseInput(saved || { date: state.today, payer: Model.currentMember(state) });
|
||
return { ...draft, date: draft.date || state.today };
|
||
}
|
||
function PurchaseFields({
|
||
state,
|
||
value,
|
||
create = false,
|
||
minDate,
|
||
children,
|
||
}: {
|
||
state: LedgerState;
|
||
value: PurchaseInput;
|
||
create?: boolean;
|
||
minDate?: string;
|
||
children?: ReactNode;
|
||
}) {
|
||
return (
|
||
<div className="material-purchase-scroll">
|
||
<div className="material-purchase-fields">
|
||
<label>
|
||
购料日期
|
||
<input name="date" defaultValue={value.date} type="date" required min={minDate} max={state.today} />
|
||
</label>
|
||
<label>
|
||
购买克重(g)
|
||
<input
|
||
name="grams"
|
||
defaultValue={value.grams}
|
||
type="number"
|
||
required
|
||
min="0.001"
|
||
step="0.001"
|
||
inputMode="decimal"
|
||
placeholder={create ? '填实际购入克重' : undefined}
|
||
/>
|
||
</label>
|
||
<label>
|
||
购买总价(元)
|
||
<input
|
||
name="total"
|
||
defaultValue={value.total}
|
||
type="number"
|
||
min="0"
|
||
step="0.01"
|
||
required
|
||
inputMode="decimal"
|
||
placeholder={create ? '填实际支付总额' : undefined}
|
||
/>
|
||
</label>
|
||
<label>
|
||
付款人
|
||
<select name="payer" defaultValue={value.payer}>
|
||
{Model.memberOptions(state, false, { selected: value.payer }).map(([key, name]) => (
|
||
<option key={key} value={key}>
|
||
{name}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</label>
|
||
<label>
|
||
备注(选填)
|
||
<input
|
||
name="note"
|
||
defaultValue={value.note}
|
||
type="text"
|
||
maxLength={150}
|
||
placeholder={create ? '例如:上午第一笔' : undefined}
|
||
/>
|
||
</label>
|
||
{children}
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
export function PurchaseForm({
|
||
state,
|
||
rolling,
|
||
save,
|
||
blocked,
|
||
}: {
|
||
state: LedgerState;
|
||
rolling: boolean;
|
||
save: Save;
|
||
blocked: boolean;
|
||
}) {
|
||
const [draft] = useState(() => initialDraft(state)),
|
||
[error, setError] = useState('');
|
||
function remember(form: HTMLFormElement) {
|
||
localStorage.setItem(draftKey(state), JSON.stringify(purchaseInput(Object.fromEntries(new FormData(form)))));
|
||
}
|
||
async function submit(e: FormEvent<HTMLFormElement>) {
|
||
e.preventDefault();
|
||
setError('');
|
||
try {
|
||
const data = validatePurchaseInput(Object.fromEntries(new FormData(e.currentTarget)), state);
|
||
if (rolling && data.date !== state.today)
|
||
throw new Error('跨日结转已启用,新购料请登记今日。历史记录录错请从对应购料提交更正申请。');
|
||
await save('/api/material-purchases', data);
|
||
} catch (err) {
|
||
setError((err as Error).message);
|
||
}
|
||
}
|
||
return (
|
||
<section className="panel material-purchase-panel">
|
||
<div className="panel-title">
|
||
<h2>登记一笔购料</h2>
|
||
<span className="small muted">
|
||
{rolling ? '结转余料、今日购料与回料统一加权' : '同一天的多笔购料自动合并加权'}
|
||
</span>
|
||
</div>
|
||
<form
|
||
id="material-purchase-form"
|
||
onInput={e => remember(e.currentTarget)}
|
||
onChange={e => remember(e.currentTarget)}
|
||
onSubmit={submit}
|
||
>
|
||
<PurchaseFields state={state} value={draft} create>
|
||
<button type="submit" className="primary" disabled={blocked}>
|
||
保存购料
|
||
</button>
|
||
</PurchaseFields>
|
||
<div id="material-purchase-error" aria-live="polite">
|
||
{error && <div className="error">{error}</div>}
|
||
</div>
|
||
</form>
|
||
<p className="small muted material-scroll-hint">左右滑动填写完整购料信息 →</p>
|
||
<p className="small muted material-purchase-hint">
|
||
只登记购料与实际付款人,付款当天记支出,未用完的料结转留用。关联订单按实际耗用自动计算料费及与付款人的往来,销售耗用不再重复记现金支出。实物入库仍在「库存」登记。
|
||
</p>
|
||
</section>
|
||
);
|
||
}
|
||
export interface FormActions {
|
||
blocked: boolean;
|
||
stale: boolean;
|
||
error: ReactNode;
|
||
close: () => void;
|
||
submit: (job: () => Promise<void>) => Promise<void>;
|
||
save: Save;
|
||
}
|
||
export function PurchaseChange({
|
||
state,
|
||
purchase: p,
|
||
kind,
|
||
rolling,
|
||
actions,
|
||
refresh,
|
||
}: {
|
||
state: LedgerState;
|
||
purchase: Purchase;
|
||
kind: 'delete' | 'edit';
|
||
rolling: boolean;
|
||
actions: FormActions;
|
||
refresh: () => void;
|
||
}) {
|
||
const { blocked, stale, error, close, submit, save } = actions;
|
||
if (p.deleted_at)
|
||
return (
|
||
<>
|
||
<p>这笔购料已删除,原记录与操作历史保留。</p>
|
||
<button className="primary" type="button" data-action="refresh-changed-material-purchase" onClick={refresh}>
|
||
关闭并刷新每日购料
|
||
</button>
|
||
</>
|
||
);
|
||
if (p.recovery_id)
|
||
return (
|
||
<>
|
||
<p>这笔购料随回收/置换原单保留,不能在购料页独立修改或删除。</p>
|
||
<button type="button" className="quiet" data-action="close-material-purchase" onClick={close}>
|
||
关闭
|
||
</button>
|
||
</>
|
||
);
|
||
if (p.canEdit === false && p.canRequestChange === false)
|
||
return <p>这笔共享购料不能由当前账号更正。请由登记人或店主核对处理。</p>;
|
||
const approval = needsReview(p, rolling, state.today),
|
||
edit = kind === 'edit',
|
||
text = edit ? '修改' : '删除';
|
||
async function onSubmit(e: FormEvent<HTMLFormElement>) {
|
||
e.preventDefault();
|
||
const values = Object.fromEntries(new FormData(e.currentTarget));
|
||
await submit(async () => {
|
||
const input: Record<string, unknown> = edit
|
||
? { ...validatePurchaseInput(values, state), revision: p.revision }
|
||
: { revision: p.revision };
|
||
if (rolling && p.date === state.today && input.date && input.date !== state.today)
|
||
throw new Error('今日购料不能直接改为已结转的历史日期。请核对所选日期与原购料凭据。');
|
||
if (approval) {
|
||
const reason = String(values.change_reason || '').trim();
|
||
if (!reason || reason.length > 200) throw new Error('请填写更正原因,最多200字。');
|
||
if (values.change_verified !== 'on') throw new Error('请核对原始购料凭据与本次申请值,再勾选确认。');
|
||
Object.assign(input, { action: kind, reason, verified: true });
|
||
}
|
||
await save('/api/material-purchases/' + encodeURIComponent(p.id) + '/' + (approval ? 'change' : kind), input);
|
||
});
|
||
}
|
||
return (
|
||
<>
|
||
{!edit && (
|
||
<>
|
||
<dl className="material-purchase-facts">
|
||
{[
|
||
['购料日期', p.date],
|
||
['购买克重', grams(p.mg) + 'g'],
|
||
['购买总价', money(p.amount)],
|
||
['付款人', Model.memberName(state, payerOf(p))],
|
||
].map(([k, v]) => (
|
||
<div key={k}>
|
||
<dt>{k}</dt>
|
||
<dd>{v}</dd>
|
||
</div>
|
||
))}
|
||
</dl>
|
||
{p.note && <p className="small muted material-purchase-original-note">备注:{p.note}</p>}
|
||
<p className="small material-purchase-impact">
|
||
{approval
|
||
? '本次只提交删除申请,待店主核对订单影响并批准后才更新账务。等待期间仍按原购料记账。'
|
||
: '删除后,这笔购料不再计入实际购料与成本总额,相关订单的料费、利润和成员往来会重新核算。购料不足时,订单会显示“料费待补”;客户售价、收付款和实物库存保持原值。'}
|
||
</p>
|
||
<p className="small muted">原记录与操作历史会保留。</p>
|
||
</>
|
||
)}
|
||
<form
|
||
id={'material-purchase-' + kind + '-form'}
|
||
data-id={p.id}
|
||
data-revision={p.revision}
|
||
data-kind={kind}
|
||
data-stale={stale || undefined}
|
||
onSubmit={onSubmit}
|
||
>
|
||
<fieldset className="material-form-controls" style={{ display: 'contents' }} disabled={stale}>
|
||
{edit && (
|
||
<>
|
||
<PurchaseFields
|
||
state={state}
|
||
value={{
|
||
date: p.date,
|
||
total: (p.amount / 100).toFixed(2),
|
||
grams: grams(p.mg),
|
||
payer: payerOf(p),
|
||
note: p.note,
|
||
}}
|
||
minDate={rolling && !approval ? state.today : undefined}
|
||
/>
|
||
<p className="small muted material-scroll-hint">左右滑动填写完整购料信息 →</p>
|
||
<p className="small muted material-purchase-impact">
|
||
{approval
|
||
? '本次只提交修改申请。店主核对原值、申请值和关联订单影响并批准后,才重新核算;待批期间仍按原记录记账。'
|
||
: rolling
|
||
? '保存今日购料后,只重新核算今日料价与订单。已结转的历史日期请从对应历史购料提交更正申请。'
|
||
: '保存后重算料价、关联订单的料费、利润与结算。改日期后,订单耗用仍留在原料价日期;购料不足时会显示“料费待补”。'}
|
||
</p>
|
||
</>
|
||
)}
|
||
{(approval || rolling) && (
|
||
<div className="material-purchase-review-fields" hidden={!approval}>
|
||
<label>
|
||
更正原因
|
||
<textarea
|
||
name="change_reason"
|
||
maxLength={200}
|
||
rows={2}
|
||
required={approval}
|
||
placeholder="写清原记录哪里录错,以及核对依据。"
|
||
/>
|
||
</label>
|
||
<label className="check">
|
||
<input name="change_verified" type="checkbox" required={approval} />
|
||
已核对原始购料凭据与本次申请值,提交店主复核后再更正。
|
||
</label>
|
||
</div>
|
||
)}
|
||
</fieldset>
|
||
<div id="material-purchase-change-error" aria-live="polite">
|
||
{error}
|
||
</div>
|
||
<div className="form-actions">
|
||
<button type="button" className="quiet" data-action="close-material-purchase" onClick={close}>
|
||
取消
|
||
</button>
|
||
<button type="submit" className={edit ? 'primary' : 'danger'} disabled={blocked || stale}>
|
||
{approval ? '提交' + text + '申请' : edit ? '保存修改' : '确认删除购料'}
|
||
</button>
|
||
</div>
|
||
</form>
|
||
</>
|
||
);
|
||
}
|
||
export function Settlement({ state, pool: p, actions }: { state: LedgerState; pool: Pool; actions: FormActions }) {
|
||
const { close, blocked, save, submit, error } = actions,
|
||
due = p.settlement!.settlementDue!,
|
||
owner = Model.memberName(state, 'owner'),
|
||
assistant = Model.memberName(state, 'assistant');
|
||
function onSubmit(e: FormEvent<HTMLFormElement>) {
|
||
e.preventDefault();
|
||
const data = Object.fromEntries(new FormData(e.currentTarget));
|
||
void submit(async () => {
|
||
if (data.verified !== 'on') throw new Error('请先核实双方实际转账。');
|
||
if (Calc.cents(data.amount, '实际转账金额') <= 0) throw new Error('实际转账金额须大于0。');
|
||
await save('/api/material-pools/' + encodeURIComponent(p.id) + '/settlement', {
|
||
date: data.date,
|
||
amount: data.amount,
|
||
direction: data.direction,
|
||
note: data.note || '',
|
||
verified: true,
|
||
revision: String(p.revision),
|
||
});
|
||
});
|
||
}
|
||
return (
|
||
<>
|
||
<p className="small muted">
|
||
{due < 0 ? owner + '待转回' + assistant : assistant + '待交' + owner} ¥{yuan(Math.abs(due))}
|
||
。只登记双方实际转账,不会发起付款。
|
||
</p>
|
||
<form id="material-settlement-form" data-pool-id={p.id} data-revision={p.revision} onSubmit={onSubmit}>
|
||
<div className="grid three">
|
||
<label>
|
||
业务日期
|
||
<input name="date" defaultValue={state.today} type="date" max={state.today} required />
|
||
</label>
|
||
<label>
|
||
转款方向
|
||
<select name="direction" defaultValue={due < 0 ? 'toAssistant' : 'toOwner'}>
|
||
<option value="toOwner">
|
||
{assistant} → {owner}
|
||
</option>
|
||
<option value="toAssistant">
|
||
{owner} → {assistant}
|
||
</option>
|
||
</select>
|
||
</label>
|
||
<label>
|
||
实际转账金额(元)
|
||
<input
|
||
name="amount"
|
||
defaultValue={(Math.abs(due) / 100).toFixed(2)}
|
||
type="number"
|
||
min="0"
|
||
step="0.01"
|
||
required
|
||
/>
|
||
</label>
|
||
</div>
|
||
<label>
|
||
凭据/备注(选填)
|
||
<input name="note" type="text" maxLength={150} />
|
||
</label>
|
||
<label className="check">
|
||
<input name="verified" type="checkbox" required />
|
||
已核实双方实际转账。
|
||
</label>
|
||
<div id="material-settlement-error" aria-live="polite">
|
||
{error}
|
||
</div>
|
||
<div className="form-actions">
|
||
<button type="button" className="quiet" data-action="close-material-settlement" onClick={close}>
|
||
取消
|
||
</button>
|
||
<button type="submit" className="primary" disabled={blocked}>
|
||
保存实际交款
|
||
</button>
|
||
</div>
|
||
</form>
|
||
</>
|
||
);
|
||
}
|