Files
khb_microservices/packages/accounting_automation/src/finalize.ts

206 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { isDeepStrictEqual } from "node:util";
import { withTx, type Pool } from "khb_common";
type PoolClient = Parameters<Parameters<typeof withTx>[1]>[0];
/**
* Процесс «Завершение ручного разбора» (docs/approved/modules/quickbooks_bookkeeper/processes.md).
* Берёт записи *_review с done = true, которые не менялись дольше delaySeconds, проверяет их,
* переносит в *_history (с различиями относительно *_original), передаёт результат дальше
* (инвойс -> acc_invoices, сертификат -> acc_insurance_certificates) и удаляет строку из review
* (триггер БД сам убирает задачу из acc_manual_review).
*/
export type ReviewKind = "invoices" | "categorization" | "certificates";
export interface FinalizeDeps {
pool: Pool;
/** Сколько секунд запись должна оставаться без изменений. По умолчанию 30. */
delaySeconds?: number;
now?: () => Date;
/** Сообщение исполнителю (в боевом режиме - в Slack канал бухгалтерии). */
notify: (text: string) => Promise<void> | void;
}
export interface RejectedItem {
kind: ReviewKind;
id: string;
reason: string;
}
export interface FinalizeResult {
finalized: { invoices: number; categorization: number; certificates: number };
rejected: RejectedItem[];
/** Непредвиденные ошибки по записям (транзакция записи откатана, будет повтор при следующем запуске). */
errors: { kind: ReviewKind; id: string; message: string }[];
}
type Row = Record<string, unknown>;
interface KindConfig {
kind: ReviewKind;
table: string;
key: string;
label: string;
/** Текст причины отказа или null, если запись корректна. */
validate: (row: Row) => string | null;
/** Передача результата дальше (в той же транзакции). */
forward: (c: PoolClient, row: Row) => Promise<void>;
}
/** Поля, изменения которых не считаются правкой человека (служебные и отметки процесса). */
const SERVICE_FIELDS = new Set(["updated_at", "created_at", "done", "done_by", "problem_highlight", "request_sent_at"]);
/** Пусто или заглушка автомата «tbd». */
function blank(v: unknown): boolean {
if (v === null || v === undefined) return true;
if (typeof v === "string") {
const s = v.trim().toLowerCase();
return s === "" || s === "tbd";
}
return false;
}
function validateInvoice(r: Row): string | null {
const missing: string[] = [];
if (blank(r.vendor_name)) missing.push("vendor_name (вендор)");
if (blank(r.invoice_date)) missing.push("invoice_date (дата инвойса)");
if (blank(r.amount)) missing.push("amount (сумма)");
if (blank(r.project_customer_id)) missing.push("project_customer_id (проект)");
if (missing.length > 0) return `не заполнены обязательные поля: ${missing.join(", ")}`;
const amount = Number(r.amount);
if (!Number.isFinite(amount) || amount <= 0) return `сумма инвойса должна быть больше нуля (сейчас ${String(r.amount)})`;
return null;
}
function validateCertificate(r: Row): string | null {
if (blank(r.expires_on) && blank(r.certificate_id)) return "не указан ни срок окончания (expires_on), ни сертификат (certificate_id)";
return null;
}
async function forwardInvoice(c: PoolClient, r: Row): Promise<void> {
// Тот же id; если инвойс уже есть в реестре (вернулся в разбор), обновляем данные, статус не трогаем.
await c.query(
`insert into acc_invoices (id, source_message_id, drive_file_id, vendor_name, vendor_qbo_id, invoice_number, invoice_date,
amount, lines, project_customer_id, jt_job_id, contract_id, stage)
values ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, $10, $11, $12, 'checking')
on conflict (id) do update set
source_message_id = excluded.source_message_id, drive_file_id = excluded.drive_file_id, vendor_name = excluded.vendor_name,
vendor_qbo_id = excluded.vendor_qbo_id, invoice_number = excluded.invoice_number, invoice_date = excluded.invoice_date,
amount = excluded.amount, lines = excluded.lines, project_customer_id = excluded.project_customer_id,
jt_job_id = excluded.jt_job_id, contract_id = excluded.contract_id`,
[
r.id, r.source_message_id, r.drive_file_id, r.vendor_name, r.vendor_qbo_id ?? null, r.invoice_number ?? null, r.invoice_date,
r.amount, r.lines == null ? null : JSON.stringify(r.lines), r.project_customer_id, r.jt_job_id ?? null, r.contract_id ?? null,
],
);
}
/**
* Сертификат: если указан certificate_id - обновляем его срок (expires_on); иначе ищем последний сертификат вендора
* и обновляем его; если сертификатов нет - создаём запись (файл неизвестен, drive_file_id = 'manual').
*/
async function forwardCertificate(c: PoolClient, r: Row): Promise<void> {
const expires = blank(r.expires_on) ? null : r.expires_on;
let certId = blank(r.certificate_id) ? null : String(r.certificate_id);
if (!certId) {
const found = await c.query(
`select id from acc_insurance_certificates
where (($1::text is not null and vendor_qbo_id = $1) or lower(vendor_name) = lower($2))
order by valid_until desc limit 1`,
[r.vendor_qbo_id ?? null, r.vendor_name],
);
certId = found.rows[0]?.id ?? null;
}
if (certId) {
if (expires) await c.query("update acc_insurance_certificates set valid_until = $2 where id = $1", [certId, expires]);
return;
}
if (!expires) return;
await c.query(
`insert into acc_insurance_certificates (vendor_name, vendor_qbo_id, valid_until, drive_file_id) values ($1, $2, $3, 'manual')`,
[r.vendor_name, r.vendor_qbo_id ?? null, expires],
);
}
const KINDS: KindConfig[] = [
{ kind: "invoices", table: "acc_invoices_review", key: "id", label: "инвойс", validate: validateInvoice, forward: forwardInvoice },
// Категоризация: проводка в QuickBooks уже сделана Claude, обязательных полей нет; фиксируется только результат.
{ kind: "categorization", table: "acc_categorization_review", key: "feed_txn_id", label: "операция банка", validate: () => null, forward: async () => {} },
{ kind: "certificates", table: "acc_certificates_review", key: "id", label: "сертификат", validate: validateCertificate, forward: forwardCertificate },
];
/** Различия строки с оригиналом: {поле: {old, new}}; служебные поля не учитываются. */
export function diffWithOriginal(current: Row, original: Row | null): Record<string, { old: unknown; new: unknown }> {
const out: Record<string, { old: unknown; new: unknown }> = {};
if (!original) return out;
for (const k of Object.keys(current)) {
if (SERVICE_FIELDS.has(k)) continue;
const a = original[k] ?? null;
const b = current[k] ?? null;
if (!isDeepStrictEqual(a, b)) out[k] = { old: a, new: b };
}
return out;
}
type Outcome = { status: "skipped" } | { status: "finalized" } | { status: "rejected"; reason: string; doneBy: string | null };
async function finalizeOne(pool: Pool, cfg: KindConfig, id: string, cutoff: Date, now: Date): Promise<Outcome> {
return withTx(pool, async (c) => {
// Блокировка строки; занятую другим запуском пропускаем. Условия проверяются заново уже под блокировкой.
const locked = await c.query(
`select to_jsonb(r) as j from ${cfg.table} r where r.${cfg.key}::text = $1 and r.done and r.updated_at <= $2 for update skip locked`,
[id, cutoff],
);
if (locked.rowCount === 0) return { status: "skipped" } as Outcome;
const row = locked.rows[0].j as Row;
const doneBy = (row.done_by as string | null) ?? null;
const reason = cfg.validate(row);
if (reason) {
await c.query(`update ${cfg.table} set done = false, problem_highlight = $2 where ${cfg.key}::text = $1`, [id, `Завершение отклонено: ${reason}`]);
return { status: "rejected", reason, doneBy } as Outcome;
}
const orig = await c.query(`select to_jsonb(o) as j from ${cfg.table}_original o where o.${cfg.key}::text = $1`, [id]);
const changed = diffWithOriginal(row, (orig.rows[0]?.j as Row | undefined) ?? null);
const hist = { ...row, closed_by: doneBy, closed_at: now.toISOString(), changed_fields: changed };
await c.query(`insert into ${cfg.table}_history select (jsonb_populate_record(null::${cfg.table}_history, $1::jsonb)).*`, [JSON.stringify(hist)]);
await cfg.forward(c, row);
await c.query(`delete from ${cfg.table} where ${cfg.key}::text = $1`, [id]);
return { status: "finalized" } as Outcome;
});
}
export async function runFinalize(deps: FinalizeDeps): Promise<FinalizeResult> {
const delay = deps.delaySeconds ?? 30;
const now = (deps.now ?? (() => new Date()))();
const cutoff = new Date(now.getTime() - delay * 1000);
const result: FinalizeResult = { finalized: { invoices: 0, categorization: 0, certificates: 0 }, rejected: [], errors: [] };
for (const cfg of KINDS) {
const cand = await deps.pool.query(`select ${cfg.key}::text as id from ${cfg.table} where done and updated_at <= $1 order by created_at`, [cutoff]);
for (const { id } of cand.rows as { id: string }[]) {
try {
const out = await finalizeOne(deps.pool, cfg, id, cutoff, now);
if (out.status === "finalized") result.finalized[cfg.kind]++;
else if (out.status === "rejected") {
result.rejected.push({ kind: cfg.kind, id, reason: out.reason });
try {
await deps.notify(
`Завершение разбора отклонено (${cfg.label}, ${id}${out.doneBy ? `, отметил ${out.doneBy}` : ""}): ${out.reason}. Отметка «выполнено» снята, исправьте запись и отметьте заново.`,
);
} catch {
// сбой уведомления не должен ломать обработку; причина осталась в problem_highlight
}
}
} catch (e) {
result.errors.push({ kind: cfg.kind, id, message: e instanceof Error ? e.message : String(e) });
}
}
}
return result;
}