Files
khb_microservices/packages/accounting_automation/src/main.ts
Yuri Yaryshev 74ffe8613b accounting_automation: сверка инвойсов с QuickBooks (invoice-reconcile), оплата независима от согласования, сумма и вендор из ленты, сводка Анастасии, правки finalize, поиска чека, проверки инвойса, chargeback; документы
Миграция 071: acc_discrepancies.reason и уникальный индекс открытых расхождений, уникальный открытый card_fraud по операции, insurer в разборе сертификатов.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 19:43:58 +03:00

181 lines
9.6 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 { readFileSync } from "node:fs";
import { createLogger, createPool, itNotify, loadServiceSettings } from "khb_common";
import { reapplyCategorizationRoles } from "./approval.js";
import { runCategorization } from "./categorize.js";
import { runFraudWeekly } from "./chargeback.js";
import { manualMessenger, runCertificates } from "./certificates.js";
import { makeClaudeRunner } from "./claude-runner.js";
import { DriveClient } from "./drive.js";
import { runFinalize } from "./finalize.js";
import { runFraudFlags } from "./fraud.js";
import { runInvoiceCheck } from "./invoice-check.js";
import { runInvoicePaid } from "./invoice-paid.js";
import { runInvoiceReconcile } from "./invoice-reconcile.js";
import { GmailClient } from "./gmail.js";
import { GoogleAuth } from "./google.js";
import { runHistoryWeekly } from "./history-report.js";
import { makeClaudeStatementReader, runMonthlyReconcile } from "./reconcile.js";
import { buildApi } from "./http-api.js";
import { instructionsFromFile } from "./mcp.js";
import { runInvoiceIngest } from "./invoices-mail.js";
import { makePromptLoader } from "./prompt-loader.js";
import { accountingSchema } from "./settings.js";
import { createSlackClient } from "./slack.js";
import { postCfoSummary, postDailySummary } from "./summary.js";
import { runReceiptSearch, runReceiptWeeklyReport } from "./receipt-search.js";
import { runReceiptsSlack } from "./receipts.js";
import { loadNonWorkdays } from "./workdays.js";
const { common, service: s } = loadServiceSettings("accounting_automation", accountingSchema);
const log = createLogger("accounting_automation", common.logLevel);
const pool = createPool(common.database.url, 6);
const claude = makeClaudeRunner({
bin: s.claude.bin,
workDir: s.claude.workDir,
timeoutMs: s.claude.timeoutMs,
extraArgs: s.claude.extraArgs,
env: s.claude.sqlUrl ? { KHB_SQL_URL: s.claude.sqlUrl } : undefined,
});
const auth = s.google ? new GoogleAuth({ client_email: s.google.client_email, private_key: s.google.private_key }) : null;
const drive = auth && s.google?.rootFolderId ? new DriveClient({ auth, rootFolderId: s.google.rootFolderId }) : null;
const slack = s.slack ? createSlackClient({ botToken: s.slack.botToken }) : null;
const notify = async (text: string): Promise<void> => {
if (slack && s.slack) await slack.post(s.slack.accountingChannelId, text).catch((e) => log.error({ err: String(e) }, "slack"));
else if (!(await itNotify(common, text).catch(() => false))) log.warn({ text }, "уведомление некуда отправить");
};
/** Компания QuickBooks берётся из подключения qbo_auth. */
async function realmId(): Promise<string> {
// realm_id в qbo_connection зашифрован (требование Intuit); компания берётся из последней успешной загрузки зеркала
const { rows } = await pool.query("select realm_id from qbo_sync_run where status = 'ok' and realm_id is not null order by started_at desc limit 1");
if (!rows[0]) throw new Error("QuickBooks не подключён или зеркало ещё не загружено (нет успешной загрузки в qbo_sync_run)");
return rows[0].realm_id as string;
}
const nonWorkdays = (): Promise<ReadonlySet<string>> => loadNonWorkdays(pool);
/** Куда слать отчёты Анастасии (сверка, разбор правок, fraud). */
function reportSlack(): { slack: NonNullable<typeof slack>; channelId: string } {
if (!slack || !s.slack) throw new Error("не настроен slack (botToken, accountingChannelId)");
return { slack, channelId: s.slack.reportChannelId ?? s.slack.accountingChannelId };
}
let mcpInstructions: string | undefined;
try {
mcpInstructions = instructionsFromFile(readFileSync(`${process.env.KHB_REPO_ROOT ?? process.cwd()}/docs/proposed/modules/quickbooks_bookkeeper/p-mcp-instructions.md`, "utf8"));
} catch (e) {
log.warn({ err: String(e) }, "p-mcp-instructions.md недоступен, используются встроенные инструкции MCP");
}
const app = buildApi({
pool,
settings: s,
mcpInstructions,
jobs: {
"invoices-mail": async () => {
if (!auth || !drive || !s.google) throw new Error("не настроены google (ключ сервисного аккаунта, rootFolderId)");
const mail = new GmailClient({
auth,
user: s.google.gmailUser,
query: s.google.gmailQuery,
includeSpam: s.google.gmailIncludeSpam,
processedIds: async (ids) => {
const { rows } = await pool.query("select message_id from acc_mail_processed where message_id = any($1) and result <> 'error'", [ids]);
return new Set(rows.map((r) => r.message_id as string));
},
});
return runInvoiceIngest({ pool, mail, drive, claude, now: () => new Date(), log });
},
finalize: () => runFinalize({
pool,
delaySeconds: s.finalizeDelaySeconds,
noReceiptLimitUsd: s.receipts.noReceiptLimitUsd,
notify,
notifyPerson: slack ? async (slackUserId, text) => void (await slack.postMessage(slackUserId, text)) : undefined,
}),
categorize: async () =>
runCategorization({
pool,
claude,
realmId: await realmId(),
log,
approvalThresholdUsd: s.approvalThresholdUsd,
fraud: s.fraud,
loadPrompt: makePromptLoader({
docId: s.prompt.driveDocId,
fallbackFile: s.prompt.fallbackFile,
rootDir: process.env.KHB_REPO_ROOT ?? process.cwd(),
exportDocText: drive ? (id) => drive.exportDocText(id) : undefined,
log: (msg, extra) => log.warn(extra ?? {}, msg),
}),
}),
"fraud-flags": async () => {
const realm = await realmId();
const flags = await runFraudFlags(pool, { settings: s.fraud, realmId: realm });
// роль подтверждающего повторяется для задач, у которых она не проставилась при записи категоризации (идемпотентно)
const roles = await reapplyCategorizationRoles(pool, { threshold: s.approvalThresholdUsd, realmId: realm });
return { ...flags, roles };
},
"invoice-check": () => runInvoiceCheck({ pool }),
"invoice-paid": async () => runInvoicePaid({ pool, realmId: await realmId() }),
"invoice-reconcile": async () => runInvoiceReconcile({ pool, realmId: await realmId() }),
certificates: () =>
runCertificates({
pool,
log,
// реальной отправки в JobTread пока нет (data_collector только читает): письмо готовится, Юля отправляет вручную
messenger: manualMessenger,
autoSend: s.stage2.certificateAutoSend,
loadTemplate: s.stage2.certificateTemplateDocId && drive ? () => drive.exportDocText(s.stage2.certificateTemplateDocId!) : undefined,
}),
"reconcile-monthly": async () => {
if (!drive) throw new Error("не настроены google (ключ сервисного аккаунта, rootFolderId)");
return runMonthlyReconcile({
pool,
log,
...reportSlack(),
realmId,
toleranceDays: s.stage2.statementDateToleranceDays,
reader: makeClaudeStatementReader({ claude }),
source: {
list: async () => (await drive.listPdfFiles([s.stage2.statementsFolder])).map((f) => ({ id: f.id, name: f.name, getBytes: () => drive.download(f.id) })),
},
});
},
"history-weekly": () => runHistoryWeekly({ pool, ...reportSlack() }),
"fraud-weekly": () => runFraudWeekly({ pool, ...reportSlack() }),
summary: async () => {
if (!slack || !s.slack) throw new Error("не настроен slack (botToken, accountingChannelId)");
const options = { nonWorkdays: await nonWorkdays(), mathesarUrl: s.mathesarUrl, bankFeedUrl: s.receipts.qboBankingUrl };
const text = await postDailySummary({ pool, slack, channelId: s.slack.accountingChannelId, tz: "Asia/Nicosia", options });
const cfo = await postCfoSummary({ pool, slack, tz: "Asia/Nicosia", options });
if (!cfo.sent) log.warn({ reason: cfo.reason }, "сводка Анастасии не отправлена");
return { sent: true, length: text.length, cfo };
},
"receipts-slack": async () => {
if (!slack || !drive) throw new Error("не настроены slack (botToken) и google (ключ сервисного аккаунта, rootFolderId)");
return runReceiptsSlack({
pool, slack, drive, claude, now: () => new Date(), log,
options: { lookbackHours: s.receipts.lookbackHours, senderPersonIds: s.receipts.senderPersonIds },
});
},
"receipt-search": async () => {
if (!slack) throw new Error("не настроен slack (botToken, accountingChannelId)");
const r = s.receipts;
return runReceiptSearch({
pool, slack, now: () => new Date(), log, nonWorkdays,
options: { tz: r.tz, graceWorkdays: r.graceWorkdays, escalationWorkdays: r.escalationWorkdays, subscriptionVendors: r.subscriptionVendors, qboBankingUrl: r.qboBankingUrl },
});
},
"receipt-weekly-report": async () => {
if (!slack || !s.slack) throw new Error("не настроен slack (botToken, accountingChannelId)");
return runReceiptWeeklyReport({ pool, slack, now: () => new Date(), fallbackChannelId: s.slack.accountingChannelId });
},
},
});
await app.listen({ host: s.http.host, port: s.http.port });
log.info({ port: s.http.port }, "accounting_automation запущен");
process.on("SIGTERM", () => void app.close());