import { readFileSync } from "node:fs"; import { createLogger, createPool, itNotify, loadServiceSettings } from "khb_common"; import { runCategorization } from "./categorize.js"; import { makeClaudeRunner } from "./claude-runner.js"; import { DriveClient } from "./drive.js"; import { runFinalize } from "./finalize.js"; import { GmailClient } from "./gmail.js"; import { GoogleAuth } from "./google.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 { createSlackPoster } from "./slack.js"; import { postDailySummary } from "./summary.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 ? createSlackPoster({ botToken: s.slack.botToken }) : null; const notify = async (text: string): Promise => { 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 { // 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; } async function nonWorkdays(): Promise> { const { rows } = await pool.query("select to_char(day, 'YYYY-MM-DD') as d from calendar_day where not is_workday"); return new Set(rows.map((r) => r.d as string)); } 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, 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, notify }), categorize: async () => runCategorization({ pool, claude, realmId: await realmId(), log, 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), }), }), summary: async () => { if (!slack || !s.slack) throw new Error("не настроен slack (botToken, accountingChannelId)"); const text = await postDailySummary({ pool, slack, channelId: s.slack.accountingChannelId, tz: "Asia/Nicosia", options: { nonWorkdays: await nonWorkdays() } }); return { sent: true, length: text.length }; }, }, }); 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());