Ручки для ассистентов: очередь кратко, остаток по контракту, поиск чека (список и ответ); раздел интерфейсов в передаче
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { createTestDb, testDatabaseUrl, type TestDb } from "khb_common";
|
||||
import { buildApi } from "./http-api.js";
|
||||
|
||||
const url = testDatabaseUrl();
|
||||
const d = url ? describe : describe.skip;
|
||||
|
||||
d("ручки для ассистентов (временная БД)", () => {
|
||||
let db: TestDb;
|
||||
let app: FastifyInstance;
|
||||
let emp: string;
|
||||
const auth = { authorization: "Bearer svc-token" };
|
||||
const post = async (path: string, payload: Record<string, unknown>, headers: Record<string, string> = auth) => {
|
||||
const r = await app.inject({ method: "POST", url: path, headers, payload });
|
||||
return { status: r.statusCode, body: r.json() as Record<string, any> };
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
db = await createTestDb(url!);
|
||||
emp = (await db.pool.query("insert into person (display_name, slack_user_id) values ('Алёна','U1') returning id")).rows[0].id as string;
|
||||
const settings = { http: { host: "127.0.0.1", port: 0, token: "svc-token" }, reviewers: [], mcp: { enabled: false, staticTokens: [] } };
|
||||
app = buildApi({ pool: db.pool, settings, jobs: { "invoices-mail": async () => 1, finalize: async () => 1, categorize: async () => 1, summary: async () => 1 } });
|
||||
});
|
||||
afterAll(async () => {
|
||||
await app?.close();
|
||||
await db?.drop();
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await db.pool.query("truncate acc_manual_review, acc_receipt_search, acc_contracts cascade");
|
||||
});
|
||||
|
||||
it("закрыты токеном сервиса", async () => {
|
||||
expect((await post("/queue/summary", {}, {})).status).toBe(401);
|
||||
});
|
||||
|
||||
it("очередь кратко: по ролям и видам, с проблемой, отложенные не считаются", async () => {
|
||||
await db.pool.query(`insert into acc_manual_review (kind, ref_table, ref_id, assignee_role, problem_highlight, snoozed_until) values
|
||||
('invoice','acc_invoices_review','1','accountant','нет проекта',null),
|
||||
('invoice','acc_invoices_review','2','accountant',null,null),
|
||||
('categorization','acc_categorization_review','3','cfo',null,null),
|
||||
('invoice','acc_invoices_review','4','accountant',null, now() + interval '1 day')`);
|
||||
const all = await post("/queue/summary", {});
|
||||
expect(all.body.total).toBe(3);
|
||||
expect(all.body.queue.find((r: any) => r.role === "accountant" && r.kind === "invoice")).toMatchObject({ total: 2, with_problem: 1 });
|
||||
const cfo = await post("/queue/summary", { role: "cfo" });
|
||||
expect(cfo.body.total).toBe(1);
|
||||
expect((await post("/queue/summary", { role: "boss" })).status).toBe(400);
|
||||
});
|
||||
|
||||
it("остаток по контракту", async () => {
|
||||
await db.pool.query("insert into acc_contracts (vendor_name, project_customer_id, total_amount, paid_amount, retained_amount) values ('Window Co','C1',10000,2000,3000)");
|
||||
const r = await post("/contract/balance", { vendor_name: "window co" });
|
||||
expect(r.status).toBe(200);
|
||||
expect(r.body.contracts).toHaveLength(1);
|
||||
expect(r.body.contracts[0].vendor_name).toBe("Window Co");
|
||||
expect((await post("/contract/balance", {})).status).toBe(400);
|
||||
});
|
||||
|
||||
it("поиск чека: открытые по slack_user_id и запись ответа (личный расход, не знаю, повтор)", async () => {
|
||||
const mk = async (feed: string) =>
|
||||
(await db.pool.query("insert into acc_receipt_search (feed_txn_id, responsible_person_id, vendor_name, amount) values ($1,$2,'Home Depot',120) returning id", [feed, emp])).rows[0].id as string;
|
||||
const s1 = await mk("F1");
|
||||
const s2 = await mk("F2");
|
||||
const open = await post("/receipt-search/open", { slack_user_id: "U1" });
|
||||
expect(open.body.searches).toHaveLength(2);
|
||||
expect((await post("/receipt-search/open", { slack_user_id: "NOPE" })).status).toBe(400);
|
||||
|
||||
const a1 = await post("/receipt-search/answer", { search_id: s1, kind: "personal" });
|
||||
expect(a1.body).toMatchObject({ ok: true, already: false, answer: "personal" });
|
||||
const t1 = (await db.pool.query("select assignee_role, problem_highlight from acc_manual_review where ref_id = $1", [s1])).rows[0];
|
||||
expect(t1.assignee_role).toBe("accountant");
|
||||
expect(t1.problem_highlight).toMatch(/Личный расход/);
|
||||
|
||||
const a2 = await post("/receipt-search/answer", { search_id: s2, kind: "unknown" });
|
||||
expect(a2.body.answer).toBe("unknown");
|
||||
expect((await db.pool.query("select assignee_role from acc_manual_review where ref_id = $1", [s2])).rows[0].assignee_role).toBe("cfo");
|
||||
|
||||
expect((await post("/receipt-search/answer", { search_id: s1, kind: "personal" })).body.already).toBe(true);
|
||||
expect((await post("/receipt-search/answer", { search_id: s1, kind: "maybe" })).status).toBe(400);
|
||||
expect((await post("/receipt-search/answer", { search_id: "00000000-0000-0000-0000-000000000000", kind: "personal" })).status).toBe(404);
|
||||
});
|
||||
});
|
||||
86
packages/accounting_automation/src/assistant-http.ts
Normal file
86
packages/accounting_automation/src/assistant-http.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import type { FastifyInstance, FastifyReply } from "fastify";
|
||||
import type { Pool } from "khb_common";
|
||||
import { ChargebackError, contractBalance } from "./chargeback.js";
|
||||
import { recordSearchAnswer, type AnswerKind } from "./receipts.js";
|
||||
|
||||
type Json = Record<string, unknown>;
|
||||
|
||||
/**
|
||||
* Ручки под токеном сервиса для ассистентов в Slack (ассистент бухгалтерии, ассистент менеджера):
|
||||
* очередь кратко, остаток по контракту, открытые «поиски чека» человека и запись ответа по ним.
|
||||
* Только данные и расчёты; сообщения в Slack пишут сами ассистенты. Тела - JSON-объекты; ошибки: {error, message}.
|
||||
*/
|
||||
export function registerAssistantRoutes(app: FastifyInstance, deps: { pool: Pool }): void {
|
||||
const body = (req: { body: unknown }): Json => (req.body && typeof req.body === "object" && !Array.isArray(req.body) ? (req.body as Json) : {});
|
||||
const run = async (reply: FastifyReply, fn: () => Promise<unknown>): Promise<unknown> => {
|
||||
try {
|
||||
return await fn();
|
||||
} catch (e) {
|
||||
if (e instanceof ChargebackError) return reply.code(e.status).send({ error: e.code, message: e.message });
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
/** Очередь acc_manual_review кратко: по ролям и видам - сколько всего и сколько с проблемой (отложенные не считаются). */
|
||||
app.post("/queue/summary", (req, reply) =>
|
||||
run(reply, async () => {
|
||||
const b = body(req);
|
||||
const role = typeof b.role === "string" ? b.role : null;
|
||||
if (role !== null && role !== "accountant" && role !== "cfo") throw new ChargebackError(400, "bad_request", "role: accountant или cfo");
|
||||
const { rows } = await deps.pool.query(
|
||||
`select assignee_role as role, kind, count(*)::int as total,
|
||||
count(*) filter (where nullif(btrim(problem_highlight), '') is not null)::int as with_problem,
|
||||
min(created_at) as oldest
|
||||
from acc_manual_review
|
||||
where ($1::text is null or assignee_role = $1) and (snoozed_until is null or snoozed_until <= now())
|
||||
group by 1, 2 order by 1, 2`,
|
||||
[role],
|
||||
);
|
||||
return { queue: rows, total: rows.reduce((n, r) => n + Number(r.total), 0) };
|
||||
}),
|
||||
);
|
||||
|
||||
/** Остаток по контракту: сумма, удержания, оплачено, остаток (поиск по contract_id или vendor_name, можно с project_customer_id). */
|
||||
app.post("/contract/balance", (req, reply) => run(reply, () => contractBalance(deps.pool, body(req))));
|
||||
|
||||
/** Открытые «поиски чека» человека (person_id или slack_user_id): что у него без чека. */
|
||||
app.post("/receipt-search/open", (req, reply) =>
|
||||
run(reply, async () => {
|
||||
const b = body(req);
|
||||
let personId = typeof b.person_id === "string" ? b.person_id : null;
|
||||
if (!personId && typeof b.slack_user_id === "string") {
|
||||
personId = (await deps.pool.query<{ id: string }>("select id from person where slack_user_id = $1 and is_active limit 1", [b.slack_user_id])).rows[0]?.id ?? null;
|
||||
}
|
||||
if (!personId) throw new ChargebackError(400, "bad_request", "нужен person_id или известный slack_user_id");
|
||||
const { rows } = await deps.pool.query(
|
||||
`select id, vendor_name, amount, to_char(txn_date, 'YYYY-MM-DD') as txn_date, card_or_account, escalation_level, last_asked_at, answer, asks
|
||||
from acc_receipt_search where responsible_person_id = $1 and closed_at is null order by created_at`,
|
||||
[personId],
|
||||
);
|
||||
return { person_id: personId, searches: rows };
|
||||
}),
|
||||
);
|
||||
|
||||
/** Запись ответа человека по поиску чека: kind personal (личный расход) или unknown (не знаю, что это). */
|
||||
app.post("/receipt-search/answer", (req, reply) =>
|
||||
run(reply, async () => {
|
||||
const b = body(req);
|
||||
const kind = b.kind;
|
||||
if (kind !== "personal" && kind !== "unknown") throw new ChargebackError(400, "bad_request", "kind: personal или unknown");
|
||||
if (typeof b.search_id !== "string") throw new ChargebackError(400, "bad_request", "нужен search_id");
|
||||
const s = (
|
||||
await deps.pool.query<{ id: string; vendor_name: string | null; amount: string | null; answer: string | null; closed_at: string | null; who: string | null }>(
|
||||
`select s.id, s.vendor_name, s.amount, s.answer, s.closed_at, p.display_name as who
|
||||
from acc_receipt_search s left join person p on p.id = s.responsible_person_id where s.id::text = $1`,
|
||||
[b.search_id],
|
||||
)
|
||||
).rows[0];
|
||||
if (!s) throw new ChargebackError(404, "not_found", "поиск чека не найден");
|
||||
if (s.closed_at) throw new ChargebackError(409, "closed", "поиск чека уже закрыт");
|
||||
if (s.answer) return { ok: true, already: true, answer: s.answer };
|
||||
const op = `${s.vendor_name ?? "вендор неизвестен"}${s.amount != null ? ` $${Number(s.amount).toFixed(2)}` : ""}`;
|
||||
await recordSearchAnswer(deps.pool, s.id, kind as AnswerKind, typeof b.who === "string" ? b.who : (s.who ?? "сотрудник"), op);
|
||||
return { ok: true, already: false, answer: kind };
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import Fastify, { type FastifyInstance } from "fastify";
|
||||
import type { Pool } from "khb_common";
|
||||
import { registerAssistantRoutes } from "./assistant-http.js";
|
||||
import { registerChargebackRoutes } from "./chargeback-http.js";
|
||||
import { registerMcp } from "./mcp.js";
|
||||
import type { AccountingSettings } from "./settings.js";
|
||||
@@ -91,6 +92,7 @@ export function buildApi(deps: ApiDeps): FastifyInstance {
|
||||
|
||||
// --- ручки chargeback для ассистента менеджера (под токеном сервиса)
|
||||
registerChargebackRoutes(app, { pool: deps.pool });
|
||||
registerAssistantRoutes(app, { pool: deps.pool });
|
||||
|
||||
// --- MCP для Claude сотрудников (Streamable HTTP, без сессий)
|
||||
if (deps.settings.mcp.enabled) {
|
||||
|
||||
@@ -179,6 +179,21 @@ export async function upsertSearchTask(pool: Pool, searchId: string, role: "acco
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Записывает ответ человека на вопрос «Поиска чека» (шаг 7): личный расход - задача Юле, «не знаю» - задача Анастасии.
|
||||
* Вызывается из разбора Slack и из ручки /receipt-search/answer (ассистент бухгалтерии); в Slack сама ничего не отвечает.
|
||||
*/
|
||||
export async function recordSearchAnswer(pool: Pool, searchId: string, kind: AnswerKind, who: string, op: string): Promise<void> {
|
||||
await pool.query("update acc_receipt_search set answer = $2 where id = $1", [searchId, kind]);
|
||||
if (kind === "personal") {
|
||||
// шаг 7: Юля оформляет возврат от сотрудника или удержание, Анастасия подтверждает
|
||||
await upsertSearchTask(pool, searchId, "accountant", `Личный расход по словам ${who} (${op}): оформить как возврат от сотрудника или удержание, подтверждает Анастасия`);
|
||||
} else {
|
||||
// шаг 7: подозрительное списание - решает Анастасия (fraud)
|
||||
await upsertSearchTask(pool, searchId, "cfo", `Подозрительное списание (${op}): ${who} не знает, что это. Решить про fraud (процесс «Подозрительные операции по карте (fraud)»)`);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------- основной процесс
|
||||
|
||||
const safeName = (s: string): string => s.replace(/[\\/:*?"<>|\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, 100) || "_";
|
||||
@@ -368,16 +383,12 @@ async function processText(deps: ReceiptsDeps, ctx: Ctx, m: SlackMessage, person
|
||||
}
|
||||
const s = searches[0]!;
|
||||
const op = `${s.vendor_name ?? "вендор неизвестен"}${s.amount != null ? ` ${money(Number(s.amount))}` : ""}`;
|
||||
await pool.query("update acc_receipt_search set answer = $2 where id = $1", [s.id, kind]);
|
||||
if (kind === "personal") {
|
||||
// шаг 7: Юля оформляет возврат от сотрудника или удержание, Анастасия подтверждает
|
||||
await upsertSearchTask(pool, s.id, "accountant", `Личный расход по словам ${person.display_name} (${op}): оформить как возврат от сотрудника или удержание, подтверждает Анастасия`);
|
||||
await say(deps, m, "Принято: личный расход. Бухгалтер оформит возврат или удержание.");
|
||||
} else {
|
||||
// шаг 7: подозрительное списание - решает Анастасия (fraud)
|
||||
await upsertSearchTask(pool, s.id, "cfo", `Подозрительное списание (${op}): ${person.display_name} не знает, что это. Решить про fraud (процесс «Подозрительные операции по карте»)`);
|
||||
await say(deps, m, "Принято. Передал вопрос Анастасии: она проверит списание.");
|
||||
}
|
||||
await recordSearchAnswer(pool, s.id, kind, person.display_name, op);
|
||||
await say(
|
||||
deps,
|
||||
m,
|
||||
kind === "personal" ? "Принято: личный расход. Бухгалтер оформит возврат или удержание." : "Принято. Передал вопрос Анастасии: она проверит списание.",
|
||||
);
|
||||
ctx.result.answers++;
|
||||
return "answer";
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user