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:
@@ -77,4 +77,5 @@ WebUI и бэкенд платёжного процесса: реестр инв
|
|||||||
- Загрузка файлов инвойса и платежа на Google Drive из интерфейса не сделана: пока вводится ссылка (в спецификации «проставляется в момент загрузки файла»).
|
- Загрузка файлов инвойса и платежа на Google Drive из интерфейса не сделана: пока вводится ссылка (в спецификации «проставляется в момент загрузки файла»).
|
||||||
- Создание инвойса из письма, из платежа и из recipe не переведено на новые поля: письма по-прежнему создают записи через accounting_automation (поля `author`, `is_draft = false`, `invoice_url` для них ставятся миграцией только для уже существующих строк).
|
- Создание инвойса из письма, из платежа и из recipe не переведено на новые поля: письма по-прежнему создают записи через accounting_automation (поля `author`, `is_draft = false`, `invoice_url` для них ставятся миграцией только для уже существующих строк).
|
||||||
- `llm_result` заполняет задание `invoice-check` (то же заключение, что в `conclusion`: «OK» или текст проблем); проверок сверх прежних (сумма в документе против таблицы, сверка с JobTread) пока нет.
|
- `llm_result` заполняет задание `invoice-check` (то же заключение, что в `conclusion`: «OK» или текст проблем); проверок сверх прежних (сумма в документе против таблицы, сверка с JobTread) пока нет.
|
||||||
|
- MCP: всё, что делает WebUI, доступно и через MCP accounting_automation (инструменты `acc_inv_list`, `acc_inv_get`, `acc_inv_lookups`, `acc_inv_create`, `acc_inv_update`, `acc_inv_set_lines`, `acc_inv_action` (submit, draft, sent_to_bank, paid_manual, cancel), `acc_inv_manual_result`, `acc_inv_assign_approvers`, `acc_inv_decide`, `acc_inv_log`). Инструмент вызывает API acc_invoices от имени человека (внутренний токен `auth.internalToken` + заголовок `x-person-id`), поэтому права, проверки и журнал те же; в журнале действие помечено «via mcp:<инструмент>». Анализ журнала: `acc_inv_log` с фильтрами (инвойс, автор, действие, поле, период) и группировкой (по автору, действию, инвойсу, дню); в WebUI доступен только журнал одного инвойса.
|
||||||
- Журнал изменений: таблица `acc_invoices_log` (миграция 085), пишется триггерами на `acc_invoices`, `acc_invoices_details`, `acc_invoices_approves`: время, автор и роль, действие WebUI, что изменилось (старое и новое значение). Правки заданий и ручные правки в БД попадают в журнал без автора (с именем пользователя БД). В WebUI виден бухгалтерии: панель «История изменений», API `GET /api/invoices/:id/log`. Строки, импортированные до миграции, начинаются без истории.
|
- Журнал изменений: таблица `acc_invoices_log` (миграция 085), пишется триггерами на `acc_invoices`, `acc_invoices_details`, `acc_invoices_approves`: время, автор и роль, действие WebUI, что изменилось (старое и новое значение). Правки заданий и ручные правки в БД попадают в журнал без автора (с именем пользователя БД). В WebUI виден бухгалтерии: панель «История изменений», API `GET /api/invoices/:id/log`. Строки, импортированные до миграции, начинаются без истории.
|
||||||
|
|||||||
@@ -34,14 +34,18 @@ export function withAudit(pool: Pool): Pool {
|
|||||||
}) as Pool["query"];
|
}) as Pool["query"];
|
||||||
wrapped.connect = (async () => {
|
wrapped.connect = (async () => {
|
||||||
const c = await pool.connect();
|
const c = await pool.connect();
|
||||||
const orig = c.query.bind(c) as (t: unknown, p?: unknown[]) => Promise<unknown>;
|
// прокси, а не подмена метода: клиент возвращается в пул и должен остаться нетронутым
|
||||||
c.query = (async (text: unknown, params?: unknown[]) => {
|
return new Proxy(c, {
|
||||||
const r = await orig(text, params);
|
get(target, prop) {
|
||||||
const a = auditStore.getStore();
|
if (prop !== "query") { const v = Reflect.get(target, prop, target) as unknown; return typeof v === "function" ? (v as (...x: unknown[]) => unknown).bind(target) : v; }
|
||||||
if (a?.actorId && typeof text === "string" && /^\s*begin\b/i.test(text)) await orig(SET_SQL, setArgs(a));
|
return async (text: unknown, params?: unknown[]) => {
|
||||||
|
const r = await (target.query as (t: unknown, p?: unknown[]) => Promise<unknown>).call(target, text, params);
|
||||||
|
const st = auditStore.getStore();
|
||||||
|
if (st?.actorId && typeof text === "string" && /^\s*begin/i.test(text)) await target.query(SET_SQL, setArgs(st));
|
||||||
return r;
|
return r;
|
||||||
}) as typeof c.query;
|
};
|
||||||
return c;
|
},
|
||||||
|
});
|
||||||
}) as Pool["connect"];
|
}) as Pool["connect"];
|
||||||
return wrapped;
|
return wrapped;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ export interface Actor {
|
|||||||
acting: ActingRole;
|
acting: ActingRole;
|
||||||
}
|
}
|
||||||
|
|
||||||
const safeEqual = (a: string, b: string): boolean => {
|
export const safeEqual = (a: string, b: string): boolean => {
|
||||||
const x = Buffer.from(a);
|
const x = Buffer.from(a);
|
||||||
const y = Buffer.from(b);
|
const y = Buffer.from(b);
|
||||||
return x.length === y.length && timingSafeEqual(x, y);
|
return x.length === y.length && timingSafeEqual(x, y);
|
||||||
@@ -67,7 +67,7 @@ export function effectiveRoles(real: string[], requested?: string): { roles: Rol
|
|||||||
return { roles: acting === "employee" ? [] : [acting], canSwitch, acting };
|
return { roles: acting === "employee" ? [] : [acting], canSwitch, acting };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function actorOf(pool: Pool, personId: string, requested?: string): Promise<Actor> {
|
export async function actorOf(pool: Pool, personId: string, requested?: string): Promise<Actor> {
|
||||||
const p = (await pool.query("select id, display_name from person where id = $1 and is_active", [personId])).rows[0];
|
const p = (await pool.query("select id, display_name from person where id = $1 and is_active", [personId])).rows[0];
|
||||||
if (!p) throw new AuthError("человек не найден или неактивен", 403);
|
if (!p) throw new AuthError("человек не найден или неактивен", 403);
|
||||||
const realRoles = await loadRoles(pool, personId);
|
const realRoles = await loadRoles(pool, personId);
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { extname, join, normalize } from "node:path";
|
|||||||
import Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify";
|
import Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify";
|
||||||
import { withTx, type Logger, type Pool } from "khb_common";
|
import { withTx, type Logger, type Pool } from "khb_common";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { AuthError, createAuth, type Actor, type JwtVerifier } from "./auth.js";
|
import { AuthError, actorOf, createAuth, safeEqual, type Actor, type JwtVerifier } from "./auth.js";
|
||||||
import { LOOKUP, getApproves, getContractPanel, getDetails, getInvoice, listInvoices, recomputeApproved, type ListItem } from "./repo.js";
|
import { LOOKUP, getApproves, getContractPanel, getDetails, getInvoice, listInvoices, recomputeApproved, type ListItem } from "./repo.js";
|
||||||
import {
|
import {
|
||||||
QUICK_FILTERS, STATUS_LABELS, canCancel, canMarkPaid, canReturnToDraft, canSendToBank, canView, dayInTz, editableFields, errorsOf, isStaff, matchesFilter, normResult, statusOf, submitProblems,
|
QUICK_FILTERS, STATUS_LABELS, canCancel, canMarkPaid, canReturnToDraft, canSendToBank, canView, dayInTz, editableFields, errorsOf, isStaff, matchesFilter, normResult, statusOf, submitProblems,
|
||||||
@@ -100,9 +100,19 @@ export function buildApi(deps: ApiDeps): FastifyInstance {
|
|||||||
// контекст автора для журнала: в каждом запросе свой, заполняется после входа
|
// контекст автора для журнала: в каждом запросе свой, заполняется после входа
|
||||||
app.addHook("onRequest", (_req, _reply, done) => { auditStore.run({}, done); });
|
app.addHook("onRequest", (_req, _reply, done) => { auditStore.run({}, done); });
|
||||||
const need = async (req: FastifyRequest): Promise<Actor> => {
|
const need = async (req: FastifyRequest): Promise<Actor> => {
|
||||||
const a = await authenticate(req.headers.authorization, typeof req.headers["x-acting-role"] === "string" ? req.headers["x-acting-role"] : undefined);
|
const acting = typeof req.headers["x-acting-role"] === "string" ? req.headers["x-acting-role"] : undefined;
|
||||||
|
const internal = req.headers["x-internal-token"];
|
||||||
|
let a: Actor;
|
||||||
|
let via = "";
|
||||||
|
if (typeof internal === "string" && settings.auth.internalToken) {
|
||||||
|
// MCP (accounting_automation): уже аутентифицированный человек, его id передаётся заголовком
|
||||||
|
const pid = req.headers["x-person-id"];
|
||||||
|
if (!safeEqual(internal, settings.auth.internalToken) || typeof pid !== "string" || !uuid.safeParse(pid).success) throw new AuthError("внутренний токен не принят", 401);
|
||||||
|
a = await actorOf(rawPool, pid, acting);
|
||||||
|
via = ` via ${String(req.headers["x-via"] ?? "mcp").slice(0, 60)}`;
|
||||||
|
} else a = await authenticate(req.headers.authorization, acting);
|
||||||
const st = auditStore.getStore();
|
const st = auditStore.getStore();
|
||||||
if (st) Object.assign(st, { actorId: a.personId, actorName: a.displayName, actingRole: a.acting, action: `${req.method} ${req.routeOptions?.url ?? req.url}` });
|
if (st) Object.assign(st, { actorId: a.personId, actorName: a.displayName, actingRole: a.acting, action: `${req.method} ${req.routeOptions?.url ?? req.url}${via}` });
|
||||||
return a;
|
return a;
|
||||||
};
|
};
|
||||||
const fail = (reply: FastifyReply, status: number, error: string) => reply.code(status).send({ error });
|
const fail = (reply: FastifyReply, status: number, error: string) => reply.code(status).send({ error });
|
||||||
@@ -171,6 +181,39 @@ export function buildApi(deps: ApiDeps): FastifyInstance {
|
|||||||
return { items: rows };
|
return { items: rows };
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/** Общий журнал и его разбор (бухгалтерия): фильтры по инвойсу, автору, действию, таблице, полю, периоду; group - счётчики вместо строк. */
|
||||||
|
app.get("/api/log", async (req, reply) => {
|
||||||
|
const a = await need(req);
|
||||||
|
if (!isStaff(a)) return fail(reply, 403, "журнал доступен бухгалтерии");
|
||||||
|
const q = z.object({
|
||||||
|
invoice_id: uuid.optional(), actor: z.string().max(100).optional(), action: z.string().max(100).optional(),
|
||||||
|
tbl: z.enum(["acc_invoices", "acc_invoices_details", "acc_invoices_approves"]).optional(), field: z.string().max(60).optional(),
|
||||||
|
since: z.string().max(40).optional(), until: z.string().max(40).optional(), system_only: z.enum(["true", "false"]).optional(),
|
||||||
|
group: z.enum(["actor", "action", "invoice", "day"]).optional(), limit: z.coerce.number().int().min(1).max(500).default(100),
|
||||||
|
}).parse(req.query);
|
||||||
|
const w: string[] = [];
|
||||||
|
const v: unknown[] = [];
|
||||||
|
const add = (sql: string, val: unknown) => { v.push(val); w.push(sql.replace("?", "$" + v.length)); };
|
||||||
|
if (q.invoice_id) add("l.invoice_id = ?", q.invoice_id);
|
||||||
|
if (q.actor) add("l.actor_name ilike ?", "%" + q.actor + "%");
|
||||||
|
if (q.action) add("l.action ilike ?", "%" + q.action + "%");
|
||||||
|
if (q.tbl) add("l.tbl = ?", q.tbl);
|
||||||
|
if (q.field) add("jsonb_exists(l.changes, ?)", q.field);
|
||||||
|
if (q.since) add("l.at >= ?::timestamptz", q.since);
|
||||||
|
if (q.until) add("l.at < ?::timestamptz", q.until);
|
||||||
|
if (q.system_only === "true") w.push("l.actor_id is null");
|
||||||
|
const where = w.length ? "where " + w.join(" and ") : "";
|
||||||
|
if (q.group) {
|
||||||
|
const key = { actor: "coalesce(l.actor_name, 'система (' || l.db_user || ')')", action: "coalesce(l.action, 'вне WebUI')", invoice: "l.invoice_id::text", day: "(l.at at time zone 'America/New_York')::date::text" }[q.group];
|
||||||
|
const rows = (await pool.query(`select ${key} as key, count(*)::int as events, min(l.at) as first_at, max(l.at) as last_at from acc_invoices_log l ${where} group by 1 order by events desc limit ${q.limit}`, v)).rows;
|
||||||
|
return { items: rows };
|
||||||
|
}
|
||||||
|
const rows = (await pool.query(
|
||||||
|
`select l.id, l.at, l.invoice_id, i.vendor_name, i.invoice_number, l.tbl, l.op, l.actor_name, l.acting_role, l.action, l.db_user, l.changes
|
||||||
|
from acc_invoices_log l left join acc_invoices i on i.id = l.invoice_id ${where} order by l.id desc limit ${q.limit}`, v)).rows;
|
||||||
|
return { items: rows };
|
||||||
|
});
|
||||||
|
|
||||||
/* ------------------------------------------------------------- создание */
|
/* ------------------------------------------------------------- создание */
|
||||||
app.post("/api/invoices", async (req, reply) => {
|
app.post("/api/invoices", async (req, reply) => {
|
||||||
const a = await need(req);
|
const a = await need(req);
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ export const accInvoicesSchema = z.object({
|
|||||||
/** Пускаются только адреса этого домена (вход Keycloak через Google). */
|
/** Пускаются только адреса этого домена (вход Keycloak через Google). */
|
||||||
emailDomain: z.string().default("khbuild.pro"),
|
emailDomain: z.string().default("khbuild.pro"),
|
||||||
/** Статические токены (человек -> токен): для тестов и сотрудников без Keycloak. */
|
/** Статические токены (человек -> токен): для тестов и сотрудников без Keycloak. */
|
||||||
|
/** Внутренний токен: сервис accounting_automation (MCP) ходит с ним от имени человека (заголовки x-internal-token, x-person-id). */
|
||||||
|
internalToken: z.string().min(24).optional(),
|
||||||
staticTokens: z.array(z.object({ token: z.string().min(16), personId: z.string() })).default([]),
|
staticTokens: z.array(z.object({ token: z.string().min(16), personId: z.string() })).default([]),
|
||||||
})
|
})
|
||||||
.default({}),
|
.default({}),
|
||||||
|
|||||||
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 { allowWithoutReceipt } from "./receipt-search.js";
|
||||||
import type { AccountingSettings } from "./settings.js";
|
import type { AccountingSettings } from "./settings.js";
|
||||||
import { Stage2Tools } from "./stage2-tools.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";
|
import { STAGE2_TOOL_NAMES, STAGE2_TOOLS } from "./stage2-tool-defs.js";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -22,7 +24,7 @@ export class McpToolError extends Error {}
|
|||||||
|
|
||||||
export interface ReviewDeps {
|
export interface ReviewDeps {
|
||||||
pool: Pool;
|
pool: Pool;
|
||||||
settings: Pick<AccountingSettings, "reviewers"> & { receipts?: { qboBankingUrl?: string } };
|
settings: Pick<AccountingSettings, "reviewers"> & { receipts?: { qboBankingUrl?: string }; accInvoices?: { url: string; internalToken?: string } };
|
||||||
/** Лимит расхода без чека (USD), по умолчанию 500. */
|
/** Лимит расхода без чека (USD), по умолчанию 500. */
|
||||||
noReceiptLimitUsd?: number;
|
noReceiptLimitUsd?: number;
|
||||||
now?: () => Date;
|
now?: () => Date;
|
||||||
@@ -148,8 +150,10 @@ const metaOf = (t: Pick<Task, "kind">): KindMeta | undefined => KINDS[t.kind];
|
|||||||
export class ReviewTools {
|
export class ReviewTools {
|
||||||
private readonly now: () => Date;
|
private readonly now: () => Date;
|
||||||
private readonly stage2: Stage2Tools;
|
private readonly stage2: Stage2Tools;
|
||||||
|
private readonly accInv: AccInvoicesTools;
|
||||||
constructor(private readonly d: ReviewDeps) {
|
constructor(private readonly d: ReviewDeps) {
|
||||||
this.now = d.now ?? (() => new Date());
|
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 });
|
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);
|
case "acc_receipt_allow_without": return this.allowWithoutReceipt(personId, a);
|
||||||
default:
|
default:
|
||||||
if (STAGE2_TOOL_NAMES.has(name)) return this.stage2.call(personId, name, a);
|
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}`);
|
throw new McpToolError(`Неизвестный инструмент ${name}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -681,6 +686,7 @@ export const TOOLS: { name: string; description: string; inputSchema: Json; anno
|
|||||||
),
|
),
|
||||||
},
|
},
|
||||||
...STAGE2_TOOLS,
|
...STAGE2_TOOLS,
|
||||||
|
...ACC_INV_TOOLS,
|
||||||
];
|
];
|
||||||
|
|
||||||
/** Встроенный текст инструкций (копия: docs/.../p-mcp-instructions.md; сервис подставляет файл, если он доступен). */
|
/** Встроенный текст инструкций (копия: 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"),
|
qboBankingUrl: z.string().default("https://app.qbo.intuit.com/app/banking"),
|
||||||
})
|
})
|
||||||
.default({}),
|
.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
|
mcp: z
|
||||||
.object({
|
.object({
|
||||||
enabled: z.boolean().default(true),
|
enabled: z.boolean().default(true),
|
||||||
|
|||||||
@@ -116,7 +116,7 @@
|
|||||||
},
|
},
|
||||||
acc_invoices: { // WebUI и API инвойсов и платежей (services.khbuild.freeddns.org/invoices/); таблицы acc_invoices*, роли - user_roles
|
acc_invoices: { // WebUI и API инвойсов и платежей (services.khbuild.freeddns.org/invoices/); таблицы acc_invoices*, роли - user_roles
|
||||||
http: { host: "0.0.0.0", port: 8097 },
|
http: { host: "0.0.0.0", port: 8097 },
|
||||||
auth: { issuer: "https://keycloak.khbuild.freeddns.org/realms/khbuild", staticTokens: [] }, // person ищется по email из токена
|
auth: { issuer: "https://keycloak.khbuild.freeddns.org/realms/khbuild", staticTokens: [], internalToken: "<тот же, что accounting_automation.accInvoices.internalToken, 24+ символов>" }, // person ищется по email из токена
|
||||||
bankConfirmHours: 24, // через сколько часов «Отправлено в банк» без оплаты в QuickBooks - ошибка
|
bankConfirmHours: 24, // через сколько часов «Отправлено в банк» без оплаты в QuickBooks - ошибка
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user