From 9f8bf1932fc0488d8a007ba243331fdc991fd266 Mon Sep 17 00:00:00 2001 From: Yuri Yaryshev Date: Mon, 23 Nov 2026 16:44:33 +0300 Subject: [PATCH] =?UTF-8?q?accounting=5Fautomation,=20=D1=8D=D1=82=D0=B0?= =?UTF-8?q?=D0=BF=202=20(=D1=87=D0=B0=D1=81=D1=82=D1=8C=20A):=20=D1=80?= =?UTF-8?q?=D0=BE=D0=BB=D1=8C=20cfo=20=D0=BF=D0=BE=20=D1=81=D1=83=D0=BC?= =?UTF-8?q?=D0=BC=D0=B5,=20=D1=84=D0=BB=D0=B0=D0=B6=D0=BA=D0=B8=20fraud,?= =?UTF-8?q?=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B0=20=D0=B8=20?= =?UTF-8?q?=D0=BE=D0=BF=D0=BB=D0=B0=D1=82=D0=B0=20=D0=B8=D0=BD=D0=B2=D0=BE?= =?UTF-8?q?=D0=B9=D1=81=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- .../acc_categorization_review.md | 7 +- .../accounting_automation/acc_invoices.md | 8 +- .../acc_manual_review.md | 2 +- .../p-mcp-instructions.md | 5 + .../quickbooks_bookkeeper/processes.md | 2 +- .../modules/quickbooks_bookkeeper/stage2.md | 2 +- .../accounting_automation/src/approval.ts | 41 +++ .../accounting_automation/src/categorize.ts | 19 +- .../accounting_automation/src/finalize.ts | 2 +- packages/accounting_automation/src/fraud.ts | 176 ++++++++++++ .../src/http-api.test.ts | 3 + .../accounting_automation/src/http-api.ts | 5 +- .../src/invoice-check.ts | 129 +++++++++ .../accounting_automation/src/invoice-paid.ts | 53 ++++ packages/accounting_automation/src/main.ts | 8 + .../accounting_automation/src/mcp.int.test.ts | 2 +- packages/accounting_automation/src/mcp.ts | 101 ++++++- .../accounting_automation/src/settings.ts | 2 + .../src/stage2.int.test.ts | 272 ++++++++++++++++++ .../accounting_automation/src/stage2.test.ts | 70 +++++ .../migrations/041_acc_stage2_flags.sql | 13 + 21 files changed, 902 insertions(+), 20 deletions(-) create mode 100644 packages/accounting_automation/src/approval.ts create mode 100644 packages/accounting_automation/src/fraud.ts create mode 100644 packages/accounting_automation/src/invoice-check.ts create mode 100644 packages/accounting_automation/src/invoice-paid.ts create mode 100644 packages/accounting_automation/src/stage2.int.test.ts create mode 100644 packages/accounting_automation/src/stage2.test.ts create mode 100644 packages/khb_common/migrations/041_acc_stage2_flags.sql diff --git a/docs/proposed/data_objects/accounting_automation/acc_categorization_review.md b/docs/proposed/data_objects/accounting_automation/acc_categorization_review.md index 7c3eaa3..dcd3bf5 100644 --- a/docs/proposed/data_objects/accounting_automation/acc_categorization_review.md +++ b/docs/proposed/data_objects/accounting_automation/acc_categorization_review.md @@ -1,18 +1,21 @@ # acc_categorization_review -Предложения категоризации операций ленты банка QuickBooks. Заполняет Claude-агент (промпт `p-categorization.md`); подтверждает Юля, а при сумме от $5 000 или первой оплате новому вендору и Анастасия. Сумма и вендор в таблице не хранятся: берутся из QuickBooks по `feed_txn_id`. Префикс `acc_` - таблицы автоматизации бухгалтерии (зеркала QuickBooks - `qbo_`). +Предложения категоризации операций ленты банка QuickBooks. Заполняет Claude-агент (промпт `p-categorization.md`); подтверждает Юля, а при сумме от $5 000 или первой оплате новому вендору и Анастасия. Сумма и вендор лежат в `suggestion` (их пишет агент): по ним сервис при создании задачи выбирает роль подтверждающего и ставит красные флажки fraud. Порог суммы для роли `cfo` и параметры fraud - настройки сервиса (`approvalThresholdUsd`, по умолчанию 5000; `fraud.multiplier`, по умолчанию 3; `fraud.minHistory`, по умолчанию 3). Префикс `acc_` - таблицы автоматизации бухгалтерии (зеркала QuickBooks - `qbo_`). | Колонка | Тип | Null | Описание | |---|---|---|---| | feed_txn_id | text PK | нет | идентификатор операции ленты QuickBooks | | run_id | text | нет | идентификатор прогона категоризации в QuickBooks | | run_started_at | timestamptz | нет | время начала прогона | -| suggestion | jsonb | да | предложение: `account`, `project_customer_id`, `splits`, `invoice_ids`, `receipt_id`; пусто, если агент не уверен | +| suggestion | jsonb | да | предложение: `account`, `project_customer_id`, `splits`, `invoice_ids`, `receipt_id`, а также данные операции: `amount` (сумма числом), `vendor_qbo_id`, `vendor_name`, `bank_account_id` (счёт или карта QuickBooks), `is_card` (true для кредитной карты); пусто, если агент не уверен | | confidence | smallint | да | уверенность, 0-100 | | problem_highlight | text | да | заполняется тогда и только тогда, когда есть проблема, которую агент не может решить («ждёт документ», «подозрение на дубль», описание) | | done | boolean | нет | операция подтверждена и проведена в QuickBooks (default false) | | created_at | timestamptz | нет | создана | | updated_at | timestamptz | нет | последнее изменение (ставит триггер); процесс «Завершение ручного разбора» ждёт 30 секунд без изменений | | done_by | text | да | кто отметил запись выполненной (попадает в `closed_by` таблицы `_history`) | +| fraud_checked_at | timestamptz | да | когда строку проверил красными флажками fraud (при записи или задание `fraud-flags`); служебная отметка идемпотентности, в `changed_fields` не попадает | + +Роль задачи в `acc_manual_review.assignee_role` сервис ставит сам при создании: `cfo`, если `suggestion.amount` не меньше порога или это первая оплата вендору (нет ни покупок вендору в `qbo_purchase`, ни прежних строк этого вендора в `acc_categorization_review_history`), иначе `accountant`. Для операций по карте сервис дописывает в `problem_highlight` (не затирая текст агента, без дублей) причины «первая оплата вендору» и «резкое изменение суммы» (сумма не меньше 3 x медианы прошлых платежей по картам этому вендору, минимум 3 платежа в истории). Подчиняется общей схеме ручного разбора: рядом таблица `acc_categorization_review_original` (те же колонки, строка как её записал автомат; тот же ключ) и `acc_categorization_review_history` (после завершения разбора: те же колонки плюс `closed_by` text, `closed_at` timestamptz, `changed_fields` jsonb - поля, которые изменил человек, со старым и новым значением). Строка попадает в `_history` и удаляется из основной таблицы процессом «Завершение ручного разбора». diff --git a/docs/proposed/data_objects/accounting_automation/acc_invoices.md b/docs/proposed/data_objects/accounting_automation/acc_invoices.md index b59b2e9..e0f99d1 100644 --- a/docs/proposed/data_objects/accounting_automation/acc_invoices.md +++ b/docs/proposed/data_objects/accounting_automation/acc_invoices.md @@ -17,8 +17,10 @@ | jt_job_id | text FK jt_job | да | проект в JobTread | | contract_id | uuid FK acc_contracts | да | контракт | | stage | text | нет | `checking` (на проверке), `to_approve` (на согласование), `approved`, `rejected`, `wait`, `paid` | -| conclusion | jsonb | да | заключение проверки: контракт, остаток, повтор, страховка («нет страховки») | -| decided_by | text | да | кто согласовал или отклонил | +| conclusion | jsonb | да | заключение проверки (его считает задание `invoice-check`, пока `stage = checking` и заключения нет): `contract` (найден ли, `id`, `stage`, `total_amount`, `paid_amount`, `retained_amount`, `remaining`), `exceeds_balance`, `duplicate` (`found`, `invoice_ids`), `insurance` (`valid`, `valid_until`), `problems` (список текстов; он же уходит в `problem_highlight` задачи), `checked_at`; после решения Анастасии добавляется `last_decision` (`decision`, `by`, `at`, `comment`, `until`) | +| decided_by | text | да | кто принял решение (person_id; ставит MCP-инструмент `acc_invoice_decide`, в том числе при `wait`) | | decided_at | timestamptz | да | когда | -| paid_on | date | да | дата оплаты | +| paid_on | date | да | дата оплаты (ставит задание `invoice-paid`) | | qbo_txn_id | text | да | проводка оплаты в QuickBooks | + +Движение по стадиям: инвойс попадает сюда в `checking`; задание `invoice-check` пишет заключение и создаёт задачу `invoice_approval` (`ref_table = acc_invoices`, `ref_id` = id инвойса) для `accountant`; Юля инструментом `acc_invoice_to_approve` переводит инвойс в `to_approve`, задача переходит к `cfo`; Анастасия инструментом `acc_invoice_decide` ставит `approved`, `rejected` (задача удаляется) или `wait` (задача скрыта до даты повторного показа, стадия `wait`, решение возможно снова). Задание `invoice-paid` для `approved` инвойса находит оплату вендору в `qbo_purchase` (тот же вендор, та же сумма, проводка не раньше даты решения, не занята другим инвойсом), ставит `paid`, `paid_on`, `qbo_txn_id` и добавляет сумму к `acc_contracts.paid_amount`. Остаток для проверки: `total_amount` - `retained_amount` - `paid_amount`. diff --git a/docs/proposed/data_objects/accounting_automation/acc_manual_review.md b/docs/proposed/data_objects/accounting_automation/acc_manual_review.md index 891731f..3586ee9 100644 --- a/docs/proposed/data_objects/accounting_automation/acc_manual_review.md +++ b/docs/proposed/data_objects/accounting_automation/acc_manual_review.md @@ -6,7 +6,7 @@ |---|---|---|---| | id | uuid PK | нет | внутренний ID | | kind | text | нет | вид задачи: `invoice`, `categorization`, `certificate`, `discrepancy`, `acc_receipt_search`, `acc_chargeback`, `invoice_approval` | -| ref_table | text | нет | таблица с данными задачи | +| ref_table | text | нет | таблица с данными задачи (для `invoice_approval` - `acc_invoices`) | | ref_id | text | нет | ключ строки в `ref_table` | | assignee_role | text | нет | кому: `accountant` (Юля) или `cfo` (Анастасия); значения сверяются с `person.role_code` | | problem_highlight | text | да | копия проблемы из строки; пусто, если автомат уверен | diff --git a/docs/proposed/modules/quickbooks_bookkeeper/p-mcp-instructions.md b/docs/proposed/modules/quickbooks_bookkeeper/p-mcp-instructions.md index 08aeb48..f81b54b 100644 --- a/docs/proposed/modules/quickbooks_bookkeeper/p-mcp-instructions.md +++ b/docs/proposed/modules/quickbooks_bookkeeper/p-mcp-instructions.md @@ -23,4 +23,9 @@ - id задач в таблице короткие (8 символов); во всех инструментах (done, handoff, snooze, batch и др.) передавай их как есть, полный uuid не нужен. Не ищи id в других источниках (SQL, Supabase): очередь доступна только через этот коннектор; - если нужного инструмента нет в списке, найди его по имени (acc_review_batch, acc_review_done, acc_review_handoff, acc_review_snooze) в инструментах коннектора accounting_automation, прежде чем сообщать, что действие невозможно. +Задачи вида invoice_approval (проверка и согласование инвойса): +- Юля (accountant) после проверки заключения и, при необходимости, переписки с подрядчиком просит перевести инвойс на согласование: acc_invoice_to_approve; задача уходит Анастасии (cfo); +- Анастасия решает инструментом acc_invoice_decide: approved, rejected или wait (для wait обязательна дата until, до неё задача скрыта); вызывай только после явного решения пользователя; +- система инвойс не согласует и деньги не двигает: оплату делает человек в банке, оплату в учёте проставит сервис. + Если у пользователя нет доступа к очереди (ошибка «Доступ запрещён»), не пытайся обойти: скажи об этом одной фразой. diff --git a/docs/proposed/modules/quickbooks_bookkeeper/processes.md b/docs/proposed/modules/quickbooks_bookkeeper/processes.md index aee6d7a..c44d5e9 100644 --- a/docs/proposed/modules/quickbooks_bookkeeper/processes.md +++ b/docs/proposed/modules/quickbooks_bookkeeper/processes.md @@ -37,7 +37,7 @@ 2. АВТОМАТИЧЕСКИ Банк через соединение с QuickBooks передаёт операцию в ленту банка QuickBooks (раздел «For Review»). 3. АВТОМАТИЧЕСКИ по расписанию accounting_automation раз в день (можно чаще) запускает Claude-агента, которому передается задание из файла Google Drive «Промпт категоризации банковских операций» (Технически это `claude -p` из под agents@khbuild.pro) с промптом из Google Drive: документ «Промпт категоризации банковских операций» https://docs.google.com/document/d/1BVIDzP-yolt-A9AzRtx1IqBBiMKIUlsrAQUDZch5aJA. Анастасия может менять промпт, добавляя/изменяя правила категоризации. 4. АВТОМАТИЧЕСКИ запущенный Claude-агент читает в QuickBooks ленту банка «For Review» и для каждой новой операции устанавливает предложенную категорию в QuickBooks (прогон категоризации; в учёт ничего не проводится). Дополнительно агент записывает в Supabase (таблица `acc_categorization_review`, видна в Mathesar) строку на операцию: идентификатор операции, идентификатор и время прогона, предложение, уверенность и `problem_highlight` (заполняется только если есть проблема, которую агент не может решить: «ждёт документ», «подозрение на дубль» или описание того, чего не хватает). Копия строки как есть уходит в `categorization_review_original`. -5. АВТОМАТИЧЕСКИ триггер на таблице `acc_categorization_review` добавляет по каждой строке задачу в `acc_manual_review`; роль определяется по сумме операции в QuickBooks и вендору: Юля, а при сумме от $5 000 или первой оплате новому вендору - Юля и Анастасия; дальше задачу разбирают в процессе «Review проблем в Claude». +5. АВТОМАТИЧЕСКИ триггер на таблице `acc_categorization_review` добавляет по каждой строке задачу в `acc_manual_review`; сразу после записи строки accounting_automation ставит в задаче роль по сумме операции и вендору (сумма и вендор берутся из `suggestion`): `accountant` (Юля), а при сумме от порога (настройка, по умолчанию $5 000) или первой оплате новому вендору - `cfo` (Анастасия; Юля тоже может её закрыть, если ей выданы обе роли); по операциям с карты сервис дополнительно дописывает в `problem_highlight` красные флажки (процесс «Подозрительные операции по карте (fraud)», шаг 1; задание `fraud-flags` доделывает строки, где данных на момент записи не хватало); дальше задачу разбирают в процессе «Review проблем в Claude». Итог: операция либо проведена в QuickBooks, либо стоит в `acc_categorization_review`: без проблемы (ждёт подтверждения) или с описанной проблемой в `problem_highlight` («ждёт документ», «подозрение на дубль», «нужен человек»). diff --git a/docs/proposed/modules/quickbooks_bookkeeper/stage2.md b/docs/proposed/modules/quickbooks_bookkeeper/stage2.md index 783c4b9..e30168c 100644 --- a/docs/proposed/modules/quickbooks_bookkeeper/stage2.md +++ b/docs/proposed/modules/quickbooks_bookkeeper/stage2.md @@ -24,7 +24,7 @@ ## 3. Определение роли подтверждающего -- Сервис по сумме операции и вендору сам решает, кому уходит задача (`accountant` или `cfo`), и меняет `acc_manual_review.assignee_role`, агент в этом не участвует (порог из настройки). +- Реализовано (сервис accounting_automation, модуль `approval.ts`): сумма и вендор берутся из `suggestion` строки `acc_categorization_review`; `cfo` при сумме от порога (настройка `approvalThresholdUsd`) или первой оплате вендору. Сервис по сумме операции и вендору сам решает, кому уходит задача (`accountant` или `cfo`), и меняет `acc_manual_review.assignee_role`, агент в этом не участвует (порог из настройки). ## 4. Не вошедшее в первый этап diff --git a/packages/accounting_automation/src/approval.ts b/packages/accounting_automation/src/approval.ts new file mode 100644 index 0000000..2065598 --- /dev/null +++ b/packages/accounting_automation/src/approval.ts @@ -0,0 +1,41 @@ +import type { Pool } from "khb_common"; +import { queryVendorHistory, suggestionAmount, vendorOf, type Suggestion } from "./fraud.js"; + +/** + * Роль подтверждающего задачу категоризации (stage2.md п. 3; processes.md «Категоризация банковских операций», шаг 5): + * cfo (Анастасия) - при сумме операции от порога или первой оплате новому вендору; иначе accountant (Юля). + * Задачу по-прежнему может закрыть и пользователь с ролью accountant+cfo; в acc_manual_review.assignee_role пишется основная роль. + * Сумма и вендор берутся из suggestion (amount, vendor_qbo_id, vendor_name) строки acc_categorization_review. + */ + +export type AssigneeRole = "accountant" | "cfo"; + +export function decideAssigneeRole(i: { amount: number | null; threshold: number; firstPayment: boolean }): { role: AssigneeRole; reason: string | null } { + if (i.amount !== null && Math.abs(i.amount) >= i.threshold) return { role: "cfo", reason: `сумма ${Math.abs(i.amount).toFixed(2)} >= порога ${i.threshold}` }; + if (i.firstPayment) return { role: "cfo", reason: "первая оплата новому вендору" }; + return { role: "accountant", reason: null }; +} + +/** Определяет роль и обновляет задачу в acc_manual_review; задачу, уже переданную вручную (роль не accountant), не трогает. */ +export async function applyCategorizationRole( + pool: Pool, + feedTxnId: string, + opts: { threshold: number; realmId?: string | null }, +): Promise<{ role: AssigneeRole; reason: string | null }> { + const row = (await pool.query("select suggestion from acc_categorization_review where feed_txn_id = $1", [feedTxnId])).rows[0] as { suggestion: Suggestion | null } | undefined; + const s = row?.suggestion ?? null; + const v = vendorOf(s); + let firstPayment = false; + if (v.qboId || v.name) { + const h = await queryVendorHistory(pool, { realmId: opts.realmId, vendorQboId: v.qboId, vendorName: v.name, feedTxnId }); + firstPayment = h.priorCount === 0; + } + const decision = decideAssigneeRole({ amount: suggestionAmount(s), threshold: opts.threshold, firstPayment }); + if (decision.role === "cfo") { + await pool.query( + "update acc_manual_review set assignee_role = 'cfo' where ref_table = 'acc_categorization_review' and ref_id = $1 and assignee_role = 'accountant'", + [feedTxnId], + ); + } + return decision; +} diff --git a/packages/accounting_automation/src/categorize.ts b/packages/accounting_automation/src/categorize.ts index 325a50d..08770fc 100644 --- a/packages/accounting_automation/src/categorize.ts +++ b/packages/accounting_automation/src/categorize.ts @@ -1,6 +1,8 @@ import { z } from "zod"; import type { Logger, Pool } from "khb_common"; +import { applyCategorizationRole } from "./approval.js"; import type { ClaudeRunner } from "./claude-runner.js"; +import { DEFAULT_FRAUD, flagOne, type FraudSettings } from "./fraud.js"; /** * Процесс «Категоризация банковских операций», шаги 3-5: запуск Claude-агента с промптом из Google Docs. @@ -50,6 +52,9 @@ export interface CategorizeDeps { realmId: string; now?: () => Date; log: Logger; + /** Порог суммы (USD), с которого задачу подтверждает cfo. По умолчанию 5000. */ + approvalThresholdUsd?: number; + fraud?: FraudSettings; } export interface CategorizeResult { status: "ok" | "busy" | "agent_failed" | "bad_output"; @@ -74,7 +79,7 @@ export function buildAgentPrompt(prompt: string, ctx: { realmId: string; runStar В самом конце ответа выведи ровно один блок: \`\`\`json {"run_id": "<идентификатор прогона QuickBooks>", "results": [ - {"feed_txn_id": "", "suggestion": {"account": "...", "project_customer_id": "...", "splits": [], "invoice_ids": [], "receipt_id": null} или null, "confidence": 0-100 или null, "problem_highlight": "текст проблемы" или null} + {"feed_txn_id": "", "suggestion": {"account": "...", "project_customer_id": "...", "splits": [], "invoice_ids": [], "receipt_id": null, "amount": сумма операции числом, "vendor_qbo_id": "...", "vendor_name": "...", "bank_account_id": "счёт или карта QuickBooks", "is_card": true для кредитной карты} или null, "confidence": 0-100 или null, "problem_highlight": "текст проблемы" или null} ]} \`\`\` По одному элементу на каждую операцию ленты, которую ты рассмотрел. Если нечего обрабатывать - results: [].`; @@ -113,8 +118,16 @@ export async function runCategorization(deps: CategorizeDeps): Promise= множитель x медиана прошлых платежей, не меньше minHistory платежей в истории). + * Причина дописывается в problem_highlight (существующий текст не затирается, повторно не дублируется). + * Данные операции берутся из suggestion в acc_categorization_review: amount, vendor_qbo_id, vendor_name, + * bank_account_id (счёт или карта QuickBooks), is_card / payment_type. + */ + +export interface FraudSettings { + /** Во сколько раз сумма должна превысить медиану прошлых платежей вендору, чтобы поставить флажок. */ + multiplier: number; + /** Минимум прошлых платежей вендору, при которых проверяется «резкое изменение суммы». */ + minHistory: number; +} +export const DEFAULT_FRAUD: FraudSettings = { multiplier: 3, minHistory: 3 }; + +/** Метки причин: по ним определяется, что причина уже записана (идемпотентность). */ +export const FIRST_PAYMENT_MARK = "Красный флажок (fraud): первая оплата вендору"; +export const AMOUNT_JUMP_MARK = "Красный флажок (fraud): резкое изменение суммы"; + +export interface VendorHistory { + /** Сколько платежей этому вендору было раньше (покупки QuickBooks + ранее разобранные операции). */ + priorCount: number; + /** Суммы прошлых платежей по картам (положительные). */ + cardAmounts: number[]; +} + +export interface FraudInput { + amount: number | null; + isCard: boolean; + vendorKnown: boolean; + history: VendorHistory; +} + +export function median(xs: number[]): number { + const s = [...xs].sort((a, b) => a - b); + const m = Math.floor(s.length / 2); + return s.length % 2 ? s[m]! : (s[m - 1]! + s[m]!) / 2; +} + +const money = (n: number): string => `$${n.toFixed(2)}`; + +/** Чистая оценка: список причин (пустой - флажков нет). Не карта или нет данных о вендоре - без флажков. */ +export function evaluateFraud(i: FraudInput, s: FraudSettings = DEFAULT_FRAUD): string[] { + if (!i.isCard || !i.vendorKnown) return []; + const reasons: string[] = []; + if (i.history.priorCount === 0) reasons.push(`${FIRST_PAYMENT_MARK}, раньше платежей не было`); + const amt = i.amount === null ? null : Math.abs(i.amount); + if (amt !== null && i.history.cardAmounts.length >= s.minHistory) { + const med = median(i.history.cardAmounts); + if (med > 0 && amt >= med * s.multiplier) + reasons.push(`${AMOUNT_JUMP_MARK}: ${money(amt)} при обычных ${money(med)} (медиана ${i.history.cardAmounts.length} платежей, порог x${s.multiplier})`); + } + return reasons; +} + +/** Дописывает причины к тексту проблемы; причины с уже записанной меткой пропускаются. */ +export function mergeProblem(existing: string | null, reasons: string[]): string | null { + let out = existing ?? ""; + for (const r of reasons) { + const mark = r.startsWith(FIRST_PAYMENT_MARK) ? FIRST_PAYMENT_MARK : r.startsWith(AMOUNT_JUMP_MARK) ? AMOUNT_JUMP_MARK : r; + if (out.includes(mark)) continue; + out = out.trim() ? `${out} | ${r}` : r; + } + return out === (existing ?? "") ? existing : out; +} + +export interface Suggestion { + amount?: unknown; + vendor_qbo_id?: unknown; + vendor_name?: unknown; + bank_account_id?: unknown; + is_card?: unknown; + payment_type?: unknown; +} +const str = (v: unknown): string | null => (typeof v === "string" && v.trim() ? v.trim() : null); +export function suggestionAmount(s: Suggestion | null): number | null { + const v = s?.amount; + const n = typeof v === "string" && v.trim() !== "" ? Number(v) : v; + return typeof n === "number" && Number.isFinite(n) ? Math.abs(n) : null; +} +export const vendorOf = (s: Suggestion | null): { qboId: string | null; name: string | null } => ({ qboId: str(s?.vendor_qbo_id), name: str(s?.vendor_name) }); + +/** История платежей вендору: покупки qbo_purchase (кроме самой операции, если она уже проведена) и ранее закрытые разборы. */ +export async function queryVendorHistory( + pool: Pool, + q: { realmId?: string | null; vendorQboId: string | null; vendorName: string | null; feedTxnId: string }, +): Promise { + const purchases = await pool.query( + `select total_amt, payment_type from qbo_purchase + where ($1::text is null or realm_id = $1) + and ((entity_id is not null and entity_id = $2::text) or ($3::text is not null and lower(entity_name) = lower($3::text))) + and position($4::text in coalesce(private_note, '')) = 0 + order by txn_date desc nulls last limit 100`, + [q.realmId ?? null, q.vendorQboId, q.vendorName, q.feedTxnId], + ); + const hist = await pool.query( + `select count(*)::int as n from acc_categorization_review_history + where feed_txn_id <> $3 + and (($1::text is not null and suggestion ->> 'vendor_qbo_id' = $1::text) + or ($2::text is not null and lower(suggestion ->> 'vendor_name') = lower($2::text)))`, + [q.vendorQboId, q.vendorName, q.feedTxnId], + ); + const cardAmounts = (purchases.rows as { total_amt: string | null; payment_type: string | null }[]) + .filter((r) => r.payment_type === "CreditCard" && r.total_amt !== null && Number(r.total_amt) > 0) + .map((r) => Number(r.total_amt)); + return { priorCount: purchases.rows.length + (hist.rows[0]?.n ?? 0), cardAmounts }; +} + +/** Операция по карте: явный признак в suggestion либо счёт - кредитная карта (qbo_account) или карта из acc_card_holders. */ +export async function isCardOperation(pool: Pool, s: Suggestion | null, realmId?: string | null): Promise { + if (s?.is_card === true || s?.payment_type === "CreditCard") return true; + const acct = str(s?.bank_account_id); + if (!acct) return false; + const r = await pool.query( + `select (exists (select 1 from qbo_account where id = $1::text and account_type = 'Credit Card' and ($2::text is null or realm_id = $2::text)) + or exists (select 1 from acc_card_holders where card_or_account = $1::text)) as card`, + [acct, realmId ?? null], + ); + return r.rows[0]?.card === true; +} + +export interface FlagResult { + checked: number; + flagged: number; + /** Не хватило данных (нет suggestion или вендора): строка останется на следующий прогон. */ + skipped: number; +} + +/** + * Проверка одной строки (используется и при записи категоризации, и заданием fraud-flags). + * Возвращает "flagged" / "clean" / "no_data". При "flagged" и "clean" ставит fraud_checked_at. + */ +export async function flagOne( + pool: Pool, + feedTxnId: string, + opts: { settings?: FraudSettings; realmId?: string | null } = {}, +): Promise<"flagged" | "clean" | "no_data"> { + const row = (await pool.query("select suggestion, problem_highlight from acc_categorization_review where feed_txn_id = $1 and not done", [feedTxnId])).rows[0] as + | { suggestion: Suggestion | null; problem_highlight: string | null } + | undefined; + if (!row) return "no_data"; + const s = row.suggestion; + const card = await isCardOperation(pool, s, opts.realmId); + if (!card) { + // Не карта: флажки не нужны. Отметку ставим только если есть suggestion (иначе признак «карта» могут ещё дописать). + if (!s) return "no_data"; + await pool.query("update acc_categorization_review set fraud_checked_at = now() where feed_txn_id = $1", [feedTxnId]); + return "clean"; + } + const v = vendorOf(s); + if (!v.qboId && !v.name) return "no_data"; + const history = await queryVendorHistory(pool, { realmId: opts.realmId, vendorQboId: v.qboId, vendorName: v.name, feedTxnId }); + const reasons = evaluateFraud({ amount: suggestionAmount(s), isCard: true, vendorKnown: true, history }, opts.settings ?? DEFAULT_FRAUD); + const merged = mergeProblem(row.problem_highlight, reasons); + await pool.query("update acc_categorization_review set problem_highlight = $2, fraud_checked_at = now() where feed_txn_id = $1", [feedTxnId, merged]); + return merged !== row.problem_highlight ? "flagged" : "clean"; +} + +/** Задание 'fraud-flags': необработанные открытые строки acc_categorization_review. Идемпотентно. */ +export async function runFraudFlags(pool: Pool, opts: { settings?: FraudSettings; realmId?: string | null } = {}): Promise { + const { rows } = await pool.query("select feed_txn_id from acc_categorization_review where not done and fraud_checked_at is null order by created_at"); + const res: FlagResult = { checked: 0, flagged: 0, skipped: 0 }; + for (const { feed_txn_id } of rows as { feed_txn_id: string }[]) { + const r = await flagOne(pool, feed_txn_id, opts); + if (r === "no_data") res.skipped++; + else { + res.checked++; + if (r === "flagged") res.flagged++; + } + } + return res; +} diff --git a/packages/accounting_automation/src/http-api.test.ts b/packages/accounting_automation/src/http-api.test.ts index 43f6490..095f864 100644 --- a/packages/accounting_automation/src/http-api.test.ts +++ b/packages/accounting_automation/src/http-api.test.ts @@ -12,6 +12,9 @@ function mk(over: Partial = {}) { finalize: async () => { calls.push("finalize"); return { finalized: 0 }; }, categorize: async () => { calls.push("categorize"); return { status: "ok" }; }, summary: async () => { calls.push("summary"); return { sent: true }; }, + "fraud-flags": async () => ({}), + "invoice-check": async () => ({}), + "invoice-paid": async () => ({}), ...over, }; return { app: buildApi({ pool: {} as Pool, settings, jobs }), calls }; diff --git a/packages/accounting_automation/src/http-api.ts b/packages/accounting_automation/src/http-api.ts index d391ca6..50cf48c 100644 --- a/packages/accounting_automation/src/http-api.ts +++ b/packages/accounting_automation/src/http-api.ts @@ -9,8 +9,11 @@ export interface JobHandlers { finalize: () => Promise; categorize: () => Promise; summary: () => Promise; + "fraud-flags": () => Promise; + "invoice-check": () => Promise; + "invoice-paid": () => Promise; } -export const JOB_NAMES = ["invoices-mail", "finalize", "categorize", "summary"] as const; +export const JOB_NAMES = ["invoices-mail", "finalize", "categorize", "summary", "fraud-flags", "invoice-check", "invoice-paid"] as const; export interface ApiDeps { pool: Pool; diff --git a/packages/accounting_automation/src/invoice-check.ts b/packages/accounting_automation/src/invoice-check.ts new file mode 100644 index 0000000..13f3f48 --- /dev/null +++ b/packages/accounting_automation/src/invoice-check.ts @@ -0,0 +1,129 @@ +import { withTx, type Pool } from "khb_common"; + +/** + * «Проверка инвойса перед согласованием» (processes.md): для новых записей acc_invoices (stage 'checking', conclusion пусто) + * сервис считает заключение, пишет его в conclusion и создаёт задачу в acc_manual_review для accountant + * (kind 'invoice_approval', ref_table 'acc_invoices'; дальше задача переходит к cfo при переводе инвойса «на согласование»). + * Инвойс система не согласует. + */ + +export interface Conclusion { + checked_at: string; + contract: { found: boolean; id: string | null; stage: string | null; total_amount: number | null; paid_amount: number | null; retained_amount: number | null; remaining: number | null }; + exceeds_balance: boolean; + duplicate: { found: boolean; invoice_ids: string[] }; + insurance: { valid: boolean; valid_until: string | null }; + problems: string[]; +} + +export interface ContractFacts { + id: string; + stage: string | null; + total_amount: number; + paid_amount: number; + retained_amount: number; +} + +/** Чистая сборка заключения. */ +export function buildConclusion(i: { + amount: number; + contract: ContractFacts | null; + duplicateIds: string[]; + insuranceValidUntil: string | null; + today: string; + now: Date; +}): Conclusion { + const problems: string[] = []; + const c = i.contract; + const remaining = c ? Math.round((c.total_amount - c.retained_amount - c.paid_amount) * 100) / 100 : null; + if (!c) problems.push("нет контракта с этим вендором на этом проекте"); + const exceeds = remaining !== null && i.amount > remaining; + if (exceeds) problems.push(`сумма инвойса ${i.amount.toFixed(2)} больше остатка по контракту ${remaining!.toFixed(2)}`); + if (i.duplicateIds.length > 0) problems.push(`возможный дубль инвойса (${i.duplicateIds.length} шт.: тот же номер или та же сумма и дата)`); + const insured = i.insuranceValidUntil !== null && i.insuranceValidUntil >= i.today; + if (!insured) problems.push(i.insuranceValidUntil ? `нет страховки: сертификат истёк ${i.insuranceValidUntil}` : "нет страховки: сертификата нет"); + return { + checked_at: i.now.toISOString(), + contract: { + found: !!c, id: c?.id ?? null, stage: c?.stage ?? null, + total_amount: c?.total_amount ?? null, paid_amount: c?.paid_amount ?? null, retained_amount: c?.retained_amount ?? null, remaining, + }, + exceeds_balance: exceeds, + duplicate: { found: i.duplicateIds.length > 0, invoice_ids: i.duplicateIds }, + insurance: { valid: insured, valid_until: i.insuranceValidUntil }, + problems, + }; +} + +export interface InvoiceCheckResult { + checked: number; + withProblems: number; + errors: { id: string; message: string }[]; +} + +export async function runInvoiceCheck(deps: { pool: Pool; now?: () => Date }): Promise { + const now = (deps.now ?? (() => new Date()))(); + const today = now.toISOString().slice(0, 10); + const res: InvoiceCheckResult = { checked: 0, withProblems: 0, errors: [] }; + const { rows } = await deps.pool.query("select id from acc_invoices where stage = 'checking' and conclusion is null order by created_at"); + for (const { id } of rows as { id: string }[]) { + try { + const problems = await withTx(deps.pool, async (c) => { + const inv = (await c.query("select * from acc_invoices where id = $1 and stage = 'checking' and conclusion is null for update skip locked", [id])).rows[0]; + if (!inv) return null; + // контракт: указанный в инвойсе, иначе по вендору и проекту + const contractRow = ( + await c.query( + `select id, stage, total_amount, paid_amount, retained_amount from acc_contracts + where ($1::uuid is not null and id = $1::uuid) + or ($1::uuid is null and project_customer_id = $4 + and (($2::text is not null and vendor_qbo_id = $2) or lower(vendor_name) = lower($3))) + order by (id = $1::uuid) desc nulls last, id limit 1`, + [inv.contract_id, inv.vendor_qbo_id, inv.vendor_name, inv.project_customer_id], + ) + ).rows[0]; + const contract: ContractFacts | null = contractRow + ? { + id: contractRow.id, stage: contractRow.stage, total_amount: Number(contractRow.total_amount), + paid_amount: Number(contractRow.paid_amount), retained_amount: Number(contractRow.retained_amount ?? 0), + } + : null; + const dup = await c.query( + `select id from acc_invoices + where id <> $1 and stage <> 'rejected' + and (($2::text is not null and vendor_qbo_id = $2) or lower(vendor_name) = lower($3)) + and ((nullif(btrim($4::text), '') is not null and lower(btrim(invoice_number)) = lower(btrim($4::text))) + or (amount = $5 and invoice_date = $6)) + order by created_at`, + [id, inv.vendor_qbo_id, inv.vendor_name, inv.invoice_number, inv.amount, inv.invoice_date], + ); + const cert = await c.query( + `select max(valid_until)::text as v from acc_insurance_certificates + where ($1::text is not null and vendor_qbo_id = $1) or lower(vendor_name) = lower($2)`, + [inv.vendor_qbo_id, inv.vendor_name], + ); + const concl = buildConclusion({ + amount: Number(inv.amount), contract, duplicateIds: (dup.rows as { id: string }[]).map((r) => r.id), + insuranceValidUntil: cert.rows[0]?.v ?? null, today, now, + }); + await c.query( + "update acc_invoices set conclusion = $2::jsonb, contract_id = coalesce(contract_id, $3::uuid) where id = $1", + [id, JSON.stringify(concl), contract?.id ?? null], + ); + const highlight = concl.problems.length > 0 ? concl.problems.join("; ") : null; + await c.query( + `insert into acc_manual_review (kind, ref_table, ref_id, assignee_role, problem_highlight) + values ('invoice_approval', 'acc_invoices', $1, 'accountant', $2) on conflict (ref_table, ref_id) do nothing`, + [id, highlight], + ); + return concl.problems.length; + }); + if (problems === null) continue; + res.checked++; + if (problems > 0) res.withProblems++; + } catch (e) { + res.errors.push({ id, message: e instanceof Error ? e.message : String(e) }); + } + } + return res; +} diff --git a/packages/accounting_automation/src/invoice-paid.ts b/packages/accounting_automation/src/invoice-paid.ts new file mode 100644 index 0000000..aaa675e --- /dev/null +++ b/packages/accounting_automation/src/invoice-paid.ts @@ -0,0 +1,53 @@ +import { withTx, type Pool } from "khb_common"; + +/** + * «Согласование и оплата инвойса», шаг 5 (processes.md): подтверждённая проводка оплаты вендору (qbo_purchase) -> + * инвойс получает stage 'paid', paid_on, qbo_txn_id, а сумма добавляется к paid_amount контракта. + * Сопоставление: согласованный инвойс (stage 'approved'), тот же вендор (qbo id или имя), та же сумма, + * проводка не раньше даты решения и не занята другим инвойсом; берётся самая ранняя. + */ + +/** Ставит оплату инвойсу и накапливает paid_amount контракта. Возвращает false, если инвойс уже оплачен или не согласован. */ +export async function markPaid(pool: Pool, invoiceId: string, paid: { paidOn: string; qboTxnId: string | null }): Promise { + return withTx(pool, async (c) => { + const inv = (await c.query("select amount, contract_id, stage from acc_invoices where id = $1 for update", [invoiceId])).rows[0]; + if (!inv || inv.stage !== "approved") return false; + await c.query("update acc_invoices set stage = 'paid', paid_on = $2, qbo_txn_id = $3 where id = $1", [invoiceId, paid.paidOn, paid.qboTxnId]); + if (inv.contract_id) await c.query("update acc_contracts set paid_amount = paid_amount + $2 where id = $1", [inv.contract_id, inv.amount]); + return true; + }); +} + +export interface InvoicePaidResult { + matched: number; + errors: { id: string; message: string }[]; +} + +export async function runInvoicePaid(deps: { pool: Pool; realmId?: string | null }): Promise { + const res: InvoicePaidResult = { matched: 0, errors: [] }; + const { rows } = await deps.pool.query("select id from acc_invoices where stage = 'approved' and paid_on is null order by decided_at nulls last, created_at"); + for (const { id } of rows as { id: string }[]) { + try { + const m = ( + await deps.pool.query( + `select p.id, p.txn_date::text as txn_date + from acc_invoices i + join qbo_purchase p + on (($2::text is null or p.realm_id = $2::text) + and ((i.vendor_qbo_id is not null and p.entity_id = i.vendor_qbo_id) or lower(p.entity_name) = lower(i.vendor_name)) + and p.total_amt = i.amount + and p.txn_date >= coalesce(i.decided_at::date, i.invoice_date)) + where i.id = $1 + and not exists (select 1 from acc_invoices o where o.qbo_txn_id = p.id and o.id <> i.id) + order by p.txn_date, p.id limit 1`, + [id, deps.realmId ?? null], + ) + ).rows[0] as { id: string; txn_date: string } | undefined; + if (!m) continue; + if (await markPaid(deps.pool, id, { paidOn: m.txn_date, qboTxnId: m.id })) res.matched++; + } catch (e) { + res.errors.push({ id, message: e instanceof Error ? e.message : String(e) }); + } + } + return res; +} diff --git a/packages/accounting_automation/src/main.ts b/packages/accounting_automation/src/main.ts index 36cfb27..c262e50 100644 --- a/packages/accounting_automation/src/main.ts +++ b/packages/accounting_automation/src/main.ts @@ -4,6 +4,9 @@ import { runCategorization } from "./categorize.js"; import { makeClaudeRunner } from "./claude-runner.js"; import { DriveClient } from "./drive.js"; import { runFinalize } from "./finalize.js"; +import { runFraudFlags } from "./fraud.js"; +import { runInvoiceCheck } from "./invoice-check.js"; +import { runInvoicePaid } from "./invoice-paid.js"; import { GmailClient } from "./gmail.js"; import { GoogleAuth } from "./google.js"; import { buildApi } from "./http-api.js"; @@ -79,6 +82,8 @@ const app = buildApi({ claude, realmId: await realmId(), log, + approvalThresholdUsd: s.approvalThresholdUsd, + fraud: s.fraud, loadPrompt: makePromptLoader({ docId: s.prompt.driveDocId, fallbackFile: s.prompt.fallbackFile, @@ -87,6 +92,9 @@ const app = buildApi({ log: (msg, extra) => log.warn(extra ?? {}, msg), }), }), + "fraud-flags": async () => runFraudFlags(pool, { settings: s.fraud, realmId: await realmId() }), + "invoice-check": () => runInvoiceCheck({ pool }), + "invoice-paid": async () => runInvoicePaid({ pool, realmId: await realmId() }), summary: async () => { if (!slack || !s.slack) throw new Error("не настроен slack (botToken, accountingChannelId)"); const text = await postDailySummary({ pool, slack, channelId: s.slack.accountingChannelId, tz: "Asia/Nicosia", options: { nonWorkdays: await nonWorkdays() } }); diff --git a/packages/accounting_automation/src/mcp.int.test.ts b/packages/accounting_automation/src/mcp.int.test.ts index c814d14..9e3fec9 100644 --- a/packages/accounting_automation/src/mcp.int.test.ts +++ b/packages/accounting_automation/src/mcp.int.test.ts @@ -295,7 +295,7 @@ d("MCP бухгалтерии (временная БД)", () => { expect(((await post(bearer(TOKEN_A), rpc("ping"))).json()).result).toEqual({ resultType: "complete" }); const l = (await post(bearer(TOKEN_A), rpc("tools/list"))).json(); expect(l.result.tools.map((t: { name: string }) => t.name)).toEqual([ - "acc_review_list", "acc_review_get", "acc_review_update", "acc_review_done", "acc_review_handoff", "acc_review_return", "acc_review_batch", "acc_review_snooze", + "acc_review_list", "acc_review_get", "acc_review_update", "acc_review_done", "acc_review_handoff", "acc_review_return", "acc_review_batch", "acc_review_snooze", "acc_invoice_to_approve", "acc_invoice_decide", ]); const tl = l.result.tools as Array<{ name: string; annotations?: { readOnlyHint?: boolean }; _meta?: { ui?: { resourceUri?: string } } }>; expect(tl.find((t) => t.name === "acc_review_list")?.annotations?.readOnlyHint).toBe(true); diff --git a/packages/accounting_automation/src/mcp.ts b/packages/accounting_automation/src/mcp.ts index edcc0a9..079e49d 100644 --- a/packages/accounting_automation/src/mcp.ts +++ b/packages/accounting_automation/src/mcp.ts @@ -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, id: string, lock = false): Promise { + 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 { + 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 { + 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 { 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; сервис подставляет файл, если он доступен). */ diff --git a/packages/accounting_automation/src/settings.ts b/packages/accounting_automation/src/settings.ts index 695108d..011d231 100644 --- a/packages/accounting_automation/src/settings.ts +++ b/packages/accounting_automation/src/settings.ts @@ -38,6 +38,8 @@ export const accountingSchema = z.object({ slack: z.object({ botToken: z.string(), accountingChannelId: z.string() }).optional(), /** Порог суммы, с которого подтверждает Анастасия (USD). */ approvalThresholdUsd: z.number().default(5000), + /** Красные флажки fraud по операциям с карты: множитель к медиане прошлых платежей вендору и минимум платежей в истории. */ + fraud: z.object({ multiplier: z.number().positive().default(3), minHistory: z.number().int().min(1).default(3) }).default({}), /** Какие роли очереди закрывает каждый человек (person_id -> роли). Пока Юли нет, Анастасия закрывает обе. */ reviewers: z .array(z.object({ personId: z.string(), roles: z.array(z.enum(["accountant", "cfo"])).default(["accountant", "cfo"]) })) diff --git a/packages/accounting_automation/src/stage2.int.test.ts b/packages/accounting_automation/src/stage2.int.test.ts new file mode 100644 index 0000000..adb29c0 --- /dev/null +++ b/packages/accounting_automation/src/stage2.int.test.ts @@ -0,0 +1,272 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { createLogger, createTestDb, testDatabaseUrl, type TestDb } from "khb_common"; +import type { ClaudeRunner } from "./claude-runner.js"; +import { runCategorization } from "./categorize.js"; +import { runFraudFlags } from "./fraud.js"; +import { runInvoiceCheck } from "./invoice-check.js"; +import { runInvoicePaid } from "./invoice-paid.js"; +import { runFinalize } from "./finalize.js"; +import { ReviewTools } from "./mcp.js"; + +const log = createLogger("test", "silent"); +const url = testDatabaseUrl(); +const d = url ? describe : describe.skip; +const NOW = new Date("2026-11-23T12:00:00Z"); + +d("этап 2, часть A: роли, fraud, проверка и оплата инвойсов (временная БД)", () => { + let db: TestDb; + let tools: ReviewTools; + let yulia: string; + let nastia: string; + const q = async (sql: string, p: unknown[] = []) => (await db.pool.query(sql, p)).rows; + + beforeAll(async () => { + db = await createTestDb(url!); + yulia = (await q("insert into person (display_name, email) values ('Юля', 'y@khbuild.pro') returning id"))[0].id; + nastia = (await q("insert into person (display_name, email) values ('Анастасия', 'n@khbuild.pro') returning id"))[0].id; + tools = new ReviewTools({ + pool: db.pool, + settings: { reviewers: [{ personId: yulia, roles: ["accountant"] }, { personId: nastia, roles: ["accountant", "cfo"] }] }, + now: () => NOW, + }); + }); + afterAll(async () => { await db?.drop(); }); + beforeEach(async () => { + await q(`truncate acc_manual_review, acc_invoices_review, acc_invoices_review_original, acc_categorization_review, acc_categorization_review_original, + acc_categorization_review_history, acc_invoices, acc_contracts, acc_insurance_certificates, qbo_purchase, qbo_account, acc_card_holders cascade`); + }); + + const purchase = (id: string, vendor: string, amt: number, type = "CreditCard", date = "2026-10-01", note: string | null = null) => + q(`insert into qbo_purchase (realm_id, id, txn_date, payment_type, entity_id, entity_name, total_amt, private_note, raw) values ('R', $1, $2, $3, $4, $5, $6, $7, '{}')`, + [id, date, type, `v-${vendor}`, vendor, amt, note]); + + const runCat = (results: unknown[], extra: Record = {}) => { + const claude: ClaudeRunner = async () => ({ ok: true, exitCode: 0, timedOut: false, stderr: "", stdout: "```json\n" + JSON.stringify({ run_id: "r1", results }) + "\n```" }); + return runCategorization({ pool: db.pool, claude, loadPrompt: async () => "П", realmId: "R", log, now: () => NOW, ...extra }); + }; + const roleOf = async (feed: string) => (await q("select assignee_role, problem_highlight from acc_manual_review where ref_id = $1", [feed]))[0]; + + describe("роль подтверждающего при создании задачи категоризации", () => { + it("от порога и первая оплата - cfo, иначе accountant; порог настраивается", async () => { + await purchase("p1", "Known", 100, "Check"); + await runCat([ + { feed_txn_id: "small", suggestion: { account: "A", amount: 120, vendor_qbo_id: "v-Known" } }, + { feed_txn_id: "big", suggestion: { account: "A", amount: 5000, vendor_qbo_id: "v-Known" } }, + { feed_txn_id: "new", suggestion: { account: "A", amount: 10, vendor_qbo_id: "v-New", vendor_name: "New" } }, + { feed_txn_id: "nosuggest", suggestion: null, problem_highlight: "ждёт документ" }, + ]); + expect((await roleOf("small")).assignee_role).toBe("accountant"); + expect((await roleOf("big")).assignee_role).toBe("cfo"); + expect((await roleOf("new")).assignee_role).toBe("cfo"); + expect((await roleOf("nosuggest")).assignee_role).toBe("accountant"); + await q("truncate acc_manual_review, acc_categorization_review, acc_categorization_review_original"); + await runCat([{ feed_txn_id: "mid", suggestion: { account: "A", amount: 300, vendor_qbo_id: "v-Known" } }], { approvalThresholdUsd: 200 }); + expect((await roleOf("mid")).assignee_role).toBe("cfo"); + }); + + it("ранее закрытая операция вендора (history) - уже не первая оплата", async () => { + await q(`insert into acc_categorization_review_history (feed_txn_id, run_id, run_started_at, suggestion) values ('old', 'r0', now(), '{"vendor_name":"Zoom"}')`); + await runCat([{ feed_txn_id: "z", suggestion: { account: "A", amount: 10, vendor_name: "zoom" } }]); + expect((await roleOf("z")).assignee_role).toBe("accountant"); + }); + + it("cfo не мешает существующему закрытию: Анастасия закрывает задачу cfo через MCP", async () => { + await runCat([{ feed_txn_id: "big", suggestion: { account: "A", amount: 9000, vendor_qbo_id: "v-X" } }]); + const id = (await roleOf("big")) && (await q("select id from acc_manual_review where ref_id = 'big'"))[0].id; + await expect(tools.call(yulia, "acc_review_done", { id })).rejects.toThrow(/cfo/); + await tools.call(nastia, "acc_review_done", { id }); + }); + }); + + describe("красные флажки fraud", () => { + it("при записи: первая оплата по карте; сохраняется текст агента; не-карта без флажка", async () => { + await runCat([ + { feed_txn_id: "c1", suggestion: { account: "A", amount: 15, vendor_name: "Linode", is_card: true }, problem_highlight: "ждёт документ" }, + { feed_txn_id: "b1", suggestion: { account: "A", amount: 15, vendor_name: "Linode2" } }, + ]); + const c1 = await roleOf("c1"); + expect(c1.problem_highlight).toContain("ждёт документ"); + expect(c1.problem_highlight).toContain("первая оплата вендору"); + expect((await roleOf("b1")).problem_highlight).toBeNull(); + expect((await q("select fraud_checked_at from acc_categorization_review where feed_txn_id = 'b1'"))[0].fraud_checked_at).not.toBeNull(); + }); + + it("резкий рост суммы регулярного платежа (3x медианы, 3+ платежа); карта определяется по счёту", async () => { + await q("insert into qbo_account (realm_id, id, name, account_type, raw) values ('R', 'card1', 'Visa', 'Credit Card', '{}')"); + for (const [i, a] of [50, 55, 50, 45].entries()) await purchase(`z${i}`, "Zoom", a); + await runCat([ + { feed_txn_id: "zoom-bad", suggestion: { account: "A", amount: 500, vendor_qbo_id: "v-Zoom", bank_account_id: "card1" } }, + { feed_txn_id: "zoom-ok", suggestion: { account: "A", amount: 60, vendor_qbo_id: "v-Zoom", bank_account_id: "card1" } }, + ]); + expect((await roleOf("zoom-bad")).problem_highlight).toContain("резкое изменение суммы"); + expect((await roleOf("zoom-ok")).problem_highlight).toBeNull(); + }); + + it("задание fraud-flags: ставит флажки по необработанным, идемпотентно, не трогает done, строки без данных ждут", async () => { + // строки вставлены напрямую (мимо categorize): fraud_checked_at пусто + const ins = (feed: string, sug: unknown, extra = "false") => + q(`insert into acc_categorization_review (feed_txn_id, run_id, run_started_at, suggestion, problem_highlight, done) values ($1, 'r', now(), $2::jsonb, 'исходный текст', ${extra})`, + [feed, sug === null ? null : JSON.stringify(sug)]); + await ins("n1", { amount: 20, vendor_name: "Brand New", is_card: true }); + await ins("nodata", null); + await ins("done1", { amount: 20, vendor_name: "Brand New 2", is_card: true }, "true"); + const r1 = await runFraudFlags(db.pool, { realmId: "R" }); + expect(r1).toMatchObject({ checked: 1, flagged: 1, skipped: 1 }); + const text1 = (await roleOf("n1")).problem_highlight as string; + expect(text1.startsWith("исходный текст | ")).toBe(true); + const r2 = await runFraudFlags(db.pool, { realmId: "R" }); + expect(r2).toMatchObject({ checked: 0, flagged: 0, skipped: 1 }); + expect((await roleOf("n1")).problem_highlight).toBe(text1); + // принудительный повторный прогон не дублирует текст + await q("update acc_categorization_review set fraud_checked_at = null where feed_txn_id = 'n1'"); + const r3 = await runFraudFlags(db.pool, { realmId: "R" }); + expect(r3.flagged).toBe(0); + expect((await roleOf("n1")).problem_highlight).toBe(text1); + expect((await q("select problem_highlight from acc_categorization_review where feed_txn_id = 'done1'"))[0].problem_highlight).toBe("исходный текст"); + }); + + it("флажок fraud не попадает в changed_fields при завершении разбора", async () => { + await runCat([{ feed_txn_id: "c9", suggestion: { account: "A", amount: 15, vendor_name: "Linode", is_card: true } }]); + await q("update acc_categorization_review set done = true, done_by = 'x' where feed_txn_id = 'c9'"); + const fin = await runFinalize({ pool: db.pool, delaySeconds: 0, notify: () => {}, now: () => new Date(Date.now() + 7200_000) }); + expect(fin.finalized.categorization).toBe(1); + const h = (await q("select changed_fields from acc_categorization_review_history where feed_txn_id = 'c9'"))[0]; + expect(JSON.stringify(h.changed_fields)).not.toContain("fraud_checked_at"); + }); + }); + + describe("проверка инвойса, согласование и оплата", () => { + const addInvoice = async (over: Record = {}) => { + const r = { vendor_name: "ACME", vendor_qbo_id: "v-ACME", invoice_number: "INV-1", invoice_date: "2026-11-01", amount: 1000, project: "proj-1", stage: "checking", ...over }; + return (await q( + `insert into acc_invoices (id, source_message_id, drive_file_id, vendor_name, vendor_qbo_id, invoice_number, invoice_date, amount, project_customer_id, stage) + values (gen_random_uuid(), 'm', 'f', $1, $2, $3, $4, $5, $6, $7) returning id`, + [r.vendor_name, r.vendor_qbo_id, r.invoice_number, r.invoice_date, r.amount, r.project, r.stage], + ))[0].id as string; + }; + const addContract = async (over: Record = {}) => + (await q( + `insert into acc_contracts (vendor_name, vendor_qbo_id, project_customer_id, total_amount, paid_amount, retained_amount) values ($1, 'v-ACME', 'proj-1', $2, $3, $4) returning id`, + ["ACME", over.total ?? 10000, over.paid ?? 0, over.retained ?? 0], + ))[0].id as string; + const taskId = async (inv: string) => (await q("select id from acc_manual_review where ref_id = $1", [inv]))[0].id as string; + + it("invoice-check: всё в порядке - заключение без проблем, задача для accountant, контракт привязан; повтор не дублирует", async () => { + const cid = await addContract({ total: 10000, paid: 5000, retained: 1000 }); + await q("insert into acc_insurance_certificates (vendor_name, vendor_qbo_id, valid_until, drive_file_id) values ('ACME', 'v-ACME', '2027-01-01', 'f')"); + const inv = await addInvoice(); + const r = await runInvoiceCheck({ pool: db.pool, now: () => NOW }); + expect(r).toEqual({ checked: 1, withProblems: 0, errors: [] }); + const row = (await q("select * from acc_invoices where id = $1", [inv]))[0]; + expect(row.stage).toBe("checking"); + expect(row.contract_id).toBe(cid); + expect(row.conclusion.problems).toEqual([]); + expect(row.conclusion.contract.remaining).toBe(4000); + const t = (await q("select kind, ref_table, assignee_role, problem_highlight from acc_manual_review where ref_id = $1", [inv]))[0]; + expect(t).toEqual({ kind: "invoice_approval", ref_table: "acc_invoices", assignee_role: "accountant", problem_highlight: null }); + expect(await runInvoiceCheck({ pool: db.pool, now: () => NOW })).toMatchObject({ checked: 0 }); + expect(await q("select 1 from acc_manual_review")).toHaveLength(1); + }); + + it("invoice-check: нет контракта и страховки, превышение остатка, дубль - проблемы в problem_highlight", async () => { + await addContract({ total: 1500, paid: 1000 }); + const first = await addInvoice({ amount: 400 }); + const dup = await addInvoice({ invoice_number: "inv-1", amount: 900 }); + const noContract = await addInvoice({ project: "other", invoice_number: "X", amount: 5 }); + await runInvoiceCheck({ pool: db.pool, now: () => NOW }); + const ph = async (id: string) => (await q("select problem_highlight from acc_manual_review where ref_id = $1", [id]))[0].problem_highlight as string; + expect(await ph(first)).toContain("возможный дубль"); + expect(await ph(dup)).toContain("больше остатка по контракту"); + expect(await ph(dup)).toContain("нет страховки"); + expect(await ph(noContract)).toContain("нет контракта"); + const c = (await q("select conclusion from acc_invoices where id = $1", [dup]))[0].conclusion; + expect(c.duplicate.found).toBe(true); + expect(c.exceeds_balance).toBe(true); + }); + + it("invoice-check: просроченный сертификат и дубль по сумме и дате", async () => { + await q("insert into acc_insurance_certificates (vendor_name, vendor_qbo_id, valid_until, drive_file_id) values ('ACME', 'v-ACME', '2026-11-22', 'f')"); + await addInvoice({ invoice_number: null, amount: 777 }); + const b = await addInvoice({ invoice_number: null, amount: 777 }); + await runInvoiceCheck({ pool: db.pool, now: () => NOW }); + const c = (await q("select conclusion from acc_invoices where id = $1", [b]))[0].conclusion; + expect(c.duplicate.found).toBe(true); + expect(c.insurance).toEqual({ valid: false, valid_until: "2026-11-22" }); + }); + + it("MCP: Юля переводит на согласование, Анастасия решает; роли и стадии проверяются", async () => { + await addContract(); + const inv = await addInvoice(); + await runInvoiceCheck({ pool: db.pool, now: () => NOW }); + const t = await taskId(inv); + const list = (await tools.call(yulia, "acc_review_list", { kind: "invoice_approval" })) as { tasks: Array> }; + expect(list.tasks[0].review.vendor_name).toBe("ACME"); + expect(list.tasks[0].file_url).toBe("https://drive.google.com/file/d/f/view"); + const g = (await tools.call(yulia, "acc_review_get", { id: t })) as Record; + expect(g.review.stage).toBe("checking"); + expect(g.file_url).toContain("drive.google.com"); + + await expect(tools.call(yulia, "acc_invoice_decide", { id: t, decision: "approved" })).rejects.toThrow(/cfo/); + await expect(tools.call(nastia, "acc_invoice_decide", { id: t, decision: "approved" })).rejects.toThrow(/не переведён/); + await tools.call(yulia, "acc_invoice_to_approve", { id: t, comment: "подрядчик подтвердил" }); + expect((await q("select stage from acc_invoices where id = $1", [inv]))[0].stage).toBe("to_approve"); + expect((await roleOf(inv)).assignee_role).toBe("cfo"); + expect((await roleOf(inv)).problem_highlight).toContain("подрядчик подтвердил"); + await expect(tools.call(yulia, "acc_invoice_to_approve", { id: t })).rejects.toThrow(/назначена роли cfo/); + expect(((await tools.call(yulia, "acc_review_list", {})) as { total: number }).total).toBe(0); + + await expect(tools.call(nastia, "acc_invoice_decide", { id: t, decision: "maybe" })).rejects.toThrow(/decision/); + await expect(tools.call(nastia, "acc_invoice_decide", { id: t, decision: "wait" })).rejects.toThrow(/until/); + await expect(tools.call(nastia, "acc_invoice_decide", { id: t, decision: "wait", until: "2026-11-01" })).rejects.toThrow(/будущем/); + await tools.call(nastia, "acc_invoice_decide", { id: t, decision: "wait", until: "2026-12-01" }); + let row = (await q("select stage, decided_by, decided_at from acc_invoices where id = $1", [inv]))[0]; + expect(row).toMatchObject({ stage: "wait", decided_by: nastia }); + expect(row.decided_at).toBeInstanceOf(Date); + expect(((await tools.call(nastia, "acc_review_list", {})) as { total: number }).total).toBe(0); + expect(((await tools.call(nastia, "acc_review_list", { include_snoozed: true })) as { total: number }).total).toBe(1); + + await tools.call(nastia, "acc_invoice_decide", { id: t, decision: "approved", comment: "ок" }); + row = (await q("select stage, decided_by, conclusion from acc_invoices where id = $1", [inv]))[0]; + expect(row.stage).toBe("approved"); + expect(row.conclusion.last_decision).toMatchObject({ decision: "approved", comment: "ок", by: nastia }); + expect(await q("select 1 from acc_manual_review")).toHaveLength(0); + }); + + it("MCP: отклонение закрывает задачу; задача другого вида не подходит", async () => { + const inv = await addInvoice({ stage: "to_approve" }); + await q("update acc_invoices set conclusion = '{}'::jsonb where id = $1", [inv]); + await q("insert into acc_manual_review (kind, ref_table, ref_id, assignee_role) values ('invoice_approval', 'acc_invoices', $1, 'cfo')", [inv]); + await tools.call(nastia, "acc_invoice_decide", { id: await taskId(inv), decision: "rejected" }); + expect((await q("select stage from acc_invoices where id = $1", [inv]))[0].stage).toBe("rejected"); + await runCat([{ feed_txn_id: "f", suggestion: null, problem_highlight: "x" }]); + const ct = (await q("select id from acc_manual_review where ref_id = 'f'"))[0].id; + await expect(tools.call(nastia, "acc_invoice_decide", { id: ct, decision: "approved" })).rejects.toThrow(/invoice_approval/); + }); + + it("invoice-paid: сопоставляет оплату вендору с согласованным инвойсом, копит paid_amount, не берёт одну проводку дважды", async () => { + const cid = await addContract({ paid: 100 }); + const a = await addInvoice({ amount: 1000 }); + const b = await addInvoice({ amount: 1000, invoice_number: "INV-2" }); + const notApproved = await addInvoice({ amount: 333, invoice_number: "INV-3", stage: "to_approve" }); + await q("update acc_invoices set stage = 'approved', decided_at = '2026-11-10', contract_id = $2 where id = any($1)", [[a, b], cid]); + await purchase("pay1", "ACME", 1000, "Check", "2026-11-12"); + await purchase("old", "ACME", 1000, "Check", "2026-10-01"); // до решения - не оплата + await purchase("other", "Someone", 1000, "Check", "2026-11-12"); + await purchase("n3", "ACME", 333, "Check", "2026-11-12"); + const r1 = await runInvoicePaid({ pool: db.pool, realmId: "R" }); + expect(r1).toEqual({ matched: 1, errors: [] }); + const paid = (await q("select id, stage, paid_on::text, qbo_txn_id from acc_invoices where stage = 'paid'")); + expect(paid).toHaveLength(1); + expect(paid[0]).toMatchObject({ paid_on: "2026-11-12", qbo_txn_id: "pay1" }); + expect(Number((await q("select paid_amount from acc_contracts where id = $1", [cid]))[0].paid_amount)).toBe(1100); + // повторный запуск: та же проводка второй инвойс не оплачивает, итог не меняется + expect(await runInvoicePaid({ pool: db.pool, realmId: "R" })).toEqual({ matched: 0, errors: [] }); + expect(Number((await q("select paid_amount from acc_contracts where id = $1", [cid]))[0].paid_amount)).toBe(1100); + // вторая проводка - второй инвойс + await purchase("pay2", "ACME", 1000, "Check", "2026-11-15"); + expect(await runInvoicePaid({ pool: db.pool, realmId: "R" })).toMatchObject({ matched: 1 }); + expect(Number((await q("select paid_amount from acc_contracts where id = $1", [cid]))[0].paid_amount)).toBe(2100); + expect((await q("select stage from acc_invoices where id = $1", [notApproved]))[0].stage).toBe("to_approve"); + }); + }); +}); diff --git a/packages/accounting_automation/src/stage2.test.ts b/packages/accounting_automation/src/stage2.test.ts new file mode 100644 index 0000000..d86b356 --- /dev/null +++ b/packages/accounting_automation/src/stage2.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from "vitest"; +import { decideAssigneeRole } from "./approval.js"; +import { AMOUNT_JUMP_MARK, FIRST_PAYMENT_MARK, evaluateFraud, median, mergeProblem } from "./fraud.js"; +import { buildConclusion } from "./invoice-check.js"; + +describe("роль подтверждающего", () => { + it("cfo при сумме от порога или первой оплате, иначе accountant", () => { + expect(decideAssigneeRole({ amount: 5000, threshold: 5000, firstPayment: false }).role).toBe("cfo"); + expect(decideAssigneeRole({ amount: 4999.99, threshold: 5000, firstPayment: false }).role).toBe("accountant"); + expect(decideAssigneeRole({ amount: -7000, threshold: 5000, firstPayment: false }).role).toBe("cfo"); + expect(decideAssigneeRole({ amount: 10, threshold: 5000, firstPayment: true })).toEqual({ role: "cfo", reason: "первая оплата новому вендору" }); + expect(decideAssigneeRole({ amount: null, threshold: 5000, firstPayment: false }).role).toBe("accountant"); + expect(decideAssigneeRole({ amount: 100, threshold: 50, firstPayment: false }).role).toBe("cfo"); + }); +}); + +describe("красные флажки fraud (чистая оценка)", () => { + const h = (priorCount: number, cardAmounts: number[]) => ({ priorCount, cardAmounts }); + it("медиана", () => { + expect(median([1, 9, 5])).toBe(5); + expect(median([2, 4, 6, 8])).toBe(5); + }); + it("первая оплата вендору по карте", () => { + const r = evaluateFraud({ amount: 20, isCard: true, vendorKnown: true, history: h(0, []) }); + expect(r).toHaveLength(1); + expect(r[0]).toContain(FIRST_PAYMENT_MARK); + }); + it("не карта или вендор неизвестен - без флажков", () => { + expect(evaluateFraud({ amount: 20, isCard: false, vendorKnown: true, history: h(0, []) })).toEqual([]); + expect(evaluateFraud({ amount: 20, isCard: true, vendorKnown: false, history: h(0, []) })).toEqual([]); + }); + it("резкий рост суммы: 3x от медианы, минимум 3 платежа в истории", () => { + const hist = h(3, [50, 50, 50]); + expect(evaluateFraud({ amount: 500, isCard: true, vendorKnown: true, history: hist })[0]).toContain(AMOUNT_JUMP_MARK); + expect(evaluateFraud({ amount: 150, isCard: true, vendorKnown: true, history: hist })).toHaveLength(1); + expect(evaluateFraud({ amount: 149.99, isCard: true, vendorKnown: true, history: hist })).toEqual([]); + expect(evaluateFraud({ amount: 500, isCard: true, vendorKnown: true, history: h(2, [50, 50]) })).toEqual([]); + expect(evaluateFraud({ amount: 120, isCard: true, vendorKnown: true, history: hist }, { multiplier: 2, minHistory: 3 })).toHaveLength(1); + }); + it("mergeProblem не затирает и не дублирует", () => { + const r = [`${FIRST_PAYMENT_MARK}, раньше платежей не было`]; + const once = mergeProblem("ждёт документ", r); + expect(once).toBe(`ждёт документ | ${r[0]}`); + expect(mergeProblem(once, r)).toBe(once); + expect(mergeProblem(null, r)).toBe(r[0]); + expect(mergeProblem("x", [])).toBe("x"); + expect(mergeProblem(null, [])).toBeNull(); + }); +}); + +describe("заключение по инвойсу (чистая сборка)", () => { + const base = { amount: 1000, duplicateIds: [], insuranceValidUntil: "2027-01-01", today: "2026-11-23", now: new Date("2026-11-23T10:00:00Z") }; + const contract = { id: "c1", stage: "rough", total_amount: 10000, paid_amount: 6000, retained_amount: 1000 }; + it("без проблем", () => { + const c = buildConclusion({ ...base, contract }); + expect(c.problems).toEqual([]); + expect(c.contract.remaining).toBe(3000); + expect(c.insurance.valid).toBe(true); + }); + it("нет контракта, превышение, дубль, нет страховки", () => { + const c = buildConclusion({ ...base, contract: null, duplicateIds: ["d1"], insuranceValidUntil: null }); + expect(c.problems).toHaveLength(3); + const over = buildConclusion({ ...base, amount: 3000.01, contract }); + expect(over.exceeds_balance).toBe(true); + expect(buildConclusion({ ...base, amount: 3000, contract }).exceeds_balance).toBe(false); + const expired = buildConclusion({ ...base, contract, insuranceValidUntil: "2026-11-22" }); + expect(expired.insurance.valid).toBe(false); + expect(expired.problems[0]).toContain("истёк"); + }); +}); diff --git a/packages/khb_common/migrations/041_acc_stage2_flags.sql b/packages/khb_common/migrations/041_acc_stage2_flags.sql new file mode 100644 index 0000000..f9581a4 --- /dev/null +++ b/packages/khb_common/migrations/041_acc_stage2_flags.sql @@ -0,0 +1,13 @@ +-- Автоматизация бухгалтерии, этап 2 (часть A): флажки fraud, проверка и оплата инвойсов. Только добавляет. +-- fraud_checked_at: когда задание fraud-flags проверило строку категоризации (идемпотентность; в _original и _history колонка нужна, +-- потому что триггер копирует строку целиком через select ($1).*). +alter table acc_categorization_review add column if not exists fraud_checked_at timestamptz; +alter table acc_categorization_review_original add column if not exists fraud_checked_at timestamptz; +alter table acc_categorization_review_history add column if not exists fraud_checked_at timestamptz; + +-- Удержание по контракту (удержанная сумма не доступна к оплате); колонку добавляет и часть C - if not exists. +alter table acc_contracts add column if not exists retained_amount numeric(14,2) not null default 0; + +-- Поиск задания invoice-check и invoice-paid. +create index if not exists acc_invoices_stage_idx on acc_invoices (stage); +create index if not exists qbo_purchase_entity_idx on qbo_purchase (realm_id, entity_id);