166 lines
12 KiB
TypeScript
166 lines
12 KiB
TypeScript
import * as Ariakit from "@ariakit/react";
|
||
import { useState } from "react";
|
||
import { ApiError, api, type Line, type Lookups, type Row } from "./api.js";
|
||
|
||
type Form = {
|
||
vendor_name: string; invoice_number: string; invoice_date: string; amount: string; project_customer_id: string; contract_id: string;
|
||
target_employee: string; invoice_url: string; payment_url: string; pay_link: string; description: string; project: string; no_invoice_file: boolean; review_date: string; need_employee_refund: boolean; is_employee_refunded: boolean; is_paid_manual: boolean; pay_method: string;
|
||
};
|
||
const empty: Form = {
|
||
vendor_name: "", invoice_number: "", invoice_date: new Date().toISOString().slice(0, 10), amount: "", project_customer_id: "", contract_id: "",
|
||
target_employee: "", invoice_url: "", payment_url: "", pay_link: "", description: "", project: "", no_invoice_file: false, review_date: "", need_employee_refund: false, is_employee_refunded: false, is_paid_manual: false, pay_method: "",
|
||
};
|
||
const from = (r: Row): Form => ({
|
||
vendor_name: r.vendor_name, invoice_number: r.invoice_number ?? "", invoice_date: r.invoice_date ?? "", amount: String(r.amount), project_customer_id: r.project_customer_id ?? "", contract_id: r.contract_id ?? "",
|
||
target_employee: r.target_employee ?? "", invoice_url: r.invoice_url ?? "", payment_url: r.payment_url ?? "", pay_link: r.pay_link ?? "", description: r.description ?? "",
|
||
project: r.internal_project_id ? `internal:${r.internal_project_id}` : r.project_customer_id ?? "", no_invoice_file: r.no_invoice_file, review_date: r.review_date ?? "", need_employee_refund: r.need_employee_refund, is_employee_refunded: r.is_employee_refunded,
|
||
is_paid_manual: r.is_paid_manual, pay_method: r.pay_method ?? "",
|
||
});
|
||
const nz = (s: string): string | null => (s.trim() ? s.trim() : null);
|
||
const NEW_FIELDS = ["vendor_name", "invoice_number", "invoice_date", "amount", "project_customer_id", "internal_project_id", "contract_id", "target_employee", "invoice_url", "payment_url", "need_employee_refund", "pay_method", "pay_link", "description", "no_invoice_file"];
|
||
|
||
interface Props {
|
||
store: Ariakit.DialogStore;
|
||
lookups: Lookups;
|
||
/** null - создание нового черновика */
|
||
row: Row | null;
|
||
lines: Line[];
|
||
onSaved: (id: string) => void;
|
||
/** человек по умолчанию для «Кто ждёт инвойс» при создании (автор) */
|
||
defaultPerson: string;
|
||
}
|
||
|
||
export function FormDialog(p: Props) {
|
||
const open = Ariakit.useStoreState(p.store, "open");
|
||
return open ? <Inner key={p.row?.id ?? "new"} {...p} /> : null;
|
||
}
|
||
|
||
function Inner({ store, lookups, row, lines, onSaved, defaultPerson }: Props) {
|
||
const [f, setF] = useState<Form>(row ? from(row) : { ...empty, target_employee: defaultPerson });
|
||
const [ls, setLs] = useState<Line[]>(lines);
|
||
const [err, setErr] = useState<string | null>(null);
|
||
const [busy, setBusy] = useState(false);
|
||
const ed = new Set<string>(row ? row.editable : NEW_FIELDS);
|
||
const can = (k: string) => ed.has(k);
|
||
const set = <K extends keyof Form>(k: K, v: Form[K]) => setF((p) => ({ ...p, [k]: v }));
|
||
const linesEditable = !row || row.is_draft;
|
||
const canCategorize = !row || row.is_draft || row.editable.includes("contract_id");
|
||
const sum = ls.reduce((s, l) => s + (Number.isFinite(l.amount) ? l.amount : 0), 0);
|
||
|
||
async function save() {
|
||
setBusy(true);
|
||
setErr(null);
|
||
try {
|
||
const all: Record<string, unknown> = {
|
||
vendor_name: f.vendor_name.trim(), invoice_number: nz(f.invoice_number), invoice_date: nz(f.invoice_date), amount: Number(f.amount || 0),
|
||
project_customer_id: f.project.startsWith("internal:") ? null : nz(f.project), internal_project_id: f.project.startsWith("internal:") ? f.project.slice(9) : null,
|
||
pay_link: nz(f.pay_link), description: nz(f.description), no_invoice_file: f.no_invoice_file && !nz(f.invoice_url), contract_id: nz(f.contract_id), target_employee: nz(f.target_employee), invoice_url: nz(f.invoice_url), payment_url: nz(f.payment_url),
|
||
review_date: nz(f.review_date), need_employee_refund: f.need_employee_refund, is_employee_refunded: f.is_employee_refunded, is_paid_manual: f.is_paid_manual, pay_method: nz(f.pay_method),
|
||
};
|
||
let id = row?.id;
|
||
if (!row) {
|
||
const create = Object.fromEntries(Object.entries(all).filter(([k]) => NEW_FIELDS.includes(k)));
|
||
id = (await api<{ id: string }>("invoices", { method: "POST", body: create })).id;
|
||
} else {
|
||
const patch = Object.fromEntries(Object.entries(all).filter(([k]) => can(k)));
|
||
if (Object.keys(patch).length) await api(`invoices/${row.id}`, { method: "PATCH", body: patch });
|
||
}
|
||
if (id && (ls.length > 0 || lines.length > 0) && canCategorize) await api(`invoices/${id}/details`, { method: "PUT", body: { lines: ls } });
|
||
store.hide();
|
||
onSaved(id!);
|
||
} catch (e) {
|
||
setErr(e instanceof ApiError ? [e.message, ...(e.problems ?? [])].join(": ") : String(e));
|
||
} finally {
|
||
setBusy(false);
|
||
}
|
||
}
|
||
|
||
const text = (k: keyof Form, label: string, type = "text") => (
|
||
<label className="field">{label}
|
||
<input type={type} value={String(f[k])} disabled={!can(k)} onChange={(e) => set(k, e.target.value as never)} />
|
||
</label>
|
||
);
|
||
const select = (k: keyof Form, label: string, opts: { id: string; name: string }[]) => (
|
||
<label className="field">{label}
|
||
<select value={String(f[k])} disabled={!can(k)} onChange={(e) => set(k, e.target.value as never)}>
|
||
<option value="">—</option>
|
||
{opts.map((o) => <option key={o.id} value={o.id}>{o.name}</option>)}
|
||
</select>
|
||
</label>
|
||
);
|
||
const check = (k: "need_employee_refund" | "is_employee_refunded" | "is_paid_manual", label: string) => (
|
||
<label className="check"><input type="checkbox" checked={f[k]} disabled={!can(k)} onChange={(e) => set(k, e.target.checked)} /> {label}</label>
|
||
);
|
||
const setLine = (i: number, p: Partial<Line>) => setLs((a) => a.map((l, j) => (j === i ? { ...l, ...p } : l)));
|
||
|
||
return (
|
||
<Ariakit.Dialog store={store} backdrop={<div className="backdrop" />} className="dialog" aria-label={row ? "Редактирование" : "Новый инвойс"}>
|
||
<Ariakit.DialogHeading className="dialog-title">{row ? `Редактирование: ${row.vendor_name} ${row.invoice_number ?? ""}` : "Новый инвойс (черновик)"}</Ariakit.DialogHeading>
|
||
{row && !row.is_draft && <p className="hint">Инвойс в платёжном процессе: сумма, вендор, дата и строки меняются только в черновике (кнопка «Вернуть в черновик» отменит согласования и проверки).</p>}
|
||
<div className="grid">
|
||
{text("vendor_name", "Вендор")}
|
||
{text("invoice_number", "Номер инвойса")}
|
||
{text("invoice_date", "Дата инвойса", "date")}
|
||
{text("amount", "Сумма, USD", "number")}
|
||
<label className="field">Проект
|
||
<select value={f.project} disabled={!can("project_customer_id")} onChange={(e) => set("project", e.target.value)}>
|
||
<option value="">—</option>
|
||
<optgroup label="Внутренние">{lookups.internal_projects.map((o) => <option key={o.id} value={`internal:${o.id}`}>{o.name}</option>)}</optgroup>
|
||
<optgroup label="Проекты QuickBooks">{lookups.projects.map((o) => <option key={o.id} value={o.id}>{o.name}</option>)}</optgroup>
|
||
</select>
|
||
</label>
|
||
{select("contract_id", "Контракт", lookups.contracts.map((c) => ({ id: c.id, name: `${c.vendor_name} · ${c.total_amount.toLocaleString("en-US")}` })))}
|
||
{select("target_employee", "Кто ждёт инвойс", lookups.people)}
|
||
{row && text("review_date", "Не показывать до (review_date)", "date")}
|
||
{text("invoice_url", "Ссылка на файл инвойса (Drive)", "url")}
|
||
{text("payment_url", "Ссылка на файл платежа (Drive)", "url")}
|
||
{text("pay_link", "Ссылка для оплаты (URL портала вендора)", "url")}
|
||
{text("pay_method", "Способ оплаты")}
|
||
</div>
|
||
<label className="field wide">Описание
|
||
<textarea rows={2} value={f.description} disabled={!can("description")} onChange={(e) => set("description", e.target.value)} placeholder="Что оплачивается (если строки не заданы, это описание единственной строки на всю сумму)" />
|
||
</label>
|
||
<div className="checks">
|
||
{check("need_employee_refund", "Нужно возмещение сотруднику")}
|
||
{row && check("is_employee_refunded", "Возмещено сотруднику")}
|
||
{row && check("is_paid_manual", "Оплачен (отметка сотрудника)")}
|
||
<label className="check"><input type="checkbox" checked={f.no_invoice_file && !f.invoice_url.trim()} disabled={!can("no_invoice_file") || !!f.invoice_url.trim()} onChange={(e) => set("no_invoice_file", e.target.checked)} /> Файла Invoice пока нет.</label>
|
||
</div>
|
||
<h3>
|
||
Строки инвойса <span className="muted">(необязательно: без строк считается одна строка на всю сумму)</span>{" "}
|
||
{ls.length > 0 && <span className={Math.abs(sum - Number(f.amount || 0)) > 0.005 ? "err" : "muted"}>сумма строк {sum.toFixed(2)}</span>}
|
||
</h3>
|
||
<table className="lines">
|
||
<thead><tr><th>Описание</th><th>Кол-во</th><th>Цена</th><th>Сумма</th><th>Категория</th><th /></tr></thead>
|
||
<tbody>
|
||
{ls.map((l, i) => (
|
||
<tr key={i}>
|
||
<td><input value={l.description ?? ""} disabled={!linesEditable} onChange={(e) => setLine(i, { description: e.target.value || null })} /></td>
|
||
<td><input type="number" className="num" value={l.quantity ?? ""} disabled={!linesEditable} onChange={(e) => setLine(i, { quantity: e.target.value === "" ? null : Number(e.target.value) })} /></td>
|
||
<td><input type="number" className="num" value={l.unit_price ?? ""} disabled={!linesEditable} onChange={(e) => setLine(i, { unit_price: e.target.value === "" ? null : Number(e.target.value) })} /></td>
|
||
<td><input type="number" className="num" value={l.amount} disabled={!linesEditable} onChange={(e) => setLine(i, { amount: Number(e.target.value) })} /></td>
|
||
<td>
|
||
<select value={l.category_qbo_id ?? ""} disabled={!canCategorize} onChange={(e) => setLine(i, { category_qbo_id: e.target.value || null, category_name: lookups.categories.find((c) => c.id === e.target.value)?.name ?? null })}>
|
||
<option value="">—</option>
|
||
{lookups.categories.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
|
||
</select>
|
||
</td>
|
||
<td>{linesEditable && <button type="button" className="btn small" onClick={() => setLs((a) => a.filter((_, j) => j !== i))} aria-label="Удалить строку">×</button>}</td>
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
{linesEditable && (
|
||
<button type="button" className="btn small" onClick={() => setLs((a) => [...a, { description: null, quantity: null, unit_price: null, amount: 0, category_qbo_id: null, category_name: null, contract_detail_id: null }])}>
|
||
+ строка
|
||
</button>
|
||
)}
|
||
{err && <p className="err" role="alert">{err}</p>}
|
||
<div className="dialog-actions">
|
||
<Ariakit.DialogDismiss className="btn">Отмена</Ariakit.DialogDismiss>
|
||
<button type="button" className="btn primary" disabled={busy || !f.vendor_name.trim()} onClick={save}>{busy ? "Сохранение…" : "Сохранить"}</button>
|
||
</div>
|
||
</Ariakit.Dialog>
|
||
);
|
||
}
|