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

313 lines
17 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 { createHash } from "node:crypto";
import { mkdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { withTx, type Logger, type Pool } from "khb_common";
import type { ClaudeRunner } from "./claude-runner.js";
import { UNTRUSTED_DOC_ARGS } from "./claude-runner.js";
import { parseAmount } from "./invoices-mail.js";
import type { SlackPoster } from "./slack.js";
/**
* Процесс «Ежемесячная сверка банковских счетов» (шаги 3-4, задание `reconcile-monthly`):
* PDF выписки из Google Drive (папка «Выписки») -> Claude извлекает конечный остаток и операции -> сравнение с зеркалом
* QuickBooks (qbo_account, qbo_purchase) -> расхождения в acc_discrepancies (kind statement_vs_qbo) -> отчёт Анастасии в Slack.
*
* Ограничения: в зеркале только расходы (Purchase). Поэтому сверяются расходные операции выписки (списания, платежи по карте),
* а остаток на конец периода восстанавливается из текущего остатка счёта вычитанием расходов после периода (приближённо:
* поступления и переводы после периода зеркало не знает, расхождение остатка - повод посмотреть, а не диагноз).
*/
export interface StatementTxn {
date: string; // YYYY-MM-DD
description: string;
/** Положительная - расход (списание, покупка по карте), отрицательная - поступление, возврат. */
amount: number;
}
export interface ParsedStatement {
bank: string | null;
/** Последние цифры номера счёта или карты, либо название счёта, как в выписке. */
accountHint: string | null;
accountKind: "bank" | "credit_card" | null;
periodStart: string | null;
periodEnd: string | null;
/** Конечный остаток; для кредитной карты - сумма задолженности (положительная). */
endingBalance: number | null;
transactions: StatementTxn[];
}
export interface StatementFile {
id: string;
name: string;
getBytes(): Promise<Buffer>;
}
/** Источник выписок (в боевом режиме - Drive); в тестах подменяется. */
export interface StatementSource {
list(): Promise<StatementFile[]>;
}
/** Чтение PDF выписки (в боевом режиме - Claude); в тестах подменяется. */
export interface StatementReader {
read(file: { name: string; bytes: Buffer }): Promise<ParsedStatement>;
}
// ----------------------------------------------------------------- Claude
export function buildStatementPrompt(pdfPath: string): string {
return [
"Ты читаешь банковскую выписку (PDF) строительной компании.",
`Прочитай файл ${pdfPath} и верни ТОЛЬКО один JSON-объект, без пояснений и без markdown.`,
"Поля JSON:",
"- bank: название банка",
"- account_hint: последние 4 цифры номера счёта или карты (строкой) или название счёта, как в выписке",
'- account_kind: "bank" (расчётный счёт) или "credit_card" (кредитная карта)',
"- period_start, period_end: границы периода выписки, YYYY-MM-DD",
"- ending_balance: конечный остаток на конец периода, число в долларах; для кредитной карты - сумма задолженности (положительное число)",
'- transactions: все операции периода [{"date": "YYYY-MM-DD", "description": "описание", "amount": число}]; amount положительное для расходов (списания со счёта, покупки и платежи по карте), отрицательное для поступлений и возвратов',
"Если значение не найдено, ставь null (не выдумывай).",
].join("\n");
}
const str = (v: unknown): string | null => (typeof v === "string" && v.trim() ? v.trim() : null);
const isoDate = (v: unknown): string | null => {
if (typeof v !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(v)) return null;
const d = new Date(`${v}T00:00:00Z`);
return Number.isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== v ? null : v;
};
export function parseStatement(stdout: string): ParsedStatement {
const a = stdout.indexOf("{");
const b = stdout.lastIndexOf("}");
if (a < 0 || b <= a) throw new Error("агент не вернул JSON");
let j: Record<string, unknown>;
try {
j = JSON.parse(stdout.slice(a, b + 1)) as Record<string, unknown>;
} catch (e) {
throw new Error(`агент вернул невалидный JSON: ${(e as Error).message}`);
}
const txns: StatementTxn[] = [];
if (Array.isArray(j.transactions)) {
for (const t of j.transactions) {
if (!t || typeof t !== "object") continue;
const r = t as Record<string, unknown>;
const date = isoDate(r.date);
const amount = parseAmount(r.amount);
if (date && amount !== null) txns.push({ date, description: str(r.description) ?? "", amount });
}
}
const kind = j.account_kind === "bank" || j.account_kind === "credit_card" ? j.account_kind : null;
const hint = typeof j.account_hint === "number" ? String(j.account_hint) : str(j.account_hint);
return { bank: str(j.bank), accountHint: hint, accountKind: kind, periodStart: isoDate(j.period_start), periodEnd: isoDate(j.period_end), endingBalance: parseAmount(j.ending_balance), transactions: txns };
}
export function makeClaudeStatementReader(o: { claude: ClaudeRunner; tmpDir?: string }): StatementReader {
return {
async read({ name, bytes }) {
const dir = join(o.tmpDir ?? tmpdir(), `acc-statement-${createHash("sha1").update(`${name}${Date.now()}${Math.random()}`).digest("hex").slice(0, 12)}`);
await mkdir(dir, { recursive: true });
try {
const path = join(dir, "statement.pdf");
await writeFile(path, bytes);
const res = await o.claude({ prompt: buildStatementPrompt(path), cwd: dir, extraArgs: UNTRUSTED_DOC_ARGS });
if (!res.ok) throw new Error(`Claude не отработал (код ${res.exitCode}${res.timedOut ? ", таймаут" : ""}): ${res.stderr.slice(0, 200)}`);
return parseStatement(res.stdout);
} finally {
await rm(dir, { recursive: true, force: true });
}
},
};
}
// ----------------------------------------------------------------- сверка
export interface Finding {
description: string;
amountDiff: number | null;
qboRef: string | null;
}
interface Purchase {
id: string;
txn_date: string;
total_amt: number;
entity_name: string | null;
}
const DAY = 86_400_000;
const dayDiff = (a: string, b: string): number => Math.abs(Math.round((Date.parse(`${a}T00:00:00Z`) - Date.parse(`${b}T00:00:00Z`)) / DAY));
const money = (n: number): string => n.toFixed(2);
const cents = (n: number): number => Math.round(n * 100);
/** Чистое сравнение операций выписки (расходы) с расходами QuickBooks: пропущенные, лишние и возможные дубли. */
export function compareTransactions(stmtTxns: StatementTxn[], purchases: Purchase[], start: string, end: string, tolDays: number): Finding[] {
const out: Finding[] = [];
const outflows = stmtTxns.filter((t) => t.amount > 0 && t.date >= start && t.date <= end).sort((a, b) => a.date.localeCompare(b.date));
const used = new Set<string>();
const matched: Purchase[] = [];
for (const t of outflows) {
let best: Purchase | null = null;
let bestD = Infinity;
for (const p of purchases) {
if (used.has(p.id) || cents(p.total_amt) !== cents(t.amount)) continue;
const d = dayDiff(p.txn_date, t.date);
if (d <= tolDays && d < bestD) {
best = p;
bestD = d;
}
}
if (best) {
used.add(best.id);
matched.push(best);
} else out.push({ description: `Операция из выписки не найдена в QuickBooks: ${t.date} ${t.description} ${money(t.amount)}`.trim(), amountDiff: t.amount, qboRef: null });
}
for (const p of purchases) {
if (used.has(p.id) || p.txn_date < start || p.txn_date > end) continue;
const dup = matched.find((q) => cents(q.total_amt) === cents(p.total_amt) && dayDiff(q.txn_date, p.txn_date) <= tolDays);
out.push({
description: dup
? `Возможный дубль в QuickBooks: ${p.txn_date} ${p.entity_name ?? ""} ${money(p.total_amt)} (такая же операция ${dup.id} уже сверена с выпиской)`.replace(/\s+/g, " ")
: `Операция есть в QuickBooks, но нет в выписке: ${p.txn_date} ${p.entity_name ?? ""} ${money(p.total_amt)}`.replace(/\s+/g, " "),
amountDiff: p.total_amt,
qboRef: p.id,
});
}
return out;
}
export interface ReconcileDeps {
pool: Pool;
source: StatementSource;
reader: StatementReader;
slack: SlackPoster;
channelId: string;
realmId: () => Promise<string>;
log?: Logger;
/** Допуск по датам операций, дней (по умолчанию 3). */
toleranceDays?: number;
/** Сколько строк расхождений показывать в отчёте на выписку (по умолчанию 15). */
reportLines?: number;
}
export interface ReconcileResult {
statements: number;
discrepancies: number;
errors: number;
skipped: number;
}
interface Account {
id: string;
name: string;
account_type: string | null;
current_balance: number | null;
}
async function findAccount(pool: Pool, realm: string, s: ParsedStatement): Promise<{ account?: Account; problem?: string }> {
const hint = s.accountHint ?? "";
const digits = hint.replace(/\D/g, "");
const { rows } = await pool.query<Account>(
`select id, name, account_type, current_balance::float8 as current_balance from qbo_account
where realm_id = $1 and active and account_type in ('Bank', 'Credit Card')`,
[realm],
);
const cand = rows.filter((a) => {
const hay = `${a.name} ${a.id}`.toLowerCase();
if (digits.length >= 3) return hay.includes(digits.slice(-4));
return hint.length >= 3 && hay.includes(hint.toLowerCase());
});
const typed = s.accountKind ? cand.filter((a) => (s.accountKind === "credit_card") === (a.account_type === "Credit Card")) : cand;
const use = typed.length ? typed : cand;
if (use.length === 1) return { account: use[0] };
return { problem: use.length === 0 ? `счёт QuickBooks не найден по выписке (${s.bank ?? "банк ?"}, «${hint || "номер не распознан"}»)` : `счёт QuickBooks неоднозначен (${use.map((a) => a.name).join("; ")})` };
}
async function reconcileOne(deps: ReconcileDeps, file: StatementFile, parsed: ParsedStatement): Promise<{ findings: Finding[]; header: string }> {
const { pool } = deps;
const tol = deps.toleranceDays ?? 3;
const header = `${file.name} (${parsed.bank ?? "банк ?"}, ${parsed.accountHint ?? "счёт ?"}, ${parsed.periodStart ?? "?"} - ${parsed.periodEnd ?? "?"})`;
const findings: Finding[] = [];
if (!parsed.periodStart || !parsed.periodEnd) {
return { header, findings: [{ description: "Период выписки не распознан: сверку нужно сделать вручную", amountDiff: null, qboRef: null }] };
}
const realm = await deps.realmId();
const { account, problem } = await findAccount(pool, realm, parsed);
if (!account) return { header, findings: [{ description: `Сверка не выполнена: ${problem}`, amountDiff: null, qboRef: null }] };
const { rows: purchases } = await pool.query<Purchase>(
`select id, to_char(txn_date, 'YYYY-MM-DD') as txn_date, total_amt::float8 as total_amt, entity_name from qbo_purchase
where realm_id = $1 and account_id = $2 and txn_date between ($3::date - $5::int) and ($4::date + $5::int)`,
[realm, account.id, parsed.periodStart, parsed.periodEnd, tol],
);
findings.push(...compareTransactions(parsed.transactions, purchases, parsed.periodStart, parsed.periodEnd, tol));
if (parsed.transactions.length === 0) findings.push({ description: "В выписке не распознано ни одной операции: проверьте чтение файла", amountDiff: null, qboRef: null });
if (parsed.endingBalance !== null && account.current_balance !== null) {
const { rows: after } = await pool.query<{ s: number }>(
"select coalesce(sum(total_amt), 0)::float8 as s from qbo_purchase where realm_id = $1 and account_id = $2 and txn_date > $3::date",
[realm, account.id, parsed.periodEnd],
);
const spentAfter = after[0]!.s;
const card = account.account_type === "Credit Card";
const qboEnd = card ? account.current_balance - spentAfter : account.current_balance + spentAfter;
const diff = Math.round((parsed.endingBalance - qboEnd) * 100) / 100;
if (Math.abs(diff) > 0.01) {
findings.push({
description: `Конечный остаток не сходится: в выписке ${money(parsed.endingBalance)}, в QuickBooks на ${parsed.periodEnd} около ${money(qboEnd)} (счёт «${account.name}»; расчёт приближённый: в зеркале только расходы)`,
amountDiff: diff,
qboRef: account.id,
});
}
}
return { header, findings };
}
export async function runMonthlyReconcile(deps: ReconcileDeps): Promise<ReconcileResult> {
const res: ReconcileResult = { statements: 0, discrepancies: 0, errors: 0, skipped: 0 };
const { pool } = deps;
const blocks: string[] = [];
const files = await deps.source.list();
for (const f of files) {
const marker = `statement:${f.id}`;
const prev = await pool.query<{ result: string }>("select result from acc_mail_processed where message_id = $1", [marker]);
if (prev.rows[0] && prev.rows[0].result !== "error") {
res.skipped++;
continue;
}
try {
const parsed = await deps.reader.read({ name: f.name, bytes: await f.getBytes() });
const { header, findings } = await reconcileOne(deps, f, parsed);
await withTx(pool, async (c) => {
for (const x of findings) {
await c.query("insert into acc_discrepancies (kind, qbo_ref, description, amount_diff) values ('statement_vs_qbo', $1, $2, $3)", [
x.qboRef,
`[${f.name}] ${x.description}`,
x.amountDiff,
]);
}
await c.query(
`insert into acc_mail_processed (message_id, result, details) values ($1, 'statement', $2::jsonb)
on conflict (message_id) do update set result = 'statement', details = excluded.details, processed_at = now()`,
[marker, JSON.stringify({ file: f.name, discrepancies: findings.length, transactions: parsed.transactions.length })],
);
});
res.statements++;
res.discrepancies += findings.length;
const shown = findings.slice(0, deps.reportLines ?? 15).map((x) => ` - ${x.description}`);
const more = findings.length > shown.length ? [` ...и ещё ${findings.length - shown.length} (таблица acc_discrepancies)`] : [];
blocks.push([`Выписка ${header}: ${findings.length === 0 ? "расхождений нет" : `расхождений ${findings.length}`}`, ...shown, ...more].join("\n"));
} catch (e) {
res.errors++;
deps.log?.error({ err: String(e), file: f.name }, "ошибка сверки выписки");
await pool.query(
`insert into acc_mail_processed (message_id, result, details) values ($1, 'error', $2::jsonb)
on conflict (message_id) do update set result = 'error', details = excluded.details, processed_at = now()`,
[marker, JSON.stringify({ file: f.name, message: (e as Error).message })],
);
blocks.push(`Выписка ${f.name}: не удалось прочитать или сверить (${(e as Error).message.slice(0, 200)}); повтор при следующем запуске`);
}
}
if (blocks.length) {
await deps.slack.post(deps.channelId, `Ежемесячная сверка банковских счетов. Расхождения записаны в acc_discrepancies; закрывает месяц в QuickBooks Анастасия.\n\n${blocks.join("\n\n")}`);
}
return res;
}