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,87 @@
import { timingSafeEqual } from "node:crypto";
import { createRemoteJWKSet, jwtVerify } from "jose";
import type { Pool } from "khb_common";
import type { AccInvoicesSettings } from "./settings.js";
export class AuthError extends Error {
constructor(message: string, readonly status: 401 | 403 = 401) {
super(message);
}
}
export type Role = "accountant" | "cfo";
export interface Actor {
personId: string;
displayName: string;
roles: Role[];
}
const safeEqual = (a: string, b: string): boolean => {
const x = Buffer.from(a);
const y = Buffer.from(b);
return x.length === y.length && timingSafeEqual(x, y);
};
export const bearerToken = (h: string | undefined): string | null => (h && /^Bearer\s/i.test(h) ? h.slice(7).trim() || null : null);
export type JwtVerifier = (token: string) => Promise<{ email?: string; emailVerified?: boolean }>;
export function keycloakVerifier(issuer: string): JwtVerifier {
const iss = issuer.replace(/\/$/, "");
const keys = createRemoteJWKSet(new URL(`${iss}/protocol/openid-connect/certs`));
return async (token) => {
const { payload } = await jwtVerify(token, keys, { issuer: [iss, `${iss}/`] });
return {
email: typeof payload.email === "string" ? payload.email : undefined,
emailVerified: typeof payload.email_verified === "boolean" ? payload.email_verified : undefined,
};
};
}
/** Роли человека: таблица user_roles, а если записей нет - person.role_code (accountant, cfo). */
export async function loadRoles(pool: Pool, personId: string): Promise<Role[]> {
const r = await pool.query("select role from user_roles where person_id = $1", [personId]);
const roles = new Set<Role>(r.rows.map((x) => x.role as Role));
if (!roles.size) {
const p = (await pool.query("select role_code from person where id = $1", [personId])).rows[0];
if (p?.role_code === "accountant" || p?.role_code === "cfo") roles.add(p.role_code);
}
return [...roles];
}
async function actorOf(pool: Pool, personId: string): Promise<Actor> {
const p = (await pool.query("select id, display_name from person where id = $1 and is_active", [personId])).rows[0];
if (!p) throw new AuthError("человек не найден или неактивен", 403);
return { personId: String(p.id), displayName: String(p.display_name), roles: await loadRoles(pool, personId) };
}
/** «Заголовок Authorization -> Actor». Статический токен, затем JWT Keycloak (person по email). */
export function createAuth(pool: Pool, settings: Pick<AccInvoicesSettings, "auth">, verifyJwt?: JwtVerifier): (authorization: string | undefined) => Promise<Actor> {
const verify = verifyJwt ?? (settings.auth.issuer ? keycloakVerifier(settings.auth.issuer) : undefined);
return async (authorization) => {
const t = bearerToken(authorization);
if (!t) throw new AuthError("нужен заголовок Authorization: Bearer <токен>", 401);
const st = settings.auth.staticTokens.find((x) => safeEqual(t, x.token));
if (st) return actorOf(pool, st.personId);
if (!verify) throw new AuthError("токен не принят", 401);
let email: string | undefined;
try {
const v = await verify(t);
if (v.emailVerified === false) throw new Error("email не подтверждён");
email = v.email;
} catch {
throw new AuthError("токен не принят", 401);
}
if (!email) throw new AuthError("в токене нет email", 401);
const p = (
await pool.query(
`select id from person
where is_active and (lower(email) = lower($1)
or exists (select 1 from unnest(string_to_array(lower(coalesce(additional_emails, '')), ';')) e where btrim(e) = lower($1)))
limit 1`,
[email],
)
).rows[0];
if (!p) throw new AuthError(`для ${email} нет активного person: доступ запрещён`, 403);
return actorOf(pool, String(p.id));
};
}

View File

