accounting_automation: этап 1 бухгалтерской автоматизации (инвойсы из почты, категоризация, ручной разбор, MCP), интервальные задания scheduler, миграции 033/034/038
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
87
packages/accounting_automation/src/main.ts
Normal file
87
packages/accounting_automation/src/main.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
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 { 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<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> {
|
||||
const { rows } = await pool.query("select realm_id from qbo_connection order by refreshed_at desc limit 1");
|
||||
if (!rows[0]) throw new Error("QuickBooks не подключён (нет строки в qbo_connection)");
|
||||
return rows[0].realm_id as string;
|
||||
}
|
||||
|
||||
async function nonWorkdays(): Promise<ReadonlySet<string>> {
|
||||
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));
|
||||
}
|
||||
|
||||
const app = buildApi({
|
||||
pool,
|
||||
settings: s,
|
||||
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());
|
||||
Reference in New Issue
Block a user