158 lines
9.8 KiB
TypeScript
158 lines
9.8 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import Fastify, { type FastifyInstance } from "fastify";
|
|
import type { Pool } from "khb_common";
|
|
import { registerAgentRoutes } from "./agents-api.js";
|
|
import { usageSummary, type UsageLog } from "./usage.js";
|
|
import type { PrepJob, PrepResult } from "./jobs.js";
|
|
import { checkMailAuth } from "./mail/auth.js";
|
|
import { checkAccAuth, forwardAcc } from "./acc/proxy.js";
|
|
import { checkChargebackAuth, forwardChargeback, type ChargebackConfig } from "./chargeback/proxy.js";
|
|
import { resolveForManager, sendForManager, type MailDeps } from "./mail/service.js";
|
|
|
|
export interface ChatApi {
|
|
/** Имитация входящего сообщения менеджера (без Slack): текст и локальные файлы; publish - слать ли ответ в Slack. */
|
|
simulate(opts: { managerId?: string; text: string; files?: string[]; publish?: boolean; summary?: boolean; summaryChannel?: string; summaryTs?: string }): Promise<unknown>;
|
|
/** Системное событие ассистента (напоминания 12:00/13:00/16:00 и т.п.) всем менеджерам режима. */
|
|
event(kind: string): Promise<unknown>;
|
|
/** Разовое поручение агенту менеджера от ИТ/владельца (например, применить подтверждённые изменения); ответ уходит в чат менеджера, если publish. */
|
|
apply(opts: { managerId: string; text: string; publish?: boolean }): Promise<unknown>;
|
|
}
|
|
|
|
export interface PrepApiDeps {
|
|
pool: Pool;
|
|
token: string;
|
|
run(job: PrepJob, opts: { projectId?: string; dryRun?: boolean }): Promise<PrepResult>;
|
|
chat?: ChatApi;
|
|
usageLog?: UsageLog;
|
|
/** Письма подрядчикам (команда khb-mail): токен менеджера, не общий токен сервиса. */
|
|
mail?: { deps: MailDeps; secret: string };
|
|
/** chargeback к контракту (команда khb-chargeback): токен менеджера, вызов уходит в accounting_automation. */
|
|
chargeback?: ChargebackConfig;
|
|
}
|
|
|
|
interface RunState {
|
|
id: string;
|
|
job: PrepJob;
|
|
status: "running" | "ok" | "skipped" | "error";
|
|
startedAt: string;
|
|
finishedAt?: string;
|
|
result?: PrepResult;
|
|
error?: string;
|
|
}
|
|
|
|
export function buildApi(deps: PrepApiDeps): FastifyInstance {
|
|
const app = Fastify();
|
|
const runs = new Map<string, RunState>(); // состояние последних запусков в памяти; постоянный след - ap_*, sched_run
|
|
app.addHook("onRequest", async (req, reply) => {
|
|
if (req.url === "/healthz") return;
|
|
if (req.url.startsWith("/mail/")) {
|
|
if (!deps.mail || !checkMailAuth(deps.mail.secret, String(req.headers["x-khb-caller"] ?? ""), req.headers.authorization)) return reply.code(401).send({ error: "unauthorized" });
|
|
return;
|
|
}
|
|
if (req.url.startsWith("/acc/")) {
|
|
if (!deps.chargeback || !checkAccAuth(deps.chargeback.secret, String(req.headers["x-khb-caller"] ?? ""), req.headers.authorization)) return reply.code(401).send({ error: "unauthorized" });
|
|
return;
|
|
}
|
|
if (req.url.startsWith("/chargeback/")) {
|
|
if (!deps.chargeback || !checkChargebackAuth(deps.chargeback.secret, String(req.headers["x-khb-caller"] ?? ""), req.headers.authorization)) return reply.code(401).send({ error: "unauthorized" });
|
|
return;
|
|
}
|
|
if (req.headers.authorization !== `Bearer ${deps.token}`) return reply.code(401).send({ error: "unauthorized" });
|
|
});
|
|
|
|
registerAgentRoutes(app, deps.pool);
|
|
|
|
if (deps.mail) {
|
|
const mail = deps.mail.deps;
|
|
const caller = (req: { headers: Record<string, unknown> }) => String(req.headers["x-khb-caller"]);
|
|
app.post<{ Body: { project?: string; vendor?: string; work?: string } }>("/mail/resolve", async (req) =>
|
|
resolveForManager(mail, { managerId: caller(req), project: req.body?.project, vendor: req.body?.vendor, work: req.body?.work }));
|
|
app.post<{ Body: { project?: string; vendor?: string; work?: string; date?: string; note?: string; channel?: string } }>("/mail/send", async (req) =>
|
|
sendForManager(mail, { managerId: caller(req), project: req.body?.project, vendor: req.body?.vendor, work: req.body?.work, date: String(req.body?.date ?? ""), note: req.body?.note, channel: req.body?.channel }));
|
|
}
|
|
|
|
if (deps.chargeback) {
|
|
const cb = deps.chargeback;
|
|
app.post<{ Params: { action: string }; Body: Record<string, unknown> }>("/chargeback/:action", async (req, reply) => {
|
|
const body = req.body && typeof req.body === "object" && !Array.isArray(req.body) ? req.body : {};
|
|
const r = await forwardChargeback(cb, req.params.action, String(req.headers["x-khb-caller"]), body);
|
|
return reply.code(r.status).send(r.body);
|
|
});
|
|
}
|
|
|
|
if (deps.chargeback) {
|
|
const cb = deps.chargeback;
|
|
// ассистент бухгалтерии (команда khb-acc): токен собеседника; суммы и очередь - только ролям cfo и accountant
|
|
app.post<{ Params: { action: string }; Body: Record<string, unknown> }>("/acc/:action", async (req, reply) => {
|
|
const caller = String(req.headers["x-khb-caller"]);
|
|
const body = req.body && typeof req.body === "object" && !Array.isArray(req.body) ? req.body : {};
|
|
const row = (await deps.pool.query("select role_code from person where id = $1 and is_active", [caller])).rows[0] as { role_code: string | null } | undefined;
|
|
const r = await forwardAcc(cb, req.params.action, caller, row?.role_code === "cfo" || row?.role_code === "accountant", body);
|
|
return reply.code(r.status).send(r.body);
|
|
});
|
|
}
|
|
|
|
app.get("/healthz", async () => {
|
|
let db = false;
|
|
try {
|
|
await deps.pool.query("select 1");
|
|
db = true;
|
|
} catch {
|
|
/* db=false */
|
|
}
|
|
return { ok: db, db, time: new Date().toISOString() };
|
|
});
|
|
|
|
app.post<{ Body: { job: PrepJob; projectId?: string; dryRun?: boolean } }>("/runs", async (req, reply) => {
|
|
const { job, projectId, dryRun } = req.body ?? ({} as never);
|
|
if (job !== "collect_morning" && job !== "recheck_noon") return reply.code(400).send({ error: "job должен быть collect_morning или recheck_noon" });
|
|
const st: RunState = { id: randomUUID(), job, status: "running", startedAt: new Date().toISOString() };
|
|
runs.set(st.id, st);
|
|
if (runs.size > 50) runs.delete(runs.keys().next().value as string);
|
|
deps.run(job, { projectId, dryRun }).then(
|
|
(r) => Object.assign(st, { status: r.status, result: r, finishedAt: new Date().toISOString() }),
|
|
(e) => Object.assign(st, { status: "error", error: e instanceof Error ? e.message : String(e), finishedAt: new Date().toISOString() }),
|
|
);
|
|
return reply.code(202).send({ runId: st.id, status: "running" });
|
|
});
|
|
|
|
// шаг 4: асинхронные запуски (агент работает минуты), состояние по id
|
|
const chatRuns = new Map<string, { status: "running" | "ok" | "error"; result?: unknown; error?: string }>();
|
|
const startChat = (fn: () => Promise<unknown>) => {
|
|
const id = randomUUID();
|
|
const st: { status: "running" | "ok" | "error"; result?: unknown; error?: string } = { status: "running" };
|
|
chatRuns.set(id, st);
|
|
if (chatRuns.size > 50) chatRuns.delete(chatRuns.keys().next().value as string);
|
|
fn().then(
|
|
(r) => Object.assign(st, { status: "ok", result: r }),
|
|
(e) => Object.assign(st, { status: "error", error: e instanceof Error ? e.message : String(e) }),
|
|
);
|
|
return id;
|
|
};
|
|
app.post<{ Body: { managerId?: string; text?: string; files?: string[]; publish?: boolean; summary?: boolean; summaryChannel?: string; summaryTs?: string } }>("/chat/simulate", async (req, reply) => {
|
|
if (!deps.chat) return reply.code(501).send({ error: "chat не настроен" });
|
|
const b = req.body ?? {};
|
|
if (!b.text) return reply.code(400).send({ error: "нужен text" });
|
|
return reply.code(202).send({ chatRunId: startChat(() => deps.chat!.simulate({ managerId: b.managerId, text: b.text!, files: b.files, publish: b.publish, summary: b.summary, summaryChannel: b.summaryChannel, summaryTs: b.summaryTs })) });
|
|
});
|
|
app.post<{ Body: { kind?: string } }>("/chat/event", async (req, reply) => {
|
|
if (!deps.chat) return reply.code(501).send({ error: "chat не настроен" });
|
|
const kind = req.body?.kind;
|
|
if (!kind) return reply.code(400).send({ error: "нужен kind" });
|
|
return reply.code(202).send({ chatRunId: startChat(() => deps.chat!.event(kind)) });
|
|
});
|
|
app.post<{ Body: { managerId?: string; text?: string; publish?: boolean } }>("/chat/apply", async (req, reply) => {
|
|
if (!deps.chat) return reply.code(501).send({ error: "chat не настроен" });
|
|
const b = req.body ?? {};
|
|
if (!b.managerId || !b.text) return reply.code(400).send({ error: "нужны managerId и text" });
|
|
return reply.code(202).send({ chatRunId: startChat(() => deps.chat!.apply({ managerId: b.managerId!, text: b.text!, publish: b.publish })) });
|
|
});
|
|
app.get<{ Params: { id: string } }>("/chat/runs/:id", async (req, reply) => chatRuns.get(req.params.id) ?? reply.code(404).send({ error: "not found" }));
|
|
app.get("/agent/runs", async () => (await deps.pool.query("select id, manager_person_id, step, attempt, resumed, status, started_at, duration_ms, error, changes from agent_run order by started_at desc limit 20")).rows);
|
|
/** Токены агентов: сводка за N часов (по умолчанию 24) по операциям и менеджерам + лимиты из globals. Денег здесь нет намеренно. */
|
|
app.get<{ Querystring: { hours?: string } }>("/agent/usage", async (req) => usageSummary(deps.pool, Number(req.query.hours) || 24, deps.usageLog));
|
|
|
|
app.get<{ Params: { id: string } }>("/runs/:id", async (req, reply) => runs.get(req.params.id) ?? reply.code(404).send({ error: "not found" }));
|
|
return app;
|
|
}
|