@@ -0,0 +1,116 @@
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { createTestDb, testDatabaseUrl, type TestDb } from "khb_common";
import { buildApi } from "./http-api.js";
import { accInvoicesSchema } from "./settings.js";
const url = testDatabaseUrl();
const d = url ? describe : describe.skip;
d("acc_invoices: API платёжного процесса (временная БД)", () => {
let db: TestDb;
let app: ReturnType<typeof buildApi>;
const ids: Record<string, string> = {};
const T = { emp: "emp-token-0123456789", acc: "acc-token-0123456789", cfo: "cfo-token-0123456789", other: "oth-token-0123456789" };
let base = "";
const raw = async (method: string, path: string, token?: string, payload?: unknown) => {
const r = await fetch(base + path, { method, headers: { ...(token ? { authorization: "Bearer " + token } : {}), ...(payload !== undefined ? { "content-type": "application/json" } : {}) }, body: payload !== undefined ? JSON.stringify(payload) : undefined });
const t = await r.text();
return { status: r.status, body: t ? JSON.parse(t) : {} };
};
const call = (who: keyof typeof T, method: "GET" | "POST" | "PATCH" | "PUT", path: string, payload?: unknown) => raw(method, "/api/" + path, T[who], payload);
beforeAll(async () => {
db = await createTestDb(url!);
const mk = async (name: string, role?: string) => (await db.pool.query("insert into person (display_name, role_code) values ($1, $2) returning id", [name, role ?? null])).rows[0].id as string;
ids.emp = await mk("Employee");
ids.acc = await mk("Accountant", "accountant");
ids.cfo = await mk("CFO");
await db.pool.query("insert into user_roles (person_id, role) values ($1, 'cfo')", [ids.cfo]);
ids.other = await mk("Other");
const settings = accInvoicesSchema.parse({ auth: { staticTokens: [
{ token: T.emp, personId: ids.emp }, { token: T.acc, personId: ids.acc }, { token: T.cfo, personId: ids.cfo }, { token: T.other, personId: ids.other },
] } });
app = buildApi({ pool: db.pool, settings, now: () => new Date("2026-12-03T15:00:00Z") });
base = await app.listen({ host: "127.0.0.1", port: 0 });
});
afterAll(async () => { await app?.close(); await db?.drop(); });
it("без токена 401, роли определяются (role_code и user_roles)", async () => {
expect((await raw("GET", "/api/me")).status).toBe(401);
expect((await call("acc", "GET", "me")).body.roles).toEqual(["accountant"]);
expect((await call("cfo", "GET", "me")).body.roles).toEqual(["cfo"]);
expect((await call("emp", "GET", "me")).body.is_staff).toBe(false);
});
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" });
expect(c.status).toBe(201);
const id = c.body.id as string;
// чужой инициатор не видит
expect((await call("other", "GET", `invoices/${id}`)).status).toBe(404);
// строки не сходятся с суммой: отправить нельзя
expect((await call("emp", "PUT", `invoices/${id}/details`, { lines: [{ description: "work", amount: 90 }] })).status).toBe(200);
const bad = await call("emp", "POST", `invoices/${id}/submit`);
expect(bad.status).toBe(422);
expect(bad.body.problems.join()).toMatch(/сумма строк/);
await call("emp", "PUT", `invoices/${id}/details`, { lines: [{ description: "work", amount: 100 }] });
expect((await call("emp", "POST", `invoices/${id}/submit`)).status).toBe(200);
// вне черновика инициатор не меняет сумму
expect((await call("emp", "PATCH", `invoices/${id}`, { amount: 5 })).status).toBe(403);
expect((await call("acc", "PATCH", `invoices/${id}`, { amount: 5 })).status).toBe(403);
// без проверок (llm_result пусто) инвойс на проверке, в «На оплату» его нет
expect((await call("acc", "GET", `invoices/${id}`)).body.invoice.status).toBe("checking");
// проверки: агент пишет llm_result (задание), сотрудник - manual-result
await db.pool.query("update acc_invoices set llm_result = 'OK' where id = $1", [id]);
expect((await call("emp", "POST", `invoices/${id}/manual-result`, { result: "OK" })).status).toBe(403);
expect((await call("acc", "POST", `invoices/${id}/manual-result`, { result: "OK" })).status).toBe(200);
// без согласующих согласование не требуется: сразу «К оплате»
let list = (await call("acc", "GET", "invoices?filter=to_pay")).body;
expect(list.items.map((r: { id: string }) => r.id)).toContain(id);
// назначили согласующим CFO: инвойс уходит из «На оплату» в «На согласовании», «в банк» нельзя
expect((await call("acc", "POST", `invoices/${id}/approvals`, { person_ids: [ids.cfo] })).status).toBe(200);
list = (await call("acc", "GET", "invoices?filter=approval")).body;
expect(list.items.map((r: { id: string }) => r.id)).toContain(id);
expect((await call("acc", "POST", `invoices/${id}/sent-to-bank`)).status).toBe(409);
expect((await call("acc", "POST", `invoices/${id}/paid-manual`)).status).toBe(409);
expect((await call("acc", "POST", `invoices/${id}/decision`, { decision: "approved" })).status).toBe(403); // бухгалтер не назначен
expect((await call("cfo", "POST", `invoices/${id}/decision`, { decision: "approved" })).status).toBe(200);
list = (await call("acc", "GET", "invoices?filter=to_pay")).body;
expect(list.items.find((r: { id: string }) => r.id === id)?.status).toBe("ready_to_pay");
// «Отправлено в банк» и повторное нажатие
expect((await call("acc", "POST", `invoices/${id}/sent-to-bank`)).body.sent_to_bank).toBeTruthy();
expect((await call("acc", "GET", `invoices/${id}`)).body.invoice.status).toBe("on_payment");
expect((await call("acc", "POST", `invoices/${id}/draft`)).status).toBe(409);
expect((await call("acc", "POST", `invoices/${id}/sent-to-bank`)).body.sent_to_bank).toBeNull();
// ручная отметка оплаты: «Оплачен, ждём QuickBooks», в «Ждут QuickBooks», не ошибка до суток
expect((await call("emp", "POST", `invoices/${id}/paid-manual`)).status).toBe(403);
expect((await call("acc", "POST", `invoices/${id}/paid-manual`)).body.is_paid_manual).toBe(true);
expect((await call("acc", "GET", `invoices/${id}`)).body.invoice.status).toBe("paid_unconfirmed");
expect((await call("acc", "GET", "invoices?filter=pending_qb")).body.items.map((r: { id: string }) => r.id)).toContain(id);
expect((await call("acc", "POST", `invoices/${id}/paid-manual`)).body.is_paid_manual).toBe(false);
// возврат в черновик сбрасывает согласования и проверки
expect((await call("emp", "POST", `invoices/${id}/draft`)).status).toBe(200);
const after = (await call("acc", "GET", `invoices/${id}`)).body;
expect(after.invoice).toMatchObject({ is_draft: true, is_approved: false, llm_result: null, manual_result: null });
expect(after.approves).toEqual([]);
});
it("существующие задания не видят черновики; отмена и ошибки", async () => {
const c = await call("emp", "POST", "invoices", { vendor_name: "Draft Co", amount: 10 });
const id = c.body.id as string;
const jobSees = (await db.pool.query("select id from acc_invoices where stage = 'checking' and conclusion is null and not is_draft and not cancelled and id = $1", [id])).rowCount;
expect(jobSees).toBe(0);
expect((await call("other", "POST", `invoices/${id}/cancel`)).status).toBe(404);
expect((await call("emp", "POST", `invoices/${id}/cancel`)).body.cancelled).toBe(true);
expect((await call("emp", "POST", `invoices/${id}/cancel`)).status).toBe(403); // снять отмену - бухгалтерия
expect((await call("acc", "POST", `invoices/${id}/cancel`)).body.cancelled).toBe(false);
});
it("ошибка «отправлен в банк, нет подтверждения 24 ч»", async () => {
const id = (await db.pool.query(
`insert into acc_invoices (id, vendor_name, invoice_date, amount, is_approved, llm_result, manual_result, invoice_url, sent_to_bank, author)
values (gen_random_uuid(), 'Late', '2026-11-30', 50, true, 'OK', 'OK', 'https://x', '2026-12-01T10:00:00Z', $1) returning id`, [ids.emp])).rows[0].id as string;
const r = (await call("acc", "GET", "invoices?filter=errors")).body;
expect(r.items.find((x: { id: string }) => x.id === id).errors.join()).toMatch(/не подтверждён в QuickBooks/);
});
});

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;
}

