accounting_automation: этап 1 бухгалтерской автоматизации (инвойсы из почты, категоризация, ручной разбор, MCP), интервальные задания scheduler, миграции 033/034/038
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
93
packages/accounting_automation/src/categorize.test.ts
Normal file
93
packages/accounting_automation/src/categorize.test.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { createLogger, createTestDb, testDatabaseUrl, type TestDb } from "khb_common";
|
||||
import type { ClaudeRunner } from "./claude-runner.js";
|
||||
import { buildAgentPrompt, extractAgentJson, runCategorization } from "./categorize.js";
|
||||
|
||||
const log = createLogger("test", "silent");
|
||||
|
||||
describe("разбор ответа агента", () => {
|
||||
it("берёт последний json-блок", () => {
|
||||
const out = 'текст\n```json\n{"results":[]}\n```\nещё\n```json\n{"run_id":"r1","results":[{"feed_txn_id":"a"}]}\n```';
|
||||
expect(extractAgentJson(out)).toEqual({ run_id: "r1", results: [{ feed_txn_id: "a" }] });
|
||||
});
|
||||
it("без блока - объект из текста", () => {
|
||||
expect(extractAgentJson('итог {"results":[]}')).toEqual({ results: [] });
|
||||
});
|
||||
it("нет JSON - ошибка", () => {
|
||||
expect(() => extractAgentJson("ничего")).toThrow();
|
||||
});
|
||||
it("промпт содержит контекст и формат", () => {
|
||||
const p = buildAgentPrompt("ПРОМПТ", { realmId: "123", runStartedAt: new Date("2026-11-17T10:00:00Z") });
|
||||
expect(p).toContain("ПРОМПТ");
|
||||
expect(p).toContain(":realm_id = 123");
|
||||
expect(p).toContain("khb-sql");
|
||||
expect(p).toContain('"results"');
|
||||
});
|
||||
});
|
||||
|
||||
const url = testDatabaseUrl();
|
||||
const d = url ? describe : describe.skip;
|
||||
|
||||
d("категоризация (временная БД)", () => {
|
||||
let db: TestDb;
|
||||
const claudeOk = (json: unknown): ClaudeRunner => async () => ({ ok: true, stdout: "рассуждения\n```json\n" + JSON.stringify(json) + "\n```", stderr: "", exitCode: 0, timedOut: false });
|
||||
const mk = (claude: ClaudeRunner) => ({ pool: db.pool, claude, loadPrompt: async () => "ПРОМПТ", realmId: "9341", now: () => new Date("2026-11-17T12:00:00Z"), log });
|
||||
|
||||
beforeAll(async () => { db = await createTestDb(url!); });
|
||||
afterAll(async () => { await db?.drop(); });
|
||||
beforeEach(async () => { await db.pool.query("truncate acc_categorization_review, acc_categorization_review_original, acc_manual_review cascade"); });
|
||||
|
||||
it("записывает результаты, триггеры создают original и задачи", async () => {
|
||||
const r = await runCategorization(mk(claudeOk({
|
||||
run_id: "run-1",
|
||||
results: [
|
||||
{ feed_txn_id: "t1", suggestion: { account: "55", project_customer_id: "7", splits: [] }, confidence: 91, problem_highlight: null },
|
||||
{ feed_txn_id: "t2", suggestion: null, confidence: null, problem_highlight: "ждёт документ" },
|
||||
{ feed_txn_id: "t3", suggestion: null },
|
||||
],
|
||||
})));
|
||||
expect(r).toMatchObject({ status: "ok", runId: "run-1", parsed: 3, inserted: 3, skipped: 0 });
|
||||
const rows = (await db.pool.query("select feed_txn_id, run_id, confidence, problem_highlight, suggestion from acc_categorization_review order by 1")).rows;
|
||||
expect(rows[0]).toMatchObject({ feed_txn_id: "t1", run_id: "run-1", confidence: 91, problem_highlight: null });
|
||||
expect(rows[0].suggestion.account).toBe("55");
|
||||
expect(rows[1].problem_highlight).toBe("ждёт документ");
|
||||
expect(rows[2].problem_highlight).toContain("нужен человек");
|
||||
expect((await db.pool.query("select count(*)::int n from acc_categorization_review_original")).rows[0].n).toBe(3);
|
||||
const q = (await db.pool.query("select kind, ref_id, assignee_role, problem_highlight from acc_manual_review order by ref_id")).rows;
|
||||
expect(q).toHaveLength(3);
|
||||
expect(q[0]).toMatchObject({ kind: "categorization", ref_id: "t1", assignee_role: "accountant", problem_highlight: null });
|
||||
expect(q[1].problem_highlight).toBe("ждёт документ");
|
||||
});
|
||||
|
||||
it("повторный прогон не дублирует уже стоящие операции", async () => {
|
||||
const out = { run_id: "r", results: [{ feed_txn_id: "t1", suggestion: { account: "1" }, confidence: 50 }] };
|
||||
await runCategorization(mk(claudeOk(out)));
|
||||
const r2 = await runCategorization(mk(claudeOk(out)));
|
||||
expect(r2).toMatchObject({ status: "ok", inserted: 0, skipped: 1 });
|
||||
expect((await db.pool.query("select count(*)::int n from acc_categorization_review")).rows[0].n).toBe(1);
|
||||
});
|
||||
|
||||
it("ошибка агента и неверный вывод не пишут ничего", async () => {
|
||||
const fail: ClaudeRunner = async () => ({ ok: false, stdout: "", stderr: "boom", exitCode: 1, timedOut: false });
|
||||
expect((await runCategorization(mk(fail))).status).toBe("agent_failed");
|
||||
const timeout: ClaudeRunner = async () => ({ ok: false, stdout: "", stderr: "", exitCode: null, timedOut: true });
|
||||
expect((await runCategorization(mk(timeout))).message).toContain("таймаут");
|
||||
const junk: ClaudeRunner = async () => ({ ok: true, stdout: "не json", stderr: "", exitCode: 0, timedOut: false });
|
||||
expect((await runCategorization(mk(junk))).status).toBe("bad_output");
|
||||
const badShape = claudeOk({ results: [{ feed_txn_id: "t1", confidence: 150 }] });
|
||||
expect((await runCategorization(mk(badShape))).status).toBe("bad_output");
|
||||
expect((await db.pool.query("select count(*)::int n from acc_categorization_review")).rows[0].n).toBe(0);
|
||||
});
|
||||
|
||||
it("одновременный второй запуск получает busy", async () => {
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>((res) => (release = res));
|
||||
const slow: ClaudeRunner = async () => { await gate; return { ok: true, stdout: '```json\n{"results":[]}\n```', stderr: "", exitCode: 0, timedOut: false }; };
|
||||
const first = runCategorization(mk(slow));
|
||||
await new Promise((r) => setTimeout(r, 300));
|
||||
const second = await runCategorization(mk(claudeOk({ results: [] })));
|
||||
expect(second.status).toBe("busy");
|
||||
release();
|
||||
expect((await first).status).toBe("ok");
|
||||
});
|
||||
});
|
||||
127
packages/accounting_automation/src/categorize.ts
Normal file
127
packages/accounting_automation/src/categorize.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
import { z } from "zod";
|
||||
import type { Logger, Pool } from "khb_common";
|
||||
import type { ClaudeRunner } from "./claude-runner.js";
|
||||
|
||||
/**
|
||||
* Процесс «Категоризация банковских операций», шаги 3-5: запуск Claude-агента с промптом из Google Docs.
|
||||
* Агент читает ленту «For Review» (коннектор QuickBooks Labs, режим предложения, post не ставит), читает базу командой khb-sql
|
||||
* (только чтение) и возвращает результат JSON-блоком; в acc_categorization_review строки пишет сервис (проверка формата здесь,
|
||||
* триггеры БД создают копию _original и задачу в acc_manual_review).
|
||||
*/
|
||||
|
||||
const LOCK_KEY = 7_340_001; // pg_try_advisory_lock: два прогона одновременно не идут
|
||||
|
||||
export const resultSchema = z.object({
|
||||
feed_txn_id: z.string().min(1),
|
||||
suggestion: z.record(z.unknown()).nullable().optional(),
|
||||
confidence: z.number().int().min(0).max(100).nullable().optional(),
|
||||
problem_highlight: z.string().min(1).nullable().optional(),
|
||||
});
|
||||
export const agentOutputSchema = z.object({
|
||||
run_id: z.string().min(1).optional(),
|
||||
results: z.array(resultSchema),
|
||||
});
|
||||
export type AgentOutput = z.infer<typeof agentOutputSchema>;
|
||||
|
||||
/** Достаёт из ответа агента последний JSON-блок (```json ... ``` или последний объект с results). */
|
||||
export function extractAgentJson(stdout: string): unknown {
|
||||
const fenced = [...stdout.matchAll(/```json\s*([\s\S]*?)```/g)];
|
||||
const candidates: string[] = fenced.map((m) => m[1]!.trim());
|
||||
if (candidates.length === 0) {
|
||||
const first = stdout.indexOf("{");
|
||||
if (first >= 0) candidates.push(stdout.slice(first).trim());
|
||||
const last = stdout.lastIndexOf('{"');
|
||||
if (last >= 0) candidates.push(stdout.slice(last).trim());
|
||||
}
|
||||
for (const c of candidates.reverse()) {
|
||||
try {
|
||||
return JSON.parse(c);
|
||||
} catch {
|
||||
/* пробуем следующий */
|
||||
}
|
||||
}
|
||||
throw new Error("в ответе агента нет JSON-блока с результатом");
|
||||
}
|
||||
|
||||
export interface CategorizeDeps {
|
||||
pool: Pool;
|
||||
claude: ClaudeRunner;
|
||||
loadPrompt: () => Promise<string>;
|
||||
realmId: string;
|
||||
now?: () => Date;
|
||||
log: Logger;
|
||||
}
|
||||
export interface CategorizeResult {
|
||||
status: "ok" | "busy" | "agent_failed" | "bad_output";
|
||||
runId?: string;
|
||||
parsed: number;
|
||||
inserted: number;
|
||||
skipped: number;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export function buildAgentPrompt(prompt: string, ctx: { realmId: string; runStartedAt: Date }): string {
|
||||
return `${prompt}
|
||||
|
||||
--- Контекст запуска (добавлен сервисом accounting_automation) ---
|
||||
- :realm_id = ${ctx.realmId}
|
||||
- Время начала прогона: ${ctx.runStartedAt.toISOString()}
|
||||
- Запросы к базе выполняй командой Bash: khb-sql --json "select ..." (только чтение; список таблиц: khb-sql --tables). В базу не пиши.
|
||||
- Таблицу acc_categorization_review заполняет сервис по твоему результату. Не обрабатывай операции, которые уже есть в acc_categorization_review.
|
||||
- Режим предложения QuickBooks: post не ставь, ничего не проводи.
|
||||
|
||||
--- Формат результата ---
|
||||
В самом конце ответа выведи ровно один блок:
|
||||
\`\`\`json
|
||||
{"run_id": "<идентификатор прогона QuickBooks>", "results": [
|
||||
{"feed_txn_id": "<id операции ленты>", "suggestion": {"account": "...", "project_customer_id": "...", "splits": [], "invoice_ids": [], "receipt_id": null} или null, "confidence": 0-100 или null, "problem_highlight": "текст проблемы" или null}
|
||||
]}
|
||||
\`\`\`
|
||||
По одному элементу на каждую операцию ленты, которую ты рассмотрел. Если нечего обрабатывать - results: [].`;
|
||||
}
|
||||
|
||||
export async function runCategorization(deps: CategorizeDeps): Promise<CategorizeResult> {
|
||||
const now = deps.now ?? (() => new Date());
|
||||
const client = await deps.pool.connect();
|
||||
try {
|
||||
const lock = await client.query("select pg_try_advisory_lock($1) as ok", [LOCK_KEY]);
|
||||
if (!lock.rows[0].ok) return { status: "busy", parsed: 0, inserted: 0, skipped: 0, message: "прогон уже идёт" };
|
||||
try {
|
||||
const startedAt = now();
|
||||
const prompt = buildAgentPrompt(await deps.loadPrompt(), { realmId: deps.realmId, runStartedAt: startedAt });
|
||||
const r = await deps.claude({ prompt });
|
||||
if (!r.ok) {
|
||||
deps.log.error({ exitCode: r.exitCode, timedOut: r.timedOut, stderr: r.stderr.slice(0, 500) }, "агент категоризации завершился с ошибкой");
|
||||
return { status: "agent_failed", parsed: 0, inserted: 0, skipped: 0, message: r.timedOut ? "таймаут агента" : `код ${r.exitCode}: ${r.stderr.slice(0, 300)}` };
|
||||
}
|
||||
let out: AgentOutput;
|
||||
try {
|
||||
out = agentOutputSchema.parse(extractAgentJson(r.stdout));
|
||||
} catch (e) {
|
||||
deps.log.error({ err: String(e), stdoutTail: r.stdout.slice(-500) }, "ответ агента категоризации не разобран");
|
||||
return { status: "bad_output", parsed: 0, inserted: 0, skipped: 0, message: String(e).slice(0, 300) };
|
||||
}
|
||||
const runId = out.run_id ?? `run-${startedAt.toISOString()}`;
|
||||
let inserted = 0;
|
||||
let skipped = 0;
|
||||
for (const x of out.results) {
|
||||
const hasSuggestion = !!x.suggestion && Object.keys(x.suggestion).length > 0;
|
||||
// правило: не уверен - предложения нет, проблема описана; нет ни того ни другого - нужен человек
|
||||
const problem = x.problem_highlight ?? (hasSuggestion ? null : "нужен человек: агент не дал предложения");
|
||||
const res = await deps.pool.query(
|
||||
`insert into acc_categorization_review (feed_txn_id, run_id, run_started_at, suggestion, confidence, problem_highlight)
|
||||
values ($1, $2, $3, $4, $5, $6) on conflict (feed_txn_id) do nothing`,
|
||||
[x.feed_txn_id, runId, startedAt, hasSuggestion ? JSON.stringify(x.suggestion) : null, x.confidence ?? null, problem],
|
||||
);
|
||||
if (res.rowCount) inserted++;
|
||||
else skipped++;
|
||||
}
|
||||
deps.log.info({ runId, parsed: out.results.length, inserted, skipped }, "категоризация завершена");
|
||||
return { status: "ok", runId, parsed: out.results.length, inserted, skipped };
|
||||
} finally {
|
||||
await client.query("select pg_advisory_unlock($1)", [LOCK_KEY]);
|
||||
}
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
45
packages/accounting_automation/src/claude-runner.ts
Normal file
45
packages/accounting_automation/src/claude-runner.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
export interface ClaudeRunOptions {
|
||||
/** Промпт целиком (stdin). */
|
||||
prompt: string;
|
||||
cwd?: string;
|
||||
timeoutMs?: number;
|
||||
/** Доп. аргументы после `-p` (например, --output-format json). */
|
||||
extraArgs?: string[];
|
||||
}
|
||||
export interface ClaudeRunResult {
|
||||
ok: boolean;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
exitCode: number | null;
|
||||
timedOut: boolean;
|
||||
}
|
||||
/** Запуск Claude-агента; в тестах подменяется. */
|
||||
export type ClaudeRunner = (o: ClaudeRunOptions) => Promise<ClaudeRunResult>;
|
||||
|
||||
export function makeClaudeRunner(cfg: { bin: string; workDir: string; timeoutMs: number; extraArgs: string[]; env?: Record<string, string> }): ClaudeRunner {
|
||||
return (o) =>
|
||||
new Promise((resolve) => {
|
||||
const args = ["--print", "--dangerously-skip-permissions", ...cfg.extraArgs, ...(o.extraArgs ?? [])];
|
||||
const child = spawn(cfg.bin, args, { cwd: o.cwd ?? cfg.workDir, stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ...cfg.env }, shell: process.platform === "win32" });
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
let timedOut = false;
|
||||
const timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
child.kill("SIGKILL");
|
||||
}, o.timeoutMs ?? cfg.timeoutMs);
|
||||
child.stdout.on("data", (d) => (stdout += d));
|
||||
child.stderr.on("data", (d) => (stderr += d));
|
||||
child.on("error", (e) => {
|
||||
clearTimeout(timer);
|
||||
resolve({ ok: false, stdout, stderr: stderr + String(e), exitCode: null, timedOut });
|
||||
});
|
||||
child.on("close", (code) => {
|
||||
clearTimeout(timer);
|
||||
resolve({ ok: code === 0 && !timedOut, stdout, stderr, exitCode: code, timedOut });
|
||||
});
|
||||
child.stdin.end(o.prompt);
|
||||
});
|
||||
}
|
||||
79
packages/accounting_automation/src/drive.ts
Normal file
79
packages/accounting_automation/src/drive.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import type { FetchFn, GoogleAuth } from "./google.js";
|
||||
|
||||
export interface DriveStore {
|
||||
/** Путь папок внутри корневой папки; создаёт недостающие, возвращает id последней. */
|
||||
ensureFolder(pathParts: string[]): Promise<string>;
|
||||
upload(name: string, mime: string, bytes: Buffer, folderId: string): Promise<{ id: string }>;
|
||||
/** Текст Google-документа (export text/plain). */
|
||||
exportDocText(docId: string): Promise<string>;
|
||||
}
|
||||
|
||||
export const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
|
||||
const API = "https://www.googleapis.com/drive/v3";
|
||||
const UPLOAD = "https://www.googleapis.com/upload/drive/v3/files";
|
||||
|
||||
/** Drive REST API v3, общие диски включены (supportsAllDrives). */
|
||||
export class DriveClient implements DriveStore {
|
||||
private folderCache = new Map<string, string>();
|
||||
constructor(private o: { auth: GoogleAuth; rootFolderId: string; fetchFn?: FetchFn }) {}
|
||||
|
||||
private async call(url: string, init: RequestInit = {}): Promise<Response> {
|
||||
const token = await this.o.auth.getAccessToken([DRIVE_SCOPE]);
|
||||
const res = await (this.o.fetchFn ?? fetch)(url, { ...init, headers: { ...(init.headers ?? {}), authorization: `Bearer ${token}` } });
|
||||
if (!res.ok) throw new Error(`Drive ${res.status}: ${(await res.text()).slice(0, 300)}`);
|
||||
return res;
|
||||
}
|
||||
|
||||
async ensureFolder(pathParts: string[]): Promise<string> {
|
||||
let parent = this.o.rootFolderId;
|
||||
for (const raw of pathParts) {
|
||||
const name = raw.trim() || "_";
|
||||
const ck = `${parent}/${name}`;
|
||||
const cached = this.folderCache.get(ck);
|
||||
if (cached) {
|
||||
parent = cached;
|
||||
continue;
|
||||
}
|
||||
const esc = name.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
|
||||
const q = `name='${esc}' and mimeType='application/vnd.google-apps.folder' and '${parent}' in parents and trashed=false`;
|
||||
const params = new URLSearchParams({ q, fields: "files(id,name)", supportsAllDrives: "true", includeItemsFromAllDrives: "true", pageSize: "2" });
|
||||
const found = (await (await this.call(`${API}/files?${params}`)).json()) as { files?: { id: string }[] };
|
||||
let id = found.files?.[0]?.id;
|
||||
if (!id) {
|
||||
const created = (await (
|
||||
await this.call(`${API}/files?supportsAllDrives=true&fields=id`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ name, mimeType: "application/vnd.google-apps.folder", parents: [parent] }),
|
||||
})
|
||||
).json()) as { id: string };
|
||||
id = created.id;
|
||||
}
|
||||
this.folderCache.set(ck, id);
|
||||
parent = id;
|
||||
}
|
||||
return parent;
|
||||
}
|
||||
|
||||
async upload(name: string, mime: string, bytes: Buffer, folderId: string): Promise<{ id: string }> {
|
||||
const boundary = "khb" + Math.random().toString(36).slice(2);
|
||||
const meta = JSON.stringify({ name, parents: [folderId] });
|
||||
const body = Buffer.concat([
|
||||
Buffer.from(`--${boundary}\r\ncontent-type: application/json; charset=UTF-8\r\n\r\n${meta}\r\n--${boundary}\r\ncontent-type: ${mime}\r\n\r\n`),
|
||||
bytes,
|
||||
Buffer.from(`\r\n--${boundary}--`),
|
||||
]);
|
||||
const res = await this.call(`${UPLOAD}?uploadType=multipart&supportsAllDrives=true&fields=id`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": `multipart/related; boundary=${boundary}` },
|
||||
body,
|
||||
});
|
||||
const j = (await res.json()) as { id: string };
|
||||
return { id: j.id };
|
||||
}
|
||||
|
||||
async exportDocText(docId: string): Promise<string> {
|
||||
const res = await this.call(`${API}/files/${encodeURIComponent(docId)}/export?mimeType=${encodeURIComponent("text/plain")}`);
|
||||
return await res.text();
|
||||
}
|
||||
}
|
||||
77
packages/accounting_automation/src/e2e.int.test.ts
Normal file
77
packages/accounting_automation/src/e2e.int.test.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { createLogger, createTestDb, testDatabaseUrl, type TestDb } from "khb_common";
|
||||
import type { ClaudeRunner } from "./claude-runner.js";
|
||||
import { runCategorization } from "./categorize.js";
|
||||
import { runFinalize } from "./finalize.js";
|
||||
import { ReviewTools } from "./mcp.js";
|
||||
import { buildDailySummary } from "./summary.js";
|
||||
|
||||
const log = createLogger("test", "silent");
|
||||
const url = testDatabaseUrl();
|
||||
const d = url ? describe : describe.skip;
|
||||
|
||||
/** Сквозной путь этапа 1: агент предлагает категории -> очередь -> сотрудник в Claude разбирает через MCP -> завершение -> история. */
|
||||
d("сквозной сценарий категоризации и разбора (временная БД)", () => {
|
||||
let db: TestDb;
|
||||
let tools: ReviewTools;
|
||||
let nastia: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
db = await createTestDb(url!);
|
||||
nastia = (await db.pool.query("insert into person (display_name, email, role_code) values ('Анастасия', 'nastia@khbuild.pro', 'cfo') returning id")).rows[0].id;
|
||||
tools = new ReviewTools({
|
||||
pool: db.pool,
|
||||
settings: { reviewers: [{ personId: nastia, roles: ["accountant", "cfo"] }], mcp: { enabled: true, staticTokens: [] } },
|
||||
});
|
||||
});
|
||||
afterAll(async () => { await db?.drop(); });
|
||||
|
||||
it("от ответа агента до истории правок", async () => {
|
||||
const claude: ClaudeRunner = async () => ({
|
||||
ok: true, exitCode: 0, timedOut: false, stderr: "",
|
||||
stdout: "```json\n" + JSON.stringify({
|
||||
run_id: "run-e2e",
|
||||
results: [
|
||||
{ feed_txn_id: "ok-1", suggestion: { account: "55", project_customer_id: "7", splits: [] }, confidence: 95 },
|
||||
{ feed_txn_id: "doc-1", suggestion: null, problem_highlight: "ждёт документ" },
|
||||
],
|
||||
}) + "\n```",
|
||||
});
|
||||
const run = await runCategorization({ pool: db.pool, claude, loadPrompt: async () => "П", realmId: "9341", log });
|
||||
expect(run).toMatchObject({ status: "ok", inserted: 2 });
|
||||
|
||||
// Claude сотрудника: список задач, сначала с проблемой
|
||||
const list = (await tools.call(nastia, "acc_review_list", {})) as { tasks?: Array<Record<string, unknown>> } & Record<string, unknown>;
|
||||
const text = JSON.stringify(list);
|
||||
expect(text).toContain("ok-1");
|
||||
expect(text).toContain("ждёт документ");
|
||||
const tasks = (list.tasks ?? (list as unknown as { items: Array<Record<string, unknown>> }).items) as Array<Record<string, unknown>>;
|
||||
expect(tasks[0]!.problem_highlight).toBe("ждёт документ");
|
||||
const okTask = tasks.find((t) => JSON.stringify(t).includes("ok-1"))!;
|
||||
|
||||
// сотрудник меняет проект и подтверждает
|
||||
await tools.call(nastia, "acc_review_update", { id: okTask.id, fields: { suggestion: { account: "55", project_customer_id: "8", splits: [] } } });
|
||||
await tools.call(nastia, "acc_review_done", { id: okTask.id });
|
||||
|
||||
// сразу после отметки запись моложе задержки: завершение её не трогает
|
||||
const notes: string[] = [];
|
||||
const early = await runFinalize({ pool: db.pool, delaySeconds: 3600, notify: (t) => void notes.push(t) });
|
||||
expect(early.finalized.categorization).toBe(0);
|
||||
|
||||
// после задержки - в историю с различиями, из очереди и review пропадает
|
||||
const fin = await runFinalize({ pool: db.pool, delaySeconds: 0, notify: (t) => void notes.push(t) });
|
||||
expect(fin.finalized.categorization).toBe(1);
|
||||
const hist = (await db.pool.query("select feed_txn_id, closed_by, changed_fields from acc_categorization_review_history")).rows;
|
||||
expect(hist).toHaveLength(1);
|
||||
expect(hist[0]).toMatchObject({ feed_txn_id: "ok-1", closed_by: nastia });
|
||||
expect(JSON.stringify(hist[0].changed_fields)).toContain("suggestion");
|
||||
expect((await db.pool.query("select feed_txn_id from acc_categorization_review order by 1")).rows.map((r) => r.feed_txn_id)).toEqual(["doc-1"]);
|
||||
expect((await db.pool.query("select ref_id from acc_manual_review")).rows.map((r) => r.ref_id)).toEqual(["doc-1"]);
|
||||
// оригинал остаётся как записал автомат
|
||||
expect((await db.pool.query("select suggestion from acc_categorization_review_original where feed_txn_id = 'ok-1'")).rows[0].suggestion.project_customer_id).toBe("7");
|
||||
|
||||
// сводка видит остаток и закрытое
|
||||
const summary = await buildDailySummary(db.pool, new Date(), "Asia/Nicosia");
|
||||
expect(summary).toContain("ждёт документ");
|
||||
});
|
||||
});
|
||||
305
packages/accounting_automation/src/finalize-summary.int.test.ts
Normal file
305
packages/accounting_automation/src/finalize-summary.int.test.ts
Normal file
@@ -0,0 +1,305 @@
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { createTestDb, testDatabaseUrl, type TestDb } from "khb_common";
|
||||
import { diffWithOriginal, runFinalize } from "./finalize.js";
|
||||
import { buildDailySummary, postDailySummary, twoWorkdaysAgo } from "./summary.js";
|
||||
import { createSlackPoster } from "./slack.js";
|
||||
|
||||
const url = testDatabaseUrl();
|
||||
const d = url ? describe : describe.skip;
|
||||
|
||||
const TABLES = [
|
||||
"acc_manual_review", "acc_invoices_review", "acc_categorization_review", "acc_certificates_review",
|
||||
"acc_invoices_review_original", "acc_categorization_review_original", "acc_certificates_review_original",
|
||||
"acc_invoices_review_history", "acc_categorization_review_history", "acc_certificates_review_history",
|
||||
"acc_invoices", "acc_insurance_certificates", "acc_receipt_search",
|
||||
];
|
||||
|
||||
d("завершение ручного разбора и сводка (временная БД)", () => {
|
||||
let db: TestDb;
|
||||
let notes: string[];
|
||||
const later = (sec = 7200) => () => new Date(Date.now() + sec * 1000);
|
||||
const fin = (over: Partial<Parameters<typeof runFinalize>[0]> = {}) =>
|
||||
runFinalize({ pool: db.pool, now: later(), notify: (t) => { notes.push(t); }, ...over });
|
||||
const q = async (sql: string, p: unknown[] = []) => (await db.pool.query(sql, p)).rows;
|
||||
|
||||
async function newInvoice(over: Record<string, unknown> = {}): Promise<string> {
|
||||
const r = { vendor_name: "ACME Plumbing", invoice_date: "2026-11-01", amount: 1000, project_customer_id: "proj-1", ...over };
|
||||
const rows = await q(
|
||||
`insert into acc_invoices_review (source_message_id, drive_file_id, vendor_name, invoice_date, amount, project_customer_id, lines)
|
||||
values ('msg-1', 'file-1', $1, $2, $3, $4, '[{"d":"работа"}]') returning id`,
|
||||
[r.vendor_name, r.invoice_date, r.amount, r.project_customer_id],
|
||||
);
|
||||
return rows[0].id;
|
||||
}
|
||||
|
||||
beforeAll(async () => { db = await createTestDb(url!); });
|
||||
afterAll(async () => { await db?.drop(); });
|
||||
beforeEach(async () => { notes = []; await q(`truncate ${TABLES.join(", ")} cascade`); });
|
||||
|
||||
it("полный путь инвойса: review -> done -> acc_invoices, history с changed_fields, очередь пуста", async () => {
|
||||
const id = await newInvoice();
|
||||
expect(await q("select kind from acc_manual_review")).toEqual([{ kind: "invoice" }]);
|
||||
await q("update acc_invoices_review set amount = 1200, vendor_name = 'ACME Plumbing LLC', done = true, done_by = 'Anastasia' where id = $1", [id]);
|
||||
|
||||
const res = await fin();
|
||||
expect(res.finalized).toEqual({ invoices: 1, categorization: 0, certificates: 0 });
|
||||
expect(res.rejected).toEqual([]);
|
||||
expect(res.errors).toEqual([]);
|
||||
|
||||
const inv = await q("select * from acc_invoices where id = $1", [id]);
|
||||
expect(inv).toHaveLength(1);
|
||||
expect(inv[0]).toMatchObject({ stage: "checking", vendor_name: "ACME Plumbing LLC", source_message_id: "msg-1", drive_file_id: "file-1", project_customer_id: "proj-1" });
|
||||
expect(Number(inv[0].amount)).toBe(1200);
|
||||
|
||||
const h = await q("select * from acc_invoices_review_history where id = $1", [id]);
|
||||
expect(h).toHaveLength(1);
|
||||
expect(h[0].closed_by).toBe("Anastasia");
|
||||
expect(h[0].closed_at).toBeInstanceOf(Date);
|
||||
expect(Number(h[0].amount)).toBe(1200);
|
||||
expect(h[0].changed_fields).toEqual({
|
||||
amount: { old: 1000, new: 1200 },
|
||||
vendor_name: { old: "ACME Plumbing", new: "ACME Plumbing LLC" },
|
||||
});
|
||||
// оригинал остался как записал автомат
|
||||
expect(Number((await q("select amount from acc_invoices_review_original where id = $1", [id]))[0].amount)).toBe(1000);
|
||||
expect(await q("select 1 from acc_invoices_review where id = $1", [id])).toHaveLength(0);
|
||||
expect(await q("select 1 from acc_manual_review")).toHaveLength(0);
|
||||
expect(notes).toEqual([]);
|
||||
});
|
||||
|
||||
it("отказ валидации: снимает done, пишет причину, уведомляет, запись остаётся в очереди", async () => {
|
||||
const id = await newInvoice({ vendor_name: "tbd", project_customer_id: null });
|
||||
await q("update acc_invoices_review set done = true, done_by = 'Yulia' where id = $1", [id]);
|
||||
const res = await fin();
|
||||
expect(res.finalized.invoices).toBe(0);
|
||||
expect(res.rejected).toHaveLength(1);
|
||||
expect(res.rejected[0]).toMatchObject({ kind: "invoices", id });
|
||||
expect(res.rejected[0].reason).toContain("vendor_name");
|
||||
expect(res.rejected[0].reason).toContain("project_customer_id");
|
||||
|
||||
const r = (await q("select done, problem_highlight from acc_invoices_review where id = $1", [id]))[0];
|
||||
expect(r.done).toBe(false);
|
||||
expect(r.problem_highlight).toContain("vendor_name");
|
||||
expect(notes).toHaveLength(1);
|
||||
expect(notes[0]).toContain("Yulia");
|
||||
expect(notes[0]).toContain("vendor_name");
|
||||
expect(await q("select 1 from acc_invoices_review_history")).toHaveLength(0);
|
||||
expect(await q("select 1 from acc_invoices")).toHaveLength(0);
|
||||
// триггер синхронизировал проблему в очереди
|
||||
expect((await q("select problem_highlight from acc_manual_review"))[0].problem_highlight).toContain("vendor_name");
|
||||
|
||||
// done снят: повторный запуск ничего не делает и не шлёт новых уведомлений
|
||||
const again = await fin();
|
||||
expect(again.rejected).toEqual([]);
|
||||
expect(notes).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("сумма не больше нуля отклоняется", async () => {
|
||||
const id = await newInvoice({ amount: 0 });
|
||||
await q("update acc_invoices_review set done = true where id = $1", [id]);
|
||||
const res = await fin();
|
||||
expect(res.rejected[0]?.reason).toContain("сумма");
|
||||
});
|
||||
|
||||
it("запись моложе задержки не трогается", async () => {
|
||||
const id = await newInvoice();
|
||||
await q("update acc_invoices_review set done = true where id = $1", [id]);
|
||||
const young = await fin({ delaySeconds: 3600, now: () => new Date() });
|
||||
expect(young.finalized.invoices).toBe(0);
|
||||
expect(young.rejected).toEqual([]);
|
||||
expect(await q("select 1 from acc_invoices_review where id = $1 and done", [id])).toHaveLength(1);
|
||||
// по умолчанию задержка 30 секунд: через минуту запись обрабатывается
|
||||
const old = await fin({ now: later(60) });
|
||||
expect(old.finalized.invoices).toBe(1);
|
||||
});
|
||||
|
||||
it("запись без done не обрабатывается", async () => {
|
||||
await newInvoice();
|
||||
const res = await fin();
|
||||
expect(res.finalized).toEqual({ invoices: 0, categorization: 0, certificates: 0 });
|
||||
expect(await q("select 1 from acc_manual_review")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("категоризация: только фиксируется результат, очередь очищается", async () => {
|
||||
await q(
|
||||
`insert into acc_categorization_review (feed_txn_id, run_id, run_started_at, suggestion, confidence, problem_highlight)
|
||||
values ('tx-1', 'run-1', now(), '{"account":"Materials"}', 80, 'ждёт документ')`,
|
||||
);
|
||||
expect(await q("select kind from acc_manual_review")).toEqual([{ kind: "categorization" }]);
|
||||
await q("update acc_categorization_review set done = true, done_by = 'Anastasia' where feed_txn_id = 'tx-1'");
|
||||
const res = await fin();
|
||||
expect(res.finalized).toEqual({ invoices: 0, categorization: 1, certificates: 0 });
|
||||
const h = await q("select closed_by, changed_fields, suggestion from acc_categorization_review_history where feed_txn_id = 'tx-1'");
|
||||
expect(h).toHaveLength(1);
|
||||
expect(h[0].closed_by).toBe("Anastasia");
|
||||
expect(h[0].changed_fields).toEqual({}); // problem_highlight и done - служебные, правкой не считаются
|
||||
expect(h[0].suggestion).toEqual({ account: "Materials" });
|
||||
expect(await q("select 1 from acc_categorization_review")).toHaveLength(0);
|
||||
expect(await q("select 1 from acc_manual_review")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("сертификат: обновляет существующий, создаёт новый, отклоняет пустой", async () => {
|
||||
const [{ id: certId }] = await q(
|
||||
"insert into acc_insurance_certificates (vendor_name, valid_until, drive_file_id) values ('Roofers Inc', '2026-11-20', 'f-1') returning id",
|
||||
);
|
||||
// 1) указан certificate_id
|
||||
await q("insert into acc_certificates_review (vendor_name, certificate_id, expires_on, problem_highlight) values ('Roofers Inc', $1, '2026-11-20', 'истекает через 5 дней')", [certId]);
|
||||
// 2) без certificate_id, но у вендора сертификат есть (ищется по имени)
|
||||
// 3) вендора нет вовсе: создаётся запись
|
||||
await q("insert into acc_certificates_review (vendor_name, expires_on) values ('New Vendor', '2027-01-31')");
|
||||
// 4) ни срока, ни сертификата
|
||||
await q("insert into acc_certificates_review (vendor_name) values ('Empty Vendor')");
|
||||
await q("update acc_certificates_review set expires_on = '2027-06-30', done = true, done_by = 'Anastasia' where vendor_name = 'Roofers Inc'");
|
||||
await q("update acc_certificates_review set done = true where vendor_name in ('New Vendor', 'Empty Vendor')");
|
||||
|
||||
const res = await fin();
|
||||
expect(res.finalized.certificates).toBe(2);
|
||||
expect(res.rejected).toHaveLength(1);
|
||||
expect(res.rejected[0].reason).toContain("expires_on");
|
||||
|
||||
const roofers = await q("select to_char(valid_until, 'YYYY-MM-DD') v from acc_insurance_certificates where id = $1", [certId]);
|
||||
expect(roofers[0].v).toBe("2027-06-30");
|
||||
const created = await q("select to_char(valid_until, 'YYYY-MM-DD') v, drive_file_id from acc_insurance_certificates where vendor_name = 'New Vendor'");
|
||||
expect(created).toEqual([{ v: "2027-01-31", drive_file_id: "manual" }]);
|
||||
const h = await q("select changed_fields from acc_certificates_review_history where vendor_name = 'Roofers Inc'");
|
||||
expect(h[0].changed_fields).toEqual({ expires_on: { old: "2026-11-20", new: "2027-06-30" } });
|
||||
// осталась только отклонённая запись
|
||||
expect((await q("select vendor_name from acc_certificates_review")).map((r) => r.vendor_name)).toEqual(["Empty Vendor"]);
|
||||
});
|
||||
|
||||
it("повторный запуск идемпотентен", async () => {
|
||||
const id = await newInvoice();
|
||||
await q("update acc_invoices_review set done = true where id = $1", [id]);
|
||||
expect((await fin()).finalized.invoices).toBe(1);
|
||||
const again = await fin();
|
||||
expect(again.finalized).toEqual({ invoices: 0, categorization: 0, certificates: 0 });
|
||||
expect(await q("select 1 from acc_invoices_review_history")).toHaveLength(1);
|
||||
expect(await q("select 1 from acc_invoices")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("вернувшийся в разбор инвойс обновляет запись реестра, не меняя статус", async () => {
|
||||
const id = await newInvoice();
|
||||
await q("update acc_invoices_review set done = true where id = $1", [id]);
|
||||
await fin();
|
||||
await q("update acc_invoices set stage = 'to_approve' where id = $1", [id]);
|
||||
// повторный разбор с тем же id (например, расхождение с QuickBooks)
|
||||
await q(
|
||||
`insert into acc_invoices_review (id, source_message_id, drive_file_id, vendor_name, invoice_date, amount, project_customer_id, done)
|
||||
values ($1, 'msg-1', 'file-1', 'ACME Plumbing', '2026-11-01', 1500, 'proj-1', true)`, [id]);
|
||||
const res = await fin();
|
||||
expect(res.errors).toEqual([]);
|
||||
expect(res.finalized.invoices).toBe(1);
|
||||
const inv = (await q("select stage, amount from acc_invoices where id = $1", [id]))[0];
|
||||
expect(inv.stage).toBe("to_approve");
|
||||
expect(Number(inv.amount)).toBe(1500);
|
||||
expect(await q("select 1 from acc_invoices_review_history where id = $1", [id])).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("параллельный запуск двух finalize: каждая запись обработана ровно один раз", async () => {
|
||||
const ids: string[] = [];
|
||||
for (let i = 0; i < 6; i++) ids.push(await newInvoice({ vendor_name: `V${i}` }));
|
||||
await q("update acc_invoices_review set done = true");
|
||||
const [a, b] = await Promise.all([fin(), fin()]);
|
||||
expect(a.errors).toEqual([]);
|
||||
expect(b.errors).toEqual([]);
|
||||
expect(a.finalized.invoices + b.finalized.invoices).toBe(6);
|
||||
expect(await q("select 1 from acc_invoices_review_history")).toHaveLength(6);
|
||||
expect(await q("select 1 from acc_invoices")).toHaveLength(6);
|
||||
expect(await q("select 1 from acc_invoices_review")).toHaveLength(0);
|
||||
expect(await q("select 1 from acc_manual_review")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("diffWithOriginal: служебные поля и равные значения не попадают в различия", () => {
|
||||
const cur = { id: "1", amount: 5, lines: [{ a: 1 }], done: true, updated_at: "x", problem_highlight: null };
|
||||
const org = { id: "1", amount: 5, lines: [{ a: 1 }], done: false, updated_at: "y", problem_highlight: "p" };
|
||||
expect(diffWithOriginal(cur, org)).toEqual({});
|
||||
expect(diffWithOriginal({ ...cur, amount: 6 }, org)).toEqual({ amount: { old: 5, new: 6 } });
|
||||
expect(diffWithOriginal(cur, null)).toEqual({});
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ сводка
|
||||
const NOW = new Date("2026-11-17T15:00:00Z"); // вторник, 17:00 по Кипру
|
||||
const TZ = "Asia/Nicosia";
|
||||
|
||||
async function seedSummary() {
|
||||
const mr = (kind: string, ref: string, role: string, problem: string | null, created: string, snoozed: string | null = null) =>
|
||||
q(
|
||||
`insert into acc_manual_review (kind, ref_table, ref_id, assignee_role, problem_highlight, created_at, snoozed_until)
|
||||
values ($1, $2, $3, $4, $5, $6, $7)`,
|
||||
[kind, `acc_${kind}_review`, ref, role, problem, created, snoozed],
|
||||
);
|
||||
await mr("invoice", "i1", "accountant", "проект неясен", "2026-11-10T09:00:00Z"); // старше 2 рабочих дней
|
||||
await mr("invoice", "i2", "accountant", null, "2026-11-17T09:00:00Z");
|
||||
await mr("categorization", "c1", "accountant", "ждёт документ", "2026-11-16T09:00:00Z");
|
||||
await mr("categorization", "c2", "accountant", "подозрение на дубль", "2026-11-16T09:00:00Z");
|
||||
await mr("categorization", "c3", "cfo", null, "2026-11-16T09:00:00Z");
|
||||
await mr("certificate", "s1", "accountant", "истекает через 5 дней", "2026-11-17T09:00:00Z");
|
||||
await mr("categorization", "c4", "accountant", "нужен человек", "2026-11-17T09:00:00Z", "2026-11-25T00:00:00Z"); // отложена: не считается
|
||||
|
||||
const hist = (table: string, key: string, by: string, created: string, closed: string, changed: string | null) =>
|
||||
q(
|
||||
table === "acc_invoices_review_history"
|
||||
? `insert into ${table} (source_message_id, drive_file_id, closed_by, created_at, closed_at, changed_fields) values ('m', 'f', $1, $2, $3, $4::jsonb)`
|
||||
: `insert into ${table} (${key}, run_id, run_started_at, closed_by, created_at, closed_at, changed_fields) values (gen_random_uuid()::text, 'r', now(), $1, $2, $3, $4::jsonb)`,
|
||||
[by, created, closed, changed],
|
||||
);
|
||||
// вчера (16.11 по Кипру): 3 закрытия, 2 из них без правок, среднее время (2 + 4 + 1) / 3 = 2 ч 20 мин
|
||||
await hist("acc_invoices_review_history", "id", "Anastasia", "2026-11-16T08:00:00Z", "2026-11-16T10:00:00Z", "{}");
|
||||
await hist("acc_invoices_review_history", "id", "Anastasia", "2026-11-16T06:00:00Z", "2026-11-16T10:00:00Z", '{"amount":{"old":1,"new":2}}');
|
||||
await hist("acc_categorization_review_history", "feed_txn_id", "Yulia", "2026-11-16T09:00:00Z", "2026-11-16T10:00:00Z", null);
|
||||
// не вчера
|
||||
await hist("acc_invoices_review_history", "id", "Anastasia", "2026-11-14T08:00:00Z", "2026-11-15T10:00:00Z", "{}");
|
||||
await hist("acc_invoices_review_history", "id", "Anastasia", "2026-11-17T08:00:00Z", "2026-11-17T10:00:00Z", "{}");
|
||||
}
|
||||
|
||||
it("сводка на заготовленных данных: числа и формулировки", async () => {
|
||||
await seedSummary();
|
||||
const text = await buildDailySummary(db.pool, NOW, TZ, { mathesarUrl: "https://mathesar.example/queue", bankFeedUrl: "https://qbo.example/feed" });
|
||||
expect(text).toContain("Сводка бухгалтерского помощника на 17.11.2026");
|
||||
expect(text).toContain("В очереди ручного разбора: 6 задач");
|
||||
expect(text).toContain("- инвойсы: 2, из них с проблемой: 1");
|
||||
expect(text).toContain("- категоризация: 3, из них с проблемой: 2");
|
||||
expect(text).toContain("- сертификаты: 1, из них с проблемой: 1");
|
||||
expect(text).toContain("бухгалтер (accountant) - 5");
|
||||
expect(text).toContain("Анастасия (cfo) - 1");
|
||||
expect(text).toContain("Отложено до даты повторного показа: 1");
|
||||
expect(text).toContain("Категоризация: ждёт документ - 1; подозрение на дубль - 1; нужен человек - 0");
|
||||
expect(text).toContain("https://qbo.example/feed");
|
||||
expect(text).toContain("Очередь в Mathesar: https://mathesar.example/queue");
|
||||
expect(text).toContain("За вчера (16.11.2026):");
|
||||
expect(text).toContain("закрыто: 3 задачи (Anastasia - 2, Yulia - 1)");
|
||||
expect(text).toContain("закрыто без правок автомата: 2 из 3 (67%)");
|
||||
expect(text).toContain("среднее время от создания задачи до закрытия: 2 ч 20 мин");
|
||||
expect(text).toContain("ждут больше 2 рабочих дней: 1");
|
||||
});
|
||||
|
||||
it("сводка на пустых данных не падает", async () => {
|
||||
const text = await buildDailySummary(db.pool, NOW, TZ);
|
||||
expect(text).toContain("В очереди ручного разбора: 0 задач");
|
||||
expect(text).toContain("закрытых задач не было");
|
||||
expect(text).toContain("ждут больше 2 рабочих дней: 0");
|
||||
expect(text).not.toContain("Mathesar");
|
||||
});
|
||||
|
||||
it("twoWorkdaysAgo пропускает выходные", () => {
|
||||
expect(twoWorkdaysAgo(new Date("2026-11-17T15:00:00Z"), TZ).toISOString()).toBe("2026-11-13T15:00:00.000Z"); // вт -> пт
|
||||
expect(twoWorkdaysAgo(new Date("2026-11-18T15:00:00Z"), TZ).toISOString()).toBe("2026-11-16T15:00:00.000Z"); // ср -> пн
|
||||
});
|
||||
|
||||
it("postDailySummary отправляет сводку в канал; SlackPoster вызывает chat.postMessage", async () => {
|
||||
const calls: { url: string; init: RequestInit }[] = [];
|
||||
const fakeFetch = (async (u: string, init: RequestInit) => {
|
||||
calls.push({ url: u, init });
|
||||
return new Response(JSON.stringify({ ok: true }), { status: 200 });
|
||||
}) as unknown as typeof fetch;
|
||||
const slack = createSlackPoster({ botToken: "xoxb-test", fetchImpl: fakeFetch });
|
||||
const text = await postDailySummary({ pool: db.pool, slack, channelId: "C123", now: () => NOW, tz: TZ });
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0].url).toBe("https://slack.com/api/chat.postMessage");
|
||||
expect((calls[0].init.headers as Record<string, string>).authorization).toBe("Bearer xoxb-test");
|
||||
expect(JSON.parse(calls[0].init.body as string)).toEqual({ channel: "C123", text });
|
||||
|
||||
const bad = createSlackPoster({ botToken: "x", fetchImpl: (async () => new Response(JSON.stringify({ ok: false, error: "channel_not_found" }))) as unknown as typeof fetch });
|
||||
await expect(bad.post("C", "t")).rejects.toThrow("channel_not_found");
|
||||
});
|
||||
});
|
||||
205
packages/accounting_automation/src/finalize.ts
Normal file
205
packages/accounting_automation/src/finalize.ts
Normal file
@@ -0,0 +1,205 @@
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { withTx, type Pool } from "khb_common";
|
||||
|
||||
type PoolClient = Parameters<Parameters<typeof withTx>[1]>[0];
|
||||
|
||||
/**
|
||||
* Процесс «Завершение ручного разбора» (docs/approved/modules/quickbooks_bookkeeper/processes.md).
|
||||
* Берёт записи *_review с done = true, которые не менялись дольше delaySeconds, проверяет их,
|
||||
* переносит в *_history (с различиями относительно *_original), передаёт результат дальше
|
||||
* (инвойс -> acc_invoices, сертификат -> acc_insurance_certificates) и удаляет строку из review
|
||||
* (триггер БД сам убирает задачу из acc_manual_review).
|
||||
*/
|
||||
|
||||
export type ReviewKind = "invoices" | "categorization" | "certificates";
|
||||
|
||||
export interface FinalizeDeps {
|
||||
pool: Pool;
|
||||
/** Сколько секунд запись должна оставаться без изменений. По умолчанию 30. */
|
||||
delaySeconds?: number;
|
||||
now?: () => Date;
|
||||
/** Сообщение исполнителю (в боевом режиме - в Slack канал бухгалтерии). */
|
||||
notify: (text: string) => Promise<void> | void;
|
||||
}
|
||||
|
||||
export interface RejectedItem {
|
||||
kind: ReviewKind;
|
||||
id: string;
|
||||
reason: string;
|
||||
}
|
||||
|
||||
export interface FinalizeResult {
|
||||
finalized: { invoices: number; categorization: number; certificates: number };
|
||||
rejected: RejectedItem[];
|
||||
/** Непредвиденные ошибки по записям (транзакция записи откатана, будет повтор при следующем запуске). */
|
||||
errors: { kind: ReviewKind; id: string; message: string }[];
|
||||
}
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
|
||||
interface KindConfig {
|
||||
kind: ReviewKind;
|
||||
table: string;
|
||||
key: string;
|
||||
label: string;
|
||||
/** Текст причины отказа или null, если запись корректна. */
|
||||
validate: (row: Row) => string | null;
|
||||
/** Передача результата дальше (в той же транзакции). */
|
||||
forward: (c: PoolClient, row: Row) => Promise<void>;
|
||||
}
|
||||
|
||||
/** Поля, изменения которых не считаются правкой человека (служебные и отметки процесса). */
|
||||
const SERVICE_FIELDS = new Set(["updated_at", "created_at", "done", "done_by", "problem_highlight", "request_sent_at"]);
|
||||
|
||||
/** Пусто или заглушка автомата «tbd». */
|
||||
function blank(v: unknown): boolean {
|
||||
if (v === null || v === undefined) return true;
|
||||
if (typeof v === "string") {
|
||||
const s = v.trim().toLowerCase();
|
||||
return s === "" || s === "tbd";
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function validateInvoice(r: Row): string | null {
|
||||
const missing: string[] = [];
|
||||
if (blank(r.vendor_name)) missing.push("vendor_name (вендор)");
|
||||
if (blank(r.invoice_date)) missing.push("invoice_date (дата инвойса)");
|
||||
if (blank(r.amount)) missing.push("amount (сумма)");
|
||||
if (blank(r.project_customer_id)) missing.push("project_customer_id (проект)");
|
||||
if (missing.length > 0) return `не заполнены обязательные поля: ${missing.join(", ")}`;
|
||||
const amount = Number(r.amount);
|
||||
if (!Number.isFinite(amount) || amount <= 0) return `сумма инвойса должна быть больше нуля (сейчас ${String(r.amount)})`;
|
||||
return null;
|
||||
}
|
||||
|
||||
function validateCertificate(r: Row): string | null {
|
||||
if (blank(r.expires_on) && blank(r.certificate_id)) return "не указан ни срок окончания (expires_on), ни сертификат (certificate_id)";
|
||||
return null;
|
||||
}
|
||||
|
||||
async function forwardInvoice(c: PoolClient, r: Row): Promise<void> {
|
||||
// Тот же id; если инвойс уже есть в реестре (вернулся в разбор), обновляем данные, статус не трогаем.
|
||||
await c.query(
|
||||
`insert into acc_invoices (id, source_message_id, drive_file_id, vendor_name, vendor_qbo_id, invoice_number, invoice_date,
|
||||
amount, lines, project_customer_id, jt_job_id, contract_id, stage)
|
||||
values ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, $10, $11, $12, 'checking')
|
||||
on conflict (id) do update set
|
||||
source_message_id = excluded.source_message_id, drive_file_id = excluded.drive_file_id, vendor_name = excluded.vendor_name,
|
||||
vendor_qbo_id = excluded.vendor_qbo_id, invoice_number = excluded.invoice_number, invoice_date = excluded.invoice_date,
|
||||
amount = excluded.amount, lines = excluded.lines, project_customer_id = excluded.project_customer_id,
|
||||
jt_job_id = excluded.jt_job_id, contract_id = excluded.contract_id`,
|
||||
[
|
||||
r.id, r.source_message_id, r.drive_file_id, r.vendor_name, r.vendor_qbo_id ?? null, r.invoice_number ?? null, r.invoice_date,
|
||||
r.amount, r.lines == null ? null : JSON.stringify(r.lines), r.project_customer_id, r.jt_job_id ?? null, r.contract_id ?? null,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Сертификат: если указан certificate_id - обновляем его срок (expires_on); иначе ищем последний сертификат вендора
|
||||
* и обновляем его; если сертификатов нет - создаём запись (файл неизвестен, drive_file_id = 'manual').
|
||||
*/
|
||||
async function forwardCertificate(c: PoolClient, r: Row): Promise<void> {
|
||||
const expires = blank(r.expires_on) ? null : r.expires_on;
|
||||
let certId = blank(r.certificate_id) ? null : String(r.certificate_id);
|
||||
if (!certId) {
|
||||
const found = await c.query(
|
||||
`select id from acc_insurance_certificates
|
||||
where (($1::text is not null and vendor_qbo_id = $1) or lower(vendor_name) = lower($2))
|
||||
order by valid_until desc limit 1`,
|
||||
[r.vendor_qbo_id ?? null, r.vendor_name],
|
||||
);
|
||||
certId = found.rows[0]?.id ?? null;
|
||||
}
|
||||
if (certId) {
|
||||
if (expires) await c.query("update acc_insurance_certificates set valid_until = $2 where id = $1", [certId, expires]);
|
||||
return;
|
||||
}
|
||||
if (!expires) return;
|
||||
await c.query(
|
||||
`insert into acc_insurance_certificates (vendor_name, vendor_qbo_id, valid_until, drive_file_id) values ($1, $2, $3, 'manual')`,
|
||||
[r.vendor_name, r.vendor_qbo_id ?? null, expires],
|
||||
);
|
||||
}
|
||||
|
||||
const KINDS: KindConfig[] = [
|
||||
{ kind: "invoices", table: "acc_invoices_review", key: "id", label: "инвойс", validate: validateInvoice, forward: forwardInvoice },
|
||||
// Категоризация: проводка в QuickBooks уже сделана Claude, обязательных полей нет; фиксируется только результат.
|
||||
{ kind: "categorization", table: "acc_categorization_review", key: "feed_txn_id", label: "операция банка", validate: () => null, forward: async () => {} },
|
||||
{ kind: "certificates", table: "acc_certificates_review", key: "id", label: "сертификат", validate: validateCertificate, forward: forwardCertificate },
|
||||
];
|
||||
|
||||
/** Различия строки с оригиналом: {поле: {old, new}}; служебные поля не учитываются. */
|
||||
export function diffWithOriginal(current: Row, original: Row | null): Record<string, { old: unknown; new: unknown }> {
|
||||
const out: Record<string, { old: unknown; new: unknown }> = {};
|
||||
if (!original) return out;
|
||||
for (const k of Object.keys(current)) {
|
||||
if (SERVICE_FIELDS.has(k)) continue;
|
||||
const a = original[k] ?? null;
|
||||
const b = current[k] ?? null;
|
||||
if (!isDeepStrictEqual(a, b)) out[k] = { old: a, new: b };
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
type Outcome = { status: "skipped" } | { status: "finalized" } | { status: "rejected"; reason: string; doneBy: string | null };
|
||||
|
||||
async function finalizeOne(pool: Pool, cfg: KindConfig, id: string, cutoff: Date, now: Date): Promise<Outcome> {
|
||||
return withTx(pool, async (c) => {
|
||||
// Блокировка строки; занятую другим запуском пропускаем. Условия проверяются заново уже под блокировкой.
|
||||
const locked = await c.query(
|
||||
`select to_jsonb(r) as j from ${cfg.table} r where r.${cfg.key}::text = $1 and r.done and r.updated_at <= $2 for update skip locked`,
|
||||
[id, cutoff],
|
||||
);
|
||||
if (locked.rowCount === 0) return { status: "skipped" } as Outcome;
|
||||
const row = locked.rows[0].j as Row;
|
||||
const doneBy = (row.done_by as string | null) ?? null;
|
||||
|
||||
const reason = cfg.validate(row);
|
||||
if (reason) {
|
||||
await c.query(`update ${cfg.table} set done = false, problem_highlight = $2 where ${cfg.key}::text = $1`, [id, `Завершение отклонено: ${reason}`]);
|
||||
return { status: "rejected", reason, doneBy } as Outcome;
|
||||
}
|
||||
|
||||
const orig = await c.query(`select to_jsonb(o) as j from ${cfg.table}_original o where o.${cfg.key}::text = $1`, [id]);
|
||||
const changed = diffWithOriginal(row, (orig.rows[0]?.j as Row | undefined) ?? null);
|
||||
|
||||
const hist = { ...row, closed_by: doneBy, closed_at: now.toISOString(), changed_fields: changed };
|
||||
await c.query(`insert into ${cfg.table}_history select (jsonb_populate_record(null::${cfg.table}_history, $1::jsonb)).*`, [JSON.stringify(hist)]);
|
||||
|
||||
await cfg.forward(c, row);
|
||||
await c.query(`delete from ${cfg.table} where ${cfg.key}::text = $1`, [id]);
|
||||
return { status: "finalized" } as Outcome;
|
||||
});
|
||||
}
|
||||
|
||||
export async function runFinalize(deps: FinalizeDeps): Promise<FinalizeResult> {
|
||||
const delay = deps.delaySeconds ?? 30;
|
||||
const now = (deps.now ?? (() => new Date()))();
|
||||
const cutoff = new Date(now.getTime() - delay * 1000);
|
||||
const result: FinalizeResult = { finalized: { invoices: 0, categorization: 0, certificates: 0 }, rejected: [], errors: [] };
|
||||
|
||||
for (const cfg of KINDS) {
|
||||
const cand = await deps.pool.query(`select ${cfg.key}::text as id from ${cfg.table} where done and updated_at <= $1 order by created_at`, [cutoff]);
|
||||
for (const { id } of cand.rows as { id: string }[]) {
|
||||
try {
|
||||
const out = await finalizeOne(deps.pool, cfg, id, cutoff, now);
|
||||
if (out.status === "finalized") result.finalized[cfg.kind]++;
|
||||
else if (out.status === "rejected") {
|
||||
result.rejected.push({ kind: cfg.kind, id, reason: out.reason });
|
||||
try {
|
||||
await deps.notify(
|
||||
`Завершение разбора отклонено (${cfg.label}, ${id}${out.doneBy ? `, отметил ${out.doneBy}` : ""}): ${out.reason}. Отметка «выполнено» снята, исправьте запись и отметьте заново.`,
|
||||
);
|
||||
} catch {
|
||||
// сбой уведомления не должен ломать обработку; причина осталась в problem_highlight
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
result.errors.push({ kind: cfg.kind, id, message: e instanceof Error ? e.message : String(e) });
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
108
packages/accounting_automation/src/gmail.ts
Normal file
108
packages/accounting_automation/src/gmail.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import type { FetchFn, GoogleAuth } from "./google.js";
|
||||
|
||||
export interface MailAttachment {
|
||||
filename: string;
|
||||
mime: string;
|
||||
getBytes(): Promise<Buffer>;
|
||||
}
|
||||
export interface MailMessage {
|
||||
id: string;
|
||||
from: string;
|
||||
subject: string;
|
||||
receivedAt: Date;
|
||||
attachments: MailAttachment[];
|
||||
}
|
||||
export interface MailSource {
|
||||
/** Письма ящика invoices@ с PDF-вложениями, которых нет в acc_mail_processed. */
|
||||
listUnprocessed(limit: number): Promise<MailMessage[]>;
|
||||
}
|
||||
|
||||
export const GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.readonly";
|
||||
const API = "https://gmail.googleapis.com/gmail/v1/users/me";
|
||||
|
||||
interface GmailPart {
|
||||
filename?: string;
|
||||
mimeType?: string;
|
||||
body?: { attachmentId?: string; data?: string; size?: number };
|
||||
parts?: GmailPart[];
|
||||
}
|
||||
export interface GmailMessageJson {
|
||||
id: string;
|
||||
internalDate?: string;
|
||||
payload?: GmailPart & { headers?: { name: string; value: string }[] };
|
||||
}
|
||||
|
||||
/** Разбор ответа messages.get (format=full) в MailMessage; байты вложений берутся через fetchAttachment. */
|
||||
export function parseGmailMessage(m: GmailMessageJson, fetchAttachment: (attachmentId: string) => Promise<Buffer>): MailMessage {
|
||||
const header = (n: string) => m.payload?.headers?.find((h) => h.name.toLowerCase() === n)?.value ?? "";
|
||||
const attachments: MailAttachment[] = [];
|
||||
const walk = (p: GmailPart | undefined): void => {
|
||||
if (!p) return;
|
||||
const name = p.filename ?? "";
|
||||
const isPdf = (p.mimeType ?? "").toLowerCase() === "application/pdf" || name.toLowerCase().endsWith(".pdf");
|
||||
if (name && isPdf && p.body) {
|
||||
const { attachmentId, data } = p.body;
|
||||
if (data) attachments.push({ filename: name, mime: "application/pdf", getBytes: async () => Buffer.from(data, "base64url") });
|
||||
else if (attachmentId) attachments.push({ filename: name, mime: "application/pdf", getBytes: () => fetchAttachment(attachmentId) });
|
||||
}
|
||||
for (const c of p.parts ?? []) walk(c);
|
||||
};
|
||||
walk(m.payload);
|
||||
return {
|
||||
id: m.id,
|
||||
from: header("from"),
|
||||
subject: header("subject"),
|
||||
receivedAt: new Date(Number(m.internalDate ?? 0)),
|
||||
attachments,
|
||||
};
|
||||
}
|
||||
|
||||
/** Gmail REST API: читаем ящик invoices@ от имени пользователя (делегирование домена). */
|
||||
export class GmailClient implements MailSource {
|
||||
constructor(
|
||||
private o: {
|
||||
auth: GoogleAuth;
|
||||
/** Ящик (google.gmailUser). */
|
||||
user: string;
|
||||
/** Какие из id писем уже разобраны (acc_mail_processed, result invoice/skipped). */
|
||||
processedIds: (ids: string[]) => Promise<Set<string>>;
|
||||
fetchFn?: FetchFn;
|
||||
query?: string;
|
||||
},
|
||||
) {}
|
||||
|
||||
private async get<T>(path: string, params: Record<string, string> = {}): Promise<T> {
|
||||
const token = await this.o.auth.getAccessToken([GMAIL_SCOPE], this.o.user);
|
||||
const url = `${API}${path}${Object.keys(params).length ? "?" + new URLSearchParams(params) : ""}`;
|
||||
const res = await (this.o.fetchFn ?? fetch)(url, { headers: { authorization: `Bearer ${token}` } });
|
||||
const text = await res.text();
|
||||
if (!res.ok) throw new Error(`Gmail ${path} ${res.status}: ${text.slice(0, 300)}`);
|
||||
return JSON.parse(text) as T;
|
||||
}
|
||||
|
||||
async listUnprocessed(limit: number): Promise<MailMessage[]> {
|
||||
const out: MailMessage[] = [];
|
||||
let pageToken: string | undefined;
|
||||
do {
|
||||
const params: Record<string, string> = { q: this.o.query ?? "has:attachment filename:pdf", maxResults: "50" };
|
||||
if (pageToken) params.pageToken = pageToken;
|
||||
const list = await this.get<{ messages?: { id: string }[]; nextPageToken?: string }>("/messages", params);
|
||||
const ids = (list.messages ?? []).map((x) => x.id);
|
||||
const done = ids.length ? await this.o.processedIds(ids) : new Set<string>();
|
||||
for (const id of ids) {
|
||||
if (done.has(id)) continue;
|
||||
const m = await this.get<GmailMessageJson>(`/messages/${id}`, { format: "full" });
|
||||
const msg = parseGmailMessage(m, (aid) => this.fetchAttachment(id, aid));
|
||||
if (msg.attachments.length) out.push(msg);
|
||||
if (out.length >= limit) return out;
|
||||
}
|
||||
pageToken = list.nextPageToken;
|
||||
} while (pageToken);
|
||||
return out;
|
||||
}
|
||||
|
||||
private async fetchAttachment(messageId: string, attachmentId: string): Promise<Buffer> {
|
||||
const a = await this.get<{ data?: string }>(`/messages/${messageId}/attachments/${attachmentId}`);
|
||||
return Buffer.from(a.data ?? "", "base64url");
|
||||
}
|
||||
}
|
||||
128
packages/accounting_automation/src/google.test.ts
Normal file
128
packages/accounting_automation/src/google.test.ts
Normal file
@@ -0,0 +1,128 @@
|
||||
import { generateKeyPairSync, createVerify } from "node:crypto";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { GoogleAuth, buildServiceAccountJwt } from "./google.js";
|
||||
import { GMAIL_SCOPE, GmailClient, parseGmailMessage } from "./gmail.js";
|
||||
import { DriveClient } from "./drive.js";
|
||||
|
||||
const { privateKey, publicKey } = generateKeyPairSync("rsa", {
|
||||
modulusLength: 2048,
|
||||
privateKeyEncoding: { type: "pkcs8", format: "pem" },
|
||||
publicKeyEncoding: { type: "spki", format: "pem" },
|
||||
});
|
||||
const key = { client_email: "sa@proj.iam.gserviceaccount.com", private_key: privateKey };
|
||||
const dec = (s: string) => JSON.parse(Buffer.from(s, "base64url").toString("utf8"));
|
||||
|
||||
describe("GoogleAuth", () => {
|
||||
it("JWT: структура, claims и подпись RS256", () => {
|
||||
const jwt = buildServiceAccountJwt(key, ["a", "b"], "invoices@khbuild.pro", 1000);
|
||||
const [h, c, s] = jwt.split(".");
|
||||
expect(dec(h)).toEqual({ alg: "RS256", typ: "JWT" });
|
||||
expect(dec(c)).toEqual({ iss: key.client_email, scope: "a b", aud: "https://oauth2.googleapis.com/token", iat: 1000, exp: 4600, sub: "invoices@khbuild.pro" });
|
||||
expect(createVerify("RSA-SHA256").update(`${h}.${c}`).verify(publicKey, Buffer.from(s, "base64url"))).toBe(true);
|
||||
});
|
||||
|
||||
it("без subject claim sub отсутствует", () => {
|
||||
expect(dec(buildServiceAccountJwt(key, ["a"], undefined, 1).split(".")[1])).not.toHaveProperty("sub");
|
||||
});
|
||||
|
||||
it("обмен на токен, кэш и обновление по истечении", async () => {
|
||||
let calls = 0;
|
||||
let t = new Date("2026-01-01T00:00:00Z");
|
||||
const fetchFn = (async (url: string, init: RequestInit) => {
|
||||
calls++;
|
||||
expect(url).toBe("https://oauth2.googleapis.com/token");
|
||||
const body = init.body as URLSearchParams;
|
||||
expect(body.get("grant_type")).toBe("urn:ietf:params:oauth:grant-type:jwt-bearer");
|
||||
expect(body.get("assertion")!.split(".")).toHaveLength(3);
|
||||
return new Response(JSON.stringify({ access_token: `tok${calls}`, expires_in: 3600 }), { status: 200 });
|
||||
}) as unknown as typeof fetch;
|
||||
const auth = new GoogleAuth(key, { fetchFn, now: () => t });
|
||||
expect(await auth.getAccessToken(["s"], "u@x")).toBe("tok1");
|
||||
expect(await auth.getAccessToken(["s"], "u@x")).toBe("tok1");
|
||||
expect(await auth.getAccessToken(["s"])).toBe("tok2"); // другой subject - другой токен
|
||||
t = new Date(t.getTime() + 3600_000);
|
||||
expect(await auth.getAccessToken(["s"], "u@x")).toBe("tok3");
|
||||
});
|
||||
|
||||
it("ошибка обмена токена - исключение", async () => {
|
||||
const fetchFn = (async () => new Response("bad", { status: 400 })) as unknown as typeof fetch;
|
||||
await expect(new GoogleAuth(key, { fetchFn }).getAccessToken(["s"])).rejects.toThrow(/400/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Gmail: разбор ответов", () => {
|
||||
const msgJson = {
|
||||
id: "m1",
|
||||
internalDate: "1767225600000",
|
||||
payload: {
|
||||
headers: [{ name: "From", value: "Bob <bob@vendor.com>" }, { name: "Subject", value: "Invoice 42" }],
|
||||
parts: [
|
||||
{ mimeType: "text/plain", body: { data: "aGk" } },
|
||||
{ filename: "inv.pdf", mimeType: "application/pdf", body: { attachmentId: "att1" } },
|
||||
{ filename: "photo.jpg", mimeType: "image/jpeg", body: { attachmentId: "att2" } },
|
||||
{ mimeType: "multipart/mixed", parts: [{ filename: "inline.PDF", mimeType: "application/octet-stream", body: { data: Buffer.from("PDFDATA").toString("base64url") } }] },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
it("parseGmailMessage: заголовки, PDF-вложения, дата", async () => {
|
||||
const m = parseGmailMessage(msgJson, async (id) => Buffer.from(`bytes-${id}`));
|
||||
expect(m).toMatchObject({ id: "m1", from: "Bob <bob@vendor.com>", subject: "Invoice 42" });
|
||||
expect(m.receivedAt.toISOString()).toBe("2026-01-01T00:00:00.000Z");
|
||||
expect(m.attachments.map((a) => a.filename)).toEqual(["inv.pdf", "inline.PDF"]);
|
||||
expect((await m.attachments[0].getBytes()).toString()).toBe("bytes-att1");
|
||||
expect((await m.attachments[1].getBytes()).toString()).toBe("PDFDATA");
|
||||
});
|
||||
|
||||
it("GmailClient.listUnprocessed: пропускает обработанные, сторонние письма без PDF и берёт вложения", async () => {
|
||||
const urls: string[] = [];
|
||||
const fetchFn = (async (url: string, init: RequestInit) => {
|
||||
urls.push(url);
|
||||
expect((init.headers as Record<string, string>).authorization).toBe("Bearer T");
|
||||
if (url.includes("/messages?")) return new Response(JSON.stringify({ messages: [{ id: "m0" }, { id: "m1" }, { id: "m2" }] }));
|
||||
if (url.includes("/messages/m1/attachments/att1")) return new Response(JSON.stringify({ data: Buffer.from("PDF1").toString("base64url") }));
|
||||
if (url.includes("/messages/m1")) return new Response(JSON.stringify(msgJson));
|
||||
if (url.includes("/messages/m2")) return new Response(JSON.stringify({ id: "m2", payload: { headers: [], parts: [] } }));
|
||||
throw new Error("unexpected " + url);
|
||||
}) as unknown as typeof fetch;
|
||||
const auth = { getAccessToken: async (scopes: string[], subject?: string) => {
|
||||
expect(scopes).toEqual([GMAIL_SCOPE]);
|
||||
expect(subject).toBe("invoices@khbuild.pro");
|
||||
return "T";
|
||||
} } as unknown as GoogleAuth;
|
||||
const c = new GmailClient({ auth, user: "invoices@khbuild.pro", processedIds: async () => new Set(["m0"]), fetchFn });
|
||||
const list = await c.listUnprocessed(10);
|
||||
expect(list.map((m) => m.id)).toEqual(["m1"]);
|
||||
expect((await list[0].attachments[0].getBytes()).toString()).toBe("PDF1");
|
||||
expect(decodeURIComponent(urls[0])).toContain("q=has:attachment+filename:pdf".replace(/\+/g, "+"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Drive: запросы", () => {
|
||||
it("ensureFolder ищет и создаёт папки, upload шлёт multipart, exportDocText берёт text/plain", async () => {
|
||||
const calls: { url: string; method: string; body?: unknown }[] = [];
|
||||
const fetchFn = (async (url: string, init: RequestInit = {}) => {
|
||||
calls.push({ url, method: init.method ?? "GET", body: init.body });
|
||||
if (url.includes("/files?q=")) {
|
||||
const found = decodeURIComponent(url).includes("name='Инвойсы'");
|
||||
return new Response(JSON.stringify({ files: found ? [{ id: "F1" }] : [] }));
|
||||
}
|
||||
if (url.includes("/files?supportsAllDrives=true&fields=id")) return new Response(JSON.stringify({ id: "F2" }));
|
||||
if (url.includes("uploadType=multipart")) return new Response(JSON.stringify({ id: "FILE" }));
|
||||
if (url.includes("/export")) return new Response("текст документа");
|
||||
throw new Error("unexpected " + url);
|
||||
}) as unknown as typeof fetch;
|
||||
const auth = { getAccessToken: async () => "T" } as unknown as GoogleAuth;
|
||||
const d = new DriveClient({ auth, rootFolderId: "ROOT", fetchFn });
|
||||
expect(await d.ensureFolder(["Инвойсы", "ACME"])).toBe("F2");
|
||||
expect(calls.every((c) => c.url.includes("supportsAllDrives=true"))).toBe(true);
|
||||
const n = calls.length;
|
||||
expect(await d.ensureFolder(["Инвойсы", "ACME"])).toBe("F2"); // из кэша
|
||||
expect(calls.length).toBe(n);
|
||||
expect(JSON.parse(calls[2].body as string)).toMatchObject({ name: "ACME", parents: ["F1"] });
|
||||
expect(await d.upload("a.pdf", "application/pdf", Buffer.from("PDF"), "F2")).toEqual({ id: "FILE" });
|
||||
const up = calls.find((c) => c.url.includes("uploadType=multipart"))!;
|
||||
expect(Buffer.from(up.body as Buffer).toString()).toContain('"parents":["F2"]');
|
||||
expect(await d.exportDocText("DOC")).toBe("текст документа");
|
||||
});
|
||||
});
|
||||
56
packages/accounting_automation/src/google.ts
Normal file
56
packages/accounting_automation/src/google.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { createSign } from "node:crypto";
|
||||
|
||||
export interface GoogleKey {
|
||||
client_email: string;
|
||||
private_key: string;
|
||||
}
|
||||
export type FetchFn = typeof fetch;
|
||||
|
||||
const TOKEN_URL = "https://oauth2.googleapis.com/token";
|
||||
|
||||
const b64url = (b: Buffer | string): string => Buffer.from(b).toString("base64url");
|
||||
|
||||
/** Подписанный JWT (RS256) для обмена на access token сервисного аккаунта. */
|
||||
export function buildServiceAccountJwt(key: GoogleKey, scopes: string[], subject: string | undefined, nowSec: number): string {
|
||||
const header = { alg: "RS256", typ: "JWT" };
|
||||
const claims: Record<string, unknown> = {
|
||||
iss: key.client_email,
|
||||
scope: scopes.join(" "),
|
||||
aud: TOKEN_URL,
|
||||
iat: nowSec,
|
||||
exp: nowSec + 3600,
|
||||
};
|
||||
if (subject) claims.sub = subject;
|
||||
const unsigned = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(claims))}`;
|
||||
const signature = createSign("RSA-SHA256").update(unsigned).sign(key.private_key);
|
||||
return `${unsigned}.${b64url(signature)}`;
|
||||
}
|
||||
|
||||
/** Токены сервисного аккаунта Google с кэшем. subject - пользователь для делегирования на уровне домена (Gmail). */
|
||||
export class GoogleAuth {
|
||||
private cache = new Map<string, { token: string; expiresAtMs: number }>();
|
||||
constructor(
|
||||
private key: GoogleKey,
|
||||
private opts: { fetchFn?: FetchFn; now?: () => Date } = {},
|
||||
) {}
|
||||
|
||||
async getAccessToken(scopes: string[], subject?: string): Promise<string> {
|
||||
const now = (this.opts.now ?? (() => new Date()))().getTime();
|
||||
const ck = `${[...scopes].sort().join(" ")}|${subject ?? ""}`;
|
||||
const hit = this.cache.get(ck);
|
||||
if (hit && hit.expiresAtMs - 60_000 > now) return hit.token;
|
||||
const jwt = buildServiceAccountJwt(this.key, scopes, subject, Math.floor(now / 1000));
|
||||
const body = new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: jwt });
|
||||
const res = await (this.opts.fetchFn ?? fetch)(TOKEN_URL, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||
body,
|
||||
});
|
||||
const text = await res.text();
|
||||
if (!res.ok) throw new Error(`Google token ${res.status}: ${text.slice(0, 300)}`);
|
||||
const j = JSON.parse(text) as { access_token?: string; expires_in?: number };
|
||||
if (!j.access_token) throw new Error("Google token: в ответе нет access_token");
|
||||
this.cache.set(ck, { token: j.access_token, expiresAtMs: now + (j.expires_in ?? 3600) * 1000 });
|
||||
return j.access_token;
|
||||
}
|
||||
}
|
||||
76
packages/accounting_automation/src/http-api.test.ts
Normal file
76
packages/accounting_automation/src/http-api.test.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Pool } from "khb_common";
|
||||
import { buildApi, type JobHandlers } from "./http-api.js";
|
||||
|
||||
const settings = { http: { host: "127.0.0.1", port: 0, token: "svc-token" }, reviewers: [], mcp: { enabled: false, staticTokens: [] } };
|
||||
const auth = { authorization: "Bearer svc-token" };
|
||||
|
||||
function mk(over: Partial<JobHandlers> = {}) {
|
||||
const calls: string[] = [];
|
||||
const jobs: JobHandlers = {
|
||||
"invoices-mail": async () => { calls.push("mail"); return { created: 1 }; },
|
||||
finalize: async () => { calls.push("finalize"); return { finalized: 0 }; },
|
||||
categorize: async () => { calls.push("categorize"); return { status: "ok" }; },
|
||||
summary: async () => { calls.push("summary"); return { sent: true }; },
|
||||
...over,
|
||||
};
|
||||
return { app: buildApi({ pool: {} as Pool, settings, jobs }), calls };
|
||||
}
|
||||
|
||||
describe("служебные ручки accounting_automation", () => {
|
||||
it("healthz открыт без токена", async () => {
|
||||
const { app } = mk();
|
||||
expect((await app.inject({ method: "GET", url: "/healthz" })).statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it("задания закрыты токеном", async () => {
|
||||
const { app, calls } = mk();
|
||||
expect((await app.inject({ method: "POST", url: "/jobs/finalize" })).statusCode).toBe(401);
|
||||
expect((await app.inject({ method: "POST", url: "/jobs/finalize", headers: { authorization: "Bearer bad" } })).statusCode).toBe(401);
|
||||
expect(calls).toEqual([]);
|
||||
});
|
||||
|
||||
it("неизвестное задание - 404 (в том числе служебные имена объекта)", async () => {
|
||||
const { app } = mk();
|
||||
expect((await app.inject({ method: "POST", url: "/jobs/nope", headers: auth })).statusCode).toBe(404);
|
||||
expect((await app.inject({ method: "POST", url: "/jobs/constructor", headers: auth })).statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it("по умолчанию задание стартует в фоне: 202 и итог в журнале", async () => {
|
||||
const { app, calls } = mk();
|
||||
const r = await app.inject({ method: "POST", url: "/jobs/categorize", headers: auth });
|
||||
expect(r.statusCode).toBe(202);
|
||||
expect(r.json()).toEqual({ job: "categorize", started: true });
|
||||
await new Promise((res) => setTimeout(res, 20));
|
||||
expect(calls).toEqual(["categorize"]);
|
||||
});
|
||||
|
||||
it("wait=true ждёт итог; ошибка задания - 502", async () => {
|
||||
const { app } = mk({ summary: async () => { throw new Error("slack не настроен"); } });
|
||||
const ok = await app.inject({ method: "POST", url: "/jobs/finalize?wait=true", headers: auth });
|
||||
expect(ok.statusCode).toBe(200);
|
||||
expect(ok.json()).toEqual({ job: "finalize", result: { finalized: 0 } });
|
||||
const bad = await app.inject({ method: "POST", url: "/jobs/summary?wait=true", headers: auth });
|
||||
expect(bad.statusCode).toBe(502);
|
||||
expect(bad.json().message).toContain("slack");
|
||||
});
|
||||
|
||||
it("то же задание параллельно - 409, после завершения снова доступно", async () => {
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>((r) => (release = r));
|
||||
const { app } = mk({ categorize: async () => { await gate; return {}; } });
|
||||
const first = app.inject({ method: "POST", url: "/jobs/categorize?wait=true", headers: auth });
|
||||
await new Promise((res) => setTimeout(res, 20));
|
||||
expect((await app.inject({ method: "POST", url: "/jobs/categorize", headers: auth })).statusCode).toBe(409);
|
||||
release();
|
||||
expect((await first).statusCode).toBe(200);
|
||||
expect((await app.inject({ method: "POST", url: "/jobs/categorize?wait=true", headers: auth })).statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it("упавшее задание освобождает блокировку", async () => {
|
||||
let n = 0;
|
||||
const { app } = mk({ finalize: async () => { if (n++ === 0) throw new Error("boom"); return {}; } });
|
||||
expect((await app.inject({ method: "POST", url: "/jobs/finalize?wait=true", headers: auth })).statusCode).toBe(502);
|
||||
expect((await app.inject({ method: "POST", url: "/jobs/finalize?wait=true", headers: auth })).statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
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;
|
||||
}
|
||||
187
packages/accounting_automation/src/invoices-mail.int.test.ts
Normal file
187
packages/accounting_automation/src/invoices-mail.int.test.ts
Normal file
@@ -0,0 +1,187 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { createLogger, createTestDb, testDatabaseUrl, type TestDb } from "khb_common";
|
||||
import type { ClaudeRunner } from "./claude-runner.js";
|
||||
import type { DriveStore } from "./drive.js";
|
||||
import type { MailMessage, MailSource } from "./gmail.js";
|
||||
import { addressKey, invoiceReviewId, normalizeVendorName, parseRecognition, runInvoiceIngest } from "./invoices-mail.js";
|
||||
|
||||
const url = testDatabaseUrl();
|
||||
const d = url ? describe : describe.skip;
|
||||
const log = createLogger("test", "silent");
|
||||
|
||||
describe("чистые функции", () => {
|
||||
it("нормализация вендора и адреса", () => {
|
||||
expect(normalizeVendorName("ACME Plumbing, LLC.")).toBe(normalizeVendorName("acme plumbing"));
|
||||
expect(addressKey("734 Placido Ave., Unit 2")).toBe("734 placido");
|
||||
expect(addressKey("no number")).toBeNull();
|
||||
});
|
||||
it("parseRecognition: обёртка ```json и невалидный ответ", () => {
|
||||
const r = parseRecognition('Вот:\n```json\n{"is_invoice":true,"amount":"$1,200.50","invoice_date":"2026-02-30","invoice_number":77}\n```');
|
||||
expect(r).toMatchObject({ is_invoice: true, amount: 1200.5, invoice_date: null, invoice_number: "77" });
|
||||
expect(() => parseRecognition("не json")).toThrow();
|
||||
expect(() => parseRecognition("{oops}")).toThrow(/невалидный/);
|
||||
});
|
||||
it("invoiceReviewId детерминирован и похож на uuid", () => {
|
||||
expect(invoiceReviewId("m", 0, "a.pdf")).toBe(invoiceReviewId("m", 0, "a.pdf"));
|
||||
expect(invoiceReviewId("m", 0, "a.pdf")).not.toBe(invoiceReviewId("m", 1, "a.pdf"));
|
||||
expect(invoiceReviewId("m", 0, "a.pdf")).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
|
||||
});
|
||||
});
|
||||
|
||||
d("загрузка инвойсов из почты (временная БД, моки Gmail/Drive/Claude)", () => {
|
||||
let db: TestDb;
|
||||
let uploads: { name: string; folder: string[] }[];
|
||||
let claudeCalls: number;
|
||||
let answers: Record<string, string>; // содержимое PDF -> ответ агента
|
||||
|
||||
const pdf = (text: string) => ({ filename: `${text}.pdf`, mime: "application/pdf", getBytes: async () => Buffer.from(text) });
|
||||
const mail = (id: string, ...texts: string[]): MailMessage => ({
|
||||
id, from: "bob@vendor.com", subject: "Invoice", receivedAt: new Date("2026-03-05T12:00:00Z"), attachments: texts.map(pdf),
|
||||
});
|
||||
const drive = (): DriveStore => {
|
||||
let lastFolder: string[] = [];
|
||||
return {
|
||||
ensureFolder: async (p) => { lastFolder = p; return p.join("/"); },
|
||||
upload: async (name) => { uploads.push({ name, folder: lastFolder }); return { id: `drv-${uploads.length}` }; },
|
||||
exportDocText: async () => "",
|
||||
};
|
||||
};
|
||||
const claude: ClaudeRunner = async (o) => {
|
||||
claudeCalls++;
|
||||
const path = /(\S+invoice\.pdf)/.exec(o.prompt)![1];
|
||||
const text = readFileSync(path, "utf8"); // файл должен существовать во время вызова
|
||||
const a = answers[text];
|
||||
return a === undefined ? { ok: false, stdout: "", stderr: "boom", exitCode: 1, timedOut: false } : { ok: true, stdout: a, stderr: "", exitCode: 0, timedOut: false };
|
||||
};
|
||||
const run = (messages: MailMessage[]) => {
|
||||
const mailSrc: MailSource = { listUnprocessed: async () => messages };
|
||||
return runInvoiceIngest({ pool: db.pool, mail: mailSrc, drive: drive(), claude, now: () => new Date("2026-03-06T00:00:00Z"), log });
|
||||
};
|
||||
const inv = (o: Record<string, unknown>) =>
|
||||
JSON.stringify({ is_invoice: true, vendor_name: "ACME Plumbing LLC", invoice_number: "INV-1", invoice_date: "2026-03-01", amount: 1500, lines: [{ description: "Работы", amount: 1500 }], object_name_or_address: "734 Placido Ave", ...o });
|
||||
const reviews = async () => (await db.pool.query("select * from acc_invoices_review order by invoice_number, id")).rows;
|
||||
|
||||
beforeAll(async () => {
|
||||
db = await createTestDb(url!);
|
||||
});
|
||||
afterAll(async () => { await db?.drop(); });
|
||||
beforeEach(async () => {
|
||||
uploads = []; claudeCalls = 0; answers = {};
|
||||
await db.pool.query("truncate acc_mail_processed, acc_manual_review, acc_invoices_review, acc_invoices_review_original, acc_invoices_review_history, acc_invoices, acc_contracts, qbo_vendor, qbo_customer cascade");
|
||||
await db.pool.query(`insert into qbo_vendor (realm_id, id, display_name, company_name, raw) values
|
||||
('r','V1','ACME Plumbing','ACME Plumbing LLC','{}'), ('r','V2','Twin Co','Twin Co','{}'), ('r','V3','twin co.','Twin Company','{}')`);
|
||||
await db.pool.query(`insert into qbo_customer (realm_id, id, display_name, is_job, raw) values
|
||||
('r','C1','734 Placido Ave',true,'{}'), ('r','C2','12 Oak Street',true,'{}'), ('r','C3','Smith: 55 Elm Road',true,'{}'), ('r','C4','55 Elm Road Annex',true,'{}'), ('r','C0','Smith',false,'{}')`);
|
||||
await db.pool.query("insert into acc_contracts (id, vendor_name, vendor_qbo_id, project_customer_id, total_amount) values ('00000000-0000-0000-0000-0000000000c1','ACME','V1','C1',9000)");
|
||||
});
|
||||
|
||||
it("чистый инвойс: вендор, проект, контракт найдены; Drive-папка; триггеры создали original и задачу", async () => {
|
||||
answers.a = inv({});
|
||||
const r = await run([mail("m1", "a")]);
|
||||
expect(r).toEqual({ processed: 1, created: 1, skipped: 0, errors: 0 });
|
||||
const [row] = await reviews();
|
||||
expect(row).toMatchObject({ source_message_id: "m1", drive_file_id: "drv-1", vendor_qbo_id: "V1", project_customer_id: "C1", invoice_number: "INV-1", problem_highlight: null });
|
||||
expect(row.contract_id).toBe("00000000-0000-0000-0000-0000000000c1");
|
||||
expect(Number(row.amount)).toBe(1500);
|
||||
expect(uploads[0].folder).toEqual(["Инвойсы", "ACME Plumbing LLC", "2026-03"]);
|
||||
expect((await db.pool.query("select 1 from acc_invoices_review_original where id = $1", [row.id])).rowCount).toBe(1);
|
||||
expect((await db.pool.query("select kind, ref_id from acc_manual_review")).rows).toEqual([{ kind: "invoice", ref_id: row.id }]);
|
||||
expect((await db.pool.query("select result from acc_mail_processed")).rows).toEqual([{ result: "invoice" }]);
|
||||
});
|
||||
|
||||
it("проблемы: вендор не найден, неоднозначный, проект неясен, нет контракта, tbd", async () => {
|
||||
answers.a = inv({ vendor_name: "Unknown Corp", invoice_number: "A", object_name_or_address: "99 Nowhere" });
|
||||
answers.b = inv({ vendor_name: "Twin Co", invoice_number: "B" });
|
||||
answers.c = inv({ invoice_number: "C", object_name_or_address: "12 Oak St" }); // проект есть, контракта нет
|
||||
answers.d = inv({ invoice_number: null, amount: null, invoice_date: null, lines: null, object_name_or_address: "55 Elm Rd" }); // 2 проекта
|
||||
const r = await run([mail("m1", "a", "b", "c", "d")]);
|
||||
expect(r.created).toBe(4);
|
||||
const by = Object.fromEntries((await reviews()).map((x) => [x.invoice_number ?? "none", x]));
|
||||
expect(by.A.vendor_qbo_id).toBeNull();
|
||||
expect(by.A.problem_highlight).toMatch(/не найден в QuickBooks/);
|
||||
expect(by.A.problem_highlight).toMatch(/проект неясен/);
|
||||
expect(by.B.vendor_qbo_id).toBeNull();
|
||||
expect(by.B.problem_highlight).toMatch(/неоднозначен/);
|
||||
expect(by.C.project_customer_id).toBe("C2");
|
||||
expect(by.C.problem_highlight).toMatch(/контракт.*не найден/);
|
||||
expect(by.none.problem_highlight).toMatch(/^tbd: invoice_number, invoice_date, amount, lines/);
|
||||
expect(by.none.problem_highlight).toMatch(/проект неясен \(.*совпадений 2\)/);
|
||||
expect(by.none.project_customer_id).toBeNull();
|
||||
expect((await db.pool.query("select count(*)::int n from acc_manual_review")).rows[0].n).toBe(4);
|
||||
});
|
||||
|
||||
it("проект по адресу в другом написании", async () => {
|
||||
answers.a = inv({ object_name_or_address: "734 PLACIDO AVENUE, Austin TX" });
|
||||
await run([mail("m1", "a")]);
|
||||
expect((await reviews())[0].project_customer_id).toBe("C1");
|
||||
});
|
||||
|
||||
it("дубль: в acc_invoices и в acc_invoices_review (из другого письма)", async () => {
|
||||
await db.pool.query(`insert into acc_invoices (id, source_message_id, drive_file_id, vendor_name, vendor_qbo_id, invoice_number, invoice_date, amount, project_customer_id)
|
||||
values (gen_random_uuid(),'old','f','ACME Plumbing','V1','INV-1','2026-02-01',1500,'C1')`);
|
||||
answers.a = inv({});
|
||||
answers.b = inv({ invoice_number: "INV-2" });
|
||||
answers.c = inv({ invoice_number: "INV-2" });
|
||||
await run([mail("m1", "a"), mail("m2", "b"), mail("m3", "c")]);
|
||||
const rows = await reviews();
|
||||
const dup = (n: string) => rows.filter((r) => r.invoice_number === n).map((r) => /подозрение на дубль/.test(r.problem_highlight ?? ""));
|
||||
expect(dup("INV-1")).toEqual([true]);
|
||||
expect(dup("INV-2").sort()).toEqual([false, true]); // первый чистый, второй дубль
|
||||
});
|
||||
|
||||
it("повторный запуск не плодит записи; ошибочное письмо повторяется", async () => {
|
||||
answers.a = inv({});
|
||||
const msgs = [mail("m1", "a"), mail("m2", "bad")];
|
||||
const r1 = await run(msgs);
|
||||
expect(r1).toEqual({ processed: 2, created: 1, skipped: 0, errors: 1 });
|
||||
expect((await db.pool.query("select message_id, result from acc_mail_processed order by 1")).rows).toEqual([
|
||||
{ message_id: "m1", result: "invoice" }, { message_id: "m2", result: "error" },
|
||||
]);
|
||||
const calls = claudeCalls;
|
||||
answers.bad = inv({ invoice_number: "INV-9" });
|
||||
const r2 = await run(msgs);
|
||||
expect(r2).toEqual({ processed: 1, created: 1, skipped: 0, errors: 0 }); // m1 пропущено, m2 повторено
|
||||
expect(claudeCalls).toBe(calls + 1);
|
||||
expect(await reviews()).toHaveLength(2);
|
||||
expect((await db.pool.query("select result from acc_mail_processed where message_id='m2'")).rows[0].result).toBe("invoice");
|
||||
});
|
||||
|
||||
it("частичный сбой письма: успешное вложение не дублируется при повторе", async () => {
|
||||
answers.a = inv({});
|
||||
const m = mail("m1", "a", "bad");
|
||||
const r1 = await run([m]);
|
||||
expect(r1).toMatchObject({ created: 1, errors: 1 });
|
||||
answers.bad = inv({ invoice_number: "INV-7" });
|
||||
const r2 = await run([m]);
|
||||
expect(r2).toMatchObject({ created: 1, errors: 0 });
|
||||
expect(await reviews()).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("невалидный JSON от Claude: ошибка, записей нет", async () => {
|
||||
answers.a = "извините, не могу";
|
||||
const r = await run([mail("m1", "a")]);
|
||||
expect(r).toEqual({ processed: 1, created: 0, skipped: 0, errors: 1 });
|
||||
expect(await reviews()).toHaveLength(0);
|
||||
expect(uploads).toHaveLength(0);
|
||||
expect((await db.pool.query("select details->>'message' m from acc_mail_processed")).rows[0].m).toMatch(/JSON/);
|
||||
});
|
||||
|
||||
it("письмо без инвойса: skipped, на Drive не пишем", async () => {
|
||||
answers.a = JSON.stringify({ is_invoice: false });
|
||||
const r = await run([mail("m1", "a"), { ...mail("m2"), attachments: [] }]);
|
||||
expect(r).toEqual({ processed: 2, created: 0, skipped: 2, errors: 0 });
|
||||
expect(uploads).toHaveLength(0);
|
||||
expect((await db.pool.query("select result from acc_mail_processed")).rows.map((x) => x.result)).toEqual(["skipped", "skipped"]);
|
||||
});
|
||||
|
||||
it("несколько вложений: по записи на каждый инвойс, не-инвойс пропускается", async () => {
|
||||
answers.a = inv({ invoice_number: "A1" });
|
||||
answers.b = JSON.stringify({ is_invoice: false });
|
||||
answers.c = inv({ invoice_number: "C1", vendor_name: "Twin Company" });
|
||||
const r = await run([mail("m1", "a", "b", "c")]);
|
||||
expect(r).toEqual({ processed: 1, created: 2, skipped: 0, errors: 0 });
|
||||
expect((await reviews()).map((x) => x.invoice_number)).toEqual(["A1", "C1"]);
|
||||
expect(uploads).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
321
packages/accounting_automation/src/invoices-mail.ts
Normal file
321
packages/accounting_automation/src/invoices-mail.ts
Normal file
@@ -0,0 +1,321 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { Logger, Pool } from "khb_common";
|
||||
import type { ClaudeRunner } from "./claude-runner.js";
|
||||
import type { DriveStore } from "./drive.js";
|
||||
import type { MailAttachment, MailMessage, MailSource } from "./gmail.js";
|
||||
|
||||
export interface InvoiceIngestDeps {
|
||||
pool: Pool;
|
||||
mail: MailSource;
|
||||
drive: DriveStore;
|
||||
claude: ClaudeRunner;
|
||||
now(): Date;
|
||||
log: Logger;
|
||||
/** Сколько писем брать за запуск (по умолчанию 20). */
|
||||
limit?: number;
|
||||
/** Куда класть временные PDF для чтения агентом (по умолчанию os.tmpdir()). */
|
||||
tmpDir?: string;
|
||||
}
|
||||
export interface InvoiceIngestResult {
|
||||
/** Писем обработано (любой итог, включая ошибку). */
|
||||
processed: number;
|
||||
/** Создано записей acc_invoices_review. */
|
||||
created: number;
|
||||
/** Писем без инвойса. */
|
||||
skipped: number;
|
||||
errors: number;
|
||||
}
|
||||
|
||||
export interface RecognizedInvoice {
|
||||
is_invoice: boolean;
|
||||
vendor_name: string | null;
|
||||
invoice_number: string | null;
|
||||
invoice_date: string | null;
|
||||
amount: number | null;
|
||||
lines: { description: string; amount: number | null }[] | null;
|
||||
object_name_or_address: string | null;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------- нормализация и разбор
|
||||
|
||||
const COMPANY_SUFFIX = new Set(["llc", "inc", "corp", "co", "ltd", "company", "corporation", "incorporated", "lp", "llp", "pllc"]);
|
||||
|
||||
/** Имя вендора для сравнения: регистр, знаки, юридические суффиксы. */
|
||||
export function normalizeVendorName(s: string | null | undefined): string {
|
||||
const words = (s ?? "")
|
||||
.toLowerCase()
|
||||
.replace(/&/g, " and ")
|
||||
.replace(/[^a-z0-9а-яё]+/g, " ")
|
||||
.split(" ")
|
||||
.filter(Boolean);
|
||||
while (words.length > 1 && COMPANY_SUFFIX.has(words[words.length - 1]!)) words.pop();
|
||||
return words.join(" ");
|
||||
}
|
||||
|
||||
const STREET_WORDS: Record<string, string> = { street: "st", avenue: "ave", road: "rd", drive: "dr", lane: "ln", court: "ct", boulevard: "blvd", place: "pl", terrace: "ter", circle: "cir", way: "way" };
|
||||
|
||||
/** Объект/адрес для сравнения: регистр, знаки, сокращения улиц. */
|
||||
export function normalizeAddress(s: string | null | undefined): string {
|
||||
return (s ?? "")
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9а-яё]+/g, " ")
|
||||
.split(" ")
|
||||
.filter(Boolean)
|
||||
.map((w) => STREET_WORDS[w] ?? w)
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
/** Ключ «номер дома + первое слово улицы» (например, «734 placido»); null, если номера нет. */
|
||||
export function addressKey(s: string | null | undefined): string | null {
|
||||
const m = normalizeAddress(s).match(/(?:^|\s)(\d{1,6})\s+([a-zа-яё0-9]+)/);
|
||||
return m ? `${m[1]} ${m[2]}` : null;
|
||||
}
|
||||
|
||||
export function parseAmount(v: unknown): number | null {
|
||||
if (typeof v === "number") return Number.isFinite(v) ? Math.round(v * 100) / 100 : null;
|
||||
if (typeof v === "string") {
|
||||
const n = Number(v.replace(/[^0-9.\-]/g, ""));
|
||||
return v.trim() !== "" && Number.isFinite(n) ? Math.round(n * 100) / 100 : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseDate(v: unknown): string | null {
|
||||
if (typeof v !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(v)) return null;
|
||||
const d = new Date(`${v}T00:00:00Z`);
|
||||
return Number.isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== v ? null : v;
|
||||
}
|
||||
|
||||
const str = (v: unknown): string | null => (typeof v === "string" && v.trim() ? v.trim() : null);
|
||||
|
||||
/** Достаёт JSON-объект из ответа агента (допускает ```json-обёртку и текст вокруг). */
|
||||
export function parseRecognition(stdout: string): RecognizedInvoice {
|
||||
const a = stdout.indexOf("{");
|
||||
const b = stdout.lastIndexOf("}");
|
||||
if (a < 0 || b <= a) throw new Error("агент не вернул JSON");
|
||||
let j: Record<string, unknown>;
|
||||
try {
|
||||
j = JSON.parse(stdout.slice(a, b + 1)) as Record<string, unknown>;
|
||||
} catch (e) {
|
||||
throw new Error(`агент вернул невалидный JSON: ${(e as Error).message}`);
|
||||
}
|
||||
if (typeof j.is_invoice !== "boolean") throw new Error("в JSON агента нет поля is_invoice");
|
||||
const lines = Array.isArray(j.lines)
|
||||
? j.lines
|
||||
.filter((l): l is Record<string, unknown> => !!l && typeof l === "object")
|
||||
.map((l) => ({ description: str(l.description) ?? "", amount: parseAmount(l.amount) }))
|
||||
: null;
|
||||
return {
|
||||
is_invoice: j.is_invoice,
|
||||
vendor_name: str(j.vendor_name),
|
||||
invoice_number: str(j.invoice_number) ?? (typeof j.invoice_number === "number" ? String(j.invoice_number) : null),
|
||||
invoice_date: parseDate(j.invoice_date),
|
||||
amount: parseAmount(j.amount),
|
||||
lines: lines && lines.length ? lines : null,
|
||||
object_name_or_address: str(j.object_name_or_address),
|
||||
};
|
||||
}
|
||||
|
||||
/** Детерминированный uuid записи инвойса: письмо + номер вложения + имя файла (повторный запуск не плодит дубли). */
|
||||
export function invoiceReviewId(messageId: string, index: number, filename: string): string {
|
||||
const h = createHash("sha1").update(`${messageId}\n${index}\n${filename}`).digest("hex");
|
||||
const variant = ((parseInt(h.slice(16, 18), 16) & 0x3f) | 0x80).toString(16).padStart(2, "0");
|
||||
return `${h.slice(0, 8)}-${h.slice(8, 12)}-5${h.slice(13, 16)}-${variant}${h.slice(18, 20)}-${h.slice(20, 32)}`;
|
||||
}
|
||||
|
||||
export function buildRecognitionPrompt(pdfPath: string, mail: { from: string; subject: string }): string {
|
||||
return [
|
||||
"Ты распознаёшь счета (invoice) подрядчиков строительной компании.",
|
||||
`Прочитай PDF-файл ${pdfPath} (письмо от ${mail.from}, тема «${mail.subject}») и верни ТОЛЬКО один JSON-объект, без пояснений и без markdown.`,
|
||||
"Поля JSON:",
|
||||
'- is_invoice: true, если документ - счёт/инвойс подрядчика к оплате; false для всего остального (КП, чек, страховка, реклама и т.п.)',
|
||||
"- vendor_name: название компании, которая выставила счёт (не получатель)",
|
||||
"- invoice_number: номер счёта",
|
||||
"- invoice_date: дата счёта в формате YYYY-MM-DD",
|
||||
"- amount: итоговая сумма к оплате, число в долларах",
|
||||
'- lines: массив строк счёта [{"description": "за что", "amount": число}]',
|
||||
"- object_name_or_address: название объекта или адрес, к которому относятся работы (Job, Project, Ship to, Site)",
|
||||
"Если значение в документе не найдено, ставь null (не выдумывай).",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------- сопоставление со справочниками
|
||||
|
||||
interface Resolved {
|
||||
vendorQboId: string | null;
|
||||
projectCustomerId: string | null;
|
||||
contractId: string | null;
|
||||
problems: string[];
|
||||
}
|
||||
|
||||
async function resolveVendor(pool: Pool, name: string | null): Promise<{ id: string | null; problem?: string }> {
|
||||
if (!name) return { id: null };
|
||||
const want = normalizeVendorName(name);
|
||||
const { rows } = await pool.query<{ id: string; display_name: string; company_name: string | null }>(
|
||||
"select distinct id, display_name, company_name from qbo_vendor where active",
|
||||
);
|
||||
const ids = new Set<string>();
|
||||
for (const r of rows) if (normalizeVendorName(r.display_name) === want || (r.company_name && normalizeVendorName(r.company_name) === want)) ids.add(r.id);
|
||||
if (ids.size === 1) return { id: [...ids][0]! };
|
||||
if (ids.size > 1) return { id: null, problem: `вендор «${name}» неоднозначен в QuickBooks (${ids.size} совпадений)` };
|
||||
return { id: null, problem: `вендор «${name}» не найден в QuickBooks` };
|
||||
}
|
||||
|
||||
async function resolveProject(pool: Pool, object: string | null): Promise<{ id: string | null; problem?: string }> {
|
||||
if (!object) return { id: null, problem: "проект неясен: в инвойсе нет названия объекта или адреса" };
|
||||
const want = normalizeAddress(object);
|
||||
const wantKey = addressKey(object);
|
||||
const { rows } = await pool.query<{ id: string; display_name: string; fully_qualified_name: string | null }>(
|
||||
"select distinct id, display_name, fully_qualified_name from qbo_customer where is_job and active",
|
||||
);
|
||||
const ids = new Set<string>();
|
||||
for (const r of rows) {
|
||||
for (const n of [r.display_name, r.fully_qualified_name]) {
|
||||
if (!n) continue;
|
||||
const cn = normalizeAddress(n);
|
||||
if (!cn) continue;
|
||||
const ck = addressKey(n);
|
||||
if ((wantKey && ck && wantKey === ck) || cn === want || (cn.length >= 5 && want.includes(cn)) || (want.length >= 5 && cn.includes(want))) {
|
||||
ids.add(r.id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ids.size === 1) return { id: [...ids][0]! };
|
||||
return { id: null, problem: `проект неясен (объект в инвойсе: «${object}», совпадений ${ids.size})` };
|
||||
}
|
||||
|
||||
async function resolveAll(pool: Pool, r: RecognizedInvoice): Promise<Resolved> {
|
||||
const problems: string[] = [];
|
||||
const v = await resolveVendor(pool, r.vendor_name);
|
||||
if (v.problem) problems.push(v.problem);
|
||||
const p = await resolveProject(pool, r.object_name_or_address);
|
||||
if (p.problem) problems.push(p.problem);
|
||||
let contractId: string | null = null;
|
||||
if (v.id && p.id) {
|
||||
const { rows } = await pool.query<{ id: string }>("select id from acc_contracts where vendor_qbo_id = $1 and project_customer_id = $2", [v.id, p.id]);
|
||||
if (rows.length === 1) contractId = rows[0]!.id;
|
||||
else problems.push(rows.length ? "контракт неоднозначен (несколько контрактов вендора на проекте)" : "контракт вендора на этом проекте не найден");
|
||||
}
|
||||
return { vendorQboId: v.id, projectCustomerId: p.id, contractId, problems };
|
||||
}
|
||||
|
||||
async function isDuplicate(pool: Pool, id: string, vendorQboId: string | null, r: RecognizedInvoice): Promise<boolean> {
|
||||
if (!r.invoice_number || r.amount == null || !r.vendor_name) return false;
|
||||
const vendorName = normalizeVendorName(r.vendor_name);
|
||||
for (const t of ["acc_invoices", "acc_invoices_review"]) {
|
||||
const { rows } = await pool.query<{ vendor_name: string | null; vendor_qbo_id: string | null }>(
|
||||
`select vendor_name, vendor_qbo_id from ${t} where id <> $1 and invoice_number = $2 and amount = $3`,
|
||||
[id, r.invoice_number, r.amount],
|
||||
);
|
||||
if (rows.some((x) => (vendorQboId && x.vendor_qbo_id === vendorQboId) || normalizeVendorName(x.vendor_name) === vendorName)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const safeName = (s: string): string => s.replace(/[\\/:*?"<>|\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, 100) || "_";
|
||||
const ym = (d: Date): string => d.toISOString().slice(0, 7);
|
||||
|
||||
// ----------------------------------------------------------------- основной процесс
|
||||
|
||||
async function recognize(deps: InvoiceIngestDeps, msg: MailMessage, att: MailAttachment, bytes: Buffer): Promise<RecognizedInvoice> {
|
||||
const dir = join(deps.tmpDir ?? tmpdir(), `acc-invoice-${createHash("sha1").update(`${msg.id}${att.filename}${deps.now().getTime()}${Math.random()}`).digest("hex").slice(0, 12)}`);
|
||||
await mkdir(dir, { recursive: true });
|
||||
try {
|
||||
const path = join(dir, "invoice.pdf");
|
||||
await writeFile(path, bytes);
|
||||
const res = await deps.claude({ prompt: buildRecognitionPrompt(path, msg), cwd: dir });
|
||||
if (!res.ok) throw new Error(`Claude не отработал (код ${res.exitCode}${res.timedOut ? ", таймаут" : ""}): ${res.stderr.slice(0, 200)}`);
|
||||
return parseRecognition(res.stdout);
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** Результат по одному вложению: created - новая запись; existing - запись уже есть; none - не инвойс. */
|
||||
async function processAttachment(deps: InvoiceIngestDeps, msg: MailMessage, att: MailAttachment, index: number): Promise<"created" | "existing" | "none"> {
|
||||
const { pool } = deps;
|
||||
const id = invoiceReviewId(msg.id, index, att.filename);
|
||||
const ex = await pool.query(
|
||||
"select 1 from acc_invoices_review where id = $1 union all select 1 from acc_invoices_review_history where id = $1 union all select 1 from acc_invoices where id = $1",
|
||||
[id],
|
||||
);
|
||||
if (ex.rowCount) return "existing";
|
||||
|
||||
const bytes = await att.getBytes();
|
||||
const rec = await recognize(deps, msg, att, bytes);
|
||||
if (!rec.is_invoice) return "none";
|
||||
|
||||
const resolved = await resolveAll(pool, rec);
|
||||
const problems = [...resolved.problems];
|
||||
if (await isDuplicate(pool, id, resolved.vendorQboId, rec)) problems.push("подозрение на дубль (тот же вендор, номер и сумма уже есть)");
|
||||
const tbd: string[] = [];
|
||||
if (!rec.vendor_name) tbd.push("vendor_name");
|
||||
if (!rec.invoice_number) tbd.push("invoice_number");
|
||||
if (!rec.invoice_date) tbd.push("invoice_date");
|
||||
if (rec.amount == null) tbd.push("amount");
|
||||
if (!rec.lines) tbd.push("lines");
|
||||
if (tbd.length) problems.unshift(`tbd: ${tbd.join(", ")}`);
|
||||
|
||||
const refDate = rec.invoice_date ? new Date(`${rec.invoice_date}T00:00:00Z`) : msg.receivedAt;
|
||||
const folder = await deps.drive.ensureFolder(["Инвойсы", safeName(rec.vendor_name ?? "Без вендора"), ym(refDate)]);
|
||||
const file = await deps.drive.upload(att.filename, att.mime || "application/pdf", bytes, folder);
|
||||
|
||||
await pool.query(
|
||||
`insert into acc_invoices_review (id, source_message_id, drive_file_id, vendor_name, vendor_qbo_id, invoice_number, invoice_date, amount, lines,
|
||||
project_customer_id, contract_id, problem_highlight)
|
||||
values ($1,$2,$3,$4,$5,$6,$7,$8,$9::jsonb,$10,$11,$12)
|
||||
on conflict (id) do nothing`,
|
||||
[
|
||||
id, msg.id, file.id, rec.vendor_name, resolved.vendorQboId, rec.invoice_number, rec.invoice_date, rec.amount,
|
||||
rec.lines ? JSON.stringify(rec.lines) : null, resolved.projectCustomerId, resolved.contractId, problems.length ? problems.join("; ") : null,
|
||||
],
|
||||
);
|
||||
return "created";
|
||||
}
|
||||
|
||||
async function markMail(pool: Pool, messageId: string, result: "invoice" | "skipped" | "error", details: unknown): Promise<void> {
|
||||
await pool.query(
|
||||
`insert into acc_mail_processed (message_id, result, details) values ($1,$2,$3::jsonb)
|
||||
on conflict (message_id) do update set result = excluded.result, details = excluded.details, processed_at = now()`,
|
||||
[messageId, result, JSON.stringify(details)],
|
||||
);
|
||||
}
|
||||
|
||||
/** Шаги 4.1-4.3 и 5 процесса «Обработка Invoice от подрядчика»: почта -> Drive -> распознавание -> acc_invoices_review. */
|
||||
export async function runInvoiceIngest(deps: InvoiceIngestDeps): Promise<InvoiceIngestResult> {
|
||||
const { pool, log } = deps;
|
||||
const out: InvoiceIngestResult = { processed: 0, created: 0, skipped: 0, errors: 0 };
|
||||
const messages = await deps.mail.listUnprocessed(deps.limit ?? 20);
|
||||
for (const msg of messages) {
|
||||
const prev = await pool.query<{ result: string }>("select result from acc_mail_processed where message_id = $1", [msg.id]);
|
||||
if (prev.rows[0] && prev.rows[0].result !== "error") continue;
|
||||
out.processed++;
|
||||
try {
|
||||
const pdfs = msg.attachments.filter((a) => a.mime.toLowerCase() === "application/pdf" || a.filename.toLowerCase().endsWith(".pdf"));
|
||||
let invoices = 0;
|
||||
let created = 0;
|
||||
for (const [i, att] of pdfs.entries()) {
|
||||
const r = await processAttachment(deps, msg, att, i);
|
||||
if (r !== "none") invoices++;
|
||||
if (r === "created") {
|
||||
created++;
|
||||
out.created++;
|
||||
}
|
||||
}
|
||||
if (invoices > 0) await markMail(pool, msg.id, "invoice", { attachments: pdfs.length, invoices, created });
|
||||
else {
|
||||
out.skipped++;
|
||||
await markMail(pool, msg.id, "skipped", { attachments: pdfs.length, reason: pdfs.length ? "не инвойс" : "нет PDF" });
|
||||
}
|
||||
} catch (e) {
|
||||
out.errors++;
|
||||
log.error({ err: e, messageId: msg.id }, "ошибка обработки письма с инвойсом");
|
||||
await markMail(pool, msg.id, "error", { message: (e as Error).message });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
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());
|
||||
81
packages/accounting_automation/src/mcp-auth.ts
Normal file
81
packages/accounting_automation/src/mcp-auth.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
import { createRemoteJWKSet, jwtVerify, type JWTVerifyGetKey } from "jose";
|
||||
import type { Pool } from "khb_common";
|
||||
import type { AccountingSettings } from "./settings.js";
|
||||
|
||||
/** Ошибка аутентификации MCP: status 401 (токен не принят) или 403 (токен верный, но человека в системе нет). */
|
||||
export class McpAuthError extends Error {
|
||||
constructor(message: string, readonly status: 401 | 403 = 401) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** Содержимое проверенного JWT, нужное нам. */
|
||||
export interface VerifiedJwt {
|
||||
email?: string;
|
||||
emailVerified?: boolean;
|
||||
}
|
||||
/** Проверка JWT (подпись, срок, issuer). Бросает исключение, если токен не годится. Внедряется для тестов. */
|
||||
export type JwtVerifier = (token: string) => Promise<VerifiedJwt>;
|
||||
|
||||
export const safeEqual = (a: string, b: string): boolean => {
|
||||
const x = Buffer.from(a);
|
||||
const y = Buffer.from(b);
|
||||
return x.length === y.length && timingSafeEqual(x, y);
|
||||
};
|
||||
|
||||
export const bearerToken = (h: string | undefined): string | null => (h && /^Bearer\s/i.test(h) ? h.slice(7).trim() || null : null);
|
||||
|
||||
/** Проверка JWT Keycloak: ключи берутся из getKey (по умолчанию - JWKS издателя; в тестах - локальный набор ключей). */
|
||||
export function keycloakVerifier(issuer: string, getKey?: JWTVerifyGetKey, audience?: string): JwtVerifier {
|
||||
const iss = issuer.replace(/\/$/, "");
|
||||
const keys = getKey ?? createRemoteJWKSet(new URL(`${iss}/protocol/openid-connect/certs`));
|
||||
return async (token) => {
|
||||
const { payload } = await jwtVerify(token, keys, { issuer: [iss, `${iss}/`], ...(audience ? { audience } : {}) });
|
||||
return {
|
||||
email: typeof payload.email === "string" ? payload.email : undefined,
|
||||
emailVerified: typeof payload.email_verified === "boolean" ? payload.email_verified : undefined,
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export interface McpAuthDeps {
|
||||
pool: Pool;
|
||||
settings: Pick<AccountingSettings, "mcp">;
|
||||
/** Если не задана, а в настройках есть mcp.issuer - используется keycloakVerifier(issuer). */
|
||||
verifyJwt?: JwtVerifier;
|
||||
}
|
||||
|
||||
/** Возвращает функцию «заголовок Authorization -> person_id». Статические токены, затем JWT Keycloak (person по email). */
|
||||
export function createMcpAuth(deps: McpAuthDeps): (authorization: string | undefined) => Promise<{ personId: string }> {
|
||||
const { pool, settings } = deps;
|
||||
const verify = deps.verifyJwt ?? (settings.mcp.issuer ? keycloakVerifier(settings.mcp.issuer) : undefined);
|
||||
return async (authorization) => {
|
||||
const t = bearerToken(authorization);
|
||||
if (!t) throw new McpAuthError("нужен заголовок Authorization: Bearer <токен>", 401);
|
||||
const st = settings.mcp.staticTokens.find((x) => safeEqual(t, x.token));
|
||||
if (st) return { personId: st.personId };
|
||||
if (!verify) throw new McpAuthError("токен не принят", 401);
|
||||
let email: string | undefined;
|
||||
try {
|
||||
const v = await verify(t);
|
||||
if (v.emailVerified === false) throw new Error("email не подтверждён");
|
||||
email = v.email;
|
||||
} catch {
|
||||
throw new McpAuthError("токен не принят", 401);
|
||||
}
|
||||
if (!email) throw new McpAuthError("в токене нет email", 401);
|
||||
const p = (
|
||||
await pool.query(
|
||||
`select id from person
|
||||
where is_active
|
||||
and (lower(email) = lower($1)
|
||||
or exists (select 1 from unnest(string_to_array(lower(coalesce(additional_emails, '')), ';')) e where btrim(e) = lower($1)))
|
||||
limit 1`,
|
||||
[email],
|
||||
)
|
||||
).rows[0];
|
||||
if (!p) throw new McpAuthError(`для ${email} нет активного person: доступ запрещён`, 403);
|
||||
return { personId: String(p.id) };
|
||||
};
|
||||
}
|
||||
290
packages/accounting_automation/src/mcp.int.test.ts
Normal file
290
packages/accounting_automation/src/mcp.int.test.ts
Normal file
@@ -0,0 +1,290 @@
|
||||
import Fastify from "fastify";
|
||||
import { exportJWK, generateKeyPair, SignJWT, createLocalJWKSet } from "jose";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { createTestDb, testDatabaseUrl, type TestDb } from "khb_common";
|
||||
import { keycloakVerifier } from "./mcp-auth.js";
|
||||
import { ReviewTools, registerMcp, type McpDeps } from "./mcp.js";
|
||||
|
||||
const url = testDatabaseUrl();
|
||||
const d = url ? describe : describe.skip;
|
||||
|
||||
const ISSUER = "https://sso.example.test/realms/khb";
|
||||
const TOKEN_A = "token-accountant-0123456789";
|
||||
const TOKEN_CFO = "token-cfo-0123456789abcd";
|
||||
const NOW = new Date("2026-11-17T12:00:00Z");
|
||||
|
||||
d("MCP бухгалтерии (временная БД)", () => {
|
||||
let db: TestDb;
|
||||
let accountant: string; // только роль accountant
|
||||
let cfo: string; // accountant + cfo
|
||||
let stranger: string; // не в reviewers
|
||||
let kc: string; // person с email из Keycloak, роль accountant
|
||||
let settings: McpDeps["settings"];
|
||||
let tools: ReviewTools;
|
||||
let signer: Awaited<ReturnType<typeof generateKeyPair>>["privateKey"];
|
||||
let verifyJwt: McpDeps["verifyJwt"];
|
||||
|
||||
const call = (who: string, name: string, args: Record<string, unknown> = {}) => tools.call(who, name, args);
|
||||
const errOf = async (p: Promise<unknown>): Promise<string> => {
|
||||
try {
|
||||
await p;
|
||||
} catch (e) {
|
||||
return (e as Error).message;
|
||||
}
|
||||
return "NO ERROR";
|
||||
};
|
||||
const addInvoice = async (extra: Record<string, unknown> = {}) => {
|
||||
const r = await db.pool.query(
|
||||
`insert into acc_invoices_review (source_message_id, drive_file_id, vendor_name, amount, problem_highlight)
|
||||
values ('m1', 'drv1', $1, 100, $2) returning id`,
|
||||
[extra.vendor ?? "Vendor A", extra.problem ?? null],
|
||||
);
|
||||
return (await db.pool.query("select id from acc_manual_review where ref_id = $1", [r.rows[0].id])).rows[0].id as string;
|
||||
};
|
||||
const addCat = async (feed: string, problem: string | null = null) => {
|
||||
await db.pool.query(
|
||||
`insert into acc_categorization_review (feed_txn_id, run_id, run_started_at, suggestion, confidence, problem_highlight)
|
||||
values ($1, 'run1', now(), '{"account":"Materials"}', 80, $2)`,
|
||||
[feed, problem],
|
||||
);
|
||||
return (await db.pool.query("select id from acc_manual_review where ref_id = $1", [feed])).rows[0].id as string;
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
db = await createTestDb(url!);
|
||||
const mk = async (name: string, email: string, extra = "null", active = true) =>
|
||||
(await db.pool.query("insert into person (display_name, email, additional_emails, is_active) values ($1, $2, $3, $4) returning id", [name, email, extra === "null" ? null : extra, active])).rows[0].id as string;
|
||||
accountant = await mk("Юля", "yulia@khbuild.pro");
|
||||
cfo = await mk("Анастасия", "anastasia@khbuild.pro");
|
||||
stranger = await mk("Чужой", "x@khbuild.pro");
|
||||
kc = await mk("KC", "kc@khbuild.pro", "other@gmail.com; kc.alias@gmail.com");
|
||||
await mk("Неактивный", "off@khbuild.pro", "null", false);
|
||||
settings = {
|
||||
reviewers: [
|
||||
{ personId: accountant, roles: ["accountant"] },
|
||||
{ personId: cfo, roles: ["accountant", "cfo"] },
|
||||
{ personId: kc, roles: ["accountant"] },
|
||||
],
|
||||
mcp: { enabled: true, issuer: ISSUER, staticTokens: [{ token: TOKEN_A, personId: accountant }, { token: TOKEN_CFO, personId: cfo }, { token: "token-stranger-0123456789", personId: stranger }] },
|
||||
};
|
||||
tools = new ReviewTools({ pool: db.pool, settings, now: () => NOW });
|
||||
const { privateKey, publicKey } = await generateKeyPair("RS256");
|
||||
signer = privateKey;
|
||||
const jwk = { ...(await exportJWK(publicKey)), kid: "k1", alg: "RS256", use: "sig" };
|
||||
verifyJwt = keycloakVerifier(ISSUER, createLocalJWKSet({ keys: [jwk] }));
|
||||
});
|
||||
afterAll(async () => {
|
||||
await db?.drop();
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await db.pool.query("truncate acc_manual_review, acc_invoices_review, acc_invoices_review_original, acc_categorization_review, acc_categorization_review_original, acc_certificates_review, acc_certificates_review_original cascade");
|
||||
});
|
||||
|
||||
describe("чистый слой", () => {
|
||||
it("без записи в reviewers доступ запрещён, пустые reviewers - тоже", async () => {
|
||||
expect(await errOf(call(stranger, "acc_review_list"))).toContain("Доступ запрещён");
|
||||
const empty = new ReviewTools({ pool: db.pool, settings: { reviewers: [] }, now: () => NOW });
|
||||
expect(await errOf(empty.call(cfo, "acc_review_list", {}))).toContain("Доступ запрещён");
|
||||
});
|
||||
|
||||
it("список: видимость по ролям, сортировка с проблемой вперёд, данные строк, ссылка на файл", async () => {
|
||||
await addInvoice();
|
||||
const withProblem = await addCat("f1", "ждёт документ");
|
||||
const cfoTask = await addCat("f2");
|
||||
await db.pool.query("update acc_manual_review set assignee_role = 'cfo' where id = $1", [cfoTask]);
|
||||
const y = (await call(accountant, "acc_review_list")) as { total: number; tasks: Array<Record<string, any>> };
|
||||
expect(y.total).toBe(2);
|
||||
expect(y.tasks[0].id).toBe(withProblem);
|
||||
expect(y.tasks[0].review.feed_txn_id).toBe("f1");
|
||||
expect(y.tasks[0].review.run_id).toBe("run1");
|
||||
expect(y.tasks[0].review.confidence).toBe(80);
|
||||
expect(y.tasks[0].problem_highlight).toBe("ждёт документ");
|
||||
expect(y.tasks[1].kind).toBe("invoice");
|
||||
expect(y.tasks[1].file_url).toBe("https://drive.google.com/file/d/drv1/view");
|
||||
expect(y.tasks.map((t) => t.id)).not.toContain(cfoTask);
|
||||
const a = (await call(cfo, "acc_review_list")) as { total: number };
|
||||
expect(a.total).toBe(3);
|
||||
const onlyCfo = (await call(cfo, "acc_review_list", { role: "cfo" })) as { tasks: Array<{ id: string }> };
|
||||
expect(onlyCfo.tasks.map((t) => t.id)).toEqual([cfoTask]);
|
||||
expect(await errOf(call(accountant, "acc_review_list", { role: "cfo" }))).toContain("нет роли cfo");
|
||||
const k = (await call(cfo, "acc_review_list", { kind: "invoice" })) as { total: number };
|
||||
expect(k.total).toBe(1);
|
||||
});
|
||||
|
||||
it("отложенные скрыты, include_snoozed их показывает; выполненные скрыты", async () => {
|
||||
const t1 = await addInvoice();
|
||||
const t2 = await addInvoice();
|
||||
await call(accountant, "acc_review_snooze", { id: t1, until: "2026-11-20" });
|
||||
expect(((await call(accountant, "acc_review_list")) as { total: number }).total).toBe(1);
|
||||
expect(((await call(accountant, "acc_review_list", { include_snoozed: true })) as { total: number }).total).toBe(2);
|
||||
await call(accountant, "acc_review_done", { id: t2 });
|
||||
expect(((await call(accountant, "acc_review_list")) as { total: number }).total).toBe(0);
|
||||
expect(await errOf(call(accountant, "acc_review_snooze", { id: t1, until: "2026-11-01" }))).toContain("в будущем");
|
||||
expect(await errOf(call(accountant, "acc_review_snooze", { id: t1, until: "завтра" }))).toContain("until");
|
||||
});
|
||||
|
||||
it("get: задача, строка, original, изменённые поля, ссылка", async () => {
|
||||
const t = await addInvoice();
|
||||
await call(accountant, "acc_review_update", { id: t, fields: { vendor_name: "Vendor B" } });
|
||||
const g = (await call(accountant, "acc_review_get", { id: t })) as Record<string, any>;
|
||||
expect(g.review.vendor_name).toBe("Vendor B");
|
||||
expect(g.original.vendor_name).toBe("Vendor A");
|
||||
expect(g.changed_fields).toEqual(["vendor_name"]);
|
||||
expect(g.file_url).toBe("https://drive.google.com/file/d/drv1/view");
|
||||
expect(await errOf(call(accountant, "acc_review_get", { id: "not-uuid" }))).toContain("uuid");
|
||||
});
|
||||
|
||||
it("update: белый список, типы, null, запрет чужих колонок", async () => {
|
||||
const t = await addInvoice();
|
||||
const r = (await call(accountant, "acc_review_update", {
|
||||
id: t,
|
||||
fields: { invoice_number: "INV-7", invoice_date: "2026-11-01", amount: "250.5", lines: [{ what: "work", sum: 250.5 }], problem_highlight: null },
|
||||
})) as { review: Record<string, any> };
|
||||
expect(r.review.invoice_number).toBe("INV-7");
|
||||
expect(r.review.invoice_date).toBe("2026-11-01");
|
||||
expect(r.review.amount).toBe(250.5);
|
||||
expect(r.review.lines).toEqual([{ what: "work", sum: 250.5 }]);
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: { done: true } }))).toContain("править нельзя");
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: { drive_file_id: "x" } }))).toContain("править нельзя");
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: { invoice_date: "01.11.2026" } }))).toContain("YYYY-MM-DD");
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: { amount: "abc" } }))).toContain("число");
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: {} }))).toContain("fields");
|
||||
// отказ откатывает всю правку целиком
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: { vendor_name: "ZZ", amount: "bad" } }))).toContain("amount");
|
||||
expect((await db.pool.query("select vendor_name from acc_invoices_review")).rows[0].vendor_name).toBe("Vendor A");
|
||||
// категоризация и сертификат
|
||||
const c = await addCat("f9");
|
||||
const cr = (await call(accountant, "acc_review_update", { id: c, fields: { suggestion: { account: "Tools" }, confidence: 55, problem_highlight: "проверить" } })) as { review: Record<string, any> };
|
||||
expect(cr.review.suggestion).toEqual({ account: "Tools" });
|
||||
expect(cr.review.confidence).toBe(55);
|
||||
expect((await db.pool.query("select problem_highlight from acc_manual_review where id = $1", [c])).rows[0].problem_highlight).toBe("проверить");
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: c, fields: { confidence: 101 } }))).toContain("0..100");
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: c, fields: { run_id: "x" } }))).toContain("править нельзя");
|
||||
await db.pool.query("insert into acc_certificates_review (vendor_name) values ('V')");
|
||||
const cert = (await db.pool.query("select id from acc_manual_review where kind = 'certificate'")).rows[0].id;
|
||||
const ce = (await call(accountant, "acc_review_update", { id: cert, fields: { expires_on: "2027-01-31", vendor_qbo_id: "q1" } })) as { review: Record<string, any> };
|
||||
expect(ce.review.expires_on).toBe("2027-01-31");
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: cert, fields: { amount: 1 } }))).toContain("править нельзя");
|
||||
});
|
||||
|
||||
it("чужая роль: нельзя читать, править, закрывать; cfo-задачу категоризации закрывает только cfo", async () => {
|
||||
const t = await addCat("f3");
|
||||
await db.pool.query("update acc_manual_review set assignee_role = 'cfo' where id = $1", [t]);
|
||||
for (const n of ["acc_review_get", "acc_review_done", "acc_review_return", "acc_review_snooze", "acc_review_handoff", "acc_review_update"]) {
|
||||
const m = await errOf(call(accountant, n, { id: t, until: "2026-12-01", reason: "r", role: "accountant", fields: { confidence: 1 } }));
|
||||
expect(m, n).toContain("роли cfo");
|
||||
}
|
||||
expect(await errOf(call(accountant, "acc_review_done", { id: t }))).toMatch(/cfo/);
|
||||
await call(cfo, "acc_review_done", { id: t });
|
||||
const row = (await db.pool.query("select done, done_by from acc_categorization_review")).rows[0];
|
||||
expect(row).toEqual({ done: true, done_by: cfo });
|
||||
});
|
||||
|
||||
it("done: отмечает done и done_by, повтор - ошибка; нет задачи - ошибка", async () => {
|
||||
const t = await addInvoice();
|
||||
await call(accountant, "acc_review_done", { id: t });
|
||||
expect((await db.pool.query("select done, done_by from acc_invoices_review")).rows[0]).toEqual({ done: true, done_by: accountant });
|
||||
expect(await errOf(call(accountant, "acc_review_done", { id: t }))).toContain("уже отмечена");
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: { vendor_name: "Q" } }))).toContain("уже отмечена");
|
||||
expect(await errOf(call(accountant, "acc_review_done", { id: "00000000-0000-4000-8000-000000000000" }))).toContain("не найдена");
|
||||
});
|
||||
|
||||
it("handoff меняет роль и дописывает комментарий; return возвращает accountant с причиной и снимает snooze", async () => {
|
||||
const t = await addCat("f4", "крупная сумма");
|
||||
const h = (await call(accountant, "acc_review_handoff", { id: t, role: "cfo", comment: "сумма $6000" })) as { task: Record<string, any> };
|
||||
expect(h.task.assignee_role).toBe("cfo");
|
||||
expect(h.task.problem_highlight).toBe("крупная сумма | Передано accountant -> cfo: сумма $6000");
|
||||
expect((await db.pool.query("select problem_highlight from acc_categorization_review")).rows[0].problem_highlight).toContain("сумма $6000");
|
||||
// после передачи accountant задачу больше не видит
|
||||
expect(await errOf(call(accountant, "acc_review_get", { id: t }))).toContain("роли cfo");
|
||||
expect(await errOf(call(cfo, "acc_review_handoff", { id: t, role: "cfo" }))).toContain("уже назначена");
|
||||
expect(await errOf(call(cfo, "acc_review_handoff", { id: t, role: "boss" }))).toContain("role");
|
||||
await call(cfo, "acc_review_snooze", { id: t, until: "2026-12-01" });
|
||||
const r = (await call(cfo, "acc_review_return", { id: t, reason: "нет документа" })) as { task: Record<string, any> };
|
||||
expect(r.task.assignee_role).toBe("accountant");
|
||||
expect(r.task.snoozed_until).toBeNull();
|
||||
expect(r.task.problem_highlight).toBe("Возвращено: нет документа");
|
||||
expect(await errOf(call(cfo, "acc_review_return", { id: t, reason: " " }))).toContain("причина");
|
||||
});
|
||||
|
||||
it("вид без review-таблицы: виден, но правка и закрытие запрещены; handoff/return работают", async () => {
|
||||
const t = (await db.pool.query("insert into acc_manual_review (kind, ref_table, ref_id) values ('chargeback', 'acc_chargeback', 'x1') returning id")).rows[0].id;
|
||||
expect(((await call(accountant, "acc_review_list")) as { total: number }).total).toBe(1);
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: { a: 1 } }))).toContain("не предусмотрена");
|
||||
expect(await errOf(call(accountant, "acc_review_done", { id: t }))).toContain("нельзя");
|
||||
await call(accountant, "acc_review_return", { id: t, reason: "уточнить" });
|
||||
expect((await db.pool.query("select problem_highlight from acc_manual_review where id = $1", [t])).rows[0].problem_highlight).toBe("Возвращено: уточнить");
|
||||
});
|
||||
});
|
||||
|
||||
describe("HTTP", () => {
|
||||
const post = async (headers: Record<string, string>, payload: unknown, deps: Partial<McpDeps> = {}) => {
|
||||
const app = Fastify();
|
||||
registerMcp(app, { pool: db.pool, settings, now: () => NOW, verifyJwt, ...deps });
|
||||
const res = await app.inject({ method: "POST", url: "/mcp", headers, payload: payload as object });
|
||||
await app.close();
|
||||
return res;
|
||||
};
|
||||
const rpc = (method: string, params?: unknown, id: number | undefined = 1) => ({ jsonrpc: "2.0", id, method, params });
|
||||
const bearer = (t: string) => ({ authorization: `Bearer ${t}` });
|
||||
const jwt = (claims: Record<string, unknown>, opts: { iss?: string; exp?: string } = {}) =>
|
||||
new SignJWT(claims).setProtectedHeader({ alg: "RS256", kid: "k1" }).setIssuer(opts.iss ?? ISSUER).setIssuedAt().setExpirationTime(opts.exp ?? "5m").sign(signer);
|
||||
|
||||
it("без токена и с неверным токеном - 401", async () => {
|
||||
const a = await post({}, rpc("initialize"));
|
||||
expect(a.statusCode).toBe(401);
|
||||
expect(a.headers["www-authenticate"]).toBe("Bearer");
|
||||
expect((await post(bearer("wrong-token-wrong-token"), rpc("initialize"))).statusCode).toBe(401);
|
||||
expect((await post({ authorization: "Basic abc" }, rpc("initialize"))).statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it("initialize, notifications/initialized, ping, tools/list", async () => {
|
||||
const i = await post(bearer(TOKEN_A), rpc("initialize", { protocolVersion: "2025-03-26" }));
|
||||
expect(i.statusCode).toBe(200);
|
||||
expect(i.json().result.serverInfo.name).toBe("khb-accounting");
|
||||
expect((await post(bearer(TOKEN_A), { jsonrpc: "2.0", method: "notifications/initialized" })).statusCode).toBe(202);
|
||||
expect(((await post(bearer(TOKEN_A), rpc("ping"))).json()).result).toEqual({});
|
||||
const l = (await post(bearer(TOKEN_A), rpc("tools/list"))).json();
|
||||
expect(l.result.tools.map((t: { name: string }) => t.name)).toEqual([
|
||||
"acc_review_list", "acc_review_get", "acc_review_update", "acc_review_done", "acc_review_handoff", "acc_review_return", "acc_review_snooze",
|
||||
]);
|
||||
expect((await post(bearer(TOKEN_A), rpc("nope"))).json().error.code).toBe(-32601);
|
||||
});
|
||||
|
||||
it("tools/call со статическим токеном: список, ошибка доступа - isError", async () => {
|
||||
await addInvoice();
|
||||
const ok = (await post(bearer(TOKEN_A), rpc("tools/call", { name: "acc_review_list", arguments: {} }))).json();
|
||||
expect(ok.result.isError).toBeUndefined();
|
||||
expect(JSON.parse(ok.result.content[0].text).total).toBe(1);
|
||||
const denied = (await post(bearer("token-stranger-0123456789"), rpc("tools/call", { name: "acc_review_list", arguments: {} }))).json();
|
||||
expect(denied.result.isError).toBe(true);
|
||||
expect(denied.result.content[0].text).toContain("Доступ запрещён");
|
||||
const bad = (await post(bearer(TOKEN_A), rpc("tools/call", { name: "acc_review_get", arguments: { id: "x" } }))).json();
|
||||
expect(bad.result.isError).toBe(true);
|
||||
});
|
||||
|
||||
it("JWT Keycloak: person по основной и дополнительной почте; чужой email - 403; плохие токены - 401", async () => {
|
||||
await addInvoice();
|
||||
const call = { name: "acc_review_list", arguments: {} };
|
||||
for (const email of ["kc@khbuild.pro", "KC.Alias@gmail.com", "other@gmail.com"]) {
|
||||
const r = await post(bearer(await jwt({ email, email_verified: true })), rpc("tools/call", call));
|
||||
expect(r.statusCode, email).toBe(200);
|
||||
expect(JSON.parse(r.json().result.content[0].text).total).toBe(1);
|
||||
}
|
||||
expect((await post(bearer(await jwt({ email: "nobody@x.com" })), rpc("tools/call", call))).statusCode).toBe(403);
|
||||
expect((await post(bearer(await jwt({ email: "off@khbuild.pro" })), rpc("tools/call", call))).statusCode).toBe(403);
|
||||
expect((await post(bearer(await jwt({ email: "kc@khbuild.pro", email_verified: false })), rpc("tools/call", call))).statusCode).toBe(401);
|
||||
expect((await post(bearer(await jwt({})), rpc("tools/call", call))).statusCode).toBe(401);
|
||||
expect((await post(bearer(await jwt({ email: "kc@khbuild.pro" }, { iss: "https://evil.test/realms/x" })), rpc("tools/call", call))).statusCode).toBe(401);
|
||||
expect((await post(bearer(await jwt({ email: "kc@khbuild.pro" }, { exp: "-1m" })), rpc("tools/call", call))).statusCode).toBe(401);
|
||||
const other = await generateKeyPair("RS256");
|
||||
const forged = await new SignJWT({ email: "kc@khbuild.pro" }).setProtectedHeader({ alg: "RS256", kid: "k1" }).setIssuer(ISSUER).setExpirationTime("5m").sign(other.privateKey);
|
||||
expect((await post(bearer(forged), rpc("tools/call", call))).statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it("mcp.enabled=false: маршрут не регистрируется", async () => {
|
||||
const r = await post(bearer(TOKEN_A), rpc("ping"), { settings: { ...settings, mcp: { ...settings.mcp, enabled: false } } });
|
||||
expect(r.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
});
|
||||
455
packages/accounting_automation/src/mcp.ts
Normal file
455
packages/accounting_automation/src/mcp.ts
Normal file
@@ -0,0 +1,455 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { withTx, type Pool } from "khb_common";
|
||||
import { createMcpAuth, McpAuthError, type JwtVerifier } from "./mcp-auth.js";
|
||||
import type { AccountingSettings } from "./settings.js";
|
||||
|
||||
/**
|
||||
* MCP для Claude сотрудника: разбор очереди acc_manual_review («Review проблем в Claude»).
|
||||
* JSON-RPC 2.0 вручную, Streamable HTTP без сессий. Чистый слой (ReviewTools) не знает про HTTP.
|
||||
*/
|
||||
|
||||
type Json = Record<string, unknown>;
|
||||
export type ReviewRole = "accountant" | "cfo";
|
||||
type PoolClient = Parameters<Parameters<typeof withTx>[1]>[0];
|
||||
const ROLES: ReviewRole[] = ["accountant", "cfo"];
|
||||
|
||||
/** Ошибка инструмента: показывается пользователю как isError с текстом по-русски. */
|
||||
export class McpToolError extends Error {}
|
||||
|
||||
export interface ReviewDeps {
|
||||
pool: Pool;
|
||||
settings: Pick<AccountingSettings, "reviewers">;
|
||||
now?: () => Date;
|
||||
}
|
||||
|
||||
interface KindMeta {
|
||||
table: string;
|
||||
key: string;
|
||||
/** Поля, которые можно править: имя -> проверка и приведение (возвращает значение и SQL-приведение типа). */
|
||||
fields: Record<string, FieldSpec>;
|
||||
}
|
||||
interface FieldSpec {
|
||||
cast: string;
|
||||
check: (v: unknown) => unknown;
|
||||
}
|
||||
|
||||
const isNull = (v: unknown): boolean => v === null;
|
||||
const text = (nullable: boolean) => (v: unknown): unknown => {
|
||||
if (v === null && nullable) return null;
|
||||
if (typeof v !== "string") throw new McpToolError("ожидалась строка");
|
||||
return v;
|
||||
};
|
||||
const dateF = (v: unknown): unknown => {
|
||||
if (isNull(v)) return null;
|
||||
if (typeof v !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(v) || Number.isNaN(Date.parse(v)) || new Date(v).toISOString().slice(0, 10) !== v)
|
||||
throw new McpToolError("ожидалась дата YYYY-MM-DD");
|
||||
return v;
|
||||
};
|
||||
const amountF = (v: unknown): unknown => {
|
||||
if (isNull(v)) return null;
|
||||
const n = typeof v === "string" && v.trim() !== "" ? Number(v) : v;
|
||||
if (typeof n !== "number" || !Number.isFinite(n) || Math.abs(n) >= 1e12) throw new McpToolError("ожидалось число");
|
||||
return Math.round(n * 100) / 100;
|
||||
};
|
||||
const jsonF = (v: unknown): unknown => {
|
||||
if (v !== null && typeof v !== "object") throw new McpToolError("ожидался JSON (объект или массив)");
|
||||
return JSON.stringify(v);
|
||||
};
|
||||
const uuidF = (v: unknown): unknown => {
|
||||
if (isNull(v)) return null;
|
||||
if (typeof v !== "string" || !UUID.test(v)) throw new McpToolError("ожидался uuid");
|
||||
return v;
|
||||
};
|
||||
const confidenceF = (v: unknown): unknown => {
|
||||
if (isNull(v)) return null;
|
||||
if (typeof v !== "number" || !Number.isInteger(v) || v < 0 || v > 100) throw new McpToolError("ожидалось целое 0..100");
|
||||
return v;
|
||||
};
|
||||
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
const problem: FieldSpec = { cast: "text", check: text(true) };
|
||||
|
||||
export const KINDS: Record<string, KindMeta> = {
|
||||
invoice: {
|
||||
table: "acc_invoices_review",
|
||||
key: "id",
|
||||
fields: {
|
||||
vendor_name: { cast: "text", check: text(true) },
|
||||
vendor_qbo_id: { cast: "text", check: text(true) },
|
||||
invoice_number: { cast: "text", check: text(true) },
|
||||
invoice_date: { cast: "date", check: dateF },
|
||||
amount: { cast: "numeric", check: amountF },
|
||||
lines: { cast: "jsonb", check: jsonF },
|
||||
project_customer_id: { cast: "text", check: text(true) },
|
||||
jt_job_id: { cast: "text", check: text(true) },
|
||||
contract_id: { cast: "uuid", check: uuidF },
|
||||
problem_highlight: problem,
|
||||
},
|
||||
},
|
||||
categorization: {
|
||||
table: "acc_categorization_review",
|
||||
key: "feed_txn_id",
|
||||
fields: {
|
||||
suggestion: { cast: "jsonb", check: jsonF },
|
||||
confidence: { cast: "smallint", check: confidenceF },
|
||||
problem_highlight: problem,
|
||||
},
|
||||
},
|
||||
certificate: {
|
||||
table: "acc_certificates_review",
|
||||
key: "id",
|
||||
fields: {
|
||||
expires_on: { cast: "date", check: dateF },
|
||||
vendor_qbo_id: { cast: "text", check: text(true) },
|
||||
problem_highlight: problem,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const driveUrl = (id: unknown): string | null => (typeof id === "string" && id ? `https://drive.google.com/file/d/${id}/view` : null);
|
||||
|
||||
interface Task {
|
||||
id: string;
|
||||
kind: string;
|
||||
ref_table: string;
|
||||
ref_id: string;
|
||||
assignee_role: string;
|
||||
problem_highlight: string | null;
|
||||
snoozed_until: Date | null;
|
||||
created_at: Date;
|
||||
}
|
||||
const taskOut = (t: Task): Json => ({
|
||||
id: t.id,
|
||||
kind: t.kind,
|
||||
assignee_role: t.assignee_role,
|
||||
problem_highlight: t.problem_highlight,
|
||||
snoozed_until: t.snoozed_until,
|
||||
created_at: t.created_at,
|
||||
});
|
||||
|
||||
const metaOf = (t: Pick<Task, "kind">): KindMeta | undefined => KINDS[t.kind];
|
||||
|
||||
/** Чистый слой инструментов: person_id вызывающего передаётся первым аргументом. */
|
||||
export class ReviewTools {
|
||||
private readonly now: () => Date;
|
||||
constructor(private readonly d: ReviewDeps) {
|
||||
this.now = d.now ?? (() => new Date());
|
||||
}
|
||||
|
||||
/** Роли человека по settings.reviewers; пусто - доступ запрещён. */
|
||||
rolesOf(personId: string): ReviewRole[] {
|
||||
const roles = new Set<ReviewRole>();
|
||||
for (const r of this.d.settings.reviewers) if (r.personId.toLowerCase() === personId.toLowerCase()) r.roles.forEach((x) => roles.add(x));
|
||||
if (roles.size === 0) throw new McpToolError("Доступ запрещён: вы не назначены на разбор очереди бухгалтерии (settings.reviewers).");
|
||||
return [...roles];
|
||||
}
|
||||
|
||||
private id(a: Json): string {
|
||||
const v = a.id;
|
||||
if (typeof v !== "string" || !UUID.test(v)) throw new McpToolError("нужно поле id (uuid задачи из acc_review_list)");
|
||||
return v;
|
||||
}
|
||||
|
||||
/** Задача под блокировкой + проверка роли. */
|
||||
private async lockTask(c: PoolClient, roles: ReviewRole[], id: string, forWhat = "работы с задачей"): Promise<Task> {
|
||||
const t = (await c.query("select * from acc_manual_review where id = $1 for update", [id])).rows[0] as Task | undefined;
|
||||
if (!t) throw new McpToolError("Задача не найдена (возможно, уже завершена и удалена из очереди).");
|
||||
if (!roles.includes(t.assignee_role as ReviewRole))
|
||||
throw new McpToolError(`Задача назначена роли ${t.assignee_role}: для ${forWhat} нужна роль ${t.assignee_role}.`);
|
||||
return t;
|
||||
}
|
||||
|
||||
private async reviewRow(c: Pick<PoolClient, "query">, t: Task, suffix = "", lock = false): Promise<Json | null> {
|
||||
const m = metaOf(t);
|
||||
if (!m) return null;
|
||||
const r = await c.query(`select to_jsonb(r) as row from ${m.table}${suffix} r where r.${m.key}::text = $1 ${lock ? "for update" : ""}`.trim(), [t.ref_id]);
|
||||
return (r.rows[0]?.row as Json | undefined) ?? null;
|
||||
}
|
||||
|
||||
/** acc_review_list */
|
||||
async list(personId: string, a: Json): Promise<Json> {
|
||||
const mine = this.rolesOf(personId);
|
||||
let roles = mine;
|
||||
if (a.role !== undefined) {
|
||||
if (!ROLES.includes(a.role as ReviewRole)) throw new McpToolError("role: accountant или cfo");
|
||||
if (!mine.includes(a.role as ReviewRole)) throw new McpToolError(`У вас нет роли ${String(a.role)}.`);
|
||||
roles = [a.role as ReviewRole];
|
||||
}
|
||||
if (a.kind !== undefined && typeof a.kind !== "string") throw new McpToolError("kind: строка");
|
||||
const limit = a.limit === undefined ? 20 : a.limit;
|
||||
if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > 100) throw new McpToolError("limit: целое 1..100");
|
||||
const { rows } = await this.d.pool.query(
|
||||
`select m.*, coalesce(to_jsonb(i), to_jsonb(c), to_jsonb(s)) as row, count(*) over()::int as total
|
||||
from acc_manual_review m
|
||||
left join acc_invoices_review i on m.ref_table = 'acc_invoices_review' and i.id::text = m.ref_id
|
||||
left join acc_categorization_review c on m.ref_table = 'acc_categorization_review' and c.feed_txn_id = m.ref_id
|
||||
left join acc_certificates_review s on m.ref_table = 'acc_certificates_review' and s.id::text = m.ref_id
|
||||
where m.assignee_role = any($1::text[])
|
||||
and ($2::text is null or m.kind = $2)
|
||||
and ($3::boolean or m.snoozed_until is null or m.snoozed_until <= $4)
|
||||
and not coalesce(i.done, c.done, s.done, false)
|
||||
order by (nullif(btrim(m.problem_highlight), '') is null), m.created_at, m.id
|
||||
limit $5`,
|
||||
[roles, (a.kind as string | undefined) ?? null, a.include_snoozed === true, this.now(), limit],
|
||||
);
|
||||
return {
|
||||
total: rows[0]?.total ?? 0,
|
||||
shown: rows.length,
|
||||
tasks: rows.map((r) => {
|
||||
const row = r.row as Json | null;
|
||||
return { ...taskOut(r as Task), review: row, ...(r.kind === "invoice" && row ? { file_url: driveUrl(row.drive_file_id) } : {}) };
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** acc_review_get */
|
||||
async get(personId: string, a: Json): Promise<Json> {
|
||||
const roles = this.rolesOf(personId);
|
||||
const id = this.id(a);
|
||||
const t = (await this.d.pool.query("select * from acc_manual_review where id = $1", [id])).rows[0] as Task | undefined;
|
||||
if (!t) throw new McpToolError("Задача не найдена (возможно, уже завершена и удалена из очереди).");
|
||||
if (!roles.includes(t.assignee_role as ReviewRole)) throw new McpToolError(`Задача назначена роли ${t.assignee_role}: у вас нет этой роли.`);
|
||||
const review = await this.reviewRow(this.d.pool, t);
|
||||
const original = await this.reviewRow(this.d.pool, t, "_original");
|
||||
let fileId: unknown = t.kind === "invoice" ? review?.drive_file_id : undefined;
|
||||
if (t.kind === "certificate" && review?.certificate_id) {
|
||||
fileId = (await this.d.pool.query("select drive_file_id from acc_insurance_certificates where id = $1", [review.certificate_id])).rows[0]?.drive_file_id;
|
||||
}
|
||||
const changed =
|
||||
review && original
|
||||
? Object.keys(review).filter((k) => !["updated_at", "done", "done_by"].includes(k) && JSON.stringify(review[k]) !== JSON.stringify(original[k]))
|
||||
: [];
|
||||
return { task: taskOut(t), review, original, changed_fields: changed, file_url: driveUrl(fileId) };
|
||||
}
|
||||
|
||||
/** acc_review_update */
|
||||
async update(personId: string, a: Json): Promise<Json> {
|
||||
const roles = this.rolesOf(personId);
|
||||
const id = this.id(a);
|
||||
const fields = a.fields;
|
||||
if (!fields || typeof fields !== "object" || Array.isArray(fields) || Object.keys(fields).length === 0) throw new McpToolError("fields: непустой объект {поле: значение}");
|
||||
return withTx(this.d.pool, async (c) => {
|
||||
const t = await this.lockTask(c, roles, id, "правки");
|
||||
const m = metaOf(t);
|
||||
if (!m) throw new McpToolError(`Для задач вида ${t.kind} правка полей через MCP не предусмотрена.`);
|
||||
const sets: string[] = [];
|
||||
const vals: unknown[] = [];
|
||||
for (const [k, v] of Object.entries(fields as Json)) {
|
||||
const spec = m.fields[k];
|
||||
if (!spec) throw new McpToolError(`Поле ${k} править нельзя. Допустимые для вида ${t.kind}: ${Object.keys(m.fields).join(", ")}.`);
|
||||
let val: unknown;
|
||||
try {
|
||||
val = spec.check(v);
|
||||
} catch (e) {
|
||||
throw new McpToolError(`Поле ${k}: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
vals.push(val);
|
||||
sets.push(`${k} = $${vals.length + 1}::${spec.cast}`);
|
||||
}
|
||||
const row = await this.reviewRow(c, t, "", true);
|
||||
if (!row) throw new McpToolError("Строка разбора не найдена.");
|
||||
if (row.done === true) throw new McpToolError("Запись уже отмечена выполненной, править нельзя.");
|
||||
await c.query(`update ${m.table} set ${sets.join(", ")} where ${m.key}::text = $1`, [t.ref_id, ...vals]);
|
||||
return { ok: true, review: await this.reviewRow(c, t) };
|
||||
});
|
||||
}
|
||||
|
||||
/** acc_review_done */
|
||||
async done(personId: string, a: Json): Promise<Json> {
|
||||
const roles = this.rolesOf(personId);
|
||||
const id = this.id(a);
|
||||
return withTx(this.d.pool, async (c) => {
|
||||
const t = await this.lockTask(c, roles, id, "закрытия");
|
||||
const m = metaOf(t);
|
||||
if (!m) throw new McpToolError(`Задачи вида ${t.kind} через MCP закрыть нельзя.`);
|
||||
if (t.kind === "categorization" && t.assignee_role === "cfo" && !roles.includes("cfo")) throw new McpToolError("Нужна роль cfo.");
|
||||
const r = await c.query(`update ${m.table} set done = true, done_by = $2 where ${m.key}::text = $1 and not done`, [t.ref_id, personId]);
|
||||
if (r.rowCount === 0) throw new McpToolError("Запись уже отмечена выполненной или не найдена.");
|
||||
return { ok: true, message: "Отмечено выполненным; запись будет перенесена в историю процессом «Завершение ручного разбора».", task: taskOut(t) };
|
||||
});
|
||||
}
|
||||
|
||||
/** Записывает текст проблемы туда же, где её видит человек: в review-строку (триггер синхронизирует очередь) или в саму очередь. */
|
||||
private async setProblem(c: PoolClient, t: Task, textValue: string | null): Promise<void> {
|
||||
const m = metaOf(t);
|
||||
if (m) await c.query(`update ${m.table} set problem_highlight = $2 where ${m.key}::text = $1`, [t.ref_id, textValue]);
|
||||
else await c.query("update acc_manual_review set problem_highlight = $2 where id = $1", [t.id, textValue]);
|
||||
}
|
||||
|
||||
/** acc_review_handoff */
|
||||
async handoff(personId: string, a: Json): Promise<Json> {
|
||||
const roles = this.rolesOf(personId);
|
||||
const id = this.id(a);
|
||||
if (!ROLES.includes(a.role as ReviewRole)) throw new McpToolError("role: accountant или cfo");
|
||||
if (a.comment !== undefined && typeof a.comment !== "string") throw new McpToolError("comment: строка");
|
||||
return withTx(this.d.pool, async (c) => {
|
||||
const t = await this.lockTask(c, roles, id, "передачи");
|
||||
if (t.assignee_role === a.role) throw new McpToolError(`Задача уже назначена роли ${String(a.role)}.`);
|
||||
await c.query("update acc_manual_review set assignee_role = $2 where id = $1", [t.id, a.role]);
|
||||
if (typeof a.comment === "string" && a.comment.trim()) {
|
||||
const base = t.problem_highlight ? `${t.problem_highlight} | ` : "";
|
||||
await this.setProblem(c, t, `${base}Передано ${t.assignee_role} -> ${String(a.role)}: ${a.comment.trim()}`);
|
||||
}
|
||||
const now = (await c.query("select * from acc_manual_review where id = $1", [t.id])).rows[0] as Task;
|
||||
return { ok: true, task: taskOut(now) };
|
||||
});
|
||||
}
|
||||
|
||||
/** acc_review_return */
|
||||
async return(personId: string, a: Json): Promise<Json> {
|
||||
const roles = this.rolesOf(personId);
|
||||
const id = this.id(a);
|
||||
if (typeof a.reason !== "string" || !a.reason.trim()) throw new McpToolError("reason: нужна причина возврата");
|
||||
const reason: string = a.reason.trim();
|
||||
return withTx(this.d.pool, async (c) => {
|
||||
const t = await this.lockTask(c, roles, id, "возврата");
|
||||
await c.query("update acc_manual_review set assignee_role = 'accountant', snoozed_until = null where id = $1", [t.id]);
|
||||
await this.setProblem(c, t, `Возвращено: ${reason}`);
|
||||
const now = (await c.query("select * from acc_manual_review where id = $1", [t.id])).rows[0] as Task;
|
||||
return { ok: true, task: taskOut(now) };
|
||||
});
|
||||
}
|
||||
|
||||
/** acc_review_snooze */
|
||||
async snooze(personId: string, a: Json): Promise<Json> {
|
||||
const roles = this.rolesOf(personId);
|
||||
const id = this.id(a);
|
||||
const until = typeof a.until === "string" ? new Date(a.until) : null;
|
||||
if (!until || Number.isNaN(until.getTime())) throw new McpToolError("until: дата или время в формате ISO (2026-11-20 или 2026-11-20T09:00:00Z)");
|
||||
if (until <= this.now()) throw new McpToolError("until должно быть в будущем.");
|
||||
return withTx(this.d.pool, async (c) => {
|
||||
const t = await this.lockTask(c, roles, id, "откладывания");
|
||||
await c.query("update acc_manual_review set snoozed_until = $2 where id = $1", [t.id, until]);
|
||||
const now = (await c.query("select * from acc_manual_review where id = $1", [t.id])).rows[0] as Task;
|
||||
return { ok: true, task: taskOut(now) };
|
||||
});
|
||||
}
|
||||
|
||||
call(personId: string, name: string, a: Json): Promise<Json> {
|
||||
switch (name) {
|
||||
case "acc_review_list": return this.list(personId, a);
|
||||
case "acc_review_get": return this.get(personId, a);
|
||||
case "acc_review_update": return this.update(personId, a);
|
||||
case "acc_review_done": return this.done(personId, a);
|
||||
case "acc_review_handoff": return this.handoff(personId, a);
|
||||
case "acc_review_return": return this.return(personId, a);
|
||||
case "acc_review_snooze": return this.snooze(personId, a);
|
||||
default: throw new McpToolError(`Неизвестный инструмент ${name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const str = { type: "string" };
|
||||
const obj = (properties: Json, required: string[] = []): Json => ({ type: "object", properties, required, additionalProperties: false });
|
||||
const idP = { type: "string", description: "id задачи (uuid из acc_review_list)" };
|
||||
|
||||
export const TOOLS: { name: string; description: string; inputSchema: Json }[] = [
|
||||
{
|
||||
name: "acc_review_list",
|
||||
description:
|
||||
"Список задач ручного разбора бухгалтерии (очередь acc_manual_review) для ролей текущего пользователя. Сначала идут задачи с проблемой (problem_highlight). В каждой задаче - данные строки разбора: инвойс (поля инвойса и ссылка на PDF), категоризация банковской операции (feed_txn_id, run_id, предложение, уверенность), сертификат страхования. Отложенные задачи скрыты, если не указан include_snoozed.",
|
||||
inputSchema: obj({
|
||||
kind: { type: "string", description: "вид задачи: invoice, categorization, certificate", enum: ["invoice", "categorization", "certificate", "discrepancy", "receipt_search", "chargeback", "invoice_approval"] },
|
||||
role: { type: "string", enum: ROLES, description: "показать задачи только этой роли (по умолчанию - все ваши роли)" },
|
||||
include_snoozed: { type: "boolean", description: "показать и отложенные задачи" },
|
||||
limit: { type: "number", description: "сколько задач вернуть (1..100, по умолчанию 20)" },
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "acc_review_get",
|
||||
description: "Одна задача ручного разбора: сама задача, строка разбора (review), как её записал автомат (original), список изменённых полей и ссылка на файл в Google Drive (для инвойса и сертификата).",
|
||||
inputSchema: obj({ id: idP }, ["id"]),
|
||||
},
|
||||
{
|
||||
name: "acc_review_update",
|
||||
description:
|
||||
"Исправить поля строки разбора по задаче. Инвойс: vendor_name, vendor_qbo_id, invoice_number, invoice_date (YYYY-MM-DD), amount, lines (JSON), project_customer_id, jt_job_id, contract_id, problem_highlight. Категоризация: suggestion (JSON), confidence (0..100), problem_highlight. Сертификат: expires_on (YYYY-MM-DD), vendor_qbo_id, problem_highlight. Значение null очищает поле. Другие поля менять нельзя.",
|
||||
inputSchema: obj({ id: idP, fields: { type: "object", description: "{имя поля: новое значение}" } }, ["id", "fields"]),
|
||||
},
|
||||
{
|
||||
name: "acc_review_done",
|
||||
description: "Отметить задачу выполненной (после подтверждения пользователем; для банковской операции - после проводки в QuickBooks). Дальше запись переносит в историю процесс «Завершение ручного разбора». Задачу роли cfo может закрыть только пользователь с ролью cfo.",
|
||||
inputSchema: obj({ id: idP }, ["id"]),
|
||||
},
|
||||
{
|
||||
name: "acc_review_handoff",
|
||||
description: "Передать задачу другой роли (accountant или cfo), например операцию от $5 000 или первую оплату новому вендору - роли cfo. Комментарий добавляется к проблеме задачи.",
|
||||
inputSchema: obj({ id: idP, role: { type: "string", enum: ROLES }, comment: { type: "string", description: "зачем передаётся" } }, ["id", "role"]),
|
||||
},
|
||||
{
|
||||
name: "acc_review_return",
|
||||
description: "Вернуть задачу в общую очередь (роль accountant) с причиной; причина записывается в problem_highlight, отложенность снимается.",
|
||||
inputSchema: obj({ id: idP, reason: { type: "string", description: "причина возврата" } }, ["id", "reason"]),
|
||||
},
|
||||
{
|
||||
name: "acc_review_snooze",
|
||||
description: "Отложить задачу («подождать»): она не показывается в списке до указанного момента.",
|
||||
inputSchema: obj({ id: idP, until: { ...str, description: "дата или время ISO, в будущем: 2026-11-20 или 2026-11-20T09:00:00Z" } }, ["id", "until"]),
|
||||
},
|
||||
];
|
||||
|
||||
const rpcError = (id: unknown, code: number, message: string): Json => ({ jsonrpc: "2.0", id: id ?? null, error: { code, message } });
|
||||
|
||||
/** Обрабатывает одно JSON-RPC сообщение от аутентифицированного человека; null - уведомление (ответа нет). */
|
||||
export async function handleMcpMessage(tools: ReviewTools, personId: string, msg: Json): Promise<Json | null> {
|
||||
const id = msg?.id;
|
||||
const method = msg?.method;
|
||||
if (typeof method !== "string") return rpcError(id, -32600, "invalid request");
|
||||
if (id === undefined) return null; // notifications/*
|
||||
switch (method) {
|
||||
case "initialize": {
|
||||
const asked = (msg.params as Json | undefined)?.protocolVersion;
|
||||
return { jsonrpc: "2.0", id, result: { protocolVersion: typeof asked === "string" ? asked : "2025-03-26", capabilities: { tools: {} }, serverInfo: { name: "khb-accounting", version: "0.1.0" } } };
|
||||
}
|
||||
case "ping":
|
||||
return { jsonrpc: "2.0", id, result: {} };
|
||||
case "tools/list":
|
||||
return { jsonrpc: "2.0", id, result: { tools: TOOLS } };
|
||||
case "tools/call": {
|
||||
const p = (msg.params ?? {}) as { name?: string; arguments?: Json };
|
||||
if (!TOOLS.some((t) => t.name === p.name)) return rpcError(id, -32602, `неизвестный инструмент ${p.name}`);
|
||||
try {
|
||||
const out = await tools.call(personId, p.name as string, p.arguments ?? {});
|
||||
return { jsonrpc: "2.0", id, result: { content: [{ type: "text", text: JSON.stringify(out) }] } };
|
||||
} catch (e) {
|
||||
const text = e instanceof McpToolError ? e.message : `Внутренняя ошибка: ${e instanceof Error ? e.message : String(e)}`;
|
||||
return { jsonrpc: "2.0", id, result: { isError: true, content: [{ type: "text", text }] } };
|
||||
}
|
||||
}
|
||||
default:
|
||||
return rpcError(id, -32601, `метод не поддерживается: ${method}`);
|
||||
}
|
||||
}
|
||||
|
||||
export interface McpDeps extends ReviewDeps {
|
||||
settings: Pick<AccountingSettings, "reviewers" | "mcp">;
|
||||
/** Проверка JWT Keycloak (для тестов - с локальным JWKS). */
|
||||
verifyJwt?: JwtVerifier;
|
||||
}
|
||||
|
||||
/** Вешает POST /mcp на Fastify. Аутентификация (Bearer) - только для /mcp. Если mcp.enabled=false - ничего не регистрирует. */
|
||||
export function registerMcp(app: FastifyInstance, deps: McpDeps): ReviewTools {
|
||||
const tools = new ReviewTools(deps);
|
||||
if (!deps.settings.mcp.enabled) return tools;
|
||||
const authenticate = createMcpAuth(deps);
|
||||
app.post("/mcp", async (req, reply) => {
|
||||
let personId: string;
|
||||
try {
|
||||
personId = (await authenticate(req.headers.authorization)).personId;
|
||||
} catch (e) {
|
||||
const status = e instanceof McpAuthError ? e.status : 401;
|
||||
if (status === 401) void reply.header("WWW-Authenticate", "Bearer");
|
||||
return reply.code(status).send({ error: e instanceof Error ? e.message : "unauthorized" });
|
||||
}
|
||||
const body = req.body as unknown;
|
||||
if (Array.isArray(body)) {
|
||||
const out = (await Promise.all(body.map((m) => handleMcpMessage(tools, personId, m as Json)))).filter((x): x is Json => x !== null);
|
||||
return out.length ? reply.send(out) : reply.code(202).send();
|
||||
}
|
||||
if (!body || typeof body !== "object") return reply.code(400).send(rpcError(null, -32700, "parse error"));
|
||||
const res = await handleMcpMessage(tools, personId, body as Json);
|
||||
return res ? reply.send(res) : reply.code(202).send();
|
||||
});
|
||||
app.get("/mcp", async (_req, reply) => reply.code(405).header("Allow", "POST").send({ error: "используйте POST" }));
|
||||
return tools;
|
||||
}
|
||||
38
packages/accounting_automation/src/prompt-loader.test.ts
Normal file
38
packages/accounting_automation/src/prompt-loader.test.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { mkdtemp, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { makePromptLoader, stripPromptFile } from "./prompt-loader.js";
|
||||
|
||||
const long = "Подготовь классификацию. ".repeat(20);
|
||||
|
||||
describe("промпт категоризации", () => {
|
||||
it("stripPromptFile убирает заголовок и раздел «Описание»", () => {
|
||||
expect(stripPromptFile("# Заголовок\n\nТекст промпта\n\n## Описание\n\nслужебное")).toBe("Текст промпта");
|
||||
});
|
||||
|
||||
it("берётся из Google Docs", async () => {
|
||||
const load = makePromptLoader({ docId: "d", fallbackFile: "/nonexistent", exportDocText: async () => long });
|
||||
expect(await load()).toBe(long.trim());
|
||||
});
|
||||
|
||||
it("Google Docs упал - копия из файла (без описания)", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "acc-"));
|
||||
await writeFile(join(dir, "p.md"), "# P\n\nТекст из файла\n\n## Описание\n\nxx", "utf8");
|
||||
const logs: string[] = [];
|
||||
const load = makePromptLoader({
|
||||
docId: "d", fallbackFile: "p.md", rootDir: dir,
|
||||
exportDocText: async () => { throw new Error("403"); },
|
||||
log: (m) => logs.push(m),
|
||||
});
|
||||
expect(await load()).toBe("Текст из файла");
|
||||
expect(logs[0]).toContain("недоступен");
|
||||
});
|
||||
|
||||
it("слишком короткий текст из Google Docs считается сбоем", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "acc-"));
|
||||
await writeFile(join(dir, "p.md"), "# P\n\nИз файла", "utf8");
|
||||
const load = makePromptLoader({ docId: "d", fallbackFile: "p.md", rootDir: dir, exportDocText: async () => "пусто" });
|
||||
expect(await load()).toBe("Из файла");
|
||||
});
|
||||
});
|
||||
34
packages/accounting_automation/src/prompt-loader.ts
Normal file
34
packages/accounting_automation/src/prompt-loader.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
export interface PromptSourceDeps {
|
||||
/** Текст Google Docs (экспорт text/plain); не задан или упал - берётся копия из файла. */
|
||||
exportDocText?: (docId: string) => Promise<string>;
|
||||
docId: string;
|
||||
fallbackFile: string;
|
||||
/** Корень репозитория для относительного fallbackFile. */
|
||||
rootDir?: string;
|
||||
log?: (msg: string, extra?: Record<string, unknown>) => void;
|
||||
}
|
||||
|
||||
/** Служебные разделы файла-копии (`## Описание`) агенту не нужны. */
|
||||
export function stripPromptFile(text: string): string {
|
||||
const noDescription = text.split(/\n## Описание/)[0] ?? text;
|
||||
return noDescription.replace(/^# [^\n]*\n+/, "").trim();
|
||||
}
|
||||
|
||||
/** Промпт категоризации: Google Docs (правит Анастасия) с запасной копией из репозитория. */
|
||||
export function makePromptLoader(d: PromptSourceDeps): () => Promise<string> {
|
||||
return async () => {
|
||||
if (d.exportDocText) {
|
||||
try {
|
||||
const t = (await d.exportDocText(d.docId)).trim();
|
||||
if (t.length > 200) return t;
|
||||
d.log?.("промпт из Google Docs слишком короткий, берётся копия из файла", { length: t.length });
|
||||
} catch (e) {
|
||||
d.log?.("промпт из Google Docs недоступен, берётся копия из файла", { err: String(e) });
|
||||
}
|
||||
}
|
||||
const path = d.rootDir && !/^([a-zA-Z]:|\/)/.test(d.fallbackFile) ? `${d.rootDir}/${d.fallbackFile}` : d.fallbackFile;
|
||||
return stripPromptFile(await readFile(path, "utf8"));
|
||||
};
|
||||
}
|
||||
55
packages/accounting_automation/src/settings.ts
Normal file
55
packages/accounting_automation/src/settings.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { z } from "zod";
|
||||
|
||||
/** Секция `accounting_automation` в settings.json5. Секреты - только там, не в Git. */
|
||||
export const accountingSchema = z.object({
|
||||
http: z.object({ host: z.string().default("0.0.0.0"), port: z.number().default(8096), token: z.string().min(1) }),
|
||||
/** Claude-агент (`claude -p`, учётная запись agents@khbuild.pro на сервере). */
|
||||
claude: z
|
||||
.object({
|
||||
bin: z.string().default("claude"),
|
||||
workDir: z.string().default("/data/agents/accounting"),
|
||||
timeoutMs: z.number().default(900_000),
|
||||
/** Доп. аргументы (например, разрешённые инструменты). */
|
||||
extraArgs: z.array(z.string()).default([]),
|
||||
/** Строка подключения роли только для чтения (khb_agent_acc): передаётся агенту в KHB_SQL_URL для команды khb-sql. */
|
||||
sqlUrl: z.string().optional(),
|
||||
})
|
||||
.default({}),
|
||||
/** Промпт категоризации лежит в Google Docs (правит Анастасия); если Drive недоступен, берётся копия из файла. */
|
||||
prompt: z
|
||||
.object({
|
||||
driveDocId: z.string().default("1BVIDzP-yolt-A9AzRtx1IqBBiMKIUlsrAQUDZch5aJA"),
|
||||
fallbackFile: z.string().default("docs/approved/modules/quickbooks_bookkeeper/p-categorization.md"),
|
||||
})
|
||||
.default({}),
|
||||
/** Google: ключ сервисного аккаунта (JSON: client_email, private_key). Drive - папки и промпт; Gmail - чтение invoices@ (нужно делегирование на уровне домена). */
|
||||
google: z
|
||||
.object({
|
||||
client_email: z.string(),
|
||||
private_key: z.string(),
|
||||
/** Ящик, который читаем (делегирование домена). */
|
||||
gmailUser: z.string().default("invoices@khbuild.pro"),
|
||||
/** Корневая папка Google Drive для инвойсов, чеков и т.д. (подпапки создаются сервисом). */
|
||||
rootFolderId: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
slack: z.object({ botToken: z.string(), accountingChannelId: z.string() }).optional(),
|
||||
/** Порог суммы, с которого подтверждает Анастасия (USD). */
|
||||
approvalThresholdUsd: z.number().default(5000),
|
||||
/** Какие роли очереди закрывает каждый человек (person_id -> роли). Пока Юли нет, Анастасия закрывает обе. */
|
||||
reviewers: z
|
||||
.array(z.object({ personId: z.string(), roles: z.array(z.enum(["accountant", "cfo"])).default(["accountant", "cfo"]) }))
|
||||
.default([]),
|
||||
/** Задержка перед обработкой выполненной записи (сек), по описанию процесса «Завершение ручного разбора». */
|
||||
finalizeDelaySeconds: z.number().default(30),
|
||||
mcp: z
|
||||
.object({
|
||||
enabled: z.boolean().default(true),
|
||||
publicUrl: z.string().optional(),
|
||||
issuer: z.string().optional(),
|
||||
/** Статические токены (person -> токен) для Claude сотрудников и тестов. */
|
||||
staticTokens: z.array(z.object({ token: z.string().min(16), personId: z.string() })).default([]),
|
||||
})
|
||||
.default({}),
|
||||
});
|
||||
export type AccountingSettings = z.infer<typeof accountingSchema>;
|
||||
26
packages/accounting_automation/src/slack.ts
Normal file
26
packages/accounting_automation/src/slack.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
/** Отправка сообщений в Slack (chat.postMessage). Интерфейс внедряется в процессы, в тестах подменяется. */
|
||||
export interface SlackPoster {
|
||||
post(channelId: string, text: string): Promise<void>;
|
||||
}
|
||||
|
||||
export interface SlackPosterOptions {
|
||||
botToken: string;
|
||||
/** Для тестов; по умолчанию глобальный fetch. */
|
||||
fetchImpl?: typeof fetch;
|
||||
}
|
||||
|
||||
export function createSlackPoster(opts: SlackPosterOptions): SlackPoster {
|
||||
const f = opts.fetchImpl ?? fetch;
|
||||
return {
|
||||
async post(channelId, text) {
|
||||
const res = await f("https://slack.com/api/chat.postMessage", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json; charset=utf-8", authorization: `Bearer ${opts.botToken}` },
|
||||
body: JSON.stringify({ channel: channelId, text }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`Slack chat.postMessage: HTTP ${res.status}`);
|
||||
const body = (await res.json()) as { ok?: boolean; error?: string };
|
||||
if (!body.ok) throw new Error(`Slack chat.postMessage: ${body.error ?? "неизвестная ошибка"}`);
|
||||
},
|
||||
};
|
||||
}
|
||||
178
packages/accounting_automation/src/summary.ts
Normal file
178
packages/accounting_automation/src/summary.ts
Normal file
@@ -0,0 +1,178 @@
|
||||
import type { Pool } from "khb_common";
|
||||
import type { SlackPoster } from "./slack.js";
|
||||
|
||||
/** Ежедневная сводка ассистента (процесс «Ежедневная сводка ассистента»). */
|
||||
|
||||
export interface SummaryOptions {
|
||||
/** Ссылка на Mathesar (очередь ручного разбора). */
|
||||
mathesarUrl?: string;
|
||||
/** Ссылка на ленту банка QuickBooks (для строки по категоризации). */
|
||||
bankFeedUrl?: string;
|
||||
/** Нерабочие дни (YYYY-MM-DD) помимо суббот и воскресений. */
|
||||
nonWorkdays?: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
function plural(n: number, one: string, few: string, many: string): string {
|
||||
const a = Math.abs(n) % 100;
|
||||
const b = a % 10;
|
||||
if (a > 10 && a < 20) return many;
|
||||
if (b === 1) return one;
|
||||
if (b >= 2 && b <= 4) return few;
|
||||
return many;
|
||||
}
|
||||
const tasks = (n: number) => `${n} ${plural(n, "задача", "задачи", "задач")}`;
|
||||
|
||||
/** Локальная дата YYYY-MM-DD в часовом поясе tz. */
|
||||
function localDate(d: Date, tz: string): string {
|
||||
const parts = new Intl.DateTimeFormat("en-US", { timeZone: tz, year: "numeric", month: "2-digit", day: "2-digit" }).formatToParts(d);
|
||||
const get = (t: string) => parts.find((p) => p.type === t)!.value;
|
||||
return `${get("year")}-${get("month")}-${get("day")}`;
|
||||
}
|
||||
function ruDate(iso: string): string {
|
||||
const [y, m, d] = iso.split("-");
|
||||
return `${d}.${m}.${y}`;
|
||||
}
|
||||
function isWorkday(d: Date, tz: string, non: ReadonlySet<string>): boolean {
|
||||
const wd = new Intl.DateTimeFormat("en-US", { timeZone: tz, weekday: "short" }).format(d);
|
||||
return wd !== "Sat" && wd !== "Sun" && !non.has(localDate(d, tz));
|
||||
}
|
||||
|
||||
/** Момент, на 2 рабочих дня раньше now: задачи, созданные раньше, ждут больше 2 рабочих дней. */
|
||||
export function twoWorkdaysAgo(now: Date, tz: string, non: ReadonlySet<string> = new Set()): Date {
|
||||
let d = new Date(now.getTime());
|
||||
let n = 0;
|
||||
while (n < 2) {
|
||||
d = new Date(d.getTime() - 24 * 3600_000);
|
||||
if (isWorkday(d, tz, non)) n++;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
function duration(seconds: number): string {
|
||||
const min = Math.round(seconds / 60);
|
||||
if (min < 60) return `${min} мин`;
|
||||
const h = Math.floor(min / 60);
|
||||
const m = min % 60;
|
||||
if (h < 48) return m === 0 ? `${h} ч` : `${h} ч ${m} мин`;
|
||||
const days = Math.floor(h / 24);
|
||||
return `${days} дн ${h % 24} ч`;
|
||||
}
|
||||
|
||||
const KIND_LABEL: Record<string, string> = { invoice: "инвойсы", categorization: "категоризация", certificate: "сертификаты" };
|
||||
const ROLE_LABEL: Record<string, string> = { accountant: "бухгалтер (accountant)", cfo: "Анастасия (cfo)" };
|
||||
|
||||
export async function buildDailySummary(pool: Pool, now: Date, tz: string, opts: SummaryOptions = {}): Promise<string> {
|
||||
const today = localDate(now, tz);
|
||||
const yesterdayInstant = new Date(now.getTime() - 24 * 3600_000);
|
||||
const yesterday = localDate(yesterdayInstant, tz);
|
||||
const old = twoWorkdaysAgo(now, tz, opts.nonWorkdays);
|
||||
|
||||
const hasProblem = "(problem_highlight is not null and btrim(problem_highlight) <> '')";
|
||||
const queue = await pool.query(
|
||||
`select kind, assignee_role,
|
||||
count(*)::int as n,
|
||||
count(*) filter (where ${hasProblem})::int as problems,
|
||||
count(*) filter (where created_at < $2)::int as old,
|
||||
count(*) filter (where problem_highlight ~* 'жд[её]т документ')::int as wait_doc,
|
||||
count(*) filter (where problem_highlight ~* 'дубл')::int as dup,
|
||||
count(*) filter (where problem_highlight ~* 'нужен человек')::int as human
|
||||
from acc_manual_review
|
||||
where snoozed_until is null or snoozed_until <= $1
|
||||
group by kind, assignee_role`,
|
||||
[now, old],
|
||||
);
|
||||
const snoozed = (await pool.query("select count(*)::int n from acc_manual_review where snoozed_until > $1", [now])).rows[0].n as number;
|
||||
|
||||
const byKind = new Map<string, { n: number; problems: number }>();
|
||||
const byRole = new Map<string, number>();
|
||||
let total = 0;
|
||||
let oldCount = 0;
|
||||
let waitDoc = 0;
|
||||
let dup = 0;
|
||||
let human = 0;
|
||||
for (const r of queue.rows) {
|
||||
const k = KIND_LABEL[r.kind] ? r.kind : "other";
|
||||
const cur = byKind.get(k) ?? { n: 0, problems: 0 };
|
||||
cur.n += r.n;
|
||||
cur.problems += r.problems;
|
||||
byKind.set(k, cur);
|
||||
byRole.set(r.assignee_role, (byRole.get(r.assignee_role) ?? 0) + r.n);
|
||||
total += r.n;
|
||||
oldCount += r.old;
|
||||
if (r.kind === "categorization") {
|
||||
waitDoc += r.wait_doc;
|
||||
dup += r.dup;
|
||||
human += r.human;
|
||||
}
|
||||
}
|
||||
|
||||
const lines: string[] = [];
|
||||
lines.push(`Сводка бухгалтерского помощника на ${ruDate(today)}`);
|
||||
lines.push("");
|
||||
lines.push(`В очереди ручного разбора: ${tasks(total)}`);
|
||||
for (const k of ["invoice", "categorization", "certificate", "other"]) {
|
||||
const v = byKind.get(k);
|
||||
if (k === "other" && !v) continue;
|
||||
const label = k === "other" ? "прочие" : KIND_LABEL[k]!;
|
||||
lines.push(`- ${label}: ${v?.n ?? 0}, из них с проблемой: ${v?.problems ?? 0}`);
|
||||
}
|
||||
const roles = [...byRole.keys()].sort();
|
||||
for (const role of ["accountant", "cfo"]) if (!roles.includes(role)) roles.push(role);
|
||||
lines.push(`Ждут по ролям: ${roles.map((r) => `${ROLE_LABEL[r] ?? r} - ${byRole.get(r) ?? 0}`).join("; ")}`);
|
||||
if (snoozed > 0) lines.push(`Отложено до даты повторного показа: ${snoozed}`);
|
||||
lines.push(`Категоризация: ждёт документ - ${waitDoc}; подозрение на дубль - ${dup}; нужен человек - ${human}${opts.bankFeedUrl ? ` (лента банка: ${opts.bankFeedUrl})` : ""}`);
|
||||
if (opts.mathesarUrl) lines.push(`Очередь в Mathesar: ${opts.mathesarUrl}`);
|
||||
|
||||
// Сводка за вчера: границы суток в tz.
|
||||
const hist = await pool.query(
|
||||
`with h as (
|
||||
select closed_by, closed_at, created_at, changed_fields from acc_invoices_review_history
|
||||
union all select closed_by, closed_at, created_at, changed_fields from acc_categorization_review_history
|
||||
union all select closed_by, closed_at, created_at, changed_fields from acc_certificates_review_history
|
||||
), bounds as (
|
||||
select (date_trunc('day', $1::timestamptz at time zone $2) - interval '1 day') at time zone $2 as s,
|
||||
date_trunc('day', $1::timestamptz at time zone $2) at time zone $2 as e
|
||||
)
|
||||
select coalesce(closed_by, '') as closed_by,
|
||||
count(*)::int as n,
|
||||
count(*) filter (where coalesce(changed_fields, '{}'::jsonb) = '{}'::jsonb)::int as clean,
|
||||
coalesce(sum(extract(epoch from (closed_at - created_at))), 0)::float8 as secs
|
||||
from h, bounds where closed_at >= s and closed_at < e
|
||||
group by 1 order by n desc, 1`,
|
||||
[now, tz],
|
||||
);
|
||||
const closed = hist.rows.reduce((a, r) => a + r.n, 0);
|
||||
const clean = hist.rows.reduce((a, r) => a + r.clean, 0);
|
||||
const secs = hist.rows.reduce((a, r) => a + r.secs, 0);
|
||||
|
||||
lines.push("");
|
||||
lines.push(`За вчера (${ruDate(yesterday)}):`);
|
||||
if (closed === 0) {
|
||||
lines.push("- закрытых задач не было");
|
||||
} else {
|
||||
const who = hist.rows.map((r) => `${r.closed_by === "" ? "кто не указан" : r.closed_by} - ${r.n}`).join(", ");
|
||||
lines.push(`- закрыто: ${tasks(closed)} (${who})`);
|
||||
lines.push(`- закрыто без правок автомата: ${clean} из ${closed} (${Math.round((clean / closed) * 100)}%)`);
|
||||
lines.push(`- среднее время от создания задачи до закрытия: ${duration(secs / closed)}`);
|
||||
}
|
||||
lines.push(`- ждут больше 2 рабочих дней: ${oldCount}`);
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export interface PostSummaryDeps {
|
||||
pool: Pool;
|
||||
slack: SlackPoster;
|
||||
/** Канал бухгалтерии (settings.slack.accountingChannelId). */
|
||||
channelId: string;
|
||||
now?: () => Date;
|
||||
/** Часовой пояс сводки, например "Asia/Nicosia" (10:00 по Кипру). */
|
||||
tz: string;
|
||||
options?: SummaryOptions;
|
||||
}
|
||||
|
||||
/** Строит сводку и отправляет в канал бухгалтерии; возвращает отправленный текст. */
|
||||
export async function postDailySummary(deps: PostSummaryDeps): Promise<string> {
|
||||
const text = await buildDailySummary(deps.pool, (deps.now ?? (() => new Date()))(), deps.tz, deps.options);
|
||||
await deps.slack.post(deps.channelId, text);
|
||||
return text;
|
||||
}
|
||||
Reference in New Issue
Block a user