acc_invoices: журнал без зависания (Proxy вместо подмены query), общий журнал /api/log, MCP-инструменты acc_inv_* (все функции WebUI и анализ журнала)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
90
packages/accounting_automation/src/acc-invoices-tool-defs.ts
Normal file
90
packages/accounting_automation/src/acc-invoices-tool-defs.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
/** Описания MCP-инструментов платёжного процесса (acc_inv_*), отдельный файл без импорта mcp.ts: нет циклической зависимости. */
|
||||
type Json = Record<string, unknown>;
|
||||
|
||||
const obj = (properties: Json, required: string[] = []): Json => ({ type: "object", properties, required, additionalProperties: false });
|
||||
const idP = { type: "string", description: "id инвойса (полный uuid из acc_inv_list)" };
|
||||
const actingP = { type: "string", enum: ["cfo", "accountant", "employee"], description: "действовать под этой ролью (только для CFO и admin, как переключатель в WebUI); по умолчанию - роль по умолчанию человека" };
|
||||
const write = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };
|
||||
const read = { readOnlyHint: true, openWorldHint: false };
|
||||
const FIELDS =
|
||||
"vendor_name, vendor_qbo_id, invoice_number, invoice_date (YYYY-MM-DD), amount, project_customer_id (проект QuickBooks) или internal_project_id (внутренний проект из acc_inv_lookups; нельзя вместе), jt_job_id, contract_id, target_employee (кто ждёт инвойс, person id; по умолчанию автор), need_employee_refund, is_employee_refunded, invoice_url, payment_url, pay_method, pay_link (URL для оплаты), description (описание текстом), no_invoice_file (true = «Файла Invoice пока нет»), review_date (YYYY-MM-DD, отложить), is_paid_manual, manual_result. Что можно менять, зависит от роли и стадии: смотри editable в acc_inv_get.";
|
||||
|
||||
export const ACC_INV_TOOLS: { name: string; description: string; inputSchema: Json; annotations?: Json }[] = [
|
||||
{
|
||||
name: "acc_inv_list",
|
||||
annotations: read,
|
||||
description:
|
||||
"Список инвойсов платёжного процесса (то же, что таблица WebUI /invoices/): статус, проверки, ошибки, суммы, кто ждёт. Сотрудник видит только свои, бухгалтерия и CFO - все. filter: approval (на согласовании), to_pay (К оплате), pending_qb (ждут QuickBooks), paid, errors, drafts, all; q - поиск по вендору, номеру, проекту, людям, сумме. В ответе items и counts по фильтрам.",
|
||||
inputSchema: obj({ filter: { type: "string", enum: ["approval", "to_pay", "pending_qb", "paid", "errors", "drafts", "all"] }, q: { type: "string" }, acting_role: actingP }),
|
||||
},
|
||||
{
|
||||
name: "acc_inv_get",
|
||||
annotations: read,
|
||||
description: "Один инвойс целиком: поля, статус, ошибки, editable (что вам можно менять), строки (если строк нет, одна виртуальная на всю сумму), согласования, панель контракта. История изменений: acc_inv_log.",
|
||||
inputSchema: obj({ id: idP, acting_role: actingP }, ["id"]),
|
||||
},
|
||||
{
|
||||
name: "acc_inv_lookups",
|
||||
annotations: read,
|
||||
description: "Справочники для создания и правки инвойса: люди, проекты QuickBooks, внутренние проекты (acc_internal_projects: «ИТ KHBuild», «KHBuild внутренние затраты»), категории, строки контракта и т. п.",
|
||||
inputSchema: obj({}),
|
||||
},
|
||||
{
|
||||
name: "acc_inv_create",
|
||||
annotations: write,
|
||||
description: `Создать инвойс (черновик). Обязательно vendor_name; сумма по умолчанию 0. Поля: ${FIELDS} Строки задавать не обязательно (acc_inv_set_lines). Дальше: acc_inv_action submit. Ответ: {id}.`,
|
||||
inputSchema: obj({ fields: { type: "object", description: "{поле: значение}" }, acting_role: actingP }, ["fields"]),
|
||||
},
|
||||
{
|
||||
name: "acc_inv_update",
|
||||
annotations: write,
|
||||
description: `Изменить поля инвойса. Поля: ${FIELDS}`,
|
||||
inputSchema: obj({ id: idP, fields: { type: "object", description: "{поле: новое значение}" }, acting_role: actingP }, ["id", "fields"]),
|
||||
},
|
||||
{
|
||||
name: "acc_inv_set_lines",
|
||||
annotations: write,
|
||||
description: "Заменить строки инвойса (черновик: состав и суммы; вне черновика только бухгалтерия и только категории). lines: [{description, amount, quantity?, unit_price?, category_qbo_id?, category_name?, contract_detail_id?}]. Сумма строк должна совпадать с суммой инвойса при отправке; пустой список = одна строка на всю сумму.",
|
||||
inputSchema: obj({ id: idP, lines: { type: "array", items: { type: "object" } }, acting_role: actingP }, ["id", "lines"]),
|
||||
},
|
||||
{
|
||||
name: "acc_inv_action",
|
||||
annotations: write,
|
||||
description:
|
||||
"Действие над инвойсом, как кнопки WebUI: submit (отправить в процесс из черновика; запускает проверку агента), draft (вернуть в черновик, сбрасывает проверки и согласования), sent_to_bank (переключатель «Отправлено в банк»; через 24 ч без оплаты в QuickBooks - ошибка), paid_manual (переключатель «Оплачен вручную», QuickBooks подтвердит позже), cancel (переключатель «Отменён»). Ответ покажет новое состояние или проблемы (например, суммы строк не сходятся).",
|
||||
inputSchema: obj({ id: idP, action: { type: "string", enum: ["submit", "draft", "sent_to_bank", "paid_manual", "cancel"] }, acting_role: actingP }, ["id", "action"]),
|
||||
},
|
||||
{
|
||||
name: "acc_inv_manual_result",
|
||||
annotations: write,
|
||||
description: "Только бухгалтерия: результат ручной проверки инвойса. «OK» (любой регистр, латиница или кириллица: OK, ok, ОК, ок) = проверка пройдена, любой другой текст = найденная проблема.",
|
||||
inputSchema: obj({ id: idP, result: { type: "string" }, acting_role: actingP }, ["id", "result"]),
|
||||
},
|
||||
{
|
||||
name: "acc_inv_assign_approvers",
|
||||
annotations: write,
|
||||
description: "Только бухгалтерия: назначить согласующих инвойса (person id из acc_inv_lookups); инвойс уходит в «На согласовании», пока все не согласуют.",
|
||||
inputSchema: obj({ id: idP, person_ids: { type: "array", items: { type: "string" } }, acting_role: actingP }, ["id", "person_ids"]),
|
||||
},
|
||||
{
|
||||
name: "acc_inv_decide",
|
||||
annotations: write,
|
||||
description: "Решение согласующего: approved или rejected (с комментарием). Решает назначенный согласующий; CFO может за любого (on_behalf_of = person id). После отправки в банк согласование не меняется.",
|
||||
inputSchema: obj({ id: idP, decision: { type: "string", enum: ["approved", "rejected"] }, comment: { type: "string" }, on_behalf_of: { type: "string" }, acting_role: actingP }, ["id", "decision"]),
|
||||
},
|
||||
{
|
||||
name: "acc_inv_log",
|
||||
annotations: read,
|
||||
description:
|
||||
"Журнал изменений платёжного процесса и его анализ (только бухгалтерия, CFO, admin): кто, когда, через какое действие и что изменил (старое и новое значение) в инвойсах, строках и согласованиях; изменения заданий и ручные правки в БД идут без автора. Фильтры: invoice_id, actor (часть имени), action (часть, например sent-to-bank или mcp), tbl, field (было ли изменено это поле), since/until (ISO дата или время), system_only (только не из WebUI). group: actor | action | invoice | day - вернуть счётчики событий вместо строк (разбор: кто что чаще делает, какие инвойсы самые активные). limit до 500 (по умолчанию 100), новые сверху.",
|
||||
inputSchema: obj({
|
||||
invoice_id: { type: "string" }, actor: { type: "string" }, action: { type: "string" },
|
||||
tbl: { type: "string", enum: ["acc_invoices", "acc_invoices_details", "acc_invoices_approves"] }, field: { type: "string" },
|
||||
since: { type: "string" }, until: { type: "string" }, system_only: { type: "boolean" },
|
||||
group: { type: "string", enum: ["actor", "action", "invoice", "day"] }, limit: { type: "number" }, acting_role: actingP,
|
||||
}),
|
||||
},
|
||||
];
|
||||
|
||||
export const ACC_INV_TOOL_NAMES = new Set(ACC_INV_TOOLS.map((t) => t.name));
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ACC_INV_TOOLS, AccInvoicesTools } from "./acc-invoices-tools.js";
|
||||
import { McpToolError, TOOLS } from "./mcp.js";
|
||||
|
||||
const PERSON = "11111111-1111-1111-1111-111111111111";
|
||||
const INV = "22222222-2222-2222-2222-222222222222";
|
||||
|
||||
function fake(status = 200, body: unknown = { ok: true }) {
|
||||
const calls: { url: string; init: RequestInit }[] = [];
|
||||
const f = (async (url: string, init: RequestInit) => {
|
||||
calls.push({ url, init });
|
||||
return new Response(JSON.stringify(body), { status });
|
||||
}) as unknown as typeof fetch;
|
||||
return { calls, f };
|
||||
}
|
||||
|
||||
describe("MCP платёжного процесса (acc_inv_*)", () => {
|
||||
it("инструменты подключены к общему списку, имена уникальны", () => {
|
||||
const names = TOOLS.map((t) => t.name);
|
||||
for (const t of ACC_INV_TOOLS) expect(names).toContain(t.name);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
});
|
||||
|
||||
it("вызов идёт в API от имени человека с внутренним токеном и пометкой инструмента", async () => {
|
||||
const { calls, f } = fake();
|
||||
const t = new AccInvoicesTools({ url: "http://acc:8097/", internalToken: "x".repeat(30) }, f);
|
||||
await t.call(PERSON, "acc_inv_action", { id: INV, action: "sent_to_bank", acting_role: "cfo" });
|
||||
expect(calls[0].url).toBe(`http://acc:8097/api/invoices/${INV}/sent-to-bank`);
|
||||
expect(calls[0].init.method).toBe("POST");
|
||||
const h = calls[0].init.headers as Record<string, string>;
|
||||
expect(h["x-person-id"]).toBe(PERSON);
|
||||
expect(h["x-internal-token"]).toBe("x".repeat(30));
|
||||
expect(h["x-via"]).toBe("mcp:acc_inv_action");
|
||||
expect(h["x-acting-role"]).toBe("cfo");
|
||||
});
|
||||
|
||||
it("журнал: фильтры уходят в query", async () => {
|
||||
const { calls, f } = fake(200, { items: [] });
|
||||
const t = new AccInvoicesTools({ url: "http://acc", internalToken: "x".repeat(30) }, f);
|
||||
await t.call(PERSON, "acc_inv_log", { actor: "Анастасия", group: "action", system_only: true, limit: 5 });
|
||||
const u = new URL(calls[0].url);
|
||||
expect(u.pathname).toBe("/api/log");
|
||||
expect(u.searchParams.get("actor")).toBe("Анастасия");
|
||||
expect(u.searchParams.get("group")).toBe("action");
|
||||
expect(u.searchParams.get("system_only")).toBe("true");
|
||||
expect(u.searchParams.get("limit")).toBe("5");
|
||||
});
|
||||
|
||||
it("ошибка API становится ошибкой инструмента с текстом проблем; без токена и с плохим id - понятные сообщения", async () => {
|
||||
const { f } = fake(422, { error: "нельзя отправить", problems: ["сумма строк не равна сумме инвойса"] });
|
||||
const t = new AccInvoicesTools({ url: "http://acc", internalToken: "x".repeat(30) }, f);
|
||||
await expect(t.call(PERSON, "acc_inv_action", { id: INV, action: "submit" })).rejects.toThrow(/нельзя отправить: сумма строк/);
|
||||
await expect(t.call(PERSON, "acc_inv_get", { id: "abc" })).rejects.toBeInstanceOf(McpToolError);
|
||||
await expect(new AccInvoicesTools(undefined, f).call(PERSON, "acc_inv_list", {})).rejects.toThrow(/internalToken/);
|
||||
});
|
||||
});
|
||||
77
packages/accounting_automation/src/acc-invoices-tools.ts
Normal file
77
packages/accounting_automation/src/acc-invoices-tools.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import { ACC_INV_TOOL_NAMES, ACC_INV_TOOLS } from "./acc-invoices-tool-defs.js";
|
||||
import { McpToolError } from "./mcp.js";
|
||||
|
||||
export { ACC_INV_TOOL_NAMES, ACC_INV_TOOLS };
|
||||
|
||||
/**
|
||||
* MCP-инструменты платёжного процесса (сервис acc_invoices): всё, что можно сделать в WebUI /invoices/, доступно и здесь.
|
||||
* Инструмент не дублирует правила: он вызывает API acc_invoices от имени человека (внутренний токен + x-person-id),
|
||||
* поэтому права, проверки и журнал изменений те же, что в WebUI; в журнале действие помечено «via mcp:<инструмент>».
|
||||
*/
|
||||
type Json = Record<string, unknown>;
|
||||
|
||||
export interface AccInvoicesCfg { url: string; internalToken?: string }
|
||||
|
||||
const ACTION_PATH: Record<string, string> = { submit: "submit", draft: "draft", sent_to_bank: "sent-to-bank", paid_manual: "paid-manual", cancel: "cancel" };
|
||||
|
||||
export class AccInvoicesTools {
|
||||
constructor(private readonly cfg: AccInvoicesCfg | undefined, private readonly fetchFn: typeof fetch = fetch) {}
|
||||
|
||||
private async req(personId: string, via: string, method: string, path: string, a: Json, body?: unknown): Promise<Json> {
|
||||
if (!this.cfg?.internalToken) throw new McpToolError("Платёжный процесс не подключён к MCP: не задан accInvoices.internalToken.");
|
||||
const headers: Record<string, string> = { "x-internal-token": this.cfg.internalToken, "x-person-id": personId, "x-via": `mcp:${via}`, accept: "application/json" };
|
||||
if (typeof a.acting_role === "string") headers["x-acting-role"] = a.acting_role;
|
||||
if (body !== undefined) headers["content-type"] = "application/json";
|
||||
let res: Response;
|
||||
try {
|
||||
res = await this.fetchFn(`${this.cfg.url.replace(/\/$/, "")}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
|
||||
} catch (e) {
|
||||
throw new McpToolError(`Сервис платёжного процесса недоступен: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
const text = await res.text();
|
||||
let j: Json;
|
||||
try { j = text ? (JSON.parse(text) as Json) : {}; } catch { j = { raw: text.slice(0, 500) }; }
|
||||
if (!res.ok) {
|
||||
const extra = Array.isArray(j.problems) ? `: ${(j.problems as string[]).join("; ")}` : Array.isArray(j.issues) ? `: ${(j.issues as string[]).join("; ")}` : "";
|
||||
throw new McpToolError(`${String(j.error ?? `HTTP ${res.status}`)}${extra}`);
|
||||
}
|
||||
return j;
|
||||
}
|
||||
|
||||
private id(a: Json): string {
|
||||
if (typeof a.id !== "string" || !/^[0-9a-f-]{36}$/i.test(a.id)) throw new McpToolError("id: нужен полный uuid инвойса (из acc_inv_list).");
|
||||
return a.id;
|
||||
}
|
||||
|
||||
async call(personId: string, name: string, a: Json): Promise<Json> {
|
||||
const r = (m: string, p: string, body?: unknown) => this.req(personId, name, m, p, a, body);
|
||||
switch (name) {
|
||||
case "acc_inv_list": {
|
||||
const qs = new URLSearchParams();
|
||||
if (typeof a.filter === "string") qs.set("filter", a.filter);
|
||||
if (typeof a.q === "string") qs.set("q", a.q);
|
||||
return r("GET", `/api/invoices?${qs}`);
|
||||
}
|
||||
case "acc_inv_get": return r("GET", `/api/invoices/${this.id(a)}`);
|
||||
case "acc_inv_lookups": return r("GET", "/api/lookups");
|
||||
case "acc_inv_create": return r("POST", "/api/invoices", (a.fields as Json) ?? {});
|
||||
case "acc_inv_update": return r("PATCH", `/api/invoices/${this.id(a)}`, (a.fields as Json) ?? {});
|
||||
case "acc_inv_set_lines": return r("PUT", `/api/invoices/${this.id(a)}/details`, { lines: a.lines ?? [] });
|
||||
case "acc_inv_action": {
|
||||
const p = ACTION_PATH[String(a.action)];
|
||||
if (!p) throw new McpToolError("action: submit, draft, sent_to_bank, paid_manual или cancel.");
|
||||
return r("POST", `/api/invoices/${this.id(a)}/${p}`);
|
||||
}
|
||||
case "acc_inv_manual_result": return r("POST", `/api/invoices/${this.id(a)}/manual-result`, { result: a.result });
|
||||
case "acc_inv_assign_approvers": return r("POST", `/api/invoices/${this.id(a)}/approvals`, { person_ids: a.person_ids });
|
||||
case "acc_inv_decide": return r("POST", `/api/invoices/${this.id(a)}/decision`, { decision: a.decision, comment: a.comment ?? null, ...(typeof a.on_behalf_of === "string" ? { on_behalf_of: a.on_behalf_of } : {}) });
|
||||
case "acc_inv_log": {
|
||||
const qs = new URLSearchParams();
|
||||
for (const k of ["invoice_id", "actor", "action", "tbl", "field", "since", "until", "group", "limit"]) if (a[k] !== undefined && a[k] !== null) qs.set(k, String(a[k]));
|
||||
if (a.system_only === true) qs.set("system_only", "true");
|
||||
return r("GET", `/api/log?${qs}`);
|
||||
}
|
||||
default: throw new McpToolError(`Неизвестный инструмент ${name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import { REVIEW_UI_HTML, REVIEW_UI_MIME, REVIEW_UI_URI, REVIEW_UI_URI_LEGACY, ro
|
||||
import { allowWithoutReceipt } from "./receipt-search.js";
|
||||
import type { AccountingSettings } from "./settings.js";
|
||||
import { Stage2Tools } from "./stage2-tools.js";
|
||||
import { AccInvoicesTools } from "./acc-invoices-tools.js";
|
||||
import { ACC_INV_TOOLS, ACC_INV_TOOL_NAMES } from "./acc-invoices-tool-defs.js";
|
||||
import { STAGE2_TOOL_NAMES, STAGE2_TOOLS } from "./stage2-tool-defs.js";
|
||||
|
||||
/**
|
||||
@@ -22,7 +24,7 @@ export class McpToolError extends Error {}
|
||||
|
||||
export interface ReviewDeps {
|
||||
pool: Pool;
|
||||
settings: Pick<AccountingSettings, "reviewers"> & { receipts?: { qboBankingUrl?: string } };
|
||||
settings: Pick<AccountingSettings, "reviewers"> & { receipts?: { qboBankingUrl?: string }; accInvoices?: { url: string; internalToken?: string } };
|
||||
/** Лимит расхода без чека (USD), по умолчанию 500. */
|
||||
noReceiptLimitUsd?: number;
|
||||
now?: () => Date;
|
||||
@@ -148,8 +150,10 @@ const metaOf = (t: Pick<Task, "kind">): KindMeta | undefined => KINDS[t.kind];
|
||||
export class ReviewTools {
|
||||
private readonly now: () => Date;
|
||||
private readonly stage2: Stage2Tools;
|
||||
private readonly accInv: AccInvoicesTools;
|
||||
constructor(private readonly d: ReviewDeps) {
|
||||
this.now = d.now ?? (() => new Date());
|
||||
this.accInv = new AccInvoicesTools(d.settings.accInvoices);
|
||||
this.stage2 = new Stage2Tools({ pool: d.pool, rolesOf: (p) => this.rolesOf(p), now: this.now });
|
||||
}
|
||||
|
||||
@@ -566,6 +570,7 @@ export class ReviewTools {
|
||||
case "acc_receipt_allow_without": return this.allowWithoutReceipt(personId, a);
|
||||
default:
|
||||
if (STAGE2_TOOL_NAMES.has(name)) return this.stage2.call(personId, name, a);
|
||||
if (ACC_INV_TOOL_NAMES.has(name)) return this.accInv.call(personId, name, a);
|
||||
throw new McpToolError(`Неизвестный инструмент ${name}`);
|
||||
}
|
||||
}
|
||||
@@ -681,6 +686,7 @@ export const TOOLS: { name: string; description: string; inputSchema: Json; anno
|
||||
),
|
||||
},
|
||||
...STAGE2_TOOLS,
|
||||
...ACC_INV_TOOLS,
|
||||
];
|
||||
|
||||
/** Встроенный текст инструкций (копия: docs/.../p-mcp-instructions.md; сервис подставляет файл, если он доступен). */
|
||||
|
||||
@@ -93,6 +93,13 @@ export const accountingSchema = z.object({
|
||||
qboBankingUrl: z.string().default("https://app.qbo.intuit.com/app/banking"),
|
||||
})
|
||||
.default({}),
|
||||
/** Платёжный процесс (сервис acc_invoices): MCP-инструменты acc_inv_* ходят к его API с внутренним токеном (тот же, что auth.internalToken в секции acc_invoices). */
|
||||
accInvoices: z
|
||||
.object({
|
||||
url: z.string().default("http://khb-acc-invoices:8097"),
|
||||
internalToken: z.string().min(24).optional(),
|
||||
})
|
||||
.default({}),
|
||||
mcp: z
|
||||
.object({
|
||||
enabled: z.boolean().default(true),
|
||||
|
||||
Reference in New Issue
Block a user