acc_invoices: сервис WebUI и бэкенд платёжного процесса (миграция 082, правила статусов, согласования, ручная отметка оплаты), статусы оплат, предложения к ТЗ
All checks were successful
ci / test (push) Successful in 59s
ci / deploy (push) Successful in 3m14s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-04 12:44:58 +03:00
parent 37778d8b11
commit 16e9b2c085
31 changed files with 2458 additions and 6 deletions

View File

@@ -0,0 +1,354 @@
import { existsSync, readFileSync } from "node:fs";
import { extname, join, normalize } from "node:path";
import Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify";
import { withTx, type Logger, type Pool } from "khb_common";
import { z } from "zod";
import { AuthError, createAuth, type Actor, type JwtVerifier } from "./auth.js";
import { LOOKUP, getApproves, getContractPanel, getDetails, getInvoice, listInvoices, recomputeApproved, type ListItem } from "./repo.js";
import {
QUICK_FILTERS, STATUS_LABELS, canCancel, canMarkPaid, canReturnToDraft, canSendToBank, canView, dayInTz, editableFields, errorsOf, isStaff, matchesFilter, statusOf, submitProblems,
type QuickFilter,
} from "./rules.js";
import type { AccInvoicesSettings } from "./settings.js";
export interface ApiDeps {
pool: Pool;
settings: AccInvoicesSettings;
log?: Logger;
/** Папка собранного WebUI (dist/web); не задана или нет - только API. */
webDir?: string;
now?: () => Date;
verifyJwt?: JwtVerifier;
}
const MIME: Record<string, string> = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".map": "application/json", ".svg": "image/svg+xml" };
const uuid = z.string().uuid();
const nullableStr = z.string().trim().max(2000).nullable();
const money = z.number().finite().min(0).max(1e9);
const FIELD_SCHEMA = z
.object({
vendor_name: z.string().trim().min(1).max(300),
vendor_qbo_id: nullableStr,
invoice_number: nullableStr,
invoice_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).nullable(),
amount: money,
project_customer_id: nullableStr,
jt_job_id: nullableStr,
contract_id: uuid.nullable(),
target_employee: uuid.nullable(),
need_employee_refund: z.boolean(),
is_employee_refunded: z.boolean(),
invoice_url: z.string().trim().url().max(2000).nullable(),
payment_url: z.string().trim().url().max(2000).nullable(),
pay_method: nullableStr,
review_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).nullable(),
is_paid_manual: z.boolean(),
manual_result: nullableStr,
})
.partial()
.strict();
const DETAIL = z.object({
description: z.string().trim().max(1000).nullable().default(null),
quantity: z.number().finite().nullable().default(null),
unit_price: z.number().finite().nullable().default(null),
amount: z.number().finite(),
category_qbo_id: nullableStr.default(null),
category_name: nullableStr.default(null),
contract_detail_id: uuid.nullable().default(null),
});
export function buildApi(deps: ApiDeps): FastifyInstance {
const { pool, settings } = deps;
const now = deps.now ?? (() => new Date());
const app = Fastify({ logger: false, bodyLimit: 1_000_000 });
const authenticate = createAuth(pool, settings, deps.verifyJwt);
const ctx = () => ({ today: dayInTz(now(), settings.tz), now: now(), bankConfirmHours: settings.bankConfirmHours });
const decorate = (r: ListItem, actor: Actor) => {
const c = ctx();
const status = statusOf(r, c.today);
return {
...r,
status,
status_label: STATUS_LABELS[status],
errors: errorsOf(r, c.now, c.bankConfirmHours),
editable: editableFields(actor, r),
};
};
app.get("/healthz", async () => ({ ok: true, time: now().toISOString() }));
app.setErrorHandler((err: unknown, _req, reply) => {
if (err instanceof AuthError) return reply.code(err.status).send({ error: err.message });
if (err instanceof z.ZodError) return reply.code(400).send({ error: "неверные данные", issues: err.issues.map((i) => `${i.path.join(".")}: ${i.message}`) });
const status = (err as { statusCode?: number }).statusCode;
if (status && status < 500) return reply.code(status).send({ error: (err as Error).message });
deps.log?.error({ err: String(err) }, "ошибка запроса");
return reply.code(500).send({ error: "внутренняя ошибка" });
});
const need = async (req: FastifyRequest): Promise<Actor> => authenticate(req.headers.authorization);
const fail = (reply: FastifyReply, status: number, error: string) => reply.code(status).send({ error });
/** Загружает инвойс и проверяет, что он виден этому человеку (чужой выглядит как несуществующий). */
async function load(actor: Actor, id: string, reply: FastifyReply) {
if (!uuid.safeParse(id).success) return void fail(reply, 400, "неверный id");
const row = await getInvoice(pool, id);
if (!row || !canView(actor, row)) return void fail(reply, 404, "инвойс не найден");
return row;
}
app.get("/api/me", async (req) => {
const a = await need(req);
return { person_id: a.personId, name: a.displayName, roles: a.roles, is_staff: isStaff(a), filters: QUICK_FILTERS };
});
app.get("/api/lookups", async (req) => {
await need(req);
const out: Record<string, unknown[]> = {};
for (const [k, sql] of Object.entries(LOOKUP)) out[k] = (await pool.query(sql)).rows;
return out;
});
app.get("/api/invoices", async (req) => {
const a = await need(req);
const q = z.object({ filter: z.enum(["approval", "to_pay", "pending_qb", "paid", "errors", "drafts", "all"]).default("all"), q: z.string().max(200).optional() }).parse(req.query);
const c = ctx();
const rows = await listInvoices(pool, isStaff(a) ? {} : { viewerPersonId: a.personId });
const needle = q.q?.trim().toLowerCase();
const items = rows
.filter((r) => matchesFilter(q.filter as QuickFilter, r, c))
.filter((r) => !needle || [r.vendor_name, r.invoice_number, r.project_name, r.author_name, r.target_name, String(r.amount)].some((v) => (v ?? "").toLowerCase().includes(needle)))
.map((r) => decorate(r, a));
// счётчики быстрых фильтров считаются по всем доступным строкам (без поиска)
const counts: Record<string, number> = {};
for (const f of QUICK_FILTERS) counts[f.key] = rows.filter((r) => matchesFilter(f.key, r, c)).length;
return { items, counts };
});
app.get<{ Params: { id: string } }>("/api/invoices/:id", async (req, reply) => {
const a = await need(req);
const row = await load(a, req.params.id, reply);
if (!row) return;
const lines = await getDetails(pool, row.id);
return {
invoice: decorate(row, a),
details: lines,
approves: await getApproves(pool, row.id),
contract: await getContractPanel(pool, row.contract_id, row.id),
};
});
/* ------------------------------------------------------------- создание */
app.post("/api/invoices", async (req, reply) => {
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 })
.extend({ vendor_name: z.string().trim().min(1).max(300), amount: money.default(0) })
.parse(req.body ?? {});
const row = (
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,
target_employee, need_employee_refund, invoice_url, payment_url, pay_method, is_draft, author, stage)
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')
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.target_employee ?? a.personId, body.need_employee_refund ?? null, body.invoice_url ?? null, body.payment_url ?? null, body.pay_method ?? null, a.personId],
)
).rows[0];
return reply.code(201).send({ id: row.id });
});
/* ------------------------------------------------------------- правка полей */
app.patch<{ Params: { id: string } }>("/api/invoices/:id", async (req, reply) => {
const a = await need(req);
const row = await load(a, req.params.id, reply);
if (!row) return;
const patch = FIELD_SCHEMA.parse(req.body ?? {});
const allowed = new Set(editableFields(a, row));
const keys = Object.keys(patch);
if (!keys.length) return fail(reply, 400, "нет полей для изменения");
const denied = keys.filter((k) => !allowed.has(k));
if (denied.length) {
const hint = !row.is_draft && ["vendor_name", "amount", "invoice_date", "invoice_number"].some((k) => denied.includes(k)) ? ": сумму и строки меняют только в черновике, верните инвойс в черновик" : "";
return fail(reply, row.cancelled ? 409 : 403, `нельзя менять: ${denied.join(", ")}${hint}`);
}
if (patch.manual_result !== undefined && !isStaff(a)) return fail(reply, 403, "manual_result ставит бухгалтерия");
await withTx(pool, async (c) => {
const sets: string[] = [];
const vals: unknown[] = [row.id];
for (const k of keys) {
vals.push((patch as Record<string, unknown>)[k]);
sets.push(`${k} = $${vals.length}`);
}
if (patch.is_paid_manual !== undefined && patch.is_paid_manual !== row.is_paid_manual) sets.push(patch.is_paid_manual ? "paid_manual_at = now()" : "paid_manual_at = null");
await c.query(`update acc_invoices set ${sets.join(", ")}, updated_at = now() where id = $1`, vals);
});
return { ok: true };
});
/* ------------------------------------------------------------- строки */
app.put<{ Params: { id: string } }>("/api/invoices/:id/details", async (req, reply) => {
const a = await need(req);
const row = await load(a, req.params.id, reply);
if (!row) return;
const body = z.object({ lines: z.array(DETAIL).max(500) }).parse(req.body);
if (row.cancelled) return fail(reply, 409, "инвойс отменён");
const draftEditor = row.is_draft && (isStaff(a) || row.author === a.personId || row.target_employee === a.personId);
if (!draftEditor) {
// вне черновика меняются только категории строк (бухгалтерия) и привязка к строкам контракта; состав и суммы - нет
if (!isStaff(a)) return fail(reply, 403, "строки инвойса вне черновика меняет бухгалтерия");
const cur = await getDetails(pool, row.id);
const same = cur.length === body.lines.length && cur.every((c, i) => { const l = body.lines[i]; return !!l && Math.abs(c.amount - l.amount) < 0.005 && (c.description ?? null) === l.description; });
if (!same) return fail(reply, 409, "состав и суммы строк меняются только в черновике: верните инвойс в черновик");
}
await withTx(pool, async (c) => {
await c.query("delete from acc_invoices_details where invoice_id = $1", [row.id]);
let n = 0;
for (const l of body.lines) {
n += 1;
await c.query(
`insert into acc_invoices_details (invoice_id, line_no, description, quantity, unit_price, amount, category_qbo_id, category_name, contract_detail_id)
values ($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
[row.id, n, l.description, l.quantity, l.unit_price, l.amount, l.category_qbo_id, l.category_name, l.contract_detail_id],
);
}
await c.query("update acc_invoices set updated_at = now() where id = $1", [row.id]);
});
return { ok: true };
});
/* ------------------------------------------------------------- переходы */
/** Отправить черновик в платёжный процесс (is_draft = false). Проверки агента и сотрудника начинаются заново. */
app.post<{ Params: { id: string } }>("/api/invoices/:id/submit", async (req, reply) => {
const a = await need(req);
const row = await load(a, req.params.id, reply);
if (!row) return;
if (!row.is_draft) return fail(reply, 409, "инвойс уже в платёжном процессе");
if (row.cancelled) return fail(reply, 409, "инвойс отменён");
if (!(isStaff(a) || row.author === a.personId || row.target_employee === a.personId)) return fail(reply, 403, "нет прав");
const problems = submitProblems(row, row.details_sum);
if (problems.length) return reply.code(422).send({ error: "черновик не готов к отправке", problems });
await pool.query(
`update acc_invoices set is_draft = false, llm_result = null, manual_result = null, is_approved = true, stage = 'checking', conclusion = null, updated_at = now() where id = $1`,
[row.id],
);
return { ok: true };
});
/** Вернуть в черновик: согласования и проверки отменяются. */
app.post<{ Params: { id: string } }>("/api/invoices/:id/draft", async (req, reply) => {
const a = await need(req);
const row = await load(a, req.params.id, reply);
if (!row) return;
const ok = canReturnToDraft(a, { ...row });
if (!ok.ok) return fail(reply, ok.status, ok.error);
await withTx(pool, async (c) => {
await c.query("delete from acc_invoices_approves where invoice_id = $1", [row.id]);
await c.query(`update acc_invoices set is_draft = true, is_approved = false, llm_result = null, manual_result = null, conclusion = null, stage = 'checking', updated_at = now() where id = $1`, [row.id]);
});
return { ok: true };
});
/** «Отправлено в банк»: ставит текущее время, повторное нажатие снимает отметку. */
app.post<{ Params: { id: string } }>("/api/invoices/:id/sent-to-bank", async (req, reply) => {
const a = await need(req);
const row = await load(a, req.params.id, reply);
if (!row) return;
const ok = canSendToBank(a, row);
if (!ok.ok) return fail(reply, ok.status, ok.error);
const cleared = !!row.sent_to_bank;
await pool.query("update acc_invoices set sent_to_bank = case when sent_to_bank is null then now() else null end, updated_at = now() where id = $1", [row.id]);
return { ok: true, sent_to_bank: cleared ? null : now().toISOString() };
});
/** Ручная отметка «оплачен» (сразу после оплаты); на следующий день её подтверждает QuickBooks (задание invoice-paid). Повтор снимает отметку. */
app.post<{ Params: { id: string } }>("/api/invoices/:id/paid-manual", async (req, reply) => {
const a = await need(req);
const row = await load(a, req.params.id, reply);
if (!row) return;
const ok = canMarkPaid(a, row);
if (!ok.ok) return fail(reply, ok.status, ok.error);
await pool.query("update acc_invoices set is_paid_manual = not is_paid_manual, paid_manual_at = case when is_paid_manual then null else now() end, updated_at = now() where id = $1", [row.id]);
return { ok: true, is_paid_manual: !row.is_paid_manual };
});
/** Отмена / снятие отмены. */
app.post<{ Params: { id: string } }>("/api/invoices/:id/cancel", async (req, reply) => {
const a = await need(req);
const row = await load(a, req.params.id, reply);
if (!row) return;
const ok = canCancel(a, row);
if (!ok.ok) return fail(reply, ok.status, ok.error);
await pool.query("update acc_invoices set cancelled = not cancelled, updated_at = now() where id = $1", [row.id]);
return { ok: true, cancelled: !row.cancelled };
});
/** Результат проверки сотрудником: «OK» или текст проблемы. */
app.post<{ Params: { id: string } }>("/api/invoices/:id/manual-result", async (req, reply) => {
const a = await need(req);
if (!isStaff(a)) return fail(reply, 403, "manual_result ставит бухгалтерия");
const row = await load(a, req.params.id, reply);
if (!row) return;
if (row.is_draft || row.cancelled) return fail(reply, 409, "проверка возможна только у инвойса в платёжном процессе");
const body = z.object({ result: z.string().trim().min(1).max(2000) }).parse(req.body);
await pool.query("update acc_invoices set manual_result = $2, updated_at = now() where id = $1", [row.id, body.result]);
return { ok: true };
});
/* ------------------------------------------------------------- согласования */
/** Бухгалтерия назначает согласующих (повторное назначение уже принявшему решение его не сбрасывает). */
app.post<{ Params: { id: string } }>("/api/invoices/:id/approvals", async (req, reply) => {
const a = await need(req);
if (!isStaff(a)) return fail(reply, 403, "согласующих назначает бухгалтерия");
const row = await load(a, req.params.id, reply);
if (!row) return;
if (row.is_draft || row.cancelled) return fail(reply, 409, "согласование возможно только у инвойса в платёжном процессе");
const body = z.object({ person_ids: z.array(uuid).min(1).max(10) }).parse(req.body);
await withTx(pool, async (c) => {
for (const p of body.person_ids) {
await c.query(`insert into acc_invoices_approves (invoice_id, approver_person_id, requested_by) values ($1,$2,$3) on conflict (invoice_id, approver_person_id) do nothing`, [row.id, p, a.personId]);
}
await recomputeApproved(c, row.id);
});
return { ok: true };
});
/** Решение согласующего (или CFO за любого): approved / rejected. */
app.post<{ Params: { id: string } }>("/api/invoices/:id/decision", async (req, reply) => {
const a = await need(req);
const row = await load(a, req.params.id, reply);
if (!row) return;
if (row.is_draft || row.cancelled) return fail(reply, 409, "согласование возможно только у инвойса в платёжном процессе");
if (row.paid_on || row.sent_to_bank) return fail(reply, 409, "после отправки в банк согласование не меняется");
const body = z.object({ decision: z.enum(["approved", "rejected"]), comment: z.string().trim().max(2000).nullable().default(null), on_behalf_of: uuid.optional() }).parse(req.body);
const target = body.on_behalf_of ?? a.personId;
const mine = (await pool.query("select 1 from acc_invoices_approves where invoice_id = $1 and approver_person_id = $2", [row.id, target])).rows[0];
if (target !== a.personId && !a.roles.includes("cfo")) return fail(reply, 403, "за другого решает только CFO");
if (!mine && !a.roles.includes("cfo")) return fail(reply, 403, "вас не назначали согласующим этого инвойса");
await withTx(pool, async (c) => {
await c.query(
`insert into acc_invoices_approves (invoice_id, approver_person_id, decision, comment, requested_by, decided_at) values ($1,$2,$3,$4,$5, now())
on conflict (invoice_id, approver_person_id) do update set decision = excluded.decision, comment = excluded.comment, decided_at = now()`,
[row.id, target, body.decision, body.comment, a.personId],
);
await recomputeApproved(c, row.id);
});
return { ok: true };
});
/* ------------------------------------------------------------- WebUI */
const webDir = deps.webDir && existsSync(deps.webDir) ? deps.webDir : null;
if (webDir) {
const serve = (reply: FastifyReply, rel: string) => {
const file = normalize(join(webDir, rel));
if (!file.startsWith(normalize(webDir)) || !existsSync(file)) return reply.code(404).send({ error: "не найдено" });
return reply.header("content-type", MIME[extname(file)] ?? "application/octet-stream").header("cache-control", rel === "index.html" ? "no-cache" : "public, max-age=3600").send(readFileSync(file));
};
app.get("/", async (_req, reply) => serve(reply, "index.html"));
app.get<{ Params: { "*": string } }>("/assets/*", async (req, reply) => serve(reply, `assets/${req.params["*"]}`));
}
return app;
}