Слияние части C этапа 2 (сертификаты, сверка, история, chargeback, fraud)

This commit is contained in:
2026-11-23 16:58:46 +03:00
32 changed files with 2620 additions and 38 deletions

View File

@@ -4,6 +4,8 @@ import { createMcpAuth, McpAuthError, type JwtVerifier } from "./mcp-auth.js";
import { REVIEW_UI_HTML, REVIEW_UI_MIME, REVIEW_UI_URI, REVIEW_UI_URI_LEGACY, rowsToMarkdown, toRow } from "./mcp-ui.js";
import { allowWithoutReceipt } from "./receipt-search.js";
import type { AccountingSettings } from "./settings.js";
import { Stage2Tools } from "./stage2-tools.js";
import { STAGE2_TOOL_NAMES, STAGE2_TOOLS } from "./stage2-tool-defs.js";
/**
* MCP для Claude сотрудника: разбор очереди acc_manual_review («Review проблем в Claude»).
@@ -136,8 +138,10 @@ const metaOf = (t: Pick<Task, "kind">): KindMeta | undefined => KINDS[t.kind];
/** Чистый слой инструментов: person_id вызывающего передаётся первым аргументом. */
export class ReviewTools {
private readonly now: () => Date;
private readonly stage2: Stage2Tools;
constructor(private readonly d: ReviewDeps) {
this.now = d.now ?? (() => new Date());
this.stage2 = new Stage2Tools({ pool: d.pool, rolesOf: (p) => this.rolesOf(p), now: this.now });
}
/** Роли человека по settings.reviewers; пусто - доступ запрещён. */
@@ -163,6 +167,12 @@ export class ReviewTools {
}
private async reviewRow(c: Pick<PoolClient, "query">, t: Task, suffix = "", lock = false): Promise<Json | null> {
if (t.kind === "chargeback") {
// chargeback ведётся отдельными инструментами acc_chargeback_*: копии original у него нет
if (suffix) return null;
const r = await c.query("select to_jsonb(r) as row from acc_chargeback r where r.id::text = $1", [t.ref_id]);
return (r.rows[0]?.row as Json | undefined) ?? 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]);
@@ -182,12 +192,13 @@ 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), to_jsonb(v)) as row, count(*) over()::int as total
`select m.*, coalesce(to_jsonb(i), to_jsonb(c), to_jsonb(s), to_jsonb(v), to_jsonb(ch)) 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
left join acc_chargeback ch on m.ref_table = 'acc_chargeback' and ch.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)
@@ -219,7 +230,7 @@ export class ReviewTools {
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;
}
} else if (t.kind === "certificate" && review?.drive_file_id) fileId = review.drive_file_id;
const changed =
review && original
? Object.keys(review).filter((k) => !["updated_at", "done", "done_by", "fraud_checked_at"].includes(k) && JSON.stringify(review[k]) !== JSON.stringify(original[k]))
@@ -331,6 +342,7 @@ export class ReviewTools {
return withTx(this.d.pool, async (c) => {
const t = await this.lockTask(c, roles, id, "закрытия");
const m = metaOf(t);
if (t.kind === "chargeback") throw new McpToolError("Задачу chargeback через acc_review_done закрыть нельзя: её закрывает смена статуса: acc_chargeback_decide, acc_chargeback_link_invoice, acc_chargeback_confirm, acc_chargeback_close, acc_fraud_update.");
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]);
@@ -469,7 +481,9 @@ export class ReviewTools {
case "acc_invoice_to_approve": return this.invoiceToApprove(personId, a);
case "acc_invoice_decide": return this.invoiceDecide(personId, a);
case "acc_receipt_allow_without": return this.allowWithoutReceipt(personId, a);
default: throw new McpToolError(`Неизвестный инструмент ${name}`);
default:
if (STAGE2_TOOL_NAMES.has(name)) return this.stage2.call(personId, name, a);
throw new McpToolError(`Неизвестный инструмент ${name}`);
}
}
}
@@ -583,6 +597,7 @@ export const TOOLS: { name: string; description: string; inputSchema: Json; anno
["id", "decision"],
),
},
...STAGE2_TOOLS,
];
/** Встроенный текст инструкций (копия: docs/.../p-mcp-instructions.md; сервис подставляет файл, если он доступен). */