accounting_automation: этап 1 бухгалтерской автоматизации (инвойсы из почты, категоризация, ручной разбор, MCP), интервальные задания scheduler, миграции 033/034/038
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
83
packages/accounting_automation/src/http-api.ts
Normal file
83
packages/accounting_automation/src/http-api.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import Fastify, { type FastifyInstance } from "fastify";
|
||||
import type { Pool } from "khb_common";
|
||||
import { registerMcp } from "./mcp.js";
|
||||
import type { AccountingSettings } from "./settings.js";
|
||||
|
||||
/** Задания, которые вызывает scheduler (POST /jobs/<имя>); каждое возвращает произвольный JSON-итог. */
|
||||
export interface JobHandlers {
|
||||
"invoices-mail": () => Promise<unknown>;
|
||||
finalize: () => Promise<unknown>;
|
||||
categorize: () => Promise<unknown>;
|
||||
summary: () => Promise<unknown>;
|
||||
}
|
||||
export const JOB_NAMES = ["invoices-mail", "finalize", "categorize", "summary"] as const;
|
||||
|
||||
export interface ApiDeps {
|
||||
pool: Pool;
|
||||
settings: Pick<AccountingSettings, "http" | "reviewers" | "mcp">;
|
||||
jobs: JobHandlers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Служебные ручки закрыты токеном сервиса (`accounting_automation.http.token`); /healthz открыт.
|
||||
* /mcp - отдельная аутентификация (токены сотрудников и Keycloak), наружу публикуется через nginx только он.
|
||||
*/
|
||||
export function buildApi(deps: ApiDeps): FastifyInstance {
|
||||
const app = Fastify();
|
||||
const running = new Set<string>();
|
||||
|
||||
app.addHook("onRequest", async (req, reply) => {
|
||||
const path = req.url.split("?")[0]!;
|
||||
if (path === "/healthz" || path === "/mcp" || path.startsWith("/.well-known/")) return;
|
||||
if (req.headers.authorization !== `Bearer ${deps.settings.http.token}`) return reply.code(401).send({ error: "unauthorized" });
|
||||
});
|
||||
|
||||
app.get("/healthz", async () => ({ ok: true, time: new Date().toISOString() }));
|
||||
|
||||
/**
|
||||
* Запуск задания. По умолчанию - в фоне: 202 сразу (scheduler ждёт ответ не дольше 30 с, а агенты работают минутами),
|
||||
* итог пишется в журнал сервиса. `?wait=true` - дождаться итога: 200 - выполнено, 502 - ошибка.
|
||||
* 409 - это же задание уже идёт, 404 - нет такого задания.
|
||||
*/
|
||||
app.post<{ Params: { name: string }; Querystring: { wait?: string } }>("/jobs/:name", async (req, reply) => {
|
||||
const name = req.params.name as keyof JobHandlers;
|
||||
const handler = Object.prototype.hasOwnProperty.call(deps.jobs, name) ? deps.jobs[name] : undefined;
|
||||
if (!handler) return reply.code(404).send({ error: "unknown_job" });
|
||||
if (running.has(name)) return reply.code(409).send({ error: "already_running" });
|
||||
running.add(name);
|
||||
const exec = async (): Promise<unknown> => {
|
||||
try {
|
||||
const result = await handler();
|
||||
req.log.info({ job: name, result }, "задание выполнено");
|
||||
return result;
|
||||
} finally {
|
||||
running.delete(name);
|
||||
}
|
||||
};
|
||||
if (req.query.wait === "true") {
|
||||
try {
|
||||
return { job: name, result: await exec() };
|
||||
} catch (e) {
|
||||
req.log.error({ err: String(e), job: name }, "задание упало");
|
||||
return reply.code(502).send({ error: "job_failed", message: e instanceof Error ? e.message : String(e) });
|
||||
}
|
||||
}
|
||||
void exec().catch((e) => req.log.error({ err: String(e), job: name }, "задание упало"));
|
||||
return reply.code(202).send({ job: name, started: true });
|
||||
});
|
||||
|
||||
// --- MCP для Claude сотрудников (Streamable HTTP, без сессий)
|
||||
if (deps.settings.mcp.enabled) {
|
||||
const base = deps.settings.mcp.publicUrl?.replace(/\/$/, "");
|
||||
app.get("/.well-known/oauth-protected-resource", async (_req, reply) => {
|
||||
if (!base) return reply.code(404).send({ error: "not configured" });
|
||||
return {
|
||||
resource: `${base}/mcp`,
|
||||
...(deps.settings.mcp.issuer ? { authorization_servers: [deps.settings.mcp.issuer] } : {}),
|
||||
bearer_methods_supported: ["header"],
|
||||
};
|
||||
});
|
||||
registerMcp(app, { pool: deps.pool, settings: deps.settings });
|
||||
}
|
||||
return app;
|
||||
}
|
||||
Reference in New Issue
Block a user