accounting_automation, этап 2 (часть A): роль cfo по сумме, флажки fraud, проверка и оплата инвойсов

- approval.ts: роль подтверждающего при создании задачи категоризации (порог approvalThresholdUsd, первая оплата вендору)
- fraud.ts: красные флажки по картам (первая оплата, рост суммы от медианы), задание fraud-flags
- invoice-check.ts: заключение по инвойсу и задача invoice_approval; задание invoice-check
- invoice-paid.ts: markPaid и задание invoice-paid (paid_on, paid_amount контракта)
- MCP: acc_invoice_to_approve, acc_invoice_decide; миграция 041; документы proposed

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 16:44:33 +03:00
parent f636836f47
commit 9f8bf1932f
21 changed files with 902 additions and 20 deletions

View File

@@ -179,11 +179,12 @@ export class ReviewTools {
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
`select m.*, coalesce(to_jsonb(i), to_jsonb(c), to_jsonb(s), to_jsonb(v)) 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
left join acc_invoices v on m.ref_table = 'acc_invoices' and v.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)
@@ -197,7 +198,7 @@ export class ReviewTools {
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) } : {}) };
return { ...taskOut(r as Task), review: row, ...((r.kind === "invoice" || r.kind === "invoice_approval") && row ? { file_url: driveUrl(row.drive_file_id) } : {}) };
}),
};
}
@@ -209,19 +210,85 @@ export class ReviewTools {
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;
const isApproval = t.kind === "invoice_approval";
const review = isApproval ? await this.invoiceRow(this.d.pool, t.ref_id) : await this.reviewRow(this.d.pool, t);
const original = isApproval ? null : await this.reviewRow(this.d.pool, t, "_original");
let fileId: unknown = t.kind === "invoice" || isApproval ? 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]))
? Object.keys(review).filter((k) => !["updated_at", "done", "done_by", "fraud_checked_at"].includes(k) && JSON.stringify(review[k]) !== JSON.stringify(original[k]))
: [];
return { task: taskOut(t), review, original, changed_fields: changed, file_url: driveUrl(fileId) };
}
private async invoiceRow(c: Pick<PoolClient, "query">, id: string, lock = false): Promise<Json | null> {
const r = await c.query(`select to_jsonb(v) as row from acc_invoices v where v.id::text = $1 ${lock ? "for update" : ""}`.trim(), [id]);
return (r.rows[0]?.row as Json | undefined) ?? null;
}
/** Задача проверки инвойса (invoice_approval) под блокировкой вместе со строкой acc_invoices. */
private async lockInvoiceTask(c: PoolClient, roles: ReviewRole[], id: string, forWhat: string): Promise<{ t: Task; inv: Json }> {
const t = await this.lockTask(c, roles, id, forWhat);
if (t.kind !== "invoice_approval") throw new McpToolError(`Это задача вида ${t.kind}, а не согласования инвойса (invoice_approval).`);
const inv = await this.invoiceRow(c, t.ref_id, true);
if (!inv) throw new McpToolError("Инвойс не найден.");
return { t, inv };
}
/** acc_invoice_to_approve: Юля проверила инвойс и переводит его «на согласование» (задача уходит роли cfo). */
async invoiceToApprove(personId: string, a: Json): Promise<Json> {
const roles = this.rolesOf(personId);
const id = await this.id(a);
if (a.comment !== undefined && typeof a.comment !== "string") throw new McpToolError("comment: строка");
return withTx(this.d.pool, async (c) => {
const { t, inv } = await this.lockInvoiceTask(c, roles, id, "перевода на согласование");
if (inv.stage !== "checking") throw new McpToolError(`Инвойс в стадии ${String(inv.stage)}: на согласование переводится только инвойс на проверке (checking).`);
if (inv.conclusion == null) throw new McpToolError("У инвойса ещё нет заключения проверки: дождитесь задания invoice-check.");
await c.query("update acc_invoices set stage = 'to_approve' where id = $1", [inv.id]);
await c.query("update acc_manual_review set assignee_role = 'cfo', snoozed_until = null where id = $1", [t.id]);
if (typeof a.comment === "string" && a.comment.trim()) {
const base = t.problem_highlight ? `${t.problem_highlight} | ` : "";
await c.query("update acc_manual_review set problem_highlight = $2 where id = $1", [t.id, `${base}Юля: ${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, stage: "to_approve", task: taskOut(now) };
});
}
/** acc_invoice_decide: решение Анастасии (роль cfo): approved, rejected или wait (с датой повторного показа). */
async invoiceDecide(personId: string, a: Json): Promise<Json> {
const roles = this.rolesOf(personId);
if (!roles.includes("cfo")) throw new McpToolError("Решение по инвойсу принимает роль cfo.");
const id = await this.id(a);
const decision = a.decision;
if (decision !== "approved" && decision !== "rejected" && decision !== "wait") throw new McpToolError("decision: approved, rejected или wait");
if (a.comment !== undefined && typeof a.comment !== "string") throw new McpToolError("comment: строка");
let until: Date | null = null;
if (decision === "wait") {
until = typeof a.until === "string" ? new Date(a.until) : null;
if (!until || Number.isNaN(until.getTime())) throw new McpToolError("until: для wait нужна дата повторного показа (2026-11-20 или ISO-время)");
if (until <= this.now()) throw new McpToolError("until должно быть в будущем.");
}
const now = this.now();
return withTx(this.d.pool, async (c) => {
const { t, inv } = await this.lockInvoiceTask(c, roles, id, "решения по инвойсу");
if (t.assignee_role !== "cfo") throw new McpToolError("Инвойс ещё не переведён на согласование (задача у accountant).");
if (inv.stage !== "to_approve" && inv.stage !== "wait") throw new McpToolError(`Инвойс в стадии ${String(inv.stage)}: решение возможно для to_approve и wait.`);
const note = { decision, by: personId, at: now.toISOString(), ...(typeof a.comment === "string" && a.comment.trim() ? { comment: a.comment.trim() } : {}), ...(until ? { until: until.toISOString() } : {}) };
await c.query(
`update acc_invoices set stage = $2, decided_by = $3, decided_at = $4,
conclusion = coalesce(conclusion, '{}'::jsonb) || jsonb_build_object('last_decision', $5::jsonb) where id = $1`,
[inv.id, decision, personId, now, JSON.stringify(note)],
);
if (decision === "wait") await c.query("update acc_manual_review set snoozed_until = $2 where id = $1", [t.id, until]);
else await c.query("delete from acc_manual_review where id = $1", [t.id]);
return { ok: true, stage: decision, decided_by: personId, decided_at: now.toISOString(), ...(until ? { snoozed_until: until.toISOString() } : {}) };
});
}
/** acc_review_update */
async update(personId: string, a: Json): Promise<Json> {
const roles = this.rolesOf(personId);
@@ -376,6 +443,8 @@ export class ReviewTools {
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);
case "acc_invoice_to_approve": return this.invoiceToApprove(personId, a);
case "acc_invoice_decide": return this.invoiceDecide(personId, a);
default: throw new McpToolError(`Неизвестный инструмент ${name}`);
}
}
@@ -463,6 +532,26 @@ export const TOOLS: { name: string; description: string; inputSchema: Json; anno
description: "Отложить задачу («подождать»): она не показывается в списке до указанного момента.",
inputSchema: obj({ id: idP, until: { ...str, description: "дата или время ISO, в будущем: 2026-11-20 или 2026-11-20T09:00:00Z" } }, ["id", "until"]),
},
{
name: "acc_invoice_to_approve",
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
description: "Проверка инвойса закончена: перевести инвойс (задача вида invoice_approval) в «на согласование»; задача уходит роли cfo (Анастасия). Вызывать после того, как бухгалтер прочитал заключение и решил вопросы с подрядчиком; только по просьбе пользователя.",
inputSchema: obj({ id: idP, comment: { ...str, description: "заметка для Анастасии (добавится к проблеме задачи)" } }, ["id"]),
},
{
name: "acc_invoice_decide",
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
description: "Решение по инвойсу на согласовании (только роль cfo): approved (согласован), rejected (отклонён) или wait (подождать: нужна дата until, до неё задача скрыта). Записывает, кто и когда решил. Деньги система не двигает: оплату делает человек в банке. Вызывать только после явного решения пользователя.",
inputSchema: obj(
{
id: idP,
decision: { type: "string", enum: ["approved", "rejected", "wait"] },
until: { ...str, description: "для wait: дата или время ISO в будущем, когда показать инвойс снова" },
comment: { ...str, description: "причина или заметка (сохраняется в заключении инвойса)" },
},
["id", "decision"],
),
},
];
/** Встроенный текст инструкций (копия: docs/.../p-mcp-instructions.md; сервис подставляет файл, если он доступен). */