diff --git a/docs/proposed/modules/acc_invoices.md b/docs/proposed/modules/acc_invoices.md index 07b1283..a6e09bf 100644 --- a/docs/proposed/modules/acc_invoices.md +++ b/docs/proposed/modules/acc_invoices.md @@ -77,4 +77,4 @@ WebUI и бэкенд платёжного процесса: реестр инв - Загрузка файлов инвойса и платежа на Google Drive из интерфейса не сделана: пока вводится ссылка (в спецификации «проставляется в момент загрузки файла»). - Создание инвойса из письма, из платежа и из recipe не переведено на новые поля: письма по-прежнему создают записи через accounting_automation (поля `author`, `is_draft = false`, `invoice_url` для них ставятся миграцией только для уже существующих строк). - `llm_result` заполняет задание `invoice-check` (то же заключение, что в `conclusion`: «OK» или текст проблем); проверок сверх прежних (сумма в документе против таблицы, сверка с JobTread) пока нет. -- Журнала изменений (кто и когда менял) нет. +- Журнал изменений: таблица `acc_invoices_log` (миграция 085), пишется триггерами на `acc_invoices`, `acc_invoices_details`, `acc_invoices_approves`: время, автор и роль, действие WebUI, что изменилось (старое и новое значение). Правки заданий и ручные правки в БД попадают в журнал без автора (с именем пользователя БД). В WebUI виден бухгалтерии: панель «История изменений», API `GET /api/invoices/:id/log`. Строки, импортированные до миграции, начинаются без истории. diff --git a/packages/acc_invoices/src/audit.ts b/packages/acc_invoices/src/audit.ts new file mode 100644 index 0000000..1c2d7e3 --- /dev/null +++ b/packages/acc_invoices/src/audit.ts @@ -0,0 +1,47 @@ +import { AsyncLocalStorage } from "node:async_hooks"; +import type { Pool } from "khb_common"; + +/** Кто и каким действием меняет данные в текущем запросе; триггеры БД читают это из настроек транзакции (acc.*). */ +export interface AuditCtx { actorId?: string; actorName?: string; actingRole?: string | null; action?: string } +export const auditStore = new AsyncLocalStorage(); + +const SET_SQL = `select set_config('acc.actor_id', $1, true), set_config('acc.actor_name', $2, true), set_config('acc.acting_role', $3, true), set_config('acc.action', $4, true)`; +const setArgs = (a: AuditCtx) => [a.actorId ?? "", a.actorName ?? "", a.actingRole ?? "", a.action ?? ""]; +const MUTATING = /^\s*(insert|update|delete|with)\b/i; + +/** + * Обёртка над пулом: любая записывающая команда запроса WebUI выполняется в транзакции, где сначала проставлен автор, + * поэтому журнал (acc_invoices_log) знает, кто что сделал. Чтение идёт как обычно. + */ +export function withAudit(pool: Pool): Pool { + const wrapped = Object.create(pool) as Pool; + wrapped.query = (async (text: unknown, params?: unknown[]) => { + const a = auditStore.getStore(); + if (!a?.actorId || typeof text !== "string" || !MUTATING.test(text)) return (pool.query as (t: unknown, p?: unknown[]) => Promise)(text, params); + const c = await pool.connect(); + try { + await c.query("begin"); + await c.query(SET_SQL, setArgs(a)); + const r = await c.query(text, params); + await c.query("commit"); + return r; + } catch (e) { + await c.query("rollback").catch(() => undefined); + throw e; + } finally { + c.release(); + } + }) as Pool["query"]; + wrapped.connect = (async () => { + const c = await pool.connect(); + const orig = c.query.bind(c) as (t: unknown, p?: unknown[]) => Promise; + c.query = (async (text: unknown, params?: unknown[]) => { + const r = await orig(text, params); + const a = auditStore.getStore(); + if (a?.actorId && typeof text === "string" && /^\s*begin\b/i.test(text)) await orig(SET_SQL, setArgs(a)); + return r; + }) as typeof c.query; + return c; + }) as Pool["connect"]; + return wrapped; +} diff --git a/packages/acc_invoices/src/http-api.int.test.ts b/packages/acc_invoices/src/http-api.int.test.ts index ec47b76..998e0ff 100644 --- a/packages/acc_invoices/src/http-api.int.test.ts +++ b/packages/acc_invoices/src/http-api.int.test.ts @@ -111,6 +111,18 @@ d("acc_invoices: API платёжного процесса (временная 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([]); + // журнал: автор, действие и изменения; employee его не видит + expect((await call("emp", "GET", `invoices/${id}/log`)).status).toBe(403); + const log = (await call("acc", "GET", `invoices/${id}/log`)).body.items as { tbl: string; op: string; actor_name: string | null; action: string | null; changes: Record }[]; + expect(log[0]).toMatchObject({ tbl: "acc_invoices", op: "INSERT", action: "POST /api/invoices" }); + expect(log[0].actor_name).toBeTruthy(); + const bank = log.find((l) => l.action === "POST /api/invoices/:id/sent-to-bank" && l.changes.sent_to_bank?.from === null); + expect(bank?.changes.sent_to_bank.to).toBeTruthy(); + expect(log.find((l) => l.tbl === "acc_invoices" && l.changes.manual_result?.to === "OK")?.action).toBe("POST /api/invoices/:id/manual-result"); + expect(log.some((l) => l.tbl === "acc_invoices_approves" && l.op === "INSERT")).toBe(true); + expect(log.some((l) => l.tbl === "acc_invoices_details")).toBe(true); + // правка вне WebUI (задание, SQL) тоже попадает в журнал, но без автора + expect(log.some((l) => l.actor_name === null && l.changes.llm_result)).toBe(true); }); it("существующие задания не видят черновики; отмена и ошибки", async () => { diff --git a/packages/acc_invoices/src/http-api.ts b/packages/acc_invoices/src/http-api.ts index 0eb7d65..1369bcb 100644 --- a/packages/acc_invoices/src/http-api.ts +++ b/packages/acc_invoices/src/http-api.ts @@ -9,6 +9,7 @@ import { QUICK_FILTERS, STATUS_LABELS, canCancel, canMarkPaid, canReturnToDraft, canSendToBank, canView, dayInTz, editableFields, errorsOf, isStaff, matchesFilter, normResult, statusOf, submitProblems, type QuickFilter, } from "./rules.js"; +import { auditStore, withAudit } from "./audit.js"; import type { AccInvoicesSettings } from "./settings.js"; export interface ApiDeps { @@ -65,10 +66,12 @@ const DETAIL = z.object({ }); export function buildApi(deps: ApiDeps): FastifyInstance { - const { pool, settings } = deps; + const { settings } = deps; + const rawPool = deps.pool; + const pool = withAudit(rawPool); const now = deps.now ?? (() => new Date()); const app = Fastify({ logger: false, bodyLimit: 1_000_000 }); - const authenticate = createAuth(pool, settings, deps.verifyJwt); + const authenticate = createAuth(rawPool, settings, deps.verifyJwt); const ctx = () => ({ today: dayInTz(now(), settings.tz), now: now(), bankConfirmHours: settings.bankConfirmHours }); const decorate = (r: ListItem, actor: Actor) => { @@ -94,7 +97,14 @@ export function buildApi(deps: ApiDeps): FastifyInstance { return reply.code(500).send({ error: "внутренняя ошибка" }); }); - const need = async (req: FastifyRequest): Promise => authenticate(req.headers.authorization, typeof req.headers["x-acting-role"] === "string" ? req.headers["x-acting-role"] : undefined); + // контекст автора для журнала: в каждом запросе свой, заполняется после входа + app.addHook("onRequest", (_req, _reply, done) => { auditStore.run({}, done); }); + const need = async (req: FastifyRequest): Promise => { + const a = await authenticate(req.headers.authorization, typeof req.headers["x-acting-role"] === "string" ? req.headers["x-acting-role"] : undefined); + const st = auditStore.getStore(); + if (st) Object.assign(st, { actorId: a.personId, actorName: a.displayName, actingRole: a.acting, action: `${req.method} ${req.routeOptions?.url ?? req.url}` }); + return a; + }; const fail = (reply: FastifyReply, status: number, error: string) => reply.code(status).send({ error }); /** Загружает инвойс и проверяет, что он виден этому человеку (чужой выглядит как несуществующий). */ @@ -151,6 +161,16 @@ export function buildApi(deps: ApiDeps): FastifyInstance { }; }); + /** Журнал изменений инвойса (только бухгалтерия): кто, когда, какое действие и что изменилось. */ + app.get<{ Params: { id: string } }>("/api/invoices/:id/log", async (req, reply) => { + const a = await need(req); + if (!isStaff(a)) return fail(reply, 403, "журнал доступен бухгалтерии"); + if (!uuid.safeParse(req.params.id).success) return fail(reply, 400, "неверный id"); + const rows = (await pool.query( + `select id, at, tbl, op, row_id, actor_name, acting_role, action, db_user, changes from acc_invoices_log where invoice_id = $1 order by id`, [req.params.id])).rows; + return { items: rows }; + }); + /* ------------------------------------------------------------- создание */ app.post("/api/invoices", async (req, reply) => { const a = await need(req); diff --git a/packages/acc_invoices/web/src/App.tsx b/packages/acc_invoices/web/src/App.tsx index 27ecc63..f53f8c4 100644 --- a/packages/acc_invoices/web/src/App.tsx +++ b/packages/acc_invoices/web/src/App.tsx @@ -1,6 +1,6 @@ import * as Ariakit from "@ariakit/react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { ApiError, api, getActing, getToken, setActing, type Detail, type Line, type Lookups, type Me, type Row } from "./api.js"; +import { ApiError, api, getActing, getToken, setActing, type Detail, type Line, type LogItem, type Lookups, type Me, type Row } from "./api.js"; import { FormDialog } from "./FormDialog.js"; import { Login } from "./Login.js"; import { finishLogin, logout, relogin } from "./oidc.js"; @@ -19,6 +19,7 @@ function LinkBtn({ href, label, off }: { href?: string | null; label: string; of : ; } const isOkText = (v: string): boolean => v.trim().toLowerCase().replace(/о/g, "o").replace(/к/g, "k") === "ok"; +const fmtVal = (v: unknown): string => (v === null || v === undefined ? "∅" : typeof v === "object" ? JSON.stringify(v).slice(0, 60) : String(v).slice(0, 80)); const hashFilter = (): string => new URLSearchParams(location.hash.slice(1)).get("f") ?? "to_pay"; export function App() { @@ -51,6 +52,7 @@ function Main({ me, onLogout }: { me: Me; onLogout: () => void }) { const [list, setList] = useState({ items: [], counts: {} }); const [selected, setSelected] = useState(null); const [detail, setDetail] = useState(null); + const [history, setHistory] = useState(null); const [lookups, setLookups] = useState(null); const [toast, setToast] = useState<{ text: string; bad?: boolean } | null>(null); const [formRow, setFormRow] = useState(null); @@ -83,6 +85,7 @@ function Main({ me, onLogout }: { me: Me; onLogout: () => void }) { const loadDetail = useCallback(async (id: string | null) => { if (!id) { setDetail(null); return; } try { setDetail(await api(`invoices/${id}`)); } catch { setDetail(null); } + if (me.is_staff) { try { setHistory((await api<{ items: LogItem[] }>(`invoices/${id}/log`)).items); } catch { setHistory(null); } } else setHistory(null); }, []); useEffect(() => { const t = setTimeout(loadList, q ? 250 : 0); return () => clearTimeout(t); }, [loadList, q]); @@ -257,6 +260,22 @@ function Main({ me, onLogout }: { me: Me; onLogout: () => void }) { )} + {me.is_staff && history && history.length > 0 && ( +
+ История изменений ({history.length}) +
    + {history.map((h) => ( +
  • + {new Date(h.at).toLocaleString("ru-RU")} {h.actor_name ?? `система (${h.db_user})`}{h.acting_role ? ` [${h.acting_role}]` : ""} + {h.action ?? ""} · {h.tbl.replace("acc_invoices_", "")} {h.op} +
    {h.op === "UPDATE" + ? Object.entries(h.changes as Record).map(([k, v]) => `${k}: ${fmtVal(v.from)} → ${fmtVal(v.to)}`).join("; ") + : Object.entries(h.changes).filter(([k]) => !["id", "invoice_id", "conclusion", "lines"].includes(k)).map(([k, v]) => `${k}=${fmtVal(v)}`).join("; ")}
    +
  • + ))} +
+
+ )}
diff --git a/packages/acc_invoices/web/src/api.ts b/packages/acc_invoices/web/src/api.ts index 569dd63..43611c6 100644 --- a/packages/acc_invoices/web/src/api.ts +++ b/packages/acc_invoices/web/src/api.ts @@ -41,3 +41,5 @@ export async function api(path: string, init: { method?: string; bo if (!r.ok) throw new ApiError(data.error ?? `ошибка ${r.status}`, r.status, data.problems ?? data.issues); return data as T; } + +export interface LogItem { id: number; at: string; tbl: string; op: string; actor_name: string | null; acting_role: string | null; action: string | null; db_user: string; changes: Record } diff --git a/packages/acc_invoices/web/src/styles.css b/packages/acc_invoices/web/src/styles.css index 6e6ca98..1a07a24 100644 --- a/packages/acc_invoices/web/src/styles.css +++ b/packages/acc_invoices/web/src/styles.css @@ -108,3 +108,4 @@ body { margin: 0; background: var(--bg); color: var(--text); font: 14px/1.4 syst .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; } +.history { margin-top: 12px; font-size: 13px; } .history ul { list-style: none; padding: 0; margin: 6px 0; } .history li { padding: 4px 0; border-bottom: 1px solid var(--line); } .history .chg { color: var(--text); word-break: break-word; } .history .muted { color: var(--muted); } diff --git a/packages/khb_common/migrations/085_acc_invoices_log.sql b/packages/khb_common/migrations/085_acc_invoices_log.sql new file mode 100644 index 0000000..45f0b3f --- /dev/null +++ b/packages/khb_common/migrations/085_acc_invoices_log.sql @@ -0,0 +1,45 @@ +-- acc_invoices: журнал изменений (кто, когда, что и через какое действие поменял), пишется триггерами, поэтому ловит и UI, и задания, и ручные правки в БД +create table if not exists acc_invoices_log ( + id bigserial primary key, + at timestamptz not null default now(), + invoice_id uuid not null, -- без внешнего ключа: журнал переживает удаление инвойса + tbl text not null, -- acc_invoices | acc_invoices_details | acc_invoices_approves + op text not null, -- INSERT | UPDATE | DELETE + row_id uuid, + actor_id uuid, -- person.id пользователя WebUI; пусто - не через WebUI + actor_name text, + acting_role text, -- роль, под которой работал (переключатель CFO/accountant/employee) + action text, -- действие WebUI, например "POST /api/invoices/:id/sent-to-bank" + db_user text not null default current_user, + changes jsonb not null -- INSERT/DELETE: значения полей; UPDATE: {поле: {from, to}} +); +create index if not exists acc_invoices_log_inv_idx on acc_invoices_log (invoice_id, at); +alter table acc_invoices_log enable row level security; + +create or replace function acc_invoices_audit() returns trigger language plpgsql as $$ +declare + o jsonb; n jsonb; ch jsonb; inv uuid; rid uuid; +begin + if tg_op = 'INSERT' then n := to_jsonb(new); ch := jsonb_strip_nulls(n); + elsif tg_op = 'DELETE' then o := to_jsonb(old); ch := jsonb_strip_nulls(o); + else + o := to_jsonb(old); n := to_jsonb(new); + select coalesce(jsonb_object_agg(k, jsonb_build_object('from', o -> k, 'to', n -> k)), '{}'::jsonb) into ch + from jsonb_object_keys(n) k where k <> 'updated_at' and (o -> k) is distinct from (n -> k); + if ch = '{}'::jsonb then return null; end if; + end if; + rid := coalesce(n ->> 'id', o ->> 'id')::uuid; + inv := case when tg_table_name = 'acc_invoices' then rid else coalesce(n ->> 'invoice_id', o ->> 'invoice_id')::uuid end; + insert into acc_invoices_log (invoice_id, tbl, op, row_id, actor_id, actor_name, acting_role, action, changes) + values (inv, tg_table_name, tg_op, rid, + nullif(current_setting('acc.actor_id', true), '')::uuid, nullif(current_setting('acc.actor_name', true), ''), + nullif(current_setting('acc.acting_role', true), ''), nullif(current_setting('acc.action', true), ''), ch); + return null; +end $$; + +drop trigger if exists acc_invoices_audit_t on acc_invoices; +create trigger acc_invoices_audit_t after insert or update or delete on acc_invoices for each row execute function acc_invoices_audit(); +drop trigger if exists acc_invoices_details_audit_t on acc_invoices_details; +create trigger acc_invoices_details_audit_t after insert or update or delete on acc_invoices_details for each row execute function acc_invoices_audit(); +drop trigger if exists acc_invoices_approves_audit_t on acc_invoices_approves; +create trigger acc_invoices_approves_audit_t after insert or update or delete on acc_invoices_approves for each row execute function acc_invoices_audit();