accounting_automation, этап 2: страховые сертификаты, сверка выписок, разбор истории правок, chargeback к контракту, fraud
- Миграции 061 (сертификаты: alert_kind, drive_file_id, request_*, acc_invoices.no_insurance) и 062 (acc_chargeback: kind contract|card_fraud, колонки contract, триггеры пересчёта acc_contracts.retained_amount и закрытия по остатку). - Задания certificates, reconcile-monthly, history-weekly, fraud-weekly (JOB_NAMES, main.ts); расписание на сервере не заведено. - Письма с сертификатами разбирает invoices-mail (document_type certificate); запрос подрядчику - через интерфейс ContractorMessenger (пока ручной: текст в request_log, Юля отправляет из JobTread). - Ручки /chargeback/find|start|close|add-log|fraud для ассистента менеджера; MCP-инструменты acc_chargeback_*, acc_fraud_*, acc_contract_balance, acc_certificate_request_approve; очередь показывает задачи вида chargeback. - Тесты на временной БД (сертификаты, сверка, история правок, chargeback и fraud, служебное API); описание данных в docs/proposed. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,6 +3,8 @@ import { withTx, type Pool } from "khb_common";
|
||||
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 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»).
|
||||
@@ -133,8 +135,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; пусто - доступ запрещён. */
|
||||
@@ -160,6 +164,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]);
|
||||
@@ -179,11 +189,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(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_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)
|
||||
@@ -214,7 +225,7 @@ export class ReviewTools {
|
||||
let fileId: unknown = t.kind === "invoice" ? 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"].includes(k) && JSON.stringify(review[k]) !== JSON.stringify(original[k]))
|
||||
@@ -261,6 +272,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]);
|
||||
@@ -376,7 +388,9 @@ 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);
|
||||
default: throw new McpToolError(`Неизвестный инструмент ${name}`);
|
||||
default:
|
||||
if (STAGE2_TOOL_NAMES.has(name)) return this.stage2.call(personId, name, a);
|
||||
throw new McpToolError(`Неизвестный инструмент ${name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -463,6 +477,7 @@ 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"]),
|
||||
},
|
||||
...STAGE2_TOOLS,
|
||||
];
|
||||
|
||||
/** Встроенный текст инструкций (копия: docs/.../p-mcp-instructions.md; сервис подставляет файл, если он доступен). */
|
||||
|
||||
Reference in New Issue
Block a user