Слияние частей A и B этапа 2 (разрешены конфликты: задания, MCP-инструменты, формат ответа категоризации)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 16:55:16 +03:00
parent a5bf9bf71e
commit fa83bfbc2f
24 changed files with 1818 additions and 30 deletions

View File

@@ -1,5 +1,6 @@
import { isDeepStrictEqual } from "node:util";
import { withTx, type Pool } from "khb_common";
import { missingDocumentProblem } from "./receipt-search.js";
type PoolClient = Parameters<Parameters<typeof withTx>[1]>[0];
@@ -18,6 +19,8 @@ export interface FinalizeDeps {
/** Сколько секунд запись должна оставаться без изменений. По умолчанию 30. */
delaySeconds?: number;
now?: () => Date;
/** Расход без чека проводится только до этой суммы (USD) и с согласия Анастасии (процесс «Поиск чека», шаг 8). По умолчанию 500. */
noReceiptLimitUsd?: number;
/** Сообщение исполнителю (в боевом режиме - в Slack канал бухгалтерии). */
notify: (text: string) => Promise<void> | void;
}
@@ -43,7 +46,7 @@ interface KindConfig {
key: string;
label: string;
/** Текст причины отказа или null, если запись корректна. */
validate: (row: Row) => string | null;
validate: (row: Row, c: PoolClient, limitUsd: number) => string | null | Promise<string | null>;
/** Передача результата дальше (в той же транзакции). */
forward: (c: PoolClient, row: Row) => Promise<void>;
}
@@ -126,7 +129,8 @@ async function forwardCertificate(c: PoolClient, r: Row): Promise<void> {
const KINDS: KindConfig[] = [
{ kind: "invoices", table: "acc_invoices_review", key: "id", label: "инвойс", validate: validateInvoice, forward: forwardInvoice },
// Категоризация: проводка в QuickBooks уже сделана Claude, обязательных полей нет; фиксируется только результат.
{ kind: "categorization", table: "acc_categorization_review", key: "feed_txn_id", label: "операция банка", validate: () => null, forward: async () => {} },
// Проверка: расход без документа (чека) больше лимита ($500) не закрывается, до лимита - только с согласия Анастасии.
{ kind: "categorization", table: "acc_categorization_review", key: "feed_txn_id", label: "операция банка", validate: (row, c, limit) => missingDocumentProblem(c, row, limit), forward: async () => {} },
{ kind: "certificates", table: "acc_certificates_review", key: "id", label: "сертификат", validate: validateCertificate, forward: forwardCertificate },
];
@@ -145,7 +149,7 @@ export function diffWithOriginal(current: Row, original: Row | null): Record<str
type Outcome = { status: "skipped" } | { status: "finalized" } | { status: "rejected"; reason: string; doneBy: string | null };
async function finalizeOne(pool: Pool, cfg: KindConfig, id: string, cutoff: Date, now: Date): Promise<Outcome> {
async function finalizeOne(pool: Pool, cfg: KindConfig, id: string, cutoff: Date, now: Date, limitUsd: number): Promise<Outcome> {
return withTx(pool, async (c) => {
// Блокировка строки; занятую другим запуском пропускаем. Условия проверяются заново уже под блокировкой.
const locked = await c.query(
@@ -156,7 +160,7 @@ async function finalizeOne(pool: Pool, cfg: KindConfig, id: string, cutoff: Date
const row = locked.rows[0].j as Row;
const doneBy = (row.done_by as string | null) ?? null;
const reason = cfg.validate(row);
const reason = await cfg.validate(row, c, limitUsd);
if (reason) {
await c.query(`update ${cfg.table} set done = false, problem_highlight = $2 where ${cfg.key}::text = $1`, [id, `Завершение отклонено: ${reason}`]);
return { status: "rejected", reason, doneBy } as Outcome;
@@ -184,7 +188,7 @@ export async function runFinalize(deps: FinalizeDeps): Promise<FinalizeResult> {
const cand = await deps.pool.query(`select ${cfg.key}::text as id from ${cfg.table} where done and updated_at <= $1 order by created_at`, [cutoff]);
for (const { id } of cand.rows as { id: string }[]) {
try {
const out = await finalizeOne(deps.pool, cfg, id, cutoff, now);
const out = await finalizeOne(deps.pool, cfg, id, cutoff, now, deps.noReceiptLimitUsd ?? 500);
if (out.status === "finalized") result.finalized[cfg.kind]++;
else if (out.status === "rejected") {
result.rejected.push({ kind: cfg.kind, id, reason: out.reason });