acc_invoices: внутренние проекты (acc_internal_projects), описание, ссылка для оплаты, «Файла Invoice пока нет», строки необязательны, ждёт автор по умолчанию
All checks were successful
ci / test (push) Successful in 52s
ci / deploy (push) Successful in 3m5s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-04 15:30:38 +03:00
parent ade259515f
commit d0a22b8cec
9 changed files with 93 additions and 29 deletions

View File

@@ -42,6 +42,24 @@ d("acc_invoices: API платёжного процесса (временная
expect((await call("emp", "GET", "me")).body.is_staff).toBe(false); expect((await call("emp", "GET", "me")).body.is_staff).toBe(false);
}); });
it("создание: ждёт автор по умолчанию, строки необязательны, внутренний проект, «файла пока нет»", async () => {
const ip = (await db.pool.query("select id from acc_internal_projects where name = 'ИТ KHBuild'")).rows[0].id as string;
const c = await call("emp", "POST", "invoices", { vendor_name: "Linode", amount: 50, internal_project_id: ip, no_invoice_file: true, description: "хостинг", pay_link: "https://pay.example.com/x" });
expect(c.status).toBe(201);
const d = (await call("emp", "GET", `invoices/${c.body.id}`)).body;
expect(d.invoice.target_employee).toBe(ids.emp);
expect(d.invoice.project_name).toBe("ИТ KHBuild");
expect(d.details).toHaveLength(1);
expect(d.details[0]).toMatchObject({ virtual: true, amount: 50, description: "хостинг" });
// без файла, но с отметкой «файла Invoice пока нет» отправить можно
expect((await call("emp", "POST", `invoices/${c.body.id}/submit`)).status).toBe(200);
// без отметки и без файла - нельзя
const c2 = await call("emp", "POST", "invoices", { vendor_name: "Linode", amount: 50 });
const bad = await call("emp", "POST", `invoices/${c2.body.id}/submit`);
expect(bad.status).toBe(422);
expect(bad.body.problems.join()).toMatch(/файл/);
});
it("полный путь: черновик -> строки -> отправка -> проверки -> согласование -> «в банк» -> отмена отметки", async () => { it("полный путь: черновик -> строки -> отправка -> проверки -> согласование -> «в банк» -> отмена отметки", async () => {
const c = await call("emp", "POST", "invoices", { vendor_name: "ACME", invoice_number: "A-1", amount: 100, invoice_url: "https://drive.google.com/file/d/x/view" }); const c = await call("emp", "POST", "invoices", { vendor_name: "ACME", invoice_number: "A-1", amount: 100, invoice_url: "https://drive.google.com/file/d/x/view" });
expect(c.status).toBe(201); expect(c.status).toBe(201);

View File

@@ -35,6 +35,10 @@ const FIELD_SCHEMA = z
invoice_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).nullable(), invoice_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).nullable(),
amount: money, amount: money,
project_customer_id: nullableStr, project_customer_id: nullableStr,
internal_project_id: uuid.nullable(),
description: z.string().trim().max(4000).nullable(),
pay_link: z.string().trim().url().max(2000).nullable(),
no_invoice_file: z.boolean(),
jt_job_id: nullableStr, jt_job_id: nullableStr,
contract_id: uuid.nullable(), contract_id: uuid.nullable(),
target_employee: uuid.nullable(), target_employee: uuid.nullable(),
@@ -136,7 +140,9 @@ export function buildApi(deps: ApiDeps): FastifyInstance {
const a = await need(req); const a = await need(req);
const row = await load(a, req.params.id, reply); const row = await load(a, req.params.id, reply);
if (!row) return; if (!row) return;
const lines = await getDetails(pool, row.id); const real = await getDetails(pool, row.id);
// строки не заданы: считаем одной строкой на всю сумму инвойса (в БД не пишется)
const lines = real.length ? real : [{ id: "virtual", virtual: true, line_no: 1, description: row.description ?? null, quantity: null, unit_price: null, amount: row.amount, category_qbo_id: null, category_name: null, contract_detail_id: null }];
return { return {
invoice: decorate(row, a), invoice: decorate(row, a),
details: lines, details: lines,
@@ -148,17 +154,18 @@ export function buildApi(deps: ApiDeps): FastifyInstance {
/* ------------------------------------------------------------- создание */ /* ------------------------------------------------------------- создание */
app.post("/api/invoices", async (req, reply) => { app.post("/api/invoices", async (req, reply) => {
const a = await need(req); const a = await need(req);
const body = FIELD_SCHEMA.pick({ vendor_name: true, vendor_qbo_id: true, invoice_number: true, invoice_date: true, amount: true, project_customer_id: true, jt_job_id: true, contract_id: true, target_employee: true, need_employee_refund: true, invoice_url: true, payment_url: true, pay_method: true }) const body = FIELD_SCHEMA.pick({ vendor_name: true, vendor_qbo_id: true, invoice_number: true, invoice_date: true, amount: true, project_customer_id: true, internal_project_id: true, description: true, pay_link: true, no_invoice_file: true, jt_job_id: true, contract_id: true, target_employee: true, need_employee_refund: true, invoice_url: true, payment_url: true, pay_method: true })
.extend({ vendor_name: z.string().trim().min(1).max(300), amount: money.default(0) }) .extend({ vendor_name: z.string().trim().min(1).max(300), amount: money.default(0) })
.parse(req.body ?? {}); .parse(req.body ?? {});
const row = ( const row = (
await pool.query( await pool.query(
`insert into acc_invoices (id, vendor_name, vendor_qbo_id, invoice_number, invoice_date, amount, project_customer_id, jt_job_id, contract_id, `insert into acc_invoices (id, vendor_name, vendor_qbo_id, invoice_number, invoice_date, amount, project_customer_id, jt_job_id, contract_id,
target_employee, need_employee_refund, invoice_url, payment_url, pay_method, is_draft, author, stage) target_employee, need_employee_refund, invoice_url, payment_url, pay_method, is_draft, author, stage, internal_project_id, description, pay_link, no_invoice_file)
values (gen_random_uuid(), $1, $2, $3, coalesce($4::date, current_date), $5, $6, $7, $8, $9, coalesce($10, false), $11, $12, $13, true, $14, 'checking') values (gen_random_uuid(), $1, $2, $3, coalesce($4::date, current_date), $5, $6, $7, $8, $9, coalesce($10, false), $11, $12, $13, true, $14, 'checking', $15, $16, $17, coalesce($18, false))
returning id`, returning id`,
[body.vendor_name, body.vendor_qbo_id ?? null, body.invoice_number ?? null, body.invoice_date ?? null, body.amount, body.project_customer_id ?? null, body.jt_job_id ?? null, body.contract_id ?? null, [body.vendor_name, body.vendor_qbo_id ?? null, body.invoice_number ?? null, body.invoice_date ?? null, body.amount, body.project_customer_id ?? null, body.jt_job_id ?? null, body.contract_id ?? null,
body.target_employee ?? a.personId, body.need_employee_refund ?? null, body.invoice_url ?? null, body.payment_url ?? null, body.pay_method ?? null, a.personId], body.target_employee ?? a.personId, body.need_employee_refund ?? null, body.invoice_url ?? null, body.payment_url ?? null, body.pay_method ?? null, a.personId,
body.project_customer_id ? null : (body.internal_project_id ?? null), body.description ?? null, body.pay_link ?? null, body.no_invoice_file ?? null],
) )
).rows[0]; ).rows[0];
return reply.code(201).send({ id: row.id }); return reply.code(201).send({ id: row.id });

View File

@@ -7,12 +7,12 @@ type Q = Pick<Pool, "query">;
const LIST_SQL = ` const LIST_SQL = `
select i.id, i.invoice_number, i.vendor_name, i.vendor_qbo_id, i.invoice_date::text as invoice_date, i.amount::float8 as amount, select i.id, i.invoice_number, i.vendor_name, i.vendor_qbo_id, i.invoice_date::text as invoice_date, i.amount::float8 as amount,
i.project_customer_id, i.jt_job_id, i.contract_id, i.pay_method, i.project_customer_id, i.jt_job_id, i.contract_id, i.pay_method,
i.is_draft, i.cancelled, i.is_approved, i.llm_result, i.manual_result, i.invoice_url, i.payment_url, i.internal_project_id, i.description, i.pay_link, i.no_invoice_file, i.is_draft, i.cancelled, i.is_approved, i.llm_result, i.manual_result, i.invoice_url, i.payment_url,
i.sent_to_bank, i.qbo_txn_id, i.paid_on::text as paid_on, i.is_paid_manual, i.paid_manual_at, i.review_date::text as review_date, i.sent_to_bank, i.qbo_txn_id, i.paid_on::text as paid_on, i.is_paid_manual, i.paid_manual_at, i.review_date::text as review_date,
i.need_employee_refund, i.is_employee_refunded, i.author, i.target_employee, i.created_at, i.updated_at, i.need_employee_refund, i.is_employee_refunded, i.author, i.target_employee, i.created_at, i.updated_at,
(select display_name from person where id = i.author) as author_name, (select display_name from person where id = i.author) as author_name,
(select display_name from person where id = i.target_employee) as target_name, (select display_name from person where id = i.target_employee) as target_name,
(select c.display_name from qbo_customer c where c.id = i.project_customer_id limit 1) as project_name, coalesce((select c.display_name from qbo_customer c where c.id = i.project_customer_id limit 1), (select ip.name from acc_internal_projects ip where ip.id = i.internal_project_id)) as project_name,
(select sum(d.amount)::float8 from acc_invoices_details d where d.invoice_id = i.id) as details_sum, (select sum(d.amount)::float8 from acc_invoices_details d where d.invoice_id = i.id) as details_sum,
(select count(*)::int from acc_invoices o where o.id <> i.id and not o.cancelled and o.vendor_name = i.vendor_name (select count(*)::int from acc_invoices o where o.id <> i.id and not o.cancelled and o.vendor_name = i.vendor_name
and coalesce(o.invoice_number, '') <> '' and o.invoice_number = i.invoice_number and o.amount = i.amount) as duplicates, and coalesce(o.invoice_number, '') <> '' and o.invoice_number = i.invoice_number and o.amount = i.amount) as duplicates,
@@ -28,6 +28,9 @@ export interface ListItem extends InvoiceRow {
vendor_qbo_id: string | null; vendor_qbo_id: string | null;
invoice_date: string | null; invoice_date: string | null;
project_customer_id: string | null; project_customer_id: string | null;
internal_project_id: string | null;
description: string | null;
pay_link: string | null;
jt_job_id: string | null; jt_job_id: string | null;
contract_id: string | null; contract_id: string | null;
pay_method: string | null; pay_method: string | null;
@@ -109,6 +112,7 @@ export async function recomputeApproved(db: Q, invoiceId: string): Promise<boole
export const LOOKUP = { export const LOOKUP = {
projects: `select id, display_name as name from qbo_customer where is_job and active order by display_name`, projects: `select id, display_name as name from qbo_customer where is_job and active order by display_name`,
internal_projects: `select id, name from acc_internal_projects order by sort, name`,
vendors: `select id, display_name as name from qbo_vendor where active order by display_name`, vendors: `select id, display_name as name from qbo_vendor where active order by display_name`,
people: `select id, display_name as name from person where is_active order by display_name`, people: `select id, display_name as name from person where is_active order by display_name`,
categories: `select id, coalesce(fully_qualified_name, name) as name from qbo_account where active and classification in ('Expense','Revenue') order by 2`, categories: `select id, coalesce(fully_qualified_name, name) as name from qbo_account where active and classification in ('Expense','Revenue') order by 2`,

View File

@@ -18,6 +18,7 @@ export interface InvoiceRow {
/** когда сотрудник поставил отметку «оплачен» */ /** когда сотрудник поставил отметку «оплачен» */
paid_manual_at: Date | string | null; paid_manual_at: Date | string | null;
qbo_txn_id?: string | null; qbo_txn_id?: string | null;
no_invoice_file?: boolean;
review_date: string | null; review_date: string | null;
amount: number; amount: number;
author: string | null; author: string | null;
@@ -73,7 +74,7 @@ export function errorsOf(r: InvoiceRow, now: Date, bankConfirmHours: number): st
const e: string[] = []; const e: string[] = [];
if (r.is_draft) return e; // у черновика ошибок процесса нет if (r.is_draft) return e; // у черновика ошибок процесса нет
if (!r.cancelled) { if (!r.cancelled) {
if (!r.invoice_url && !r.paid_on) e.push("Нет файла инвойса (ссылки на Drive)"); if (!r.invoice_url && !r.paid_on && !r.no_invoice_file) e.push("Нет файла инвойса (ссылки на Drive)");
if (r.llm_result && !isOk(r.llm_result)) e.push(`Проверка агента: ${r.llm_result}`); if (r.llm_result && !isOk(r.llm_result)) e.push(`Проверка агента: ${r.llm_result}`);
if (r.manual_result && !isOk(r.manual_result)) e.push(`Проверка сотрудника: ${r.manual_result}`); if (r.manual_result && !isOk(r.manual_result)) e.push(`Проверка сотрудника: ${r.manual_result}`);
if (r.approves_rejected > 0) e.push("Согласование отклонено"); if (r.approves_rejected > 0) e.push("Согласование отклонено");
@@ -146,12 +147,12 @@ export const canView = (w: Who, r: Pick<InvoiceRow, "author" | "target_employee"
/** Поля, которые можно менять при is_draft = false (остальное - только после возврата в черновик). */ /** Поля, которые можно менять при is_draft = false (остальное - только после возврата в черновик). */
export const LIVE_FIELDS = { export const LIVE_FIELDS = {
/** сотрудники бухгалтерии */ /** сотрудники бухгалтерии */
staff: ["contract_id", "invoice_url", "payment_url", "is_paid_manual", "target_employee", "need_employee_refund", "is_employee_refunded", "review_date", "manual_result", "project_customer_id", "jt_job_id", "pay_method"], staff: ["contract_id", "invoice_url", "payment_url", "is_paid_manual", "target_employee", "need_employee_refund", "is_employee_refunded", "review_date", "manual_result", "project_customer_id", "internal_project_id", "jt_job_id", "pay_method", "pay_link", "description", "no_invoice_file"],
/** инициатор: только неплатёжные характеристики */ /** инициатор: только неплатёжные характеристики */
owner: ["target_employee"], owner: ["target_employee"],
} as const; } as const;
/** Поля черновика. */ /** Поля черновика. */
export const DRAFT_FIELDS = ["vendor_name", "vendor_qbo_id", "invoice_number", "invoice_date", "amount", "project_customer_id", "jt_job_id", "contract_id", "target_employee", "need_employee_refund", "invoice_url", "payment_url", "pay_method", "review_date"] as const; export const DRAFT_FIELDS = ["vendor_name", "vendor_qbo_id", "invoice_number", "invoice_date", "amount", "project_customer_id", "jt_job_id", "contract_id", "target_employee", "need_employee_refund", "invoice_url", "payment_url", "pay_method", "review_date", "internal_project_id", "description", "pay_link", "no_invoice_file"] as const;
export type Allowed = { ok: true } | { ok: false; status: 400 | 403 | 409; error: string }; export type Allowed = { ok: true } | { ok: false; status: 400 | 403 | 409; error: string };
const no = (status: 400 | 403 | 409, error: string): Allowed => ({ ok: false, status, error }); const no = (status: 400 | 403 | 409, error: string): Allowed => ({ ok: false, status, error });
@@ -202,12 +203,12 @@ export function canCancel(w: Who, r: Pick<InvoiceRow, "author" | "target_employe
} }
/** Проверка перед отправкой черновика в платёжный процесс. Возвращает список недостающего. */ /** Проверка перед отправкой черновика в платёжный процесс. Возвращает список недостающего. */
export function submitProblems(r: { vendor_name: string | null; amount: number | null; invoice_date: string | null; invoice_url: string | null }, detailsSum: number | null): string[] { export function submitProblems(r: { vendor_name: string | null; amount: number | null; invoice_date: string | null; invoice_url: string | null; no_invoice_file?: boolean }, detailsSum: number | null): string[] {
const p: string[] = []; const p: string[] = [];
if (!r.vendor_name?.trim()) p.push("не указан вендор"); if (!r.vendor_name?.trim()) p.push("не указан вендор");
if (!(r.amount && r.amount > 0)) p.push("сумма должна быть больше нуля"); if (!(r.amount && r.amount > 0)) p.push("сумма должна быть больше нуля");
if (!r.invoice_date) p.push("не указана дата инвойса"); if (!r.invoice_date) p.push("не указана дата инвойса");
if (!r.invoice_url) p.push("не приложен файл инвойса"); if (!r.invoice_url && !r.no_invoice_file) p.push("не приложен файл инвойса (если его пока нет, отметьте «Файла Invoice пока нет.»)");
if (detailsSum !== null && r.amount !== null && Math.abs(detailsSum - r.amount) > 0.005) p.push("сумма строк не равна сумме инвойса"); if (detailsSum !== null && r.amount !== null && Math.abs(detailsSum - r.amount) > 0.005) p.push("сумма строк не равна сумме инвойса");
return p; return p;
} }

View File

@@ -86,7 +86,7 @@ function Main({ me, onLogout }: { me: Me; onLogout: () => void }) {
useEffect(() => { const t = setTimeout(loadList, q ? 250 : 0); return () => clearTimeout(t); }, [loadList, q]); useEffect(() => { const t = setTimeout(loadList, q ? 250 : 0); return () => clearTimeout(t); }, [loadList, q]);
useEffect(() => { loadDetail(selected); }, [selected, loadDetail]); useEffect(() => { loadDetail(selected); }, [selected, loadDetail]);
useEffect(() => { api<Lookups>("lookups").then(setLookups).catch(() => setLookups({ projects: [], vendors: [], people: [], categories: [], contracts: [] })); }, []); useEffect(() => { api<Lookups>("lookups").then(setLookups).catch(() => setLookups({ projects: [], internal_projects: [], vendors: [], people: [], categories: [], contracts: [] })); }, []);
useEffect(() => { location.hash = `f=${filter}`; }, [filter]); useEffect(() => { location.hash = `f=${filter}`; }, [filter]);
useEffect(() => { if (selected && !list.items.some((r) => r.id === selected)) { /* выбранная строка ушла из фильтра: деталь остаётся, пока не выберут другую */ } }, [list, selected]); useEffect(() => { if (selected && !list.items.some((r) => r.id === selected)) { /* выбранная строка ушла из фильтра: деталь остаётся, пока не выберут другую */ } }, [list, selected]);
@@ -200,7 +200,7 @@ function Main({ me, onLogout }: { me: Me; onLogout: () => void }) {
<strong>{inv.vendor_name} {inv.invoice_number}</strong> <strong>{inv.vendor_name} {inv.invoice_number}</strong>
<span className={`badge b-${inv.status}`}>{inv.status_label}</span> <span className={`badge b-${inv.status}`}>{inv.status_label}</span>
<span className="spacer" /> <span className="spacer" />
{inv.editable.length > 0 && <button className="btn small" onClick={() => openForm(inv, detail!.details)}>Редактировать</button>} {inv.editable.length > 0 && <button className="btn small" onClick={() => openForm(inv, detail!.details.filter((l) => !l.virtual))}>Редактировать</button>}
{inv.is_draft && !inv.cancelled && <button className="btn small primary" onClick={() => act("submit", undefined, "Отправлено в платёжный процесс")}>Отправить в процесс</button>} {inv.is_draft && !inv.cancelled && <button className="btn small primary" onClick={() => act("submit", undefined, "Отправлено в платёжный процесс")}>Отправить в процесс</button>}
{!inv.is_draft && !inv.cancelled && !inv.sent_to_bank && !inv.paid_on && <button className="btn small" onClick={() => act("draft", undefined, "Возвращён в черновик, согласования сброшены")}>Вернуть в черновик</button>} {!inv.is_draft && !inv.cancelled && !inv.sent_to_bank && !inv.paid_on && <button className="btn small" onClick={() => act("draft", undefined, "Возвращён в черновик, согласования сброшены")}>Вернуть в черновик</button>}
{me.is_staff && !inv.is_draft && !inv.cancelled && <button className="btn small" onClick={() => { setPendingAction("manual"); setReason(inv.manual_result ?? "OK"); reasonDlg.show(); }}>Проверка: результат</button>} {me.is_staff && !inv.is_draft && !inv.cancelled && <button className="btn small" onClick={() => { setPendingAction("manual"); setReason(inv.manual_result ?? "OK"); reasonDlg.show(); }}>Проверка: результат</button>}
@@ -228,16 +228,19 @@ function Main({ me, onLogout }: { me: Me; onLogout: () => void }) {
<div className="details"> <div className="details">
<section className="panel" aria-label="Строки инвойса"> <section className="panel" aria-label="Строки инвойса">
<div className="panel-links"> <div className="panel-links">
<LinkBtn href={inv?.invoice_url} label="Invoice на Google Drive" off="Файла инвойса на Drive нет" /> <LinkBtn href={inv?.invoice_url} label="Invoice на Google Drive" off={inv?.no_invoice_file ? "Файла Invoice пока нет." : "Файла инвойса на Drive нет"} />
{inv?.payment_url && <LinkBtn href={inv.payment_url} label="Платёж на Google Drive" />} {inv?.payment_url && <LinkBtn href={inv.payment_url} label="Платёж на Google Drive" />}
{inv?.pay_link && <LinkBtn href={inv.pay_link} label="Оплатить по ссылке" />}
{showQb && <LinkBtn href={inv?.qbo_txn_id ? qbUrl(inv.qbo_txn_id) : null} label="Invoice в QuickBooks" off="Проводки в QuickBooks нет" />} {showQb && <LinkBtn href={inv?.qbo_txn_id ? qbUrl(inv.qbo_txn_id) : null} label="Invoice в QuickBooks" off="Проводки в QuickBooks нет" />}
</div> </div>
{inv?.no_invoice_file && !inv.invoice_url && <p className="hint">Файла Invoice пока нет.</p>}
{inv?.description && <p className="desc">{inv.description}</p>}
<h2>Строки инвойса</h2> <h2>Строки инвойса</h2>
{inv ? ( {inv ? (
<table className="mini"> <table className="mini">
<tbody> <tbody>
{detail!.details.map((l) => ( {detail!.details.map((l) => (
<tr key={l.id}><td>{l.description}</td><td className="muted">{l.category_name}</td><td className="r">{money(l.amount)}</td></tr> <tr key={l.id}><td>{l.description ?? (l.virtual ? "Вся сумма инвойса (одна строка)" : "")}{l.virtual && l.description ? <span className="muted"> · одна строка на всю сумму</span> : null}</td><td className="muted">{l.category_name}</td><td className="r">{money(l.amount)}</td></tr>
))} ))}
{!detail!.details.length && <tr><td colSpan={3} className="empty">Строк нет</td></tr>} {!detail!.details.length && <tr><td colSpan={3} className="empty">Строк нет</td></tr>}
<tr className="total"><td>Итого по строкам</td><td /><td className="r">{money(lineTotal)}</td></tr> <tr className="total"><td>Итого по строкам</td><td /><td className="r">{money(lineTotal)}</td></tr>
@@ -296,7 +299,7 @@ function Main({ me, onLogout }: { me: Me; onLogout: () => void }) {
</section> </section>
</div> </div>
{lookups && <FormDialog store={form} lookups={lookups} row={formRow} lines={formLines} onSaved={async (id) => { setSelected(id); await loadList(); await loadDetail(id); }} />} {lookups && <FormDialog store={form} lookups={lookups} defaultPerson={me.person_id} row={formRow} lines={formLines} onSaved={async (id) => { setSelected(id); await loadList(); await loadDetail(id); }} />}
<Ariakit.Dialog store={reasonDlg} backdrop={<div className="backdrop" />} className="dialog small" aria-label="Комментарий"> <Ariakit.Dialog store={reasonDlg} backdrop={<div className="backdrop" />} className="dialog small" aria-label="Комментарий">
<Ariakit.DialogHeading className="dialog-title">{pendingAction === "manual" ? "Результат проверки сотрудником" : "Причина отклонения"}</Ariakit.DialogHeading> <Ariakit.DialogHeading className="dialog-title">{pendingAction === "manual" ? "Результат проверки сотрудником" : "Причина отклонения"}</Ariakit.DialogHeading>
<p className="hint">{pendingAction === "manual" ? "«OK», если ошибок нет, иначе текст проблемы." : "Комментарий увидит бухгалтерия."}</p> <p className="hint">{pendingAction === "manual" ? "«OK», если ошибок нет, иначе текст проблемы." : "Комментарий увидит бухгалтерия."}</p>

View File

@@ -4,19 +4,20 @@ import { ApiError, api, type Line, type Lookups, type Row } from "./api.js";
type Form = { type Form = {
vendor_name: string; invoice_number: string; invoice_date: string; amount: string; project_customer_id: string; contract_id: string; 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; review_date: string; need_employee_refund: boolean; is_employee_refunded: boolean; is_paid_manual: boolean; pay_method: 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 = { const empty: Form = {
vendor_name: "", invoice_number: "", invoice_date: new Date().toISOString().slice(0, 10), amount: "", project_customer_id: "", contract_id: "", vendor_name: "", invoice_number: "", invoice_date: new Date().toISOString().slice(0, 10), amount: "", project_customer_id: "", contract_id: "",
target_employee: "", invoice_url: "", payment_url: "", review_date: "", need_employee_refund: false, is_employee_refunded: false, is_paid_manual: false, pay_method: "", 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 => ({ 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 ?? "", 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 ?? "", review_date: r.review_date ?? "", need_employee_refund: r.need_employee_refund, is_employee_refunded: r.is_employee_refunded, 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 ?? "", is_paid_manual: r.is_paid_manual, pay_method: r.pay_method ?? "",
}); });
const nz = (s: string): string | null => (s.trim() ? s.trim() : null); const nz = (s: string): string | null => (s.trim() ? s.trim() : null);
const NEW_FIELDS = ["vendor_name", "invoice_number", "invoice_date", "amount", "project_customer_id", "contract_id", "target_employee", "invoice_url", "payment_url", "need_employee_refund", "pay_method"]; 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 { interface Props {
store: Ariakit.DialogStore; store: Ariakit.DialogStore;
@@ -25,6 +26,8 @@ interface Props {
row: Row | null; row: Row | null;
lines: Line[]; lines: Line[];
onSaved: (id: string) => void; onSaved: (id: string) => void;
/** человек по умолчанию для «Кто ждёт инвойс» при создании (автор) */
defaultPerson: string;
} }
export function FormDialog(p: Props) { export function FormDialog(p: Props) {
@@ -32,8 +35,8 @@ export function FormDialog(p: Props) {
return open ? <Inner key={p.row?.id ?? "new"} {...p} /> : null; return open ? <Inner key={p.row?.id ?? "new"} {...p} /> : null;
} }
function Inner({ store, lookups, row, lines, onSaved }: Props) { function Inner({ store, lookups, row, lines, onSaved, defaultPerson }: Props) {
const [f, setF] = useState<Form>(row ? from(row) : empty); const [f, setF] = useState<Form>(row ? from(row) : { ...empty, target_employee: defaultPerson });
const [ls, setLs] = useState<Line[]>(lines); const [ls, setLs] = useState<Line[]>(lines);
const [err, setErr] = useState<string | null>(null); const [err, setErr] = useState<string | null>(null);
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
@@ -50,7 +53,8 @@ function Inner({ store, lookups, row, lines, onSaved }: Props) {
try { try {
const all: Record<string, unknown> = { 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), 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: nz(f.project_customer_id), contract_id: nz(f.contract_id), target_employee: nz(f.target_employee), invoice_url: nz(f.invoice_url), payment_url: nz(f.payment_url), 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), 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; let id = row?.id;
@@ -98,21 +102,32 @@ function Inner({ store, lookups, row, lines, onSaved }: Props) {
{text("invoice_number", "Номер инвойса")} {text("invoice_number", "Номер инвойса")}
{text("invoice_date", "Дата инвойса", "date")} {text("invoice_date", "Дата инвойса", "date")}
{text("amount", "Сумма, USD", "number")} {text("amount", "Сумма, USD", "number")}
{select("project_customer_id", "Проект (QuickBooks)", lookups.projects)} <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("contract_id", "Контракт", lookups.contracts.map((c) => ({ id: c.id, name: `${c.vendor_name} · ${c.total_amount.toLocaleString("en-US")}` })))}
{select("target_employee", "Кто ждёт инвойс", lookups.people)} {select("target_employee", "Кто ждёт инвойс", lookups.people)}
{row && text("review_date", "Не показывать до (review_date)", "date")} {row && text("review_date", "Не показывать до (review_date)", "date")}
{text("invoice_url", "Ссылка на файл инвойса (Drive)", "url")} {text("invoice_url", "Ссылка на файл инвойса (Drive)", "url")}
{text("payment_url", "Ссылка на файл платежа (Drive)", "url")} {text("payment_url", "Ссылка на файл платежа (Drive)", "url")}
{text("pay_link", "Ссылка для оплаты (URL портала вендора)", "url")}
{text("pay_method", "Способ оплаты")} {text("pay_method", "Способ оплаты")}
</div> </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"> <div className="checks">
{check("need_employee_refund", "Нужно возмещение сотруднику")} {check("need_employee_refund", "Нужно возмещение сотруднику")}
{row && check("is_employee_refunded", "Возмещено сотруднику")} {row && check("is_employee_refunded", "Возмещено сотруднику")}
{row && check("is_paid_manual", "Оплачен (отметка сотрудника)")} {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> </div>
<h3> <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>} {ls.length > 0 && <span className={Math.abs(sum - Number(f.amount || 0)) > 0.005 ? "err" : "muted"}>сумма строк {sum.toFixed(2)}</span>}
</h3> </h3>
<table className="lines"> <table className="lines">

View File

@@ -3,11 +3,12 @@ export interface Row {
id: string; invoice_number: string | null; vendor_name: string; vendor_qbo_id: string | null; invoice_date: string | null; amount: number; id: string; invoice_number: string | null; vendor_name: string; vendor_qbo_id: string | null; invoice_date: string | null; amount: number;
project_customer_id: string | null; project_name: string | null; contract_id: string | null; pay_method: string | null; project_customer_id: string | null; project_name: string | null; contract_id: string | null; pay_method: string | null;
is_draft: boolean; cancelled: boolean; is_approved: boolean; llm_result: string | null; manual_result: string | null; is_draft: boolean; cancelled: boolean; is_approved: boolean; llm_result: string | null; manual_result: string | null;
invoice_url: string | null; payment_url: string | null; qbo_txn_id: string | null; sent_to_bank: string | null; paid_on: string | null; is_paid_manual: boolean; invoice_url: string | null; payment_url: string | null; qbo_txn_id: string | null;
internal_project_id: string | null; description: string | null; pay_link: string | null; no_invoice_file: boolean; sent_to_bank: string | null; paid_on: string | null; is_paid_manual: boolean;
review_date: string | null; need_employee_refund: boolean; is_employee_refunded: boolean; author: string | null; target_employee: string | null; review_date: string | null; need_employee_refund: boolean; is_employee_refunded: boolean; author: string | null; target_employee: string | null;
author_name: string | null; target_name: string | null; approves_pending: number; approves_rejected: number; status: string; status_label: string; errors: string[]; editable: string[]; author_name: string | null; target_name: string | null; approves_pending: number; approves_rejected: number; status: string; status_label: string; errors: string[]; editable: string[];
} }
export interface Line { id?: string; line_no?: number; description: string | null; quantity: number | null; unit_price: number | null; amount: number; category_qbo_id: string | null; category_name: string | null; contract_detail_id: string | null } export interface Line { virtual?: boolean; id?: string; line_no?: number; description: string | null; quantity: number | null; unit_price: number | null; amount: number; category_qbo_id: string | null; category_name: string | null; contract_detail_id: string | null }
export interface Approve { id: string; approver_person_id: string; approver_name: string; decision: string; comment: string | null; decided_at: string | null } export interface Approve { id: string; approver_person_id: string; approver_name: string; decision: string; comment: string | null; decided_at: string | null }
export interface ContractPanel { export interface ContractPanel {
id: string; vendor_name: string; total_amount: number; paid_amount: number; retained_amount: number; drive_file_id: string | null; id: string; vendor_name: string; total_amount: number; paid_amount: number; retained_amount: number; drive_file_id: string | null;
@@ -16,7 +17,7 @@ export interface ContractPanel {
} }
export interface Detail { invoice: Row; details: Line[]; approves: Approve[]; contract: ContractPanel | null } export interface Detail { invoice: Row; details: Line[]; approves: Approve[]; contract: ContractPanel | null }
export type Named = { id: string; name: string }; export type Named = { id: string; name: string };
export interface Lookups { projects: Named[]; vendors: Named[]; people: Named[]; categories: Named[]; contracts: { id: string; vendor_name: string; project_customer_id: string; total_amount: number }[] } export interface Lookups { projects: Named[]; internal_projects: Named[]; vendors: Named[]; people: Named[]; categories: Named[]; contracts: { id: string; vendor_name: string; project_customer_id: string; total_amount: number }[] }
import { freshToken, hasSession } from "./oidc.js"; import { freshToken, hasSession } from "./oidc.js";
export const getToken = (): string => (hasSession() ? "1" : ""); export const getToken = (): string => (hasSession() ? "1" : "");

View File

@@ -106,3 +106,5 @@ body { margin: 0; background: var(--bg); color: var(--text); font: 14px/1.4 syst
.toast.bad { background: var(--bad); } .toast.bad { background: var(--bad); }
@media (max-width: 800px) { .details { grid-template-columns: 1fr; } .app { grid-template-rows: auto minmax(160px, 1fr) auto auto auto; overflow: auto; } } @media (max-width: 800px) { .details { grid-template-columns: 1fr; } .app { grid-template-rows: auto minmax(160px, 1fr) auto auto auto; overflow: auto; } }
.panel-links { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 8px; } .panel-links { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 8px; }
.field.wide { margin-top: 10px; }
.desc { margin: 0 0 8px; white-space: pre-wrap; }

View File

@@ -0,0 +1,13 @@
-- acc_invoices: внутренние проекты (спецстроки вместо проекта QuickBooks), описание, ссылка для оплаты, «файла инвойса пока нет»
create table if not exists acc_internal_projects (
id uuid primary key default gen_random_uuid(),
name text not null unique,
sort int not null default 0
);
alter table acc_internal_projects enable row level security;
insert into acc_internal_projects (name, sort) values ('ИТ KHBuild', 1), ('KHBuild внутренние затраты', 2) on conflict (name) do nothing;
alter table acc_invoices add column if not exists internal_project_id uuid references acc_internal_projects (id);
alter table acc_invoices add column if not exists description text; -- описание текстом (что оплачивается)
alter table acc_invoices add column if not exists pay_link text; -- URL для оплаты (портал вендора и т. п.)
alter table acc_invoices add column if not exists no_invoice_file boolean not null default false; -- «Файла Invoice пока нет.»