View File

@@ -0,0 +1,2 @@
export * from "./rules.js";
export * from "./settings.js";

View File

@@ -0,0 +1,12 @@
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { createLogger, createPool, loadServiceSettings } from "khb_common";
import { buildApi } from "./http-api.js";
import { accInvoicesSchema } from "./settings.js";
const { common, service: s } = loadServiceSettings("acc_invoices", accInvoicesSchema);
const log = createLogger("acc_invoices", common.logLevel);
const pool = createPool(common.database.url, 5);
const app = buildApi({ pool, settings: s, log, webDir: join(dirname(fileURLToPath(import.meta.url)), "web") });
await app.listen({ host: s.http.host, port: s.http.port });
log.info({ port: s.http.port }, "acc_invoices запущен");

View File

@@ -0,0 +1,116 @@
import type { Pool } from "khb_common";
import { approvedFrom, type InvoiceRow } from "./rules.js";
type Q = Pick<Pool, "query">;
/** Столбцы, которые отдаёт список (с агрегатами для правил). */
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,
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.sent_to_bank, 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,
(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 c.display_name from qbo_customer c where c.id = i.project_customer_id limit 1) as project_name,
(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
and coalesce(o.invoice_number, '') <> '' and o.invoice_number = i.invoice_number and o.amount = i.amount) as duplicates,
(select (c.total_amount - coalesce((select sum(o.amount) from acc_invoices o where o.contract_id = c.id and o.id <> i.id and not o.cancelled and not o.is_draft), 0))::float8
from acc_contracts c where c.id = i.contract_id) as contract_remaining,
(select count(*)::int from acc_invoices_approves a where a.invoice_id = i.id and a.decision = 'pending') as approves_pending,
(select count(*)::int from acc_invoices_approves a where a.invoice_id = i.id and a.decision = 'rejected') as approves_rejected
from acc_invoices i`;
export interface ListItem extends InvoiceRow {
invoice_number: string | null;
vendor_name: string;
vendor_qbo_id: string | null;
invoice_date: string | null;
project_customer_id: string | null;
jt_job_id: string | null;
contract_id: string | null;
pay_method: string | null;
need_employee_refund: boolean;
is_employee_refunded: boolean;
author_name: string | null;
target_name: string | null;
project_name: string | null;
created_at: Date;
updated_at: Date;
}
export async function listInvoices(db: Q, opts: { viewerPersonId?: string; limit?: number } = {}): Promise<ListItem[]> {
const params: unknown[] = [];
let where = "";
if (opts.viewerPersonId) {
params.push(opts.viewerPersonId);
where = ` where i.author = $1 or i.target_employee = $1`;
}
const { rows } = await db.query(`${LIST_SQL}${where} order by i.created_at desc limit ${Math.min(opts.limit ?? 5000, 20000)}`, params);
return rows as ListItem[];
}
export async function getInvoice(db: Q, id: string): Promise<ListItem | null> {
const { rows } = await db.query(`${LIST_SQL} where i.id = $1`, [id]);
return (rows[0] as ListItem) ?? null;
}
export async function getDetails(db: Q, invoiceId: string) {
const { rows } = await db.query(
`select id, line_no, description, quantity::float8 as quantity, unit_price::float8 as unit_price, amount::float8 as amount,
category_qbo_id, category_name, contract_detail_id
from acc_invoices_details where invoice_id = $1 order by line_no`,
[invoiceId],
);
return rows;
}
export async function getApproves(db: Q, invoiceId: string) {
const { rows } = await db.query(
`select a.id, a.approver_person_id, p.display_name as approver_name, a.decision, a.comment, a.requested_at, a.decided_at
from acc_invoices_approves a join person p on p.id = a.approver_person_id where a.invoice_id = $1 order by a.requested_at`,
[invoiceId],
);
return rows;
}
/** Контракт инвойса: итоги, строки и все инвойсы контракта (правая панель). */
export async function getContractPanel(db: Q, contractId: string | null, currentId: string) {
if (!contractId) return null;
const c = (
await db.query(
`select id, vendor_name, project_customer_id, stage, total_amount::float8 as total_amount, paid_amount::float8 as paid_amount,
retained_amount::float8 as retained_amount, drive_file_id
from acc_contracts where id = $1`,
[contractId],
)
).rows[0];
if (!c) return null;
const details = (await db.query("select id, line_no, description, amount::float8 as amount from acc_contract_details where contract_id = $1 order by line_no", [contractId])).rows;
const invoices = (
await db.query(
`select id, invoice_number, invoice_date::text as invoice_date, amount::float8 as amount, paid_on::text as paid_on,
is_paid_manual, is_draft, cancelled, (id = $2) as is_current,
case when paid_on is not null or is_paid_manual then amount::float8 else null end as paid_amount
from acc_invoices where contract_id = $1 and not cancelled order by invoice_date nulls last, created_at`,
[contractId, currentId],
)
).rows;
return { ...c, details, invoices };
}
export async function recomputeApproved(db: Q, invoiceId: string): Promise<boolean> {
const d = (await db.query("select decision from acc_invoices_approves where invoice_id = $1", [invoiceId])).rows.map((r) => String(r.decision));
const ok = approvedFrom(d);
await db.query("update acc_invoices set is_approved = $2, updated_at = now() where id = $1", [invoiceId, ok]);
return ok;
}
export const LOOKUP = {
projects: `select id, display_name as name from qbo_customer where is_job and 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`,
categories: `select id, coalesce(fully_qualified_name, name) as name from qbo_account where active and classification in ('Expense','Revenue') order by 2`,
contracts: `select id, vendor_name, project_customer_id, total_amount::float8 as total_amount from acc_contracts order by vendor_name`,
} as const;

View File

@@ -0,0 +1,118 @@
import { describe, expect, it } from "vitest";
import { approvedFrom, canCancel, canMarkPaid, canReturnToDraft, canSendToBank, editableFields, errorsOf, matchesFilter, statusOf, submitProblems, type InvoiceRow } from "./rules.js";
const base = (o: Partial<InvoiceRow> = {}): InvoiceRow => ({
id: "1", is_draft: false, cancelled: false, is_approved: true, llm_result: "OK", manual_result: "ok", invoice_url: "https://d/1", payment_url: null,
sent_to_bank: null, paid_on: null, is_paid_manual: false, paid_manual_at: null, review_date: null, amount: 100, author: "a", target_employee: "t",
details_sum: null, duplicates: 0, contract_remaining: null, approves_pending: 0, approves_rejected: 0, ...o,
});
const today = "2026-12-03";
const now = new Date("2026-12-03T12:00:00Z");
const c = { today, now, bankConfirmHours: 24 };
describe("производное состояние", () => {
it("порядок: отмена, черновик, оплачен, на оплате, отложен, проверка, согласование, к оплате", () => {
expect(statusOf(base({ cancelled: true, is_draft: true }), today)).toBe("cancelled");
expect(statusOf(base({ is_draft: true }), today)).toBe("draft");
expect(statusOf(base({ paid_on: "2026-12-02", sent_to_bank: now }), today)).toBe("paid");
expect(statusOf(base({ is_paid_manual: true, sent_to_bank: now }), today)).toBe("paid_unconfirmed");
expect(statusOf(base({ sent_to_bank: now }), today)).toBe("on_payment");
expect(statusOf(base({ review_date: "2026-12-10" }), today)).toBe("postponed");
expect(statusOf(base({ review_date: "2026-12-03" }), today)).toBe("ready_to_pay");
expect(statusOf(base({ llm_result: "нет проекта" }), today)).toBe("checking");
expect(statusOf(base({ manual_result: null }), today)).toBe("checking");
expect(statusOf(base({ approves_pending: 1 }), today)).toBe("on_approval");
expect(statusOf(base({ is_approved: false }), today)).toBe("ready_to_pay"); // без согласующих согласование не требуется
expect(statusOf(base(), today)).toBe("ready_to_pay");
});
});
describe("быстрые фильтры", () => {
it("«На оплату»: условия ТЗ плюс согласован", () => {
expect(matchesFilter("to_pay", base(), c)).toBe(true);
expect(matchesFilter("to_pay", base({ invoice_url: null }), c)).toBe(false);
expect(matchesFilter("to_pay", base({ llm_result: "ошибка" }), c)).toBe(false);
expect(matchesFilter("to_pay", base({ review_date: "2026-12-04" }), c)).toBe(false);
expect(matchesFilter("to_pay", base({ is_paid_manual: true }), c)).toBe(false);
expect(matchesFilter("to_pay", base({ approves_pending: 1 }), c)).toBe(false);
expect(matchesFilter("to_pay", base({ approves_rejected: 1 }), c)).toBe(false);
expect(matchesFilter("to_pay", base({ is_approved: false }), c)).toBe(true);
expect(matchesFilter("to_pay", base({ is_draft: true }), c)).toBe(false);
});
it("«Оплачены»: оба флага", () => {
expect(matchesFilter("paid", base({ paid_on: "2026-12-01", is_paid_manual: true }), c)).toBe(true);
expect(matchesFilter("paid", base({ paid_on: "2026-12-01" }), c)).toBe(false);
});
it("«Ждут QuickBooks» и «Черновики»", () => {
expect(matchesFilter("pending_qb", base({ is_paid_manual: true }), c)).toBe(true);
expect(matchesFilter("pending_qb", base({ sent_to_bank: now }), c)).toBe(true);
expect(matchesFilter("pending_qb", base({ is_paid_manual: true, paid_on: "2026-12-02" }), c)).toBe(false);
expect(matchesFilter("drafts", base({ is_draft: true }), c)).toBe(true);
expect(matchesFilter("drafts", base(), c)).toBe(false);
});
it("«На согласовании»", () => {
expect(matchesFilter("approval", base({ approves_pending: 2 }), c)).toBe(true);
expect(matchesFilter("approval", base(), c)).toBe(false);
});
});
describe("ошибки", () => {
it("отправлен в банк без подтверждения после 24 ч", () => {
const old = new Date(now.getTime() - 25 * 3600_000);
expect(errorsOf(base({ sent_to_bank: old }), now, 24).join()).toMatch(/не подтверждён в QuickBooks/);
expect(errorsOf(base({ sent_to_bank: new Date(now.getTime() - 3600_000) }), now, 24)).toEqual([]);
expect(errorsOf(base({ sent_to_bank: old, paid_on: "2026-12-02", is_paid_manual: true }), now, 24)).toEqual([]);
});
it("оплачен без чека и QuickBooks; расхождение флагов; сумма строк; дубль; остаток контракта", () => {
expect(errorsOf(base({ is_paid_manual: true }), now, 24).join("|")).toMatch(/нет чека и нет в QuickBooks/);
// отметка сотрудника подтверждается на следующий день: до суток не ошибка, после - ошибка
expect(errorsOf(base({ is_paid_manual: true, payment_url: "u", paid_manual_at: new Date(now.getTime() - 3600_000) }), now, 24)).toEqual([]);
expect(errorsOf(base({ is_paid_manual: true, payment_url: "u", paid_manual_at: new Date(now.getTime() - 30 * 3600_000) }), now, 24).join()).toMatch(/не найдена в QuickBooks за 24/);
expect(errorsOf(base({ paid_on: "2026-12-01" }), now, 24).join()).toMatch(/не отмечена сотрудником/);
expect(errorsOf(base({ details_sum: 90 }), now, 24).join()).toMatch(/Сумма строк/);
expect(errorsOf(base({ duplicates: 1 }), now, 24).join()).toMatch(/дубль/);
expect(errorsOf(base({ contract_remaining: 50 }), now, 24).join()).toMatch(/остаток контракта/);
});
it("у черновика ошибок нет; оплата без согласования", () => {
expect(errorsOf(base({ is_draft: true, invoice_url: null }), now, 24)).toEqual([]);
expect(errorsOf(base({ approves_pending: 1, sent_to_bank: now }), now, 24).join()).toMatch(/без согласования/);
});
});
describe("права и переходы", () => {
const acc = { personId: "acc", roles: ["accountant" as const] };
const emp = { personId: "a", roles: [] };
it("редактируемые поля", () => {
expect(editableFields(emp, { author: "a", target_employee: null, is_draft: true, cancelled: false })).toContain("amount");
expect(editableFields(emp, { author: "a", target_employee: null, is_draft: false, cancelled: false })).toEqual(["target_employee"]);
expect(editableFields(acc, { author: "a", target_employee: null, is_draft: false, cancelled: false })).not.toContain("amount");
expect(editableFields(acc, { author: "a", target_employee: null, is_draft: false, cancelled: false })).toContain("contract_id");
expect(editableFields(emp, { author: "x", target_employee: null, is_draft: true, cancelled: false })).toEqual([]);
});
it("возврат в черновик и «Отправлено в банк»", () => {
const r = { author: "a", target_employee: null, is_draft: false, cancelled: false, sent_to_bank: null, paid_on: null, is_paid_manual: false };
expect(canReturnToDraft(emp, r).ok).toBe(true);
expect(canReturnToDraft(emp, { ...r, sent_to_bank: new Date() }).ok).toBe(false);
const ap = { approves_pending: 0, approves_rejected: 0 };
expect(canSendToBank(emp, { ...r, ...ap }).ok).toBe(false);
expect(canSendToBank(acc, { ...r, approves_pending: 1, approves_rejected: 0 }).ok).toBe(false);
expect(canSendToBank(acc, { ...r, ...ap }).ok).toBe(true);
expect(canSendToBank(acc, { ...r, ...ap, sent_to_bank: new Date() }).ok).toBe(true); // снять отметку
expect(canMarkPaid(acc, { ...r, ...ap }).ok).toBe(true);
expect(canMarkPaid(acc, { ...r, ...ap, paid_on: "2026-12-01" }).ok).toBe(false);
expect(canMarkPaid(emp, { ...r, ...ap }).ok).toBe(false);
});
it("отмена", () => {
const r = { author: "a", target_employee: null, cancelled: false, paid_on: null, is_paid_manual: false };
expect(canCancel(emp, r).ok).toBe(true);
expect(canCancel({ personId: "z", roles: [] }, r).ok).toBe(false);
expect(canCancel(acc, { ...r, paid_on: "2026-12-01" }).ok).toBe(false);
});
it("отправка черновика и итог согласований", () => {
expect(submitProblems({ vendor_name: "V", amount: 10, invoice_date: "2026-12-01", invoice_url: "u" }, 10)).toEqual([]);
expect(submitProblems({ vendor_name: "", amount: 0, invoice_date: null, invoice_url: null }, null)).toHaveLength(4);
expect(approvedFrom([])).toBe(true);
expect(approvedFrom(["approved", "pending"])).toBe(false);
expect(approvedFrom(["approved", "approved"])).toBe(true);
});
});

View File

@@ -0,0 +1,217 @@
/** Правила платёжного процесса: производное состояние, быстрые фильтры, ошибки, права. Чистые функции, без БД. */
import type { Role } from "./auth.js";
/** Строка реестра вместе с агрегатами, которые нужны правилам (их считает запрос списка). */
export interface InvoiceRow {
id: string;
is_draft: boolean;
cancelled: boolean;
is_approved: boolean;
llm_result: string | null;
manual_result: string | null;
invoice_url: string | null;
payment_url: string | null;
sent_to_bank: Date | string | null;
/** дата оплаты по QuickBooks (acc_invoices.paid_on; в ТЗ - payed_date_qb) */
paid_on: string | null;
is_paid_manual: boolean;
/** когда сотрудник поставил отметку «оплачен» */
paid_manual_at: Date | string | null;
review_date: string | null;
amount: number;
author: string | null;
target_employee: string | null;
/** сумма строк acc_invoices_details; null - строк нет */
details_sum: number | null;
/** сколько ещё не отклонённых инвойсов с тем же вендором, номером и суммой */
duplicates: number;
/** остаток контракта без этого инвойса (сумма контракта минус остальные не отменённые инвойсы), null - контракта нет */
contract_remaining: number | null;
/** сколько согласований ещё pending / rejected */
approves_pending: number;
approves_rejected: number;
}
export type Status = "draft" | "cancelled" | "paid" | "paid_unconfirmed" | "on_payment" | "postponed" | "checking" | "on_approval" | "ready_to_pay";
export const STATUS_LABELS: Record<Status, string> = {
draft: "Черновик",
cancelled: "Отменён",
paid: "Оплачен",
paid_unconfirmed: "Оплачен, ждём QuickBooks",
on_payment: "На оплате",
postponed: "Отложен",
checking: "На проверке",
on_approval: "На согласовании",
ready_to_pay: "К оплате",
};
export const isOk = (v: string | null | undefined): boolean => (v ?? "").trim().toLowerCase() === "ok";
/** Согласовано: нет ни ожидающих, ни отклонённых согласований (без согласующих согласование не требуется). */
export const approvalsOk = (r: Pick<InvoiceRow, "approves_pending" | "approves_rejected">): boolean => r.approves_pending === 0 && r.approves_rejected === 0;
const isPaidQb = (r: Pick<InvoiceRow, "paid_on">): boolean => !!r.paid_on;
const toMs = (v: Date | string): number => (v instanceof Date ? v.getTime() : new Date(v).getTime());
/** Календарная дата YYYY-MM-DD в часовом поясе tz. */
export const dayInTz = (now: Date, tz: string): string => new Intl.DateTimeFormat("en-CA", { timeZone: tz, year: "numeric", month: "2-digit", day: "2-digit" }).format(now);
/** Производное состояние: в БД не хранится, считается из флагов (порядок проверок важен). */
export function statusOf(r: InvoiceRow, today: string): Status {
if (r.cancelled) return "cancelled";
if (r.is_draft) return "draft";
if (isPaidQb(r)) return "paid";
if (r.is_paid_manual) return "paid_unconfirmed";
if (r.sent_to_bank) return "on_payment";
if (r.review_date && r.review_date > today) return "postponed";
if (!isOk(r.llm_result) || !isOk(r.manual_result)) return "checking";
if (!approvalsOk(r)) return "on_approval";
return "ready_to_pay";
}
/** Ошибки и несоответствия строки (раздел «Дополнительные проверки» ТЗ и фильтр «Ошибки»). */
export function errorsOf(r: InvoiceRow, now: Date, bankConfirmHours: number): string[] {
const e: string[] = [];
if (r.is_draft) return e; // у черновика ошибок процесса нет
if (!r.cancelled) {
if (!r.invoice_url) e.push("Нет файла инвойса (ссылки на Drive)");
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.approves_rejected > 0) e.push("Согласование отклонено");
if (r.duplicates > 0) e.push("Возможный дубль: тот же вендор, номер и сумма");
if (r.details_sum !== null && Math.abs(r.details_sum - r.amount) > 0.005) e.push(`Сумма строк ${r.details_sum.toFixed(2)} не равна сумме инвойса ${r.amount.toFixed(2)}`);
if (r.contract_remaining !== null && r.amount - r.contract_remaining > 0.005) e.push(`Сумма превышает остаток контракта (${r.contract_remaining.toFixed(2)})`);
}
const paidAny = isPaidQb(r) || r.is_paid_manual;
if (r.sent_to_bank && !isPaidQb(r) && now.getTime() - toMs(r.sent_to_bank) > bankConfirmHours * 3600_000) {
e.push(`Отправлен в банк, но не подтверждён в QuickBooks за ${bankConfirmHours} ч`);
}
if ((r.sent_to_bank || paidAny) && !approvalsOk(r)) e.push("Оплата без согласования");
if (paidAny && !r.payment_url && !isPaidQb(r)) e.push("Оплачен, но нет чека и нет в QuickBooks");
if (isPaidQb(r) && !r.is_paid_manual && !r.cancelled) e.push("Оплата есть в QuickBooks, но не отмечена сотрудником");
// отметка сотрудника подтверждается QuickBooks на следующий день: ошибка только после bankConfirmHours
const manualAt = r.paid_manual_at ?? r.sent_to_bank;
if (r.is_paid_manual && !isPaidQb(r) && !r.cancelled && manualAt && now.getTime() - toMs(manualAt) > bankConfirmHours * 3600_000) {
e.push(`Оплата отмечена сотрудником, но не найдена в QuickBooks за ${bankConfirmHours} ч`);
}
if (r.cancelled && (r.sent_to_bank || paidAny)) e.push("Отменён, но оплата уже отправлялась или проведена");
return e;
}
export type QuickFilter = "approval" | "to_pay" | "pending_qb" | "paid" | "errors" | "drafts" | "all";
export const QUICK_FILTERS: { key: QuickFilter; label: string }[] = [
{ key: "approval", label: "На согласовании" },
{ key: "to_pay", label: "На оплату" },
{ key: "pending_qb", label: "Ждут QuickBooks" },
{ key: "paid", label: "Оплачены" },
{ key: "errors", label: "Ошибки" },
{ key: "drafts", label: "Черновики" },
{ key: "all", label: "Все" },
];
/** Быстрые фильтры. «На оплату» - условия ТЗ плюс is_approved, не черновик, не отменён. */
export function matchesFilter(f: QuickFilter, r: InvoiceRow, ctx: { today: string; now: Date; bankConfirmHours: number }): boolean {
switch (f) {
case "all":
return true;
case "approval":
return !r.is_draft && !r.cancelled && !approvalsOk(r) && !isPaidQb(r) && !r.is_paid_manual;
case "to_pay":
return (
!r.is_draft && !r.cancelled && approvalsOk(r) &&
!isPaidQb(r) && !r.is_paid_manual &&
!!r.invoice_url && isOk(r.llm_result) && isOk(r.manual_result) &&
(!r.review_date || r.review_date <= ctx.today)
);
case "pending_qb":
return !r.is_draft && !r.cancelled && !isPaidQb(r) && (r.is_paid_manual || !!r.sent_to_bank);
case "drafts":
return r.is_draft && !r.cancelled;
case "paid":
return !r.cancelled && isPaidQb(r) && r.is_paid_manual;
case "errors":
return errorsOf(r, ctx.now, ctx.bankConfirmHours).length > 0;
}
}
/* ------------------------------------------------------------------ права */
export interface Who {
personId: string;
roles: Role[];
}
export const isStaff = (w: Who): boolean => w.roles.includes("accountant") || w.roles.includes("cfo");
export const isOwner = (w: Who, r: Pick<InvoiceRow, "author" | "target_employee">): boolean => r.author === w.personId || r.target_employee === w.personId;
export const canView = (w: Who, r: Pick<InvoiceRow, "author" | "target_employee">): boolean => isStaff(w) || isOwner(w, r);
/** Поля, которые можно менять при is_draft = false (остальное - только после возврата в черновик). */
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"],
/** инициатор: только неплатёжные характеристики */
owner: ["target_employee"],
} 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 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 });
/** Какие поля вправе изменить этот человек у этой записи. */
export function editableFields(w: Who, r: Pick<InvoiceRow, "author" | "target_employee" | "is_draft" | "cancelled">): readonly string[] {
if (r.cancelled) return [];
if (r.is_draft) return isStaff(w) || isOwner(w, r) ? DRAFT_FIELDS : [];
if (isStaff(w)) return LIVE_FIELDS.staff;
if (isOwner(w, r)) return LIVE_FIELDS.owner;
return [];
}
export function canReturnToDraft(w: Who, r: Pick<InvoiceRow, "author" | "target_employee" | "is_draft" | "cancelled" | "sent_to_bank" | "paid_on" | "is_paid_manual">): Allowed {
if (r.cancelled) return no(409, "отменённый инвойс не редактируется");
if (r.is_draft) return no(409, "инвойс уже черновик");
if (r.sent_to_bank || r.paid_on || r.is_paid_manual) return no(409, "после отправки в банк или оплаты вернуть в черновик нельзя: сначала снимите отметку «Отправлено в банк»");
if (!isStaff(w) && r.author !== w.personId) return no(403, "вернуть в черновик может автор или бухгалтерия");
return { ok: true };
}
export function canSendToBank(w: Who, r: Pick<InvoiceRow, "is_draft" | "cancelled" | "approves_pending" | "approves_rejected" | "paid_on" | "is_paid_manual" | "sent_to_bank">): Allowed {
if (!isStaff(w)) return no(403, "отметку «Отправлено в банк» ставит бухгалтерия");
if (r.sent_to_bank) return { ok: true }; // повторное нажатие снимает отметку
if (r.is_draft) return no(409, "черновик ещё не отправлен в платёжный процесс");
if (r.cancelled) return no(409, "инвойс отменён");
if (r.paid_on || r.is_paid_manual) return no(409, "инвойс уже оплачен");
if (!approvalsOk(r)) return no(409, "инвойс не согласован");
return { ok: true };
}
/** Отметка «оплачен» (ручная): те же условия, что для «Отправлено в банк»; повторное нажатие снимает отметку, пока QuickBooks оплату не подтвердил. */
export function canMarkPaid(w: Who, r: Pick<InvoiceRow, "is_draft" | "cancelled" | "approves_pending" | "approves_rejected" | "paid_on" | "is_paid_manual">): Allowed {
if (!isStaff(w)) return no(403, "отметку «оплачен» ставит бухгалтерия");
if (r.paid_on) return no(409, "оплата уже подтверждена QuickBooks");
if (r.is_paid_manual) return { ok: true };
if (r.is_draft) return no(409, "черновик ещё не отправлен в платёжный процесс");
if (r.cancelled) return no(409, "инвойс отменён");
if (!approvalsOk(r)) return no(409, "инвойс не согласован");
return { ok: true };
}
export function canCancel(w: Who, r: Pick<InvoiceRow, "author" | "target_employee" | "cancelled" | "paid_on" | "is_paid_manual">): Allowed {
if (r.cancelled) return isStaff(w) ? { ok: true } : no(403, "снять отмену может бухгалтерия");
if (r.paid_on || r.is_paid_manual) return no(409, "оплаченный инвойс отменить нельзя");
if (!isStaff(w) && r.author !== w.personId) return no(403, "отменить может автор или бухгалтерия");
return { ok: true };
}
/** Проверка перед отправкой черновика в платёжный процесс. Возвращает список недостающего. */
export function submitProblems(r: { vendor_name: string | null; amount: number | null; invoice_date: string | null; invoice_url: string | null }, detailsSum: number | null): string[] {
const p: string[] = [];
if (!r.vendor_name?.trim()) p.push("не указан вендор");
if (!(r.amount && r.amount > 0)) p.push("сумма должна быть больше нуля");
if (!r.invoice_date) p.push("не указана дата инвойса");
if (!r.invoice_url) p.push("не приложен файл инвойса");
if (detailsSum !== null && r.amount !== null && Math.abs(detailsSum - r.amount) > 0.005) p.push("сумма строк не равна сумме инвойса");
return p;
}
/** Итог согласований -> is_approved: все назначенные одобрили (если согласующих нет, согласование не требуется). */
export function approvedFrom(decisions: readonly string[]): boolean {
return decisions.every((d) => d === "approved");
}

View File

@@ -0,0 +1,19 @@
import { z } from "zod";
/** Секция `acc_invoices` в settings.json5. */
export const accInvoicesSchema = z.object({
http: z.object({ host: z.string().default("0.0.0.0"), port: z.number().default(8097) }).default({}),
auth: z
.object({
/** Издатель Keycloak: токен из заголовка Authorization проверяется по его JWKS, person ищется по email. */
issuer: z.string().optional(),
/** Статические токены (человек -> токен): для тестов и сотрудников без Keycloak. */
staticTokens: z.array(z.object({ token: z.string().min(16), personId: z.string() })).default([]),
})
.default({}),
/** Через сколько часов после «Отправлено в банк» отсутствие оплаты в QuickBooks считается ошибкой. */
bankConfirmHours: z.number().default(24),
/** Часовой пояс для сравнения review_date и подписи «На оплате dd месяц». */
tz: z.string().default("America/New_York"),
});
export type AccInvoicesSettings = z.infer<typeof accInvoicesSchema>;