diff --git a/docs/agent_memories/06-acc-implementation-status.md b/docs/agent_memories/06-acc-implementation-status.md index f3581e2..442e814 100644 --- a/docs/agent_memories/06-acc-implementation-status.md +++ b/docs/agent_memories/06-acc-implementation-status.md @@ -32,3 +32,11 @@ - Проверка расхода без чека (> $500 нельзя, до $500 только с согласием Анастасии) - в finalize для категоризации; согласие ставит MCP-инструмент `acc_receipt_allow_without`. - Данные операции ленты (сумма, вендор, карта) берутся из `acc_feed_txn`; её заполняет job `categorize` из поля `txn` ответа агента. Промпт `p-categorization.md` (approved) про `txn` пока не знает: добавить, иначе таблица пуста и поиск чека и проверка лимита не работают. - Не проверено с реальными системами: Slack (scope-ы бота: conversations.history, conversations.replies, conversations.list types=im, im:history, files:read, chat:write), скачивание файлов, Drive (папка «Чеки»), распознавание чеков Claude (картинки и PDF). +- Туннель к БД: `ssh -N -L 15434::5432 khbuild-vps`; IP контейнера supabase-db меняется (был 172.19.0.2, стал 172.19.0.6): проверять `docker inspect supabase-db`. Vitest запускать из корня репозитория (`npx vitest run packages/accounting_automation/src/<файл>`), в worktree сначала `pnpm install` и `pnpm --filter khb_common build`. + +## Этап 2: страховки, сверка, история правок, chargeback, fraud (миграции 061-062, не выложено) +- Задания (http-api JOB_NAMES, main.ts; расписание на сервере не заведено): `certificates` (ежедневно), `reconcile-monthly`, `history-weekly`, `fraud-weekly`. Файлы: certificates.ts, certificates-ingest.ts, reconcile.ts, history-report.ts, chargeback.ts, chargeback-http.ts, stage2-tools.ts, stage2-tool-defs.ts, vendor-name.ts. +- Письма с сертификатами разбирает invoices-mail (поле `document_type` в ответе агента; без него поведение прежнее). +- Отправка запроса подрядчику: интерфейс ContractorMessenger; реальной записи в JobTread в проекте нет (data_collector только читает), поэтому в main.ts стоит manualMessenger: текст в `request_log`, Юля отправляет вручную. +- Chargeback: пересчёт acc_contracts.retained_amount и закрытие по остатку - триггеры БД (062). Ручки `/chargeback/find|start|close|add-log|fraud|fraud/status`; MCP: acc_chargeback_list/decide/link_invoice/confirm/close, acc_contract_balance, acc_fraud_create/update, acc_certificate_request_approve. +- Не проверено на реальных данных: чтение выписок и сертификатов настоящим `claude -p`, Drive (папки «Страховки», «Выписки»), Slack-отчёты, соответствие названий счетов QuickBooks последним цифрам карты. diff --git a/docs/proposed/data_objects/accounting_automation/acc_certificates_review.md b/docs/proposed/data_objects/accounting_automation/acc_certificates_review.md index d301b19..39dc660 100644 --- a/docs/proposed/data_objects/accounting_automation/acc_certificates_review.md +++ b/docs/proposed/data_objects/accounting_automation/acc_certificates_review.md @@ -15,5 +15,13 @@ | created_at | timestamptz | нет | создана | | updated_at | timestamptz | нет | последнее изменение (ставит триггер); процесс «Завершение ручного разбора» ждёт 30 секунд без изменений | | done_by | text | да | кто отметил запись выполненной (попадает в `closed_by` таблицы `_history`) | +| alert_kind | text | да | повод: `expiring_30`, `expiring_5`, `expired`, `missing`, `new_certificate` (пришёл новый сертификат, ждёт проверки человеком). Строка усиливается 30 -> 5 -> просрочен, но не дублируется; закрытая строка с тем же поводом и сроком заново не создаётся (для `expired` и `missing` - не чаще раза в 14 дней) | +| drive_file_id | text | да | файл в Google Drive, если срок или вендор из письма не распознаны и записи в `acc_insurance_certificates` ещё нет (проблема `tbd`); при завершении разбора файл попадает в сертификат | +| request_count | smallint | нет | сколько запросов нового сертификата отправлено подрядчику (default 0; максимум 2: запрос и один повтор через 5 дней) | +| request_approved_by | text | да | кто подтвердил отправку запроса (MCP `acc_certificate_request_approve`, роль accountant) | +| request_approved_at | timestamptz | да | когда подтвердили; без подтверждения запрос не уходит, пока Анастасия не включит автоотправку (настройка `stage2.certificateAutoSend`) | +| request_log | jsonb | да | журнал запросов: `[{at, delivered, channel, subject, text, ref}]`. Пока нет записи сообщений в JobTread, `delivered` = false, `channel` = `manual`: текст готов, Юля отправляет его вручную из JobTread (в `problem_highlight` добавляется пометка) | + +Новые сертификаты из писем приходят тем же заданием, что инвойсы (вид документа `certificate` в распознавании): файл в папке «Страховки» (вендор, месяц), запись в `acc_insurance_certificates`; если у вендора уже есть открытая строка разбора, она получает ссылку на новый сертификат (`alert_kind` = `new_certificate`), закрывает её человек. Колонки `alert_kind`, `drive_file_id`, `request_*` есть и в `_original`, и в `_history`. Подчиняется общей схеме ручного разбора: рядом таблица `acc_certificates_review_original` (те же колонки, строка как её записал автомат; тот же ключ) и `acc_certificates_review_history` (после завершения разбора: те же колонки плюс `closed_by` text, `closed_at` timestamptz, `changed_fields` jsonb - поля, которые изменил человек, со старым и новым значением). Строка попадает в `_history` и удаляется из основной таблицы процессом «Завершение ручного разбора». diff --git a/docs/proposed/data_objects/accounting_automation/acc_chargeback.md b/docs/proposed/data_objects/accounting_automation/acc_chargeback.md index cc21870..6b9c967 100644 --- a/docs/proposed/data_objects/accounting_automation/acc_chargeback.md +++ b/docs/proposed/data_objects/accounting_automation/acc_chargeback.md @@ -1,6 +1,6 @@ # acc_chargeback -Дела двух видов (колонка `kind`): `card_fraud` - подозрительная операция по карте (процесс «Подозрительные операции по карте (fraud)»), `contract` - удержание с контракта подрядчика за неисправленный дефект (процесс «Chargeback к контракту подрядчика»). Заполняет accounting_assistant, дальше правят Юля и Анастасия через Claude. Префикс `acc_` - таблицы автоматизации бухгалтерии (зеркала QuickBooks - `qbo_`). +Дела двух видов (колонка `kind`): `card_fraud` - подозрительная операция по карте (процесс «Подозрительные операции по карте (fraud)»), `contract` - удержание с контракта подрядчика за неисправленный дефект (процесс «Chargeback к контракту подрядчика»). Заполняют сервис accounting_automation (ручки `/chargeback/*` для ассистента менеджера и MCP-инструменты `acc_chargeback_*`, `acc_fraud_*` для Юли и Анастасии), дальше правят Юля и Анастасия через Claude. Префикс `acc_` - таблицы автоматизации бухгалтерии (зеркала QuickBooks - `qbo_`). Общие колонки: @@ -15,7 +15,9 @@ | Колонка | Тип | Null | Описание | |---|---|---|---| -| feed_txn_id | text | да | оспариваемая операция (заполнено для `card_fraud`) | +| feed_txn_id | text | да | оспариваемая операция (обязательно для `card_fraud`, для `contract` пусто) | +| kit | jsonb | да | комплект документов (fraud, шаг 5): `operation` (операция из `acc_categorization_review` или её истории), `receipt` (чек из `acc_receipts` со ссылкой на Drive) или `receipt_note` = «чека нет», `vendor_correspondence` (переписку из JobTread или Gmail прикладывает человек), `collected_at` | +| created_by | uuid FK person | да | кто завёл дело (fraud) | | reason | text | да | чужое, дубль, товар не получен, неверная сумма | | bank | text | да | банк карты | | file_by | date | да | срок подачи | @@ -30,12 +32,20 @@ | defect_daily_log_url | text | да | ссылка на этот Daily Log (шаг 3) | | defect_description | text | да | описание дефекта из сообщения менеджера (шаг 3) | | extra_daily_logs | text[] | да | ссылки на повторные Daily Log по тому же дефекту (шаг 3, добавляет ассистент менеджера; новых строк не создаётся) | -| reported_by | text FK person | да | менеджер проекта, сообщивший о дефекте (шаг 3) | -| decided_by | text FK person | да | Анастасия, решившая удерживать или отклонить (шаг 4) | +| reported_by | uuid FK person | да | менеджер проекта, сообщивший о дефекте (шаг 3) | +| decided_by | uuid FK person | да | Анастасия, решившая удерживать или отклонить (шаг 4) | | decided_at | timestamptz | да | когда решила (шаг 4) | | fix_vendor_name | text | да | подрядчик Б, исправивший дефект (шаг 4) | | fix_invoice_id | uuid FK acc_invoices | да | инвойс подрядчика Б за исправление (шаг 6) | | retained_amount | numeric(14,2) | да | сумма удержания с подрядчика А (шаг 6, уточняется на шаге 7) | | close_reason | text | да | причина закрытия без удержания: «менеджер закрыл вопрос» (шаг 3), отклонение Анастасии (шаг 4) | -| confirmed_by | text FK person | да | Анастасия, подтвердившая сумму (шаг 7) | +| confirmed_by | uuid FK person | да | Анастасия, подтвердившая сумму (шаг 7) | | confirmed_at | timestamptz | да | когда подтвердила (шаг 7) | + +Правила и автоматика (миграция 062): +- `person.id` - uuid, поэтому колонки `reported_by`, `decided_by`, `confirmed_by`, `created_by` имеют тип uuid (не text). +- Ограничения БД: для `card_fraud` обязателен `feed_txn_id`, для `contract` - `contract_id`; статус должен соответствовать виду. `defect_daily_log_id` уникален: повторный запрос ассистента менеджера с тем же Daily Log возвращает существующую строку. +- Задача в `acc_manual_review` (вид `chargeback`, `ref_table` = `acc_chargeback`) ведётся сервисом по статусу. Для `contract`: `claimed` - cfo (решить), `approved` - accountant (ждать инвойс подрядчика Б), `fix_invoiced` - cfo (подтвердить сумму), `applied` - accountant (сообщить подрядчику А в JobTread). Для `card_fraud`: accountant на всех статусах до закрытия. При `closed` задачу убирает триггер БД. +- Отклонение Анастасии (шаг 4) сразу пишет `status` = `closed` и `close_reason` = «отклонено: причина» (промежуточный `rejected` у `contract` допустим по ограничению БД, сервис им не пользуется). +- Пересчёт `acc_contracts.retained_amount` (шаг 8) и закрытие по остатку (шаг 12) делают триггеры БД, поэтому они срабатывают и при правке строки в Mathesar. +- Fraud: допустимые переходы `collecting` -> `filed`/`closed`; `filed` -> `refunded`/`rejected`/`closed`; `rejected` -> `filed`/`closed`; `refunded` -> `closed`. Недельное напоминание о незакрытых - задание `fraud-weekly`. diff --git a/docs/proposed/data_objects/accounting_automation/acc_contracts.md b/docs/proposed/data_objects/accounting_automation/acc_contracts.md index d66d1ec..3cbaa08 100644 --- a/docs/proposed/data_objects/accounting_automation/acc_contracts.md +++ b/docs/proposed/data_objects/accounting_automation/acc_contracts.md @@ -12,5 +12,5 @@ | stage | text | да | стадия работ | | total_amount | numeric(14,2) | нет | сумма контракта | | paid_amount | numeric(14,2) | нет | накоплено оплат (default 0) | -| retained_amount | numeric(14,2) | нет | удержания по chargeback к контракту (default 0): сумма `retained_amount` строк `acc_chargeback` вида `contract` со статусом `applied`; пересчитывает accounting_automation. Остаток к оплате = `total_amount` - `retained_amount` - `paid_amount` | +| retained_amount | numeric(14,2) | нет | удержания по chargeback к контракту (default 0): сумма `retained_amount` строк `acc_chargeback` вида `contract` со статусом `applied`; пересчитывает триггер БД; строка, закрытая после подтверждения суммы (`confirmed_at` заполнено), продолжает учитываться, иначе автоматическое закрытие (шаг 12) вернуло бы остаток. Остаток к оплате = `total_amount` - `retained_amount` - `paid_amount`; когда он не больше нуля, строки `applied` закрываются автоматически | | drive_file_id | text | да | файл договора в Google Drive | diff --git a/docs/proposed/data_objects/accounting_automation/acc_discrepancies.md b/docs/proposed/data_objects/accounting_automation/acc_discrepancies.md index c78789a..6f3e69d 100644 --- a/docs/proposed/data_objects/accounting_automation/acc_discrepancies.md +++ b/docs/proposed/data_objects/accounting_automation/acc_discrepancies.md @@ -14,3 +14,5 @@ | closed_at | timestamptz | да | закрыто Юлей | | closed_by | text | да | кто закрыл | | resolution | text | да | что сделано | + +Сверка выписок (`statement_vs_qbo`, задание `reconcile-monthly`): в `description` в квадратных скобках имя файла выписки; `qbo_ref` - операция QuickBooks (для лишних и дублей) или счёт (для остатка); `amount_diff` - сумма операции или разница остатков. Отчёт уходит Анастасии в Slack; задач в `acc_manual_review` по этим расхождениям пока не создаётся (решение для согласования). Сверяются расходные операции (в зеркале QuickBooks только расходы), остаток на конец периода восстанавливается приближённо. diff --git a/docs/proposed/data_objects/accounting_automation/acc_invoices.md b/docs/proposed/data_objects/accounting_automation/acc_invoices.md index e0f99d1..24291b2 100644 --- a/docs/proposed/data_objects/accounting_automation/acc_invoices.md +++ b/docs/proposed/data_objects/accounting_automation/acc_invoices.md @@ -22,5 +22,6 @@ | decided_at | timestamptz | да | когда | | paid_on | date | да | дата оплаты (ставит задание `invoice-paid`) | | qbo_txn_id | text | да | проводка оплаты в QuickBooks | +| no_insurance | boolean | нет | отметка «нет страховки» (default false): у вендора нет действующего сертификата в `acc_insurance_certificates`. Ставит и снимает ежедневное задание `certificates` у неоплаченных инвойсов; согласование не блокирует, только предупреждает | Движение по стадиям: инвойс попадает сюда в `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 3586ee9..72798fc 100644 --- a/docs/proposed/data_objects/accounting_automation/acc_manual_review.md +++ b/docs/proposed/data_objects/accounting_automation/acc_manual_review.md @@ -5,8 +5,8 @@ | Колонка | Тип | Null | Описание | |---|---|---|---| | id | uuid PK | нет | внутренний ID | -| kind | text | нет | вид задачи: `invoice`, `categorization`, `certificate`, `discrepancy`, `acc_receipt_search`, `acc_chargeback`, `invoice_approval` | -| ref_table | text | нет | таблица с данными задачи (для `invoice_approval` - `acc_invoices`) | +| kind | text | нет | вид задачи: `invoice`, `categorization`, `certificate`, `discrepancy`, `receipt_search`, `chargeback`, `invoice_approval` | +| ref_table | text | нет | таблица с данными задачи (для `invoice_approval` - `acc_invoices`, для `chargeback` - `acc_chargeback`) | | ref_id | text | нет | ключ строки в `ref_table` | | assignee_role | text | нет | кому: `accountant` (Юля) или `cfo` (Анастасия); значения сверяются с `person.role_code` | | problem_highlight | text | да | копия проблемы из строки; пусто, если автомат уверен | diff --git a/packages/accounting_automation/src/certificates-ingest.ts b/packages/accounting_automation/src/certificates-ingest.ts new file mode 100644 index 0000000..f9ce280 --- /dev/null +++ b/packages/accounting_automation/src/certificates-ingest.ts @@ -0,0 +1,75 @@ +import type { Pool } from "khb_common"; +import { normalizeVendorName } from "./vendor-name.js"; + +/** + * Процесс «Страховые сертификаты подрядчиков», шаг 2: сертификат из письма -> acc_insurance_certificates. + * Если срок или вендор не распознаны, записи сертификата не создаётся: в acc_certificates_review попадает строка «tbd» + * с файлом (дальше человек заполняет expires_on, процесс «Завершение ручного разбора» создаёт сертификат). + */ + +export interface CertificateInput { + /** Детерминированный uuid (письмо + номер вложения + имя файла): повторный запуск не плодит дубли. */ + id: string; + messageId: string; + driveFileId: string; + vendorName: string | null; + vendorQboId: string | null; + insurer: string | null; + validUntil: string | null; + now: Date; +} + +const driveUrl = (id: string): string => `https://drive.google.com/file/d/${id}/view`; +const todayOf = (d: Date): string => d.toISOString().slice(0, 10); + +/** + * Автоматическая правка строки acc_certificates_review: пишется и в _original, чтобы в истории правок + * (changed_fields) оставались только изменения человека. + */ +export async function autoUpdateCertificateReview(pool: Pick, id: string, sets: Record): Promise { + const keys = Object.keys(sets); + if (keys.length === 0) return; + const clause = keys.map((k, i) => `${k} = $${i + 2}`).join(", "); + const vals = keys.map((k) => sets[k]); + await pool.query(`update acc_certificates_review set ${clause} where id = $1`, [id, ...vals]); + await pool.query(`update acc_certificates_review_original set ${clause} where id = $1`, [id, ...vals]); +} + +/** Незакрытые строки разбора сертификатов этого вендора (по QuickBooks id или нормализованному имени). */ +export async function openReviewsOfVendor(pool: Pick, vendorName: string | null, vendorQboId: string | null): Promise<{ id: string }[]> { + const { rows } = await pool.query<{ id: string; vendor_name: string; vendor_qbo_id: string | null }>( + "select id, vendor_name, vendor_qbo_id from acc_certificates_review where not done", + ); + const want = normalizeVendorName(vendorName); + return rows.filter((r) => (vendorQboId && r.vendor_qbo_id === vendorQboId) || (want && normalizeVendorName(r.vendor_name) === want)); +} + +export async function ingestCertificate(pool: Pool, c: CertificateInput): Promise<"saved" | "review"> { + if (c.vendorName && c.validUntil) { + await pool.query( + `insert into acc_insurance_certificates (id, vendor_name, vendor_qbo_id, insurer, valid_until, source_message_id, drive_file_id) + values ($1,$2,$3,$4,$5,$6,$7) on conflict (id) do nothing`, + [c.id, c.vendorName, c.vendorQboId, c.insurer, c.validUntil, c.messageId, c.driveFileId], + ); + // Пришёл новый сертификат: открытая строка разбора по вендору получает ссылку на него (шаг 5), закрывает её человек + const expired = c.validUntil < todayOf(c.now); + for (const r of await openReviewsOfVendor(pool, c.vendorName, c.vendorQboId)) { + await autoUpdateCertificateReview(pool, r.id, { + certificate_id: c.id, + expires_on: c.validUntil, + alert_kind: "new_certificate", + problem_highlight: expired + ? `Получен сертификат, но он уже просрочен (до ${c.validUntil}): запросите действующий. Файл: ${driveUrl(c.driveFileId)}` + : `Получен новый сертификат (действует до ${c.validUntil}): проверьте и отметьте выполненным. Файл: ${driveUrl(c.driveFileId)}`, + }); + } + return "saved"; + } + const tbd = [c.vendorName ? null : "vendor_name", c.validUntil ? null : "expires_on"].filter(Boolean).join(", "); + await pool.query( + `insert into acc_certificates_review (id, vendor_name, vendor_qbo_id, expires_on, problem_highlight, alert_kind, drive_file_id) + values ($1,$2,$3,$4,$5,'new_certificate',$6) on conflict (id) do nothing`, + [c.id, c.vendorName ?? "tbd", c.vendorQboId, c.validUntil, `tbd: ${tbd}. Страховой сертификат из письма, данные не распознаны: ${driveUrl(c.driveFileId)}`, c.driveFileId], + ); + return "review"; +} diff --git a/packages/accounting_automation/src/certificates.int.test.ts b/packages/accounting_automation/src/certificates.int.test.ts new file mode 100644 index 0000000..bb2f416 --- /dev/null +++ b/packages/accounting_automation/src/certificates.int.test.ts @@ -0,0 +1,252 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { createLogger, createTestDb, testDatabaseUrl, type TestDb } from "khb_common"; +import { alertFor, alertText, manualMessenger, runCertificates, type ContractorMessenger } from "./certificates.js"; +import type { ClaudeRunner } from "./claude-runner.js"; +import type { DriveStore } from "./drive.js"; +import type { MailMessage, MailSource } from "./gmail.js"; +import { parseRecognition, runInvoiceIngest } from "./invoices-mail.js"; +import { ReviewTools } from "./mcp.js"; + +const url = testDatabaseUrl(); +const d = url ? describe : describe.skip; +const log = createLogger("test", "silent"); + +describe("сроки сертификатов (чистые функции)", () => { + const cert = (validUntil: string) => ({ id: "c", validUntil }); + it("границы: 30 и 5 дней, просрочка, отсутствие", () => { + expect(alertFor(cert("2026-12-31"), "2026-11-01")).toBeNull(); + expect(alertFor(cert("2026-12-01"), "2026-11-01")).toEqual({ kind: "expiring_30", days: 30 }); + expect(alertFor(cert("2026-11-06"), "2026-11-01")).toEqual({ kind: "expiring_5", days: 5 }); + expect(alertFor(cert("2026-11-01"), "2026-11-01")).toEqual({ kind: "expiring_5", days: 0 }); + expect(alertFor(cert("2026-10-30"), "2026-11-01")).toEqual({ kind: "expired", days: -2 }); + expect(alertFor(null, "2026-11-01")).toEqual({ kind: "missing", days: null }); + }); + it("текст проблемы", () => { + expect(alertText("ACME", null, { kind: "missing", days: null })).toContain("нет страхового сертификата"); + expect(alertText("ACME", cert("2026-10-30"), { kind: "expired", days: -2 })).toContain("просрочен"); + }); + it("parseRecognition понимает document_type certificate", () => { + const r = parseRecognition('{"document_type":"certificate","vendor_name":"ACME","insurer":"Travelers","valid_until":"2027-01-15"}'); + expect(r).toMatchObject({ is_invoice: false, document_type: "certificate", insurer: "Travelers", valid_until: "2027-01-15" }); + // старый формат без document_type + expect(parseRecognition('{"is_invoice":true}')).toMatchObject({ is_invoice: true, document_type: "invoice" }); + expect(parseRecognition('{"is_invoice":false}')).toMatchObject({ document_type: "other" }); + // сертификат побеждает is_invoice + expect(parseRecognition('{"is_invoice":true,"document_type":"certificate"}')).toMatchObject({ is_invoice: false, document_type: "certificate" }); + }); +}); + +d("страховые сертификаты (временная БД)", () => { + let db: TestDb; + let tools: ReviewTools; + const accountant = "11111111-1111-1111-1111-111111111111"; + const NOW = new Date("2026-11-20T10:00:00Z"); + const at = (days: number): Date => new Date(NOW.getTime() + days * 86_400_000); + const iso = (days: number): string => at(days).toISOString().slice(0, 10); + + const mailOf = (id: string, ...names: string[]): MailMessage => ({ + id, from: "ins@vendor.com", subject: "COI", receivedAt: new Date("2026-11-19T12:00:00Z"), + attachments: names.map((n) => ({ filename: `${n}.pdf`, mime: "application/pdf", getBytes: async () => Buffer.from(n) })), + }); + let answers: Record; + let uploads: { name: string; folder: string[] }[]; + const claude: ClaudeRunner = async (o) => { + const { readFileSync } = await import("node:fs"); + const path = /(\S+invoice\.pdf)/.exec(o.prompt)![1]; + const a = answers[readFileSync(path, "utf8")]; + return a === undefined ? { ok: false, stdout: "", stderr: "boom", exitCode: 1, timedOut: false } : { ok: true, stdout: a, stderr: "", exitCode: 0, timedOut: false }; + }; + const drive = (): DriveStore => { + let last: string[] = []; + return { + ensureFolder: async (p) => { last = p; return p.join("/"); }, + upload: async (name) => { uploads.push({ name, folder: last }); return { id: `drv-${uploads.length}` }; }, + exportDocText: async () => "", + }; + }; + const ingest = (messages: MailMessage[]) => { + const mail: MailSource = { listUnprocessed: async () => messages }; + return runInvoiceIngest({ pool: db.pool, mail, drive: drive(), claude, now: () => NOW, log }); + }; + const addVendor = async (name: string, qbo: string | null, validUntil: string | null) => { + await db.pool.query("insert into acc_contracts (vendor_name, vendor_qbo_id, project_customer_id, total_amount) values ($1,$2,'C1',5000)", [name, qbo]); + if (validUntil) await db.pool.query("insert into acc_insurance_certificates (vendor_name, vendor_qbo_id, valid_until, drive_file_id) values ($1,$2,$3,'f')", [name, qbo, validUntil]); + }; + const reviews = async () => (await db.pool.query("select vendor_name, alert_kind, problem_highlight, request_count, to_char(expires_on,'YYYY-MM-DD') as expires_on from acc_certificates_review order by vendor_name")).rows; + const run = (over: Partial[0]> = {}) => runCertificates({ pool: db.pool, now: () => NOW, log, ...over }); + + beforeAll(async () => { + db = await createTestDb(url!); + tools = new ReviewTools({ pool: db.pool, settings: { reviewers: [{ personId: accountant, roles: ["accountant"] }] }, now: () => NOW }); + }); + afterAll(async () => { await db?.drop(); }); + beforeEach(async () => { + answers = {}; uploads = []; + await db.pool.query( + `truncate acc_mail_processed, acc_manual_review, acc_certificates_review, acc_certificates_review_original, acc_certificates_review_history, + acc_insurance_certificates, acc_invoices, acc_contracts, qbo_vendor, qbo_customer cascade`, + ); + }); + + it("письмо с сертификатом: Drive «Страховки», запись сертификата, инвойсом не считается", async () => { + answers.coi = JSON.stringify({ document_type: "certificate", vendor_name: "ACME Plumbing LLC", insurer: "Travelers", valid_until: "2027-01-15" }); + const r = await ingest([mailOf("m1", "coi")]); + expect(r).toEqual({ processed: 1, created: 0, skipped: 0, errors: 0, certificates: 1 }); + expect(uploads[0]!.folder).toEqual(["Страховки", "ACME Plumbing LLC", "2027-01"]); + const c = (await db.pool.query("select vendor_name, insurer, to_char(valid_until,'YYYY-MM-DD') as vu, source_message_id, drive_file_id from acc_insurance_certificates")).rows; + expect(c).toEqual([{ vendor_name: "ACME Plumbing LLC", insurer: "Travelers", vu: "2027-01-15", source_message_id: "m1", drive_file_id: "drv-1" }]); + expect((await db.pool.query("select result from acc_mail_processed")).rows).toEqual([{ result: "certificate" }]); + expect((await db.pool.query("select count(*)::int as n from acc_invoices_review")).rows[0].n).toBe(0); + // повторная обработка того же письма (например, после ошибки в другом вложении) не плодит дубль + await db.pool.query("delete from acc_mail_processed"); + await ingest([mailOf("m1", "coi")]); + expect((await db.pool.query("select count(*)::int as n from acc_insurance_certificates")).rows[0].n).toBe(1); + }); + + it("сертификат без срока: строка разбора с файлом и tbd; после заполнения срока итоговый сертификат берёт файл", async () => { + answers.coi2 = JSON.stringify({ document_type: "certificate", vendor_name: "ACME Plumbing LLC", insurer: "Travelers", valid_until: null }); + await ingest([mailOf("m2", "coi2")]); + expect((await db.pool.query("select count(*)::int as n from acc_insurance_certificates")).rows[0].n).toBe(0); + const row = (await db.pool.query("select id, drive_file_id, problem_highlight from acc_certificates_review")).rows[0]; + expect(row.drive_file_id).toBe("drv-1"); + expect(row.problem_highlight).toContain("tbd: expires_on"); + expect((await db.pool.query("select kind from acc_manual_review")).rows).toEqual([{ kind: "certificate" }]); + // задача в MCP показывает файл + const t = (await db.pool.query("select id from acc_manual_review")).rows[0].id as string; + const got = (await tools.get(accountant, { id: t })) as { file_url: string }; + expect(got.file_url).toContain("drv-1"); + }); + + it("новый сертификат обновляет открытую строку разбора вендора, не затрагивая original", async () => { + await addVendor("ACME Plumbing", null, iso(3)); // скоро истечёт + await run(); + expect(await reviews()).toMatchObject([{ vendor_name: "ACME Plumbing", alert_kind: "expiring_5" }]); + answers.coi3 = JSON.stringify({ document_type: "certificate", vendor_name: "ACME Plumbing LLC", insurer: "X", valid_until: iso(365) }); + await ingest([mailOf("m3", "coi3")]); + const r = (await db.pool.query("select alert_kind, problem_highlight, to_char(expires_on,'YYYY-MM-DD') as e, certificate_id from acc_certificates_review")).rows[0]; + expect(r.alert_kind).toBe("new_certificate"); + expect(r.problem_highlight).toContain("Получен новый сертификат"); + expect(r.e).toBe(iso(365)); + expect(r.certificate_id).toBeTruthy(); + const o = (await db.pool.query("select alert_kind from acc_certificates_review_original")).rows[0]; + expect(o.alert_kind).toBe("new_certificate"); // автоматическая правка отражена и в original: в истории только правки людей + }); + + it("ежедневная проверка: 30 дней, 5 дней, просрочка, нет сертификата; действующие не трогаются; повтор без дублей", async () => { + await addVendor("Thirty Co", null, iso(20)); + await addVendor("Five Co", "Q5", iso(4)); + await addVendor("Expired Co", null, iso(-3)); + await addVendor("None Co", null, null); + await addVendor("Fine Co", null, iso(200)); + const r1 = await run(); + expect(r1).toMatchObject({ vendorsChecked: 5, reviewsCreated: 4, requestsSent: 0 }); + const rows = await reviews(); + expect(rows.map((x) => [x.vendor_name, x.alert_kind])).toEqual([ + ["Expired Co", "expired"], ["Five Co", "expiring_5"], ["None Co", "missing"], ["Thirty Co", "expiring_30"], + ]); + expect(rows.find((x) => x.vendor_name === "None Co")!.problem_highlight).toContain("нет страхового сертификата"); + // триггеры: по задаче на каждую строку, роль accountant (Юля) + expect((await db.pool.query("select kind, assignee_role from acc_manual_review")).rows).toEqual(Array(4).fill({ kind: "certificate", assignee_role: "accountant" })); + const r2 = await run(); + expect(r2.reviewsCreated).toBe(0); + expect((await db.pool.query("select count(*)::int as n from acc_certificates_review")).rows[0].n).toBe(4); + }); + + it("строка с 30 днями при приближении срока усиливается до 5 дней (та же строка)", async () => { + await addVendor("Thirty Co", null, iso(20)); + await run(); + expect((await reviews())[0]!.alert_kind).toBe("expiring_30"); + const later = await run({ now: () => at(17) }); // осталось 3 дня + expect(later).toMatchObject({ reviewsCreated: 0, reviewsEscalated: 1 }); + expect(await reviews()).toMatchObject([{ alert_kind: "expiring_5" }]); + }); + + it("закрытая строка с тем же поводом не создаётся заново (просрочка - не чаще раза в 14 дней)", async () => { + await addVendor("Expired Co", null, iso(-3)); + await run(); + await db.pool.query( + `insert into acc_certificates_review_history (id, vendor_name, alert_kind, expires_on, closed_at) + select id, vendor_name, alert_kind, expires_on, $1 from acc_certificates_review`, [at(0)]); + await db.pool.query("delete from acc_certificates_review"); + expect((await run({ now: () => at(5) })).reviewsCreated).toBe(0); + expect((await run({ now: () => at(20) })).reviewsCreated).toBe(1); + }); + + it("запрос подрядчику: только после подтверждения Юли; повтор через 5 дней; не больше двух", async () => { + await addVendor("None Co", null, null); + const sent: { vendorName: string; body: string }[] = []; + const messenger: ContractorMessenger = { send: async (m) => { sent.push(m); return { delivered: true, channel: "jobtread", ref: "msg1" }; } }; + const loadTemplate = async () => "Dear {{vendor}}: certificate {{status}}, until {{valid_until}}"; + const opts = { messenger, loadTemplate }; + await run(opts); + expect(sent).toHaveLength(0); // нет подтверждения + const task = (await db.pool.query("select id from acc_manual_review")).rows[0].id as string; + const ok = await tools.call(accountant, "acc_certificate_request_approve", { id: task.slice(0, 8) }); + expect(ok.ok).toBe(true); + const r = await run(opts); + expect(r.requestsSent).toBe(1); + expect(sent[0]!.body).toBe("Dear None Co: certificate is missing from our records, until n/a"); + const row = (await db.pool.query("select request_count, request_sent_at, request_log, request_approved_by from acc_certificates_review")).rows[0]; + expect(row.request_count).toBe(1); + expect(row.request_approved_by).toBe(accountant); + expect(row.request_log).toMatchObject([{ delivered: true, channel: "jobtread", ref: "msg1" }]); + expect((await run({ ...opts, now: () => at(3) })).requestsSent).toBe(0); // рано + expect((await run({ ...opts, now: () => at(5) })).requestsSent).toBe(1); // повтор + expect((await run({ ...opts, now: () => at(11) })).requestsSent).toBe(0); // третьего нет + expect(sent).toHaveLength(2); + }); + + it("без отправщика в JobTread письмо готовится: журнал и пометка Юле «отправь вручную»", async () => { + await addVendor("None Co", null, null); + await run(); + const task = (await db.pool.query("select id from acc_manual_review")).rows[0].id as string; + await tools.call(accountant, "acc_certificate_request_approve", { id: task }); + const r = await run({ messenger: manualMessenger }); + expect(r).toMatchObject({ requestsSent: 0, requestsPrepared: 1 }); + const row = (await db.pool.query("select problem_highlight, request_log from acc_certificates_review")).rows[0]; + expect(row.problem_highlight).toContain("отправь вручную из JobTread"); + expect(row.request_log[0]).toMatchObject({ delivered: false, channel: "manual" }); + expect(row.request_log[0].text).toContain("None Co"); // встроенный шаблон + // повторная подтверждение не ломается + expect((await tools.call(accountant, "acc_certificate_request_approve", { id: task })).message).toContain("уже подтверждена"); + }); + + it("автоотправка включается настройкой; сбой отправщика не ломает остальное и не списывает попытку", async () => { + await addVendor("None Co", null, null); + let fail = true; + const messenger: ContractorMessenger = { send: async () => { if (fail) throw new Error("JobTread недоступен"); return { delivered: true, channel: "jobtread" }; } }; + expect(await run({ messenger, autoSend: true })).toMatchObject({ requestErrors: 1, requestsSent: 0 }); + expect((await reviews())[0]!.request_count).toBe(0); + fail = false; + expect(await run({ messenger, autoSend: true })).toMatchObject({ requestErrors: 0, requestsSent: 1 }); + }); + + it("отметка «нет страховки» в acc_invoices ставится и снимается", async () => { + await addVendor("Covered Co", "Q1", iso(100)); + await addVendor("Bare Co", null, null); + const ins = async (vendor: string, qbo: string | null, stage: string) => + (await db.pool.query( + `insert into acc_invoices (id, source_message_id, drive_file_id, vendor_name, vendor_qbo_id, invoice_date, amount, project_customer_id, stage) + values (gen_random_uuid(),'m','f',$1,$2,'2026-11-01',100,'C1',$3) returning id`, [vendor, qbo, stage])).rows[0].id as string; + const a = await ins("Covered Co", "Q1", "checking"); + const b = await ins("Bare Co", null, "checking"); + const paid = await ins("Bare Co", null, "paid"); + const r = await run(); + expect(r.flaggedNoInsurance).toBe(1); + const flags = async () => Object.fromEntries((await db.pool.query("select id, no_insurance from acc_invoices")).rows.map((x) => [x.id, x.no_insurance])); + expect(await flags()).toEqual({ [a]: false, [b]: true, [paid]: false }); + // вендор прислал сертификат -> отметка снимается + await db.pool.query("insert into acc_insurance_certificates (vendor_name, valid_until, drive_file_id) values ('Bare Co', $1, 'f')", [iso(50)]); + await run(); + expect((await flags())[b]).toBe(false); + // сертификат истёк -> отметка возвращается (согласование не блокируется, только флаг) + await run({ now: () => at(80) }); + expect((await flags())[b]).toBe(true); + }); + + it("подтверждение запроса доступно только роли accountant", async () => { + const t = new ReviewTools({ pool: db.pool, settings: { reviewers: [{ personId: "22222222-2222-2222-2222-222222222222", roles: ["cfo"] }] } }); + await expect(t.call("22222222-2222-2222-2222-222222222222", "acc_certificate_request_approve", { id: "abcdef12" })).rejects.toThrow(/Нужна роль accountant/); + await expect(t.call("33333333-3333-3333-3333-333333333333", "acc_certificate_request_approve", { id: "abcdef12" })).rejects.toThrow(/Доступ запрещён/); + }); +}); diff --git a/packages/accounting_automation/src/certificates.ts b/packages/accounting_automation/src/certificates.ts new file mode 100644 index 0000000..abe563e --- /dev/null +++ b/packages/accounting_automation/src/certificates.ts @@ -0,0 +1,270 @@ +import type { Logger, Pool } from "khb_common"; +import { autoUpdateCertificateReview } from "./certificates-ingest.js"; +import { normalizeVendorName } from "./vendor-name.js"; + +/** + * Процесс «Страховые сертификаты подрядчиков», шаги 3, 4 и 6 (задание `certificates`, раз в день): + * - сроки действующих вендоров: за 30 и за 5 дней до окончания, при просрочке и при отсутствии сертификата - строка acc_certificates_review + * (триггер БД сам создаёт задачу для accountant в acc_manual_review); + * - письмо-запрос подрядчику (после подтверждения Юли или сразу, если включена автоотправка), повтор через 5 дней; + * - отметка «нет страховки» в acc_invoices. + * Письма с сертификатами разбирает задание invoices-mail (certificates-ingest.ts). + */ + +export type AlertKind = "expiring_30" | "expiring_5" | "expired" | "missing"; +const RANK: Record = { new_certificate: 0, expiring_30: 1, expiring_5: 2, expired: 3, missing: 3 }; + +/** Отправка сообщения подрядчику (в боевом режиме - сообщение в JobTread). */ +export interface ContractorMessenger { + send(m: { vendorName: string; vendorQboId: string | null; subject: string; body: string }): Promise<{ delivered: boolean; channel: string; ref?: string }>; +} + +/** + * Пока в проекте нет клиента записи сообщений в JobTread (data_collector только читает), письмо готовится и сохраняется + * в журнале запросов строки разбора; Юля отправляет его вручную из JobTread. + */ +export const manualMessenger: ContractorMessenger = { + async send() { + return { delivered: false, channel: "manual" }; + }, +}; + +export const DEFAULT_TEMPLATE = [ + "Hello {{vendor}},", + "", + "Our records show that your certificate of insurance {{status}}.", + "Please send us an updated certificate of insurance (general liability and workers' compensation) as soon as possible,", + "so that we can keep processing your invoices without delay.", + "", + "Thank you,", + "KH Build", +].join("\n"); +export const CERTIFICATE_SUBJECT = "Certificate of insurance request"; + +export interface CertificatesDeps { + pool: Pool; + messenger?: ContractorMessenger; + now?: () => Date; + log?: Logger; + /** Текст шаблона запроса (Google Docs «Шаблон запроса сертификата»); null/ошибка - встроенный текст. */ + loadTemplate?: () => Promise; + /** Отправлять без подтверждения Юли (решение Анастасии; по умолчанию нет). */ + autoSend?: boolean; + /** Через сколько дней повторять запрос (по умолчанию 5) и сколько запросов максимум (по умолчанию 2: первый и один повтор). */ + repeatDays?: number; + maxRequests?: number; +} + +export interface CertificatesResult { + vendorsChecked: number; + reviewsCreated: number; + reviewsEscalated: number; + requestsSent: number; + requestsPrepared: number; + requestErrors: number; + flaggedNoInsurance: number; +} + +const DAY = 86_400_000; +const dayStr = (d: Date): string => d.toISOString().slice(0, 10); +const daysBetween = (fromIso: string, toIso: string): number => Math.round((Date.parse(`${toIso}T00:00:00Z`) - Date.parse(`${fromIso}T00:00:00Z`)) / DAY); + +interface Vendor { + key: string; + name: string; + qboId: string | null; +} + +/** Действующие вендоры: контракты с остатком и инвойсы в работе (не оплаченные и не отклонённые). */ +async function activeVendors(pool: Pool): Promise { + const { rows } = await pool.query<{ vendor_name: string; vendor_qbo_id: string | null }>( + `select vendor_name, vendor_qbo_id from acc_contracts where total_amount - retained_amount - paid_amount > 0 + union all + select vendor_name, vendor_qbo_id from acc_invoices where stage in ('checking', 'to_approve', 'approved', 'wait')`, + ); + const m = new Map(); + for (const r of rows) { + const key = normalizeVendorName(r.vendor_name); + if (!key) continue; + const ex = m.get(key); + if (!ex) m.set(key, { key, name: r.vendor_name, qboId: r.vendor_qbo_id }); + else if (!ex.qboId && r.vendor_qbo_id) ex.qboId = r.vendor_qbo_id; + } + return [...m.values()]; +} + +interface Latest { + id: string; + validUntil: string; +} + +/** Самый поздний срок по вендору: ищем и по QuickBooks id, и по нормализованному имени. */ +async function latestCertificates(pool: Pool): Promise<(v: { key: string; qboId: string | null }) => Latest | null> { + const { rows } = await pool.query<{ id: string; vendor_name: string; vendor_qbo_id: string | null; valid_until: string }>( + "select id, vendor_name, vendor_qbo_id, to_char(valid_until, 'YYYY-MM-DD') as valid_until from acc_insurance_certificates", + ); + const byKey = new Map(); + const byQbo = new Map(); + const put = (m: Map, k: string, l: Latest): void => { + const ex = m.get(k); + if (!ex || ex.validUntil < l.validUntil) m.set(k, l); + }; + for (const r of rows) { + const l = { id: r.id, validUntil: r.valid_until }; + put(byKey, normalizeVendorName(r.vendor_name), l); + if (r.vendor_qbo_id) put(byQbo, r.vendor_qbo_id, l); + } + return (v) => { + const a = byKey.get(v.key); + const b = v.qboId ? byQbo.get(v.qboId) : undefined; + if (a && b) return a.validUntil >= b.validUntil ? a : b; + return a ?? b ?? null; + }; +} + +export function alertFor(latest: Latest | null, today: string): { kind: AlertKind; days: number | null } | null { + if (!latest) return { kind: "missing", days: null }; + const d = daysBetween(today, latest.validUntil); + if (d < 0) return { kind: "expired", days: d }; + if (d <= 5) return { kind: "expiring_5", days: d }; + if (d <= 30) return { kind: "expiring_30", days: d }; + return null; +} + +export function alertText(vendor: string, latest: Latest | null, a: { kind: AlertKind; days: number | null }): string { + if (a.kind === "missing") return `У вендора ${vendor} нет страхового сертификата`; + if (a.kind === "expired") return `У вендора ${vendor} сертификат просрочен: действовал до ${latest!.validUntil} (${-a.days!} дн. назад)`; + return `У вендора ${vendor} сертификат истекает ${latest!.validUntil} (через ${a.days} дн.)`; +} + +async function ensureReviews(deps: CertificatesDeps, today: string, now: Date, res: CertificatesResult): Promise { + const { pool } = deps; + const vendors = await activeVendors(pool); + const latestOf = await latestCertificates(pool); + const open = (await pool.query<{ id: string; vendor_name: string; vendor_qbo_id: string | null; alert_kind: string | null }>( + "select id, vendor_name, vendor_qbo_id, alert_kind from acc_certificates_review where not done", + )).rows; + const hist = (await pool.query<{ vendor_name: string; alert_kind: string | null; expires_on: string | null; closed_at: Date }>( + "select vendor_name, alert_kind, to_char(expires_on, 'YYYY-MM-DD') as expires_on, closed_at from acc_certificates_review_history", + )).rows; + res.vendorsChecked = vendors.length; + + for (const v of vendors) { + const latest = latestOf(v); + const a = alertFor(latest, today); + if (!a) continue; + const text = alertText(v.name, latest, a); + const mine = open.filter((r) => (v.qboId && r.vendor_qbo_id === v.qboId) || normalizeVendorName(r.vendor_name) === v.key); + if (mine.length > 0) { + // строка уже ждёт человека: усиливаем срочность, не затирая ничего другого + for (const r of mine) { + if ((RANK[r.alert_kind ?? ""] ?? 0) < RANK[a.kind]! && r.alert_kind !== "new_certificate") { + await autoUpdateCertificateReview(pool, r.id, { alert_kind: a.kind, problem_highlight: text, expires_on: latest?.validUntil ?? null }); + res.reviewsEscalated++; + } + } + continue; + } + // закрытую строку с тем же поводом не создаём заново: для истёкших и «нет сертификата» - 14 дней паузы + const sameBefore = hist.filter((h) => normalizeVendorName(h.vendor_name) === v.key && h.alert_kind === a.kind && (h.expires_on ?? null) === (latest?.validUntil ?? null)); + const recent = sameBefore.some((h) => now.getTime() - new Date(h.closed_at).getTime() < 14 * DAY); + if (a.kind === "expired" || a.kind === "missing" ? recent : sameBefore.length > 0) continue; + await pool.query( + `insert into acc_certificates_review (vendor_name, vendor_qbo_id, certificate_id, expires_on, problem_highlight, alert_kind) + values ($1,$2,$3,$4,$5,$6)`, + [v.name, v.qboId, latest?.id ?? null, latest?.validUntil ?? null, text, a.kind], + ); + res.reviewsCreated++; + } +} + +function compose(template: string, vendor: string, latest: Latest | null, today: string): string { + const status = !latest ? "is missing from our records" : latest.validUntil < today ? `expired on ${latest.validUntil}` : `expires on ${latest.validUntil}`; + return template.replace(/\{\{\s*vendor\s*\}\}/g, vendor).replace(/\{\{\s*valid_until\s*\}\}/g, latest?.validUntil ?? "n/a").replace(/\{\{\s*status\s*\}\}/g, status); +} + +type LogEntry = { at: string; delivered: boolean; channel: string; subject: string; text: string; ref?: string }; + +async function sendRequests(deps: CertificatesDeps, today: string, now: Date, res: CertificatesResult): Promise { + const { pool } = deps; + const messenger = deps.messenger ?? manualMessenger; + const repeatMs = (deps.repeatDays ?? 5) * DAY; + const maxRequests = deps.maxRequests ?? 2; + let template: string | null = null; + try { + template = (await deps.loadTemplate?.()) ?? null; + } catch (e) { + deps.log?.warn({ err: String(e) }, "шаблон запроса сертификата недоступен, используется встроенный"); + } + const tpl = template && template.trim() ? template : DEFAULT_TEMPLATE; + const latestOf = await latestCertificates(pool); + + const { rows } = await pool.query<{ + id: string; vendor_name: string; vendor_qbo_id: string | null; alert_kind: string | null; request_count: number; + request_sent_at: Date | null; request_approved_at: Date | null; request_log: LogEntry[] | null; problem_highlight: string | null; + }>( + `select id, vendor_name, vendor_qbo_id, alert_kind, request_count, request_sent_at, request_approved_at, request_log, problem_highlight + from acc_certificates_review where not done and alert_kind in ('expiring_30', 'expiring_5', 'expired', 'missing') order by created_at`, + ); + for (const r of rows) { + if (!r.request_approved_at && !deps.autoSend) continue; + const first = r.request_count === 0; + if (!first && (r.request_count >= maxRequests || !r.request_sent_at || now.getTime() - new Date(r.request_sent_at).getTime() < repeatMs)) continue; + const latest = latestOf({ key: normalizeVendorName(r.vendor_name), qboId: r.vendor_qbo_id }); + if (latest && latest.validUntil >= today && daysBetween(today, latest.validUntil) > 30) continue; // сертификат уже обновили + const body = compose(tpl, r.vendor_name, latest, today); + try { + const out = await messenger.send({ vendorName: r.vendor_name, vendorQboId: r.vendor_qbo_id, subject: CERTIFICATE_SUBJECT, body }); + const entry: LogEntry = { at: now.toISOString(), delivered: out.delivered, channel: out.channel, subject: CERTIFICATE_SUBJECT, text: body, ...(out.ref ? { ref: out.ref } : {}) }; + const log = [...(r.request_log ?? []), entry]; + await pool.query( + "update acc_certificates_review set request_sent_at = $2, request_count = request_count + 1, request_log = $3::jsonb where id = $1", + [r.id, now, JSON.stringify(log)], + ); + if (out.delivered) res.requestsSent++; + else { + res.requestsPrepared++; + const note = `Запрос подрядчику подготовлен, отправь вручную из JobTread (текст в request_log строки; запрос № ${r.request_count + 1})`; + await pool.query("update acc_certificates_review set problem_highlight = $2 where id = $1", [r.id, r.problem_highlight ? `${r.problem_highlight} | ${note}` : note]); + } + } catch (e) { + res.requestErrors++; + deps.log?.error({ err: String(e), id: r.id }, "не удалось отправить запрос сертификата"); + } + } +} + +/** Шаг 6: отметка «нет страховки» у не оплаченных инвойсов вендоров без действующего сертификата. */ +export async function refreshInsuranceFlags(pool: Pool, today: string): Promise { + const { rows: certs } = await pool.query<{ vendor_name: string; vendor_qbo_id: string | null }>( + "select vendor_name, vendor_qbo_id from acc_insurance_certificates where valid_until >= $1::date", + [today], + ); + const okKeys = new Set(certs.map((c) => normalizeVendorName(c.vendor_name))); + const okQbo = new Set(certs.map((c) => c.vendor_qbo_id).filter((x): x is string => !!x)); + const { rows: inv } = await pool.query<{ id: string; vendor_name: string; vendor_qbo_id: string | null; no_insurance: boolean }>( + "select id, vendor_name, vendor_qbo_id, no_insurance from acc_invoices where stage <> 'paid'", + ); + const flip: { id: string; v: boolean }[] = []; + for (const i of inv) { + const has = (i.vendor_qbo_id && okQbo.has(i.vendor_qbo_id)) || okKeys.has(normalizeVendorName(i.vendor_name)); + if (i.no_insurance === !!has) flip.push({ id: i.id, v: !has }); + } + if (flip.length) { + await pool.query("update acc_invoices a set no_insurance = f.v from (select unnest($1::uuid[]) as id, unnest($2::boolean[]) as v) f where a.id = f.id", [ + flip.map((f) => f.id), + flip.map((f) => f.v), + ]); + } + return flip.filter((f) => f.v).length; +} + +export async function runCertificates(deps: CertificatesDeps): Promise { + const now = (deps.now ?? (() => new Date()))(); + const today = dayStr(now); + const res: CertificatesResult = { vendorsChecked: 0, reviewsCreated: 0, reviewsEscalated: 0, requestsSent: 0, requestsPrepared: 0, requestErrors: 0, flaggedNoInsurance: 0 }; + await ensureReviews(deps, today, now, res); + await sendRequests(deps, today, now, res); + res.flaggedNoInsurance = await refreshInsuranceFlags(deps.pool, today); + return res; +} diff --git a/packages/accounting_automation/src/chargeback-http.ts b/packages/accounting_automation/src/chargeback-http.ts new file mode 100644 index 0000000..0535862 --- /dev/null +++ b/packages/accounting_automation/src/chargeback-http.ts @@ -0,0 +1,37 @@ +import type { FastifyInstance, FastifyReply } from "fastify"; +import type { Pool } from "khb_common"; +import { addDailyLog, ChargebackError, closeChargebackByManager, createFraud, findChargebacks, setFraudStatus, startChargeback } from "./chargeback.js"; + +type Json = Record; + +/** + * Ручки под токеном сервиса (общий хук buildApi) для ассистента менеджера и служебных вызовов: + * контракт - docs/proposed/modules/quickbooks_bookkeeper/p-chargeback-manager-assistant.md. + * Все тела - JSON-объекты; ошибки: {error, message}. + */ +export function registerChargebackRoutes(app: FastifyInstance, deps: { pool: Pool }): void { + const body = (req: { body: unknown }): Json => (req.body && typeof req.body === "object" && !Array.isArray(req.body) ? (req.body as Json) : {}); + const run = async (reply: FastifyReply, fn: () => Promise): Promise => { + try { + return await fn(); + } catch (e) { + if (e instanceof ChargebackError) return reply.code(e.status).send({ error: e.code, message: e.message }); + throw e; + } + }; + + app.post("/chargeback/find", (req, reply) => run(reply, () => findChargebacks(deps.pool, body(req)))); + app.post("/chargeback/start", (req, reply) => run(reply, () => startChargeback(deps.pool, body(req)))); + app.post("/chargeback/close", (req, reply) => run(reply, () => closeChargebackByManager(deps.pool, body(req)))); + app.post("/chargeback/add-log", (req, reply) => run(reply, () => addDailyLog(deps.pool, body(req)))); + + // fraud по карте (процесс «Подозрительные операции по карте (fraud)»): created_by - person id того, кто сообщил + app.post("/chargeback/fraud", (req, reply) => + run(reply, () => { + const b = body(req); + if (typeof b.created_by !== "string") throw new ChargebackError(400, "bad_request", "created_by: нужен person id"); + return createFraud(deps.pool, b.created_by, b); + }), + ); + app.post("/chargeback/fraud/status", (req, reply) => run(reply, () => setFraudStatus(deps.pool, body(req)))); +} diff --git a/packages/accounting_automation/src/chargeback.int.test.ts b/packages/accounting_automation/src/chargeback.int.test.ts new file mode 100644 index 0000000..0292280 --- /dev/null +++ b/packages/accounting_automation/src/chargeback.int.test.ts @@ -0,0 +1,294 @@ +import type { FastifyInstance } from "fastify"; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { createTestDb, testDatabaseUrl, type TestDb } from "khb_common"; +import { buildApi } from "./http-api.js"; +import { ReviewTools } from "./mcp.js"; +import { runFraudWeekly } from "./chargeback.js"; +import { STAGE2_TOOLS } from "./stage2-tool-defs.js"; + +const url = testDatabaseUrl(); +const d = url ? describe : describe.skip; + +d("chargeback и fraud (временная БД)", () => { + let db: TestDb; + let app: FastifyInstance; + let tools: ReviewTools; + let manager: string, yulia: string, anastasia: string; + const NOW = new Date("2026-11-23T12:00:00Z"); + const auth = { authorization: "Bearer svc-token" }; + let contractA: string; + let contractOther: string; + + const post = async (path: string, payload: Record) => { + const r = await app.inject({ method: "POST", url: path, headers: auth, payload }); + return { status: r.statusCode, body: r.json() as Record }; + }; + const call = (who: string, name: string, args: Record = {}) => tools.call(who, name, args); + const errOf = async (p: Promise): Promise => { + try { await p; } catch (e) { return (e as Error).message; } + return "NO ERROR"; + }; + const start = (over: Record = {}) => + post("/chargeback/start", { daily_log_id: "DL1", daily_log_url: "https://app.jobtread.com/dl/1", job_id: "J1", vendor_name: "Window Co LLC", description: "окна протекают", reported_by: manager, ...over }); + const task = async (cbId: string) => (await db.pool.query("select id, kind, assignee_role, problem_highlight from acc_manual_review where ref_id = $1", [cbId])).rows[0]; + const contract = async (id = contractA) => (await db.pool.query("select retained_amount::float8 as r, paid_amount::float8 as p, total_amount::float8 as t from acc_contracts where id = $1", [id])).rows[0]; + const invoice = async (amount: number, project = "C1") => + (await db.pool.query( + `insert into acc_invoices (id, source_message_id, drive_file_id, vendor_name, invoice_date, amount, project_customer_id) + values (gen_random_uuid(),'m','f','Fix Co','2026-11-10',$1,$2) returning id`, [amount, project])).rows[0].id as string; + + beforeAll(async () => { + db = await createTestDb(url!); + const mk = async (name: string) => (await db.pool.query("insert into person (display_name) values ($1) returning id", [name])).rows[0].id as string; + manager = await mk("Менеджер"); yulia = await mk("Юля"); anastasia = await mk("Анастасия"); + const settings = { + http: { host: "127.0.0.1", port: 0, token: "svc-token" }, + reviewers: [{ personId: yulia, roles: ["accountant" as const] }, { personId: anastasia, roles: ["accountant" as const, "cfo" as const] }], + mcp: { enabled: false, staticTokens: [] }, + }; + app = buildApi({ pool: db.pool, settings, jobs: { "invoices-mail": async () => 1, finalize: async () => 1, categorize: async () => 1, summary: async () => 1 } }); + tools = new ReviewTools({ pool: db.pool, settings, now: () => NOW }); + }); + afterAll(async () => { await app?.close(); await db?.drop(); }); + beforeEach(async () => { + await db.pool.query("truncate acc_chargeback, acc_manual_review, acc_invoices, acc_contracts, acc_categorization_review, acc_categorization_review_original, acc_categorization_review_history, acc_receipts cascade"); + contractA = (await db.pool.query( + "insert into acc_contracts (vendor_name, vendor_qbo_id, project_customer_id, jt_job_id, total_amount, paid_amount) values ('Window Co','V1','C1','J1',10000,2000) returning id")).rows[0].id; + contractOther = (await db.pool.query( + "insert into acc_contracts (vendor_name, project_customer_id, jt_job_id, total_amount) values ('Roof Co','C1','J1',5000) returning id")).rows[0].id; + }); + + describe("ручки для ассистента менеджера", () => { + it("закрыты токеном сервиса", async () => { + for (const p of ["/chargeback/find", "/chargeback/start", "/chargeback/close", "/chargeback/add-log"]) { + expect((await app.inject({ method: "POST", url: p, payload: {} })).statusCode).toBe(401); + } + }); + + it("start: строка claimed, контракт найден по проекту JobTread и подрядчику, задача cfo; повтор по daily_log_id не плодит дубль", async () => { + const r = await start(); + expect(r.status).toBe(200); + expect(r.body.result).toBe("created"); + const cb = r.body.chargeback; + expect(cb).toMatchObject({ kind: "contract", status: "claimed", contract_id: contractA, defect_daily_log_id: "DL1", defect_description: "окна протекают", reported_by: manager, contract_vendor_name: "Window Co", contract_remaining: 8000 }); + expect(await task(cb.id)).toMatchObject({ kind: "chargeback", assignee_role: "cfo" }); + expect((await task(cb.id)).problem_highlight).toContain("окна протекают"); + const again = await start({ description: "другое описание" }); + expect(again.body).toMatchObject({ result: "existing", chargeback: { id: cb.id, defect_description: "окна протекают" } }); + expect((await db.pool.query("select count(*)::int as n from acc_chargeback")).rows[0].n).toBe(1); + expect((await db.pool.query("select count(*)::int as n from acc_manual_review")).rows[0].n).toBe(1); + }); + + it("start: нет подходящего контракта - кандидаты; с contract_id создаётся; чужой контракт и неверные данные - 4xx", async () => { + const r = await start({ vendor_name: "Plumbing Inc" }); + expect(r.body.result).toBe("candidates"); + expect(r.body.candidates.map((c: any) => c.vendor_name).sort()).toEqual(["Roof Co", "Window Co"]); + expect((await db.pool.query("select count(*)::int as n from acc_chargeback")).rows[0].n).toBe(0); + const ok = await start({ vendor_name: "Plumbing Inc", contract_id: contractOther }); + expect(ok.body).toMatchObject({ result: "created", chargeback: { contract_id: contractOther } }); + // неоднозначность: два контракта подрядчика на проекте + await db.pool.query("insert into acc_contracts (vendor_name, project_customer_id, jt_job_id, total_amount, stage) values ('Roof Co','C1','J1',100,'phase 2')"); + const amb = await start({ daily_log_id: "DL2", vendor_name: "Roof Co" }); + expect(amb.body.result).toBe("candidates"); + expect(amb.body.candidates).toHaveLength(2); + expect((await start({ daily_log_id: "" })).status).toBe(400); + expect((await start({ daily_log_id: "DL3", contract_id: "00000000-0000-0000-0000-000000000000" })).status).toBe(404); + expect((await start({ daily_log_id: "DL4", reported_by: "00000000-0000-0000-0000-000000000000" })).status).toBe(400); + expect((await start({ daily_log_id: "DL5", reported_by: "не uuid" })).status).toBe(400); + }); + + it("close: строка closed с причиной «менеджер закрыл вопрос», задачи нет, повтор идемпотентен", async () => { + const r = await post("/chargeback/close", { daily_log_id: "DL1", daily_log_url: "u", job_id: "J1", vendor_name: "Window Co", description: "x", reported_by: manager }); + expect(r.body).toMatchObject({ result: "created", chargeback: { status: "closed", close_reason: "менеджер закрыл вопрос", kind: "contract" } }); + expect(await task(r.body.chargeback.id)).toBeUndefined(); + const again = await post("/chargeback/close", { daily_log_id: "DL1", job_id: "J1", vendor_name: "Window Co" }); + expect(again.body.result).toBe("existing"); + // а start по закрытому дефекту ничего не создаёт и не открывает заново + const s = await start(); + expect(s.body).toMatchObject({ result: "existing", chargeback: { status: "closed" } }); + expect((await db.pool.query("select count(*)::int as n from acc_manual_review")).rows[0].n).toBe(0); + }); + + it("find: по проекту и подрядчику, в том числе закрытые; add-log без дублей", async () => { + expect((await post("/chargeback/find", { job_id: "J1", vendor_name: "Window Co" })).body.rows).toEqual([]); + const cb = (await start()).body.chargeback; + const closed = (await post("/chargeback/close", { daily_log_id: "DL2", job_id: "J1", vendor_name: "Roof Co" })).body.chargeback; + const win = (await post("/chargeback/find", { job_id: "J1", vendor_name: "window co llc" })).body.rows; + expect(win.map((x: any) => x.id)).toEqual([cb.id]); + expect((await post("/chargeback/find", { job_id: "J1" })).body.rows).toHaveLength(2); + expect((await post("/chargeback/find", { job_id: "J1", vendor_name: "Roof Co" })).body.rows[0]).toMatchObject({ id: closed.id, status: "closed" }); + expect((await post("/chargeback/find", { job_id: "J1", daily_log_id: "DL1" })).body.rows).toHaveLength(1); + expect((await post("/chargeback/find", { vendor_name: "x" })).status).toBe(400); + + const a1 = await post("/chargeback/add-log", { chargeback_id: cb.id, daily_log_url: "https://app.jobtread.com/dl/2" }); + expect(a1.body).toMatchObject({ added: true, chargeback: { extra_daily_logs: ["https://app.jobtread.com/dl/2"] } }); + const a2 = await post("/chargeback/add-log", { chargeback_id: cb.id, daily_log_url: "https://app.jobtread.com/dl/2" }); + expect(a2.body.added).toBe(false); + expect((await post("/chargeback/add-log", { chargeback_id: cb.id, daily_log_url: "https://app.jobtread.com/dl/1" })).body.added).toBe(false); // первый лог - не extra + expect((await post("/chargeback/add-log", { chargeback_id: "00000000-0000-0000-0000-000000000000", daily_log_url: "u" })).status).toBe(404); + }); + }); + + describe("решения Юли и Анастасии (MCP) и пересчёт контракта", () => { + it("полный путь: decide -> link_invoice -> confirm; удержание уменьшает остаток; закрытие при нулевом остатке", async () => { + const cb = (await start()).body.chargeback; + const id = cb.id as string; + // права: решает только cfo + expect(await errOf(call(yulia, "acc_chargeback_decide", { id, decision: "approve" }))).toContain("Нужна роль cfo"); + expect(await errOf(call(manager, "acc_chargeback_list"))).toContain("Доступ запрещён"); + // шаг 4 + const dec = await call(anastasia, "acc_chargeback_decide", { id: id.slice(0, 8), decision: "approve", fix_vendor_name: "Fix Co" }); + expect(dec.chargeback).toMatchObject({ status: "approved", decided_by: anastasia, fix_vendor_name: "Fix Co" }); + expect(await task(id)).toMatchObject({ assignee_role: "accountant" }); + expect(await errOf(call(anastasia, "acc_chargeback_decide", { id, decision: "reject" }))).toContain("уже принято"); + // шаг 6: инвойс подрядчика Б + const inv = await invoice(3000); + expect(await errOf(call(yulia, "acc_chargeback_link_invoice", { id, invoice_id: await invoice(1000, "C2") }))).toContain("другому проекту"); + expect(await errOf(call(yulia, "acc_chargeback_link_invoice", { id, invoice_id: inv, retained_amount: 3500 }))).toContain("больше суммы инвойса"); + expect(await errOf(call(yulia, "acc_chargeback_link_invoice", { id, invoice_id: "00000000-0000-0000-0000-000000000000" }))).toContain("не найден"); + const link = await call(yulia, "acc_chargeback_link_invoice", { id, invoice_id: inv }); + expect(link.chargeback).toMatchObject({ status: "fix_invoiced", fix_invoice_id: inv, retained_amount: 3000 }); + expect(await task(id)).toMatchObject({ assignee_role: "cfo" }); + expect((await contract()).r).toBe(0); // пока не подтверждено - контракт не уменьшен + // шаг 7-8 + expect(await errOf(call(yulia, "acc_chargeback_confirm", { id }))).toContain("Нужна роль cfo"); + const conf = await call(anastasia, "acc_chargeback_confirm", { id, retained_amount: 2800 }); + expect(conf.chargeback).toMatchObject({ status: "applied", retained_amount: 2800, confirmed_by: anastasia, contract_retained: 2800, contract_remaining: 5200 }); + expect(await contract()).toEqual({ r: 2800, p: 2000, t: 10000 }); + expect(await task(id)).toMatchObject({ assignee_role: "accountant" }); // сообщить подрядчику А в JobTread + // шаг 11: остаток по контракту + const bal = (await call(yulia, "acc_contract_balance", { vendor_name: "window" })) as any; + expect(bal.contracts[0]).toMatchObject({ total_amount: 10000, retained_amount: 2800, paid_amount: 2000, remaining: 5200 }); + // очередь показывает дело chargeback + const list = (await call(anastasia, "acc_review_list", { kind: "chargeback" })) as any; + expect(list.tasks).toHaveLength(1); + expect(list.tasks[0].review).toMatchObject({ id, status: "applied" }); + const got = (await call(yulia, "acc_review_get", { id: (await task(id)).id })) as any; + expect(got.review.status).toBe("applied"); + expect(got.original).toBeNull(); + expect(await errOf(call(yulia, "acc_review_done", { id: (await task(id)).id }))).toContain("acc_chargeback_"); + // шаг 12: остаток исчерпан платежами -> строка закрывается автоматически, удержание остаётся учтённым + await db.pool.query("update acc_contracts set paid_amount = 7200 where id = $1", [contractA]); + const after = (await db.pool.query("select status, close_reason from acc_chargeback where id = $1", [id])).rows[0]; + expect(after).toEqual({ status: "closed", close_reason: "остаток по контракту оплачен" }); + expect((await contract()).r).toBe(2800); + expect(await task(id)).toBeUndefined(); + }); + + it("отклонение закрывает строку и не меняет контракт; ручное закрытие только cfo", async () => { + const a = (await start()).body.chargeback.id as string; + const rej = await call(anastasia, "acc_chargeback_decide", { id: a, decision: "reject", comment: "гарантия истекла" }); + expect(rej.chargeback).toMatchObject({ status: "closed", close_reason: "отклонено: гарантия истекла", decided_by: anastasia }); + expect(await task(a)).toBeUndefined(); + expect((await contract()).r).toBe(0); + const b = (await start({ daily_log_id: "DL9" })).body.chargeback.id as string; + expect(await errOf(call(yulia, "acc_chargeback_close", { id: b, reason: "x" }))).toContain("Нужна роль cfo"); + const closed = await call(anastasia, "acc_chargeback_close", { id: b, reason: "решили иначе" }); + expect((closed.chargeback as any).status).toBe("closed"); + expect(await errOf(call(anastasia, "acc_chargeback_close", { id: b, reason: "x" }))).toContain("уже закрыта"); + }); + + it("несколько удержаний суммируются; статус вне applied не учитывается; ручная правка в Mathesar тоже пересчитывает", async () => { + const mk = async (log: string, amount: number, status: string) => + (await db.pool.query( + `insert into acc_chargeback (kind, status, contract_id, defect_daily_log_id, retained_amount, confirmed_at) + values ('contract', $1, $2, $3, $4, case when $1 in ('applied') then now() end) returning id`, [status, contractA, log, amount])).rows[0].id as string; + const x = await mk("L1", 1000, "applied"); + await mk("L2", 500, "applied"); + await mk("L3", 700, "fix_invoiced"); + expect((await contract()).r).toBe(1500); + await db.pool.query("update acc_chargeback set retained_amount = 1200 where id = $1", [x]); + expect((await contract()).r).toBe(1700); + await db.pool.query("delete from acc_chargeback where id = $1", [x]); + expect((await contract()).r).toBe(500); + }); + + it("acc_chargeback_list: фильтры и закрытые", async () => { + const a = (await start()).body.chargeback.id as string; + await post("/chargeback/close", { daily_log_id: "DL2", job_id: "J1", vendor_name: "Roof Co" }); + const open = (await call(yulia, "acc_chargeback_list")) as any; + expect(open.rows.map((r: any) => r.id)).toEqual([a]); + expect(((await call(yulia, "acc_chargeback_list", { include_closed: true })) as any).rows).toHaveLength(2); + expect(((await call(yulia, "acc_chargeback_list", { project_customer_id: "C9" })) as any).rows).toHaveLength(0); + expect(((await call(yulia, "acc_chargeback_list", { kind: "card_fraud" })) as any).rows).toHaveLength(0); + expect(await errOf(call(yulia, "acc_chargeback_list", { kind: "zzz" }))).toContain("kind"); + }); + + it("инструменты этапа 2 описаны и доступны через tools/list", async () => { + const names = STAGE2_TOOLS.map((t) => t.name); + expect(names).toEqual(expect.arrayContaining(["acc_chargeback_decide", "acc_chargeback_link_invoice", "acc_chargeback_confirm", "acc_fraud_create", "acc_certificate_request_approve"])); + const { TOOLS } = await import("./mcp.js"); + for (const n of names) expect(TOOLS.some((t) => t.name === n)).toBe(true); + }); + }); + + describe("fraud по карте", () => { + const addOp = async (feed: string) => + db.pool.query( + `insert into acc_categorization_review (feed_txn_id, run_id, run_started_at, suggestion, confidence, problem_highlight) + values ($1,'r',now(),'{"vendor":"Linode","amount":500}',60,'первая оплата вендору')`, [feed]); + + it("создаёт запись с комплектом: операция, чек или «чека нет»; повтор возвращает ту же; задача accountant", async () => { + await addOp("F1"); + const r = (await call(yulia, "acc_fraud_create", { feed_txn_id: "F1", reason: "чужое", bank: "Chase", file_by: "2026-11-30" })) as any; + expect(r.created).toBe(true); + expect(r.chargeback).toMatchObject({ kind: "card_fraud", status: "collecting", feed_txn_id: "F1", bank: "Chase", file_by: "2026-11-30", contract_id: null }); + expect(r.chargeback.kit.operation.suggestion).toMatchObject({ vendor: "Linode" }); + expect(r.chargeback.kit.receipt_note).toBe("чека нет"); + expect(await task(r.chargeback.id)).toMatchObject({ kind: "chargeback", assignee_role: "accountant" }); + const again = (await call(yulia, "acc_fraud_create", { feed_txn_id: "F1" })) as any; + expect(again).toMatchObject({ created: false, chargeback: { id: r.chargeback.id } }); + // с чеком + await db.pool.query("insert into acc_receipts (drive_file_id, vendor_name, amount, feed_txn_id) values ('rcpt1','Zoom',500,'F2')"); + const withReceipt = (await call(yulia, "acc_fraud_create", { feed_txn_id: "F2" })) as any; + expect(withReceipt.chargeback.kit.receipt.url).toContain("rcpt1"); + expect(withReceipt.chargeback.kit.receipt_note).toBeNull(); + // через HTTP тоже + const http = await post("/chargeback/fraud", { feed_txn_id: "F3", created_by: yulia }); + expect(http.body).toMatchObject({ created: true, chargeback: { kind: "card_fraud", status: "collecting" } }); + expect((await post("/chargeback/fraud", { feed_txn_id: "F4", created_by: "нет" })).status).toBe(400); + }); + + it("статусы: collecting -> filed -> refunded -> closed; недопустимые переходы отклоняются; closed убирает задачу", async () => { + const id = ((await call(yulia, "acc_fraud_create", { feed_txn_id: "F1" })) as any).chargeback.id as string; + expect(await errOf(call(yulia, "acc_fraud_update", { id, status: "refunded" }))).toContain("можно перейти в: filed, closed"); + const filed = (await call(yulia, "acc_fraud_update", { id, status: "filed", bank_decision: "заявка принята" })) as any; + expect(filed.chargeback).toMatchObject({ status: "filed", bank_decision: "заявка принята" }); + expect((await task(id)).problem_highlight).toContain("ждём решения банка"); + const ref = (await call(yulia, "acc_fraud_update", { id, status: "refunded", bank_decision: "возврат 500" })) as any; + expect(ref.chargeback.status).toBe("refunded"); + expect((await task(id)).problem_highlight).toContain("банк вернул деньги"); + await call(yulia, "acc_fraud_update", { id, status: "closed" }); + expect(await task(id)).toBeUndefined(); + expect(await errOf(call(yulia, "acc_fraud_update", { id, status: "filed" }))).toContain("строка закрыта"); + // для chargeback к контракту инструмент fraud не подходит + const cb = (await start()).body.chargeback.id as string; + expect(await errOf(call(yulia, "acc_fraud_update", { id: cb, status: "filed" }))).toContain("не fraud"); + }); + + it("после закрытия по той же операции можно завести новое дело", async () => { + const a = ((await call(yulia, "acc_fraud_create", { feed_txn_id: "F1" })) as any).chargeback.id as string; + await call(yulia, "acc_fraud_update", { id: a, status: "closed" }); + const b = (await call(yulia, "acc_fraud_create", { feed_txn_id: "F1" })) as any; + expect(b.created).toBe(true); + expect(b.chargeback.id).not.toBe(a); + }); + + it("недельное напоминание: незакрытые и сроки; без незакрытых ничего не шлёт", async () => { + const posted: string[] = []; + const slack = { post: async (_c: string, t: string) => { posted.push(t); } }; + expect(await runFraudWeekly({ pool: db.pool, slack, channelId: "C", now: () => NOW })).toEqual({ sent: false, count: 0 }); + const a = ((await call(yulia, "acc_fraud_create", { feed_txn_id: "F1", bank: "Chase", file_by: "2026-11-20" })) as any).chargeback.id as string; + await call(yulia, "acc_fraud_create", { feed_txn_id: "F2", file_by: "2026-11-27" }); + const c = ((await call(yulia, "acc_fraud_create", { feed_txn_id: "F3" })) as any).chargeback.id as string; + await call(yulia, "acc_fraud_update", { id: c, status: "closed" }); + const r = await runFraudWeekly({ pool: db.pool, slack, channelId: "C", now: () => NOW }); + expect(r).toEqual({ sent: true, count: 2 }); + expect(posted[0]).toContain("незакрытых случаев 2"); + expect(posted[0]).toContain("операция F1 (Chase): собираем комплект, срок подачи 2026-11-20 ПРОСРОЧЕН на 3 дн."); + expect(posted[0]).toContain("операция F2: собираем комплект, срок подачи 2026-11-27 (осталось 4 дн.)"); + expect(posted[0]).not.toContain("F3"); + void a; + }); + }); +}); diff --git a/packages/accounting_automation/src/chargeback.ts b/packages/accounting_automation/src/chargeback.ts new file mode 100644 index 0000000..cb0b27c --- /dev/null +++ b/packages/accounting_automation/src/chargeback.ts @@ -0,0 +1,438 @@ +import { withTx, type Pool } from "khb_common"; +import { normalizeVendorName } from "./vendor-name.js"; + +/** + * Серверная часть процессов «Chargeback к контракту подрядчика» и «Подозрительные операции по карте (fraud)»: + * строки acc_chargeback (kind contract | card_fraud) и их задачи в acc_manual_review (kind chargeback). + * Пересчёт acc_contracts.retained_amount и закрытие по остатку делают триггеры БД (миграция 062). + * Слой чистый: им пользуются HTTP-ручки ассистента менеджера и MCP-инструменты Юли и Анастасии. + */ + +type PoolClient = Parameters[1]>[0]; +type Row = Record; + +/** Ошибка запроса: status - HTTP-код ручки, message - по-русски (MCP показывает её пользователю). */ +export class ChargebackError extends Error { + constructor( + public readonly status: number, + public readonly code: string, + message: string, + ) { + super(message); + } +} + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const bad = (message: string): ChargebackError => new ChargebackError(400, "bad_request", message); + +function reqStr(v: unknown, name: string): string { + if (typeof v !== "string" || !v.trim()) throw bad(`${name}: нужна непустая строка`); + return v.trim(); +} +function optStr(v: unknown, name: string): string | null { + if (v === undefined || v === null || v === "") return null; + if (typeof v !== "string") throw bad(`${name}: ожидалась строка`); + return v.trim() || null; +} +function optUuid(v: unknown, name: string): string | null { + const s = optStr(v, name); + if (s !== null && !UUID.test(s)) throw bad(`${name}: ожидался uuid`); + return s; +} +function amountOf(v: unknown, name: string): number { + const n = typeof v === "string" && v.trim() !== "" ? Number(v) : v; + if (typeof n !== "number" || !Number.isFinite(n) || n <= 0 || n >= 1e12) throw bad(`${name}: ожидалось положительное число`); + return Math.round(n * 100) / 100; +} +function optDate(v: unknown, name: string): string | null { + const s = optStr(v, name); + if (s === null) return null; + if (!/^\d{4}-\d{2}-\d{2}$/.test(s) || new Date(`${s}T00:00:00Z`).toISOString().slice(0, 10) !== s) throw bad(`${name}: ожидалась дата YYYY-MM-DD`); + return s; +} + +const COLS = `c.id, c.kind, c.status, c.created_at, c.contract_id, c.defect_daily_log_id, c.defect_daily_log_url, c.defect_description, + c.extra_daily_logs, c.reported_by, c.decided_by, c.decided_at, c.fix_vendor_name, c.fix_invoice_id, c.retained_amount::float8 as retained_amount, + c.close_reason, c.confirmed_by, c.confirmed_at, c.feed_txn_id, c.reason, c.bank, to_char(c.file_by, 'YYYY-MM-DD') as file_by, c.bank_decision, c.kit, + k.vendor_name as contract_vendor_name, k.project_customer_id as contract_project_customer_id, k.jt_job_id as contract_jt_job_id, + k.total_amount::float8 as contract_total, k.retained_amount::float8 as contract_retained, k.paid_amount::float8 as contract_paid, + (k.total_amount - k.retained_amount - k.paid_amount)::float8 as contract_remaining`; +const FROM = "from acc_chargeback c left join acc_contracts k on k.id = c.contract_id"; + +async function load(c: Pick, id: string, lock = false): Promise { + const r = await c.query(`select ${COLS} ${FROM} where c.id = $1 ${lock ? "for update of c" : ""}`.trim(), [id]); + if (!r.rows[0]) throw new ChargebackError(404, "not_found", "Строка chargeback не найдена."); + return r.rows[0] as Row; +} + +/** id строки: полный uuid, 8+ символов id строки или id задачи из acc_review_list. */ +export async function resolveChargebackId(pool: Pick, v: unknown): Promise { + if (typeof v !== "string" || !v.trim()) throw bad("id: нужен id строки chargeback или задачи"); + const s = v.trim().toLowerCase(); + if (UUID.test(s)) { + const t = await pool.query("select ref_id from acc_manual_review where id = $1 and ref_table = 'acc_chargeback'", [s]); + return (t.rows[0]?.ref_id as string | undefined) ?? s; + } + if (!/^[0-9a-f]{8,}$/.test(s)) throw bad("id: первые 8 символов (или полный uuid) строки chargeback либо задачи"); + const rows = (await pool.query("select id::text as id from acc_chargeback where id::text like $1 limit 2", [`${s}%`])).rows; + const tasks = (await pool.query("select ref_id from acc_manual_review where ref_table = 'acc_chargeback' and id::text like $1 limit 2", [`${s}%`])).rows; + const all = new Set([...rows.map((r) => r.id as string), ...tasks.map((r) => r.ref_id as string)]); + if (all.size === 0) throw new ChargebackError(404, "not_found", "Строка chargeback не найдена."); + if (all.size > 1) throw bad("Префикс id неоднозначен: укажите больше символов."); + return [...all][0]!; +} + +// ----------------------------------------------------------------- задачи в очереди + +function taskSpec(r: Row): { role: "accountant" | "cfo"; problem: string } | null { + const vendor = String(r.contract_vendor_name ?? "?"); + const money = (n: unknown): string => (typeof n === "number" ? n.toFixed(2) : "?"); + if (r.kind === "contract") { + switch (r.status) { + case "claimed": + return { role: "cfo", problem: `Chargeback: решить, удерживать ли с подрядчика ${vendor} стоимость исправления дефекта (${String(r.defect_description ?? "без описания")}). Daily Log ${String(r.defect_daily_log_url ?? "?")}. Остаток по контракту ${money(r.contract_remaining)}` }; + case "approved": + return { role: "accountant", problem: `Chargeback одобрен (дефект исправляет ${String(r.fix_vendor_name ?? "другой подрядчик")}): дождаться его инвойса и привязать (acc_chargeback_link_invoice) с суммой удержания с ${vendor}` }; + case "fix_invoiced": + return { role: "cfo", problem: `Chargeback: подтвердить сумму удержания ${money(r.retained_amount)} с подрядчика ${vendor} (acc_chargeback_confirm)` }; + case "applied": + return { role: "accountant", problem: `Удержание ${money(r.retained_amount)} с подрядчика ${vendor} применено: сообщить ему в JobTread (сумма, основание, новый остаток ${money(r.contract_remaining)})` }; + default: + return null; + } + } + const deadline = r.file_by ? `, срок подачи ${String(r.file_by)}` : ""; + switch (r.status) { + case "collecting": + return { role: "accountant", problem: `Fraud по операции ${String(r.feed_txn_id)}: собрать комплект и подать заявку в банк${deadline}` }; + case "filed": + return { role: "accountant", problem: `Fraud по операции ${String(r.feed_txn_id)}: ждём решения банка` }; + case "refunded": + return { role: "accountant", problem: `Fraud по операции ${String(r.feed_txn_id)}: банк вернул деньги, проверить возврат в ленте QuickBooks и закрыть` }; + case "rejected": + return { role: "accountant", problem: `Fraud по операции ${String(r.feed_txn_id)}: банк отказал (${String(r.bank_decision ?? "причина не записана")}); закрыть или подать повторно` }; + default: + return null; + } +} + +/** Приводит задачу acc_manual_review к статусу строки; для закрытых задачу убирает. */ +export async function syncTask(c: Pick, id: string): Promise { + const r = await load(c, id); + const spec = taskSpec(r); + if (!spec) { + await c.query("delete from acc_manual_review where ref_table = 'acc_chargeback' and ref_id = $1", [id]); + return; + } + await c.query( + `insert into acc_manual_review (kind, ref_table, ref_id, assignee_role, problem_highlight) values ('chargeback', 'acc_chargeback', $1, $2, $3) + on conflict (ref_table, ref_id) do update set assignee_role = excluded.assignee_role, problem_highlight = excluded.problem_highlight, snoozed_until = null`, + [id, spec.role, spec.problem], + ); +} + +// ----------------------------------------------------------------- контракт chargeback (ручки ассистента менеджера) + +export interface ContractCandidate { + id: string; + vendor_name: string; + project_customer_id: string; + jt_job_id: string | null; + stage: string | null; + total_amount: number; + paid_amount: number; + retained_amount: number; + remaining: number; +} + +const CONTRACT_COLS = `id, vendor_name, project_customer_id, jt_job_id, stage, total_amount::float8 as total_amount, paid_amount::float8 as paid_amount, + retained_amount::float8 as retained_amount, (total_amount - retained_amount - paid_amount)::float8 as remaining`; + +async function findContracts(pool: Pick, jobId: string, vendorName: string): Promise<{ matched: ContractCandidate[]; all: ContractCandidate[] }> { + const { rows } = await pool.query(`select ${CONTRACT_COLS} from acc_contracts where jt_job_id = $1 order by vendor_name, stage`, [jobId]); + const want = normalizeVendorName(vendorName); + return { matched: rows.filter((k) => normalizeVendorName(k.vendor_name) === want), all: rows }; +} + +/** Строки chargeback вида contract по проекту JobTread и подрядчику, в том числе закрытые. */ +export async function findChargebacks(pool: Pool, a: Row): Promise<{ rows: Row[] }> { + const jobId = reqStr(a.job_id, "job_id"); + const vendor = optStr(a.vendor_name, "vendor_name"); + const dl = optStr(a.daily_log_id, "daily_log_id"); + const { rows } = await pool.query(`select ${COLS} ${FROM} where c.kind = 'contract' and k.jt_job_id = $1 order by c.created_at`, [jobId]); + const want = vendor ? normalizeVendorName(vendor) : null; + return { rows: (rows as Row[]).filter((r) => (!want || normalizeVendorName(String(r.contract_vendor_name)) === want) && (!dl || r.defect_daily_log_id === dl)) }; +} + +export type StartResult = + | { result: "created" | "existing"; chargeback: Row } + | { result: "candidates"; message: string; candidates: ContractCandidate[] }; + +async function createContractRow(pool: Pool, a: Row, closed: boolean): Promise { + const dailyLogId = reqStr(a.daily_log_id, "daily_log_id"); + const dailyLogUrl = optStr(a.daily_log_url, "daily_log_url"); + const description = optStr(a.description, "description"); + const reportedBy = optUuid(a.reported_by, "reported_by"); + let contractId = optUuid(a.contract_id, "contract_id"); + + const exist = await pool.query("select id from acc_chargeback where defect_daily_log_id = $1", [dailyLogId]); + if (exist.rows[0]) return { result: "existing", chargeback: await load(pool, exist.rows[0].id as string) }; + + if (contractId) { + const k = await pool.query("select id from acc_contracts where id = $1", [contractId]); + if (!k.rows[0]) throw new ChargebackError(404, "contract_not_found", "Контракт не найден."); + } else { + const jobId = reqStr(a.job_id, "job_id"); + const vendor = reqStr(a.vendor_name, "vendor_name"); + const { matched, all } = await findContracts(pool, jobId, vendor); + if (matched.length !== 1) { + return { + result: "candidates", + message: matched.length === 0 ? "Контракт подрядчика на этом проекте не найден: уточните у менеджера и вызовите снова с contract_id." : "Подходящих контрактов несколько: уточните у менеджера и вызовите снова с contract_id.", + candidates: matched.length ? matched : all, + }; + } + contractId = matched[0]!.id; + } + if (reportedBy) { + const p = await pool.query("select 1 from person where id = $1", [reportedBy]); + if (!p.rows[0]) throw bad("reported_by: такого person нет"); + } + const id = await withTx(pool, async (c) => { + const ins = await c.query( + `insert into acc_chargeback (kind, status, contract_id, defect_daily_log_id, defect_daily_log_url, defect_description, reported_by, close_reason) + values ('contract', $1, $2, $3, $4, $5, $6, $7) on conflict (defect_daily_log_id) where defect_daily_log_id is not null do nothing returning id`, + [closed ? "closed" : "claimed", contractId, dailyLogId, dailyLogUrl, description, reportedBy, closed ? "менеджер закрыл вопрос" : null], + ); + if (!ins.rows[0]) return null; + const newId = ins.rows[0].id as string; + await syncTask(c, newId); + return newId; + }); + if (!id) { + // параллельный вызов успел раньше + const again = await pool.query("select id from acc_chargeback where defect_daily_log_id = $1", [dailyLogId]); + return { result: "existing", chargeback: await load(pool, again.rows[0]!.id as string) }; + } + return { result: "created", chargeback: await load(pool, id) }; +} + +/** chargeback_start: строка claimed и задача cfo. */ +export const startChargeback = (pool: Pool, a: Row): Promise => createContractRow(pool, a, false); +/** chargeback_close: менеджер закрыл вопрос; строка closed, задачи нет. */ +export const closeChargebackByManager = (pool: Pool, a: Row): Promise => createContractRow(pool, a, true); + +/** chargeback_add_log: ссылка на повторный Daily Log (без дублей). */ +export async function addDailyLog(pool: Pool, a: Row): Promise<{ chargeback: Row; added: boolean }> { + const id = await resolveChargebackId(pool, a.chargeback_id); + const url = reqStr(a.daily_log_url, "daily_log_url"); + return withTx(pool, async (c) => { + const r = await load(c, id, true); + if (r.kind !== "contract") throw bad("Это не chargeback к контракту."); + const known = [r.defect_daily_log_url, ...((r.extra_daily_logs as string[] | null) ?? [])]; + if (known.includes(url)) return { chargeback: r, added: false }; + await c.query("update acc_chargeback set extra_daily_logs = array_append(extra_daily_logs, $2) where id = $1", [id, url]); + return { chargeback: await load(c, id), added: true }; + }); +} + +// ----------------------------------------------------------------- решения людей (MCP) + +/** Шаг 4: Анастасия решает удерживать (approve) или отклоняет (reject; строка сразу closed). */ +export async function decideChargeback(pool: Pool, actor: string, a: Row): Promise { + const id = await resolveChargebackId(pool, a.id); + const decision = a.decision; + if (decision !== "approve" && decision !== "reject") throw bad("decision: approve или reject"); + const fixVendor = optStr(a.fix_vendor_name, "fix_vendor_name"); + const comment = optStr(a.comment, "comment"); + return withTx(pool, async (c) => { + const r = await load(c, id, true); + if (r.kind !== "contract") throw bad("Это не chargeback к контракту."); + if (r.status !== "claimed") throw bad(`Решение уже принято (статус ${String(r.status)}).`); + if (decision === "approve") + await c.query("update acc_chargeback set status = 'approved', decided_by = $2, decided_at = now(), fix_vendor_name = $3 where id = $1", [id, actor, fixVendor]); + else + await c.query("update acc_chargeback set status = 'closed', decided_by = $2, decided_at = now(), close_reason = $3 where id = $1", [id, actor, `отклонено${comment ? `: ${comment}` : ""}`]); + await syncTask(c, id); + return load(c, id); + }); +} + +/** Шаг 6: Юля привязывает инвойс подрядчика Б и сумму удержания (по умолчанию - весь инвойс). */ +export async function linkFixInvoice(pool: Pool, actor: string, a: Row): Promise { + const id = await resolveChargebackId(pool, a.id); + const invoiceId = optUuid(a.invoice_id, "invoice_id"); + if (!invoiceId) throw bad("invoice_id: нужен id инвойса из acc_invoices"); + void actor; + return withTx(pool, async (c) => { + const r = await load(c, id, true); + if (r.kind !== "contract") throw bad("Это не chargeback к контракту."); + if (r.status !== "approved") throw bad(`Привязать инвойс можно только к одобренному chargeback (сейчас ${String(r.status)}).`); + const inv = (await c.query("select amount::float8 as amount, project_customer_id from acc_invoices where id = $1", [invoiceId])).rows[0] as { amount: number; project_customer_id: string } | undefined; + if (!inv) throw new ChargebackError(404, "invoice_not_found", "Инвойс не найден в acc_invoices (возможно, ещё не завершён разбор)."); + if (inv.project_customer_id !== r.contract_project_customer_id) throw bad("Инвойс относится к другому проекту, чем контракт подрядчика А."); + const retained = a.retained_amount === undefined || a.retained_amount === null ? inv.amount : amountOf(a.retained_amount, "retained_amount"); + if (retained > inv.amount + 0.001) throw bad(`Сумма удержания ${retained.toFixed(2)} больше суммы инвойса ${inv.amount.toFixed(2)}.`); + await c.query("update acc_chargeback set fix_invoice_id = $2, retained_amount = $3, status = 'fix_invoiced' where id = $1", [id, invoiceId, retained]); + await syncTask(c, id); + return load(c, id); + }); +} + +/** Шаг 7: Анастасия подтверждает (или правит) сумму удержания; дальше триггер БД пересчитывает контракт (шаг 8). */ +export async function confirmChargeback(pool: Pool, actor: string, a: Row): Promise { + const id = await resolveChargebackId(pool, a.id); + const override = a.retained_amount === undefined || a.retained_amount === null ? null : amountOf(a.retained_amount, "retained_amount"); + return withTx(pool, async (c) => { + const r = await load(c, id, true); + if (r.kind !== "contract") throw bad("Это не chargeback к контракту."); + if (r.status !== "fix_invoiced") throw bad(`Подтвердить можно строку со статусом fix_invoiced (сейчас ${String(r.status)}).`); + await c.query("update acc_chargeback set retained_amount = coalesce($2, retained_amount), confirmed_by = $3, confirmed_at = now(), status = 'applied' where id = $1", [id, override, actor]); + await syncTask(c, id); + return load(c, id); + }); +} + +/** Закрытие вручную (Анастасия может раньше шага 12). Для fraud тоже подходит. */ +export async function closeChargebackManually(pool: Pool, a: Row): Promise { + const id = await resolveChargebackId(pool, a.id); + const reason = reqStr(a.reason, "reason"); + return withTx(pool, async (c) => { + const r = await load(c, id, true); + if (r.status === "closed") throw bad("Строка уже закрыта."); + await c.query("update acc_chargeback set status = 'closed', close_reason = $2 where id = $1", [id, reason]); + return load(c, id); + }); +} + +/** Список для Юли и Анастасии: открытые (по умолчанию) или с фильтром; по проекту QuickBooks - чтобы увидеть chargeback при разборе инвойса. */ +export async function listChargebacks(pool: Pool, a: Row): Promise<{ rows: Row[] }> { + const kind = a.kind === undefined ? null : a.kind; + if (kind !== null && kind !== "contract" && kind !== "card_fraud") throw bad("kind: contract или card_fraud"); + const status = optStr(a.status, "status"); + const project = optStr(a.project_customer_id, "project_customer_id"); + const includeClosed = a.include_closed === true; + const { rows } = await pool.query( + `select ${COLS} ${FROM} where ($1::text is null or c.kind = $1) and ($2::text is null or c.status = $2) + and ($3::text is null or k.project_customer_id = $3) and ($4::boolean or c.status <> 'closed') order by c.created_at desc limit 100`, + [kind, status, project, includeClosed || status === "closed"], + ); + return { rows: rows as Row[] }; +} + +/** «Сколько я должна заплатить по контракту»: сумма, удержания, оплачено и остаток к оплате. */ +export async function contractBalance(pool: Pool, a: Row): Promise<{ contracts: ContractCandidate[] }> { + const id = optUuid(a.contract_id, "contract_id"); + const vendor = optStr(a.vendor_name, "vendor_name"); + const project = optStr(a.project_customer_id, "project_customer_id"); + if (!id && !vendor) throw bad("нужен contract_id или vendor_name"); + const { rows } = await pool.query( + `select ${CONTRACT_COLS} from acc_contracts where ($1::uuid is null or id = $1) and ($2::text is null or project_customer_id = $2) order by vendor_name`, + [id, project], + ); + const want = vendor ? normalizeVendorName(vendor) : null; + return { contracts: rows.filter((k) => !want || normalizeVendorName(k.vendor_name).includes(want) || want.includes(normalizeVendorName(k.vendor_name))) }; +} + +// ----------------------------------------------------------------- fraud по карте + +const FRAUD_NEXT: Record = { + collecting: ["filed", "closed"], + filed: ["refunded", "rejected", "closed"], + refunded: ["closed"], + rejected: ["filed", "closed"], + closed: [], +}; + +/** Процесс fraud, шаги 4-5: запись card_fraud по операции с комплектом (операция, чек или отметка «чека нет»). */ +export async function createFraud(pool: Pool, actor: string, a: Row): Promise<{ created: boolean; chargeback: Row }> { + const feed = reqStr(a.feed_txn_id, "feed_txn_id"); + const reason = optStr(a.reason, "reason"); + const bank = optStr(a.bank, "bank"); + const fileBy = optDate(a.file_by, "file_by"); + if (!UUID.test(actor) || !(await pool.query("select 1 from person where id = $1", [actor])).rows[0]) throw bad("created_by: такого person нет"); + return withTx(pool, async (c) => { + const ex = await c.query("select id from acc_chargeback where kind = 'card_fraud' and feed_txn_id = $1 and status <> 'closed' for update", [feed]); + if (ex.rows[0]) return { created: false, chargeback: await load(c, ex.rows[0].id as string) }; + const op = ( + await c.query( + `select 'review' as source, suggestion, confidence, problem_highlight from acc_categorization_review where feed_txn_id = $1 + union all select 'history', suggestion, confidence, problem_highlight from acc_categorization_review_history where feed_txn_id = $1 limit 1`, + [feed], + ) + ).rows[0] as Row | undefined; + const receipt = ( + await c.query("select id, drive_file_id, vendor_name, amount::float8 as amount, to_char(receipt_date, 'YYYY-MM-DD') as receipt_date from acc_receipts where feed_txn_id = $1 limit 1", [feed]) + ).rows[0] as Row | undefined; + const kit = { + operation: op ?? null, + receipt: receipt ? { ...receipt, url: `https://drive.google.com/file/d/${String(receipt.drive_file_id)}/view` } : null, + receipt_note: receipt ? null : "чека нет", + vendor_correspondence: "приложить вручную: переписка с вендором из JobTread или Gmail", + collected_at: new Date().toISOString(), + }; + const ins = await c.query( + "insert into acc_chargeback (kind, status, feed_txn_id, reason, bank, file_by, kit, created_by) values ('card_fraud', 'collecting', $1, $2, $3, $4, $5::jsonb, $6) returning id", + [feed, reason, bank, fileBy, JSON.stringify(kit), actor], + ); + const id = ins.rows[0]!.id as string; + await syncTask(c, id); + return { created: true, chargeback: await load(c, id) }; + }); +} + +export async function setFraudStatus(pool: Pool, a: Row): Promise { + const id = await resolveChargebackId(pool, a.id); + const status = reqStr(a.status, "status"); + const decision = optStr(a.bank_decision, "bank_decision"); + const bank = optStr(a.bank, "bank"); + const fileBy = optDate(a.file_by, "file_by"); + return withTx(pool, async (c) => { + const r = await load(c, id, true); + if (r.kind !== "card_fraud") throw bad("Это не fraud по карте."); + const allowed = FRAUD_NEXT[String(r.status)] ?? []; + if (!allowed.includes(status)) throw bad(`Из статуса ${String(r.status)} можно перейти в: ${allowed.join(", ") || "(ничего, строка закрыта)"}.`); + await c.query( + "update acc_chargeback set status = $2, bank_decision = coalesce($3, bank_decision), bank = coalesce($4, bank), file_by = coalesce($5::date, file_by) where id = $1", + [id, status, decision, bank, fileBy], + ); + await syncTask(c, id); + return load(c, id); + }); +} + +/** Недельное напоминание о незакрытых fraud (задание fraud-weekly). Текст детерминированный. */ +export async function buildFraudReminder(pool: Pool, now: Date): Promise<{ text: string; count: number } | null> { + const { rows } = await pool.query( + `select feed_txn_id, status, bank, to_char(file_by, 'YYYY-MM-DD') as file_by, created_at from acc_chargeback + where kind = 'card_fraud' and status <> 'closed' order by file_by nulls last, created_at`, + ); + if (rows.length === 0) return null; + const today = now.toISOString().slice(0, 10); + const days = (iso: string): number => Math.round((Date.parse(`${iso}T00:00:00Z`) - Date.parse(`${today}T00:00:00Z`)) / 86_400_000); + const label: Record = { collecting: "собираем комплект", filed: "подано, ждём банк", refunded: "возврат получен, нужно закрыть", rejected: "банк отказал" }; + const lines = rows.map((r) => { + let due = ""; + if (r.status === "collecting" && r.file_by) { + const d = days(r.file_by as string); + due = d < 0 ? `, срок подачи ${r.file_by} ПРОСРОЧЕН на ${-d} дн.` : d <= 7 ? `, срок подачи ${r.file_by} (осталось ${d} дн.)` : `, срок подачи ${r.file_by}`; + } + return `- операция ${String(r.feed_txn_id)}${r.bank ? ` (${String(r.bank)})` : ""}: ${label[String(r.status)] ?? String(r.status)}${due}`; + }); + return { count: rows.length, text: `Fraud по картам: незакрытых случаев ${rows.length}.\n${lines.join("\n")}\nСтатус и решение банка записываются в acc_chargeback (Claude: acc_fraud_update).` }; +} + +export interface FraudWeeklyDeps { + pool: Pool; + slack: { post(channelId: string, text: string): Promise }; + channelId: string; + now?: () => Date; +} + +/** Задание fraud-weekly: напоминание в Slack о незакрытых fraud и сроках подачи; если незакрытых нет, ничего не шлёт. */ +export async function runFraudWeekly(deps: FraudWeeklyDeps): Promise<{ sent: boolean; count: number }> { + const rem = await buildFraudReminder(deps.pool, (deps.now ?? (() => new Date()))()); + if (!rem) return { sent: false, count: 0 }; + await deps.slack.post(deps.channelId, rem.text); + return { sent: true, count: rem.count }; +} diff --git a/packages/accounting_automation/src/drive.ts b/packages/accounting_automation/src/drive.ts index 4e28997..e1e2a43 100644 --- a/packages/accounting_automation/src/drive.ts +++ b/packages/accounting_automation/src/drive.ts @@ -72,6 +72,39 @@ export class DriveClient implements DriveStore { return { id: j.id }; } + /** Файлы PDF в папке (по пути от корня) и во вложенных папках (глубина 1); отсутствующая папка - пустой список. */ + async listPdfFiles(pathParts: string[]): Promise<{ id: string; name: string }[]> { + const root = await this.ensureFolder(pathParts); + const out: { id: string; name: string }[] = []; + const listIn = async (folder: string, depth: number): Promise => { + let pageToken: string | undefined; + do { + const params = new URLSearchParams({ + q: `'${folder}' in parents and trashed=false`, + fields: "nextPageToken,files(id,name,mimeType)", + supportsAllDrives: "true", + includeItemsFromAllDrives: "true", + pageSize: "200", + ...(pageToken ? { pageToken } : {}), + }); + const j = (await (await this.call(`${API}/files?${params}`)).json()) as { files?: { id: string; name: string; mimeType: string }[]; nextPageToken?: string }; + for (const f of j.files ?? []) { + if (f.mimeType === "application/vnd.google-apps.folder") { + if (depth > 0) await listIn(f.id, depth - 1); + } else if (f.mimeType === "application/pdf" || f.name.toLowerCase().endsWith(".pdf")) out.push({ id: f.id, name: f.name }); + } + pageToken = j.nextPageToken; + } while (pageToken); + }; + await listIn(root, 1); + return out; + } + + async download(fileId: string): Promise { + const res = await this.call(`${API}/files/${encodeURIComponent(fileId)}?alt=media&supportsAllDrives=true`); + return Buffer.from(await res.arrayBuffer()); + } + async exportDocText(docId: string): Promise { const res = await this.call(`${API}/files/${encodeURIComponent(docId)}/export?mimeType=${encodeURIComponent("text/plain")}`); return await res.text(); diff --git a/packages/accounting_automation/src/finalize.ts b/packages/accounting_automation/src/finalize.ts index b2cc1bc..f878f3e 100644 --- a/packages/accounting_automation/src/finalize.ts +++ b/packages/accounting_automation/src/finalize.ts @@ -52,7 +52,7 @@ interface KindConfig { } /** Поля, изменения которых не считаются правкой человека (служебные и отметки процесса). */ -const SERVICE_FIELDS = new Set(["updated_at", "created_at", "done", "done_by", "problem_highlight", "request_sent_at", "fraud_checked_at"]); +const SERVICE_FIELDS = new Set(["updated_at", "created_at", "done", "done_by", "problem_highlight", "request_sent_at", "fraud_checked_at", "request_count", "request_approved_by", "request_approved_at", "request_log", "alert_kind"]); /** Пусто или заглушка автомата «tbd». */ function blank(v: unknown): boolean { @@ -121,8 +121,8 @@ async function forwardCertificate(c: PoolClient, r: Row): Promise { } if (!expires) return; await c.query( - `insert into acc_insurance_certificates (vendor_name, vendor_qbo_id, valid_until, drive_file_id) values ($1, $2, $3, 'manual')`, - [r.vendor_name, r.vendor_qbo_id ?? null, expires], + `insert into acc_insurance_certificates (vendor_name, vendor_qbo_id, valid_until, drive_file_id) values ($1, $2, $3, $4)`, + [r.vendor_name, r.vendor_qbo_id ?? null, expires, blank(r.drive_file_id) ? "manual" : r.drive_file_id], ); } diff --git a/packages/accounting_automation/src/history-report.int.test.ts b/packages/accounting_automation/src/history-report.int.test.ts new file mode 100644 index 0000000..57014cb --- /dev/null +++ b/packages/accounting_automation/src/history-report.int.test.ts @@ -0,0 +1,90 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { createTestDb, testDatabaseUrl, type TestDb } from "khb_common"; +import { buildHistoryReport, runHistoryWeekly } from "./history-report.js"; + +const url = testDatabaseUrl(); +const d = url ? describe : describe.skip; + +d("разбор истории правок (временная БД)", () => { + let db: TestDb; + const NOW = new Date("2026-11-23T12:00:00Z"); + const ago = (days: number): Date => new Date(NOW.getTime() - days * 86_400_000); + + const inv = async (vendor: string, project: string | null, changed: Record, closedDaysAgo = 1) => + db.pool.query( + `insert into acc_invoices_review_history (id, source_message_id, drive_file_id, vendor_name, project_customer_id, closed_at, changed_fields) + values (gen_random_uuid(), 'm', 'f', $1, $2, $3, $4::jsonb)`, + [vendor, project, ago(closedDaysAgo), JSON.stringify(changed)], + ); + const cat = async (feed: string, suggestion: unknown, changed: Record) => + db.pool.query( + `insert into acc_categorization_review_history (feed_txn_id, run_id, run_started_at, suggestion, closed_at, changed_fields) + values ($1, 'run', now(), $2::jsonb, $3, $4::jsonb)`, + [feed, JSON.stringify(suggestion), ago(1), JSON.stringify(changed)], + ); + + beforeAll(async () => { db = await createTestDb(url!); }); + afterAll(async () => { await db?.drop(); }); + beforeEach(async () => { + await db.pool.query("truncate acc_invoices_review_history, acc_categorization_review_history, acc_certificates_review_history, qbo_customer"); + }); + + it("пустая неделя: короткий отчёт без анализа", async () => { + const r = await buildHistoryReport(db.pool, NOW); + expect(r.text).toContain("анализировать нечего"); + expect(r.stats.every((x) => x.total === 0)).toBe(true); + }); + + it("доли без изменений, поля, вендоры, проекты и кандидаты в правила; записи старше недели не учитываются", async () => { + await db.pool.query("insert into qbo_customer (realm_id, id, display_name, is_job, raw) values ('r','C1','734 Placido Ave',true,'{}')"); + for (let i = 0; i < 3; i++) await inv("ACME Plumbing", "C1", { project_customer_id: { old: null, new: "C7" } }); + await inv("ACME Plumbing", "C1", { amount: { old: 1, new: 2 } }); + await inv("Twin Co", "C2", {}); + await inv("Twin Co", "C2", {}); + await inv("Old Co", "C9", { amount: { old: 1, new: 2 } }, 9); // за пределами недели + // категоризация: люди трижды меняют счёт у Home Depot с Materials на Tools + for (let i = 0; i < 3; i++) { + await cat(`f${i}`, { vendor: "Home Depot", account: "Tools" }, { suggestion: { old: { vendor: "Home Depot", account: "Materials" }, new: { vendor: "Home Depot", account: "Tools" } } }); + } + await cat("f9", { vendor: "Lowes", account: "A" }, {}); + await db.pool.query( + `insert into acc_certificates_review_history (id, vendor_name, closed_at, changed_fields) values (gen_random_uuid(), 'Cert Co', $1, '{"expires_on":{"old":null,"new":"2027-01-01"}}'::jsonb)`, + [ago(2)], + ); + + const r = await buildHistoryReport(db.pool, NOW); + const [invS, catS, certS] = r.stats; + expect(invS).toMatchObject({ total: 6, unchanged: 2 }); + expect(invS!.fields[0]).toEqual({ field: "project_customer_id", n: 3 }); + expect(invS!.vendors[0]).toEqual({ vendor: "ACME Plumbing", changed: 4, total: 4 }); + expect(invS!.projects[0]).toEqual({ project: "734 Placido Ave", changed: 4 }); + expect(invS!.candidates).toEqual([{ n: 3, text: "у «ACME Plumbing» поле project_customer_id исправляют на «C7» (3 раз): правило распознавания" }]); + expect(catS).toMatchObject({ total: 4, unchanged: 1 }); + expect(catS!.candidates[0]).toMatchObject({ n: 3 }); + expect(catS!.candidates[0]!.text).toContain("у «Home Depot» автомат ставит счёт «Materials», люди исправляют на «Tools»"); + expect(certS).toMatchObject({ total: 1, unchanged: 0 }); + // общий текст + expect(r.text).toContain("Закрыто записей: 11, принято без изменений: 3 (27%)."); + expect(r.text).toContain("Инвойсы: закрыто 6, без изменений 2 (33%)."); + expect(r.text).toContain("Чаще всего правят поля: project_customer_id (3), amount (1)."); + expect(r.text).toContain("Кандидаты в правила"); + expect(r.text).not.toContain("Old Co"); + }); + + it("нет повторов - кандидатов в правила нет", async () => { + await inv("A", "C1", { amount: { old: 1, new: 2 } }); + await inv("B", "C1", { amount: { old: 1, new: 2 } }); + const r = await buildHistoryReport(db.pool, NOW); + expect(r.text).toContain("Кандидатов в правила нет"); + }); + + it("отчёт уходит в Slack Анастасии", async () => { + await inv("A", "C1", {}); + const posted: { channel: string; text: string }[] = []; + const res = await runHistoryWeekly({ pool: db.pool, channelId: "CANA", now: () => NOW, slack: { post: async (channel, text) => { posted.push({ channel, text }); } } }); + expect(res).toEqual({ sent: true, total: 1, candidates: 0 }); + expect(posted).toHaveLength(1); + expect(posted[0]!.channel).toBe("CANA"); + expect(posted[0]!.text).toContain("Разбор истории правок за неделю 16.11.2026 - 23.11.2026"); + }); +}); diff --git a/packages/accounting_automation/src/history-report.ts b/packages/accounting_automation/src/history-report.ts new file mode 100644 index 0000000..be8d321 --- /dev/null +++ b/packages/accounting_automation/src/history-report.ts @@ -0,0 +1,141 @@ +import type { Pool } from "khb_common"; +import type { SlackPoster } from "./slack.js"; + +/** + * «Разбор истории правок» (раздел «Завершение ручного разбора», задание `history-weekly`, раз в неделю): + * анализ *_history за неделю - какие поля люди правят чаще всего, у каких вендоров и проектов, доля записей без правок, + * повторяющиеся правки как кандидаты в правила. Текст отчёта детерминированный (SQL + шаблон), Claude не нужен. + */ + +interface Source { + table: string; + label: string; + /** SQL-выражение вендора и проекта строки history. */ + vendor: string; + project: string | null; +} + +const SOURCES: Source[] = [ + { table: "acc_invoices_review_history", label: "Инвойсы", vendor: "coalesce(vendor_name, '(не указан)')", project: "project_customer_id" }, + { table: "acc_categorization_review_history", label: "Категоризация банка", vendor: "coalesce(suggestion ->> 'vendor', '(не указан)')", project: "suggestion ->> 'project_customer_id'" }, + { table: "acc_certificates_review_history", label: "Сертификаты", vendor: "coalesce(vendor_name, '(не указан)')", project: null }, +]; + +export interface HistoryStats { + label: string; + total: number; + unchanged: number; + fields: { field: string; n: number }[]; + vendors: { vendor: string; changed: number; total: number }[]; + projects: { project: string; changed: number }[]; + candidates: { text: string; n: number }[]; +} + +export interface HistoryReport { + from: string; + to: string; + text: string; + stats: HistoryStats[]; +} + +const CHANGED = "(changed_fields is not null and changed_fields <> '{}'::jsonb)"; +const pct = (a: number, b: number): string => (b === 0 ? "0" : String(Math.round((100 * a) / b))); +const ru = (iso: string): string => `${iso.slice(8, 10)}.${iso.slice(5, 7)}.${iso.slice(0, 4)}`; +const quote = (v: unknown): string => (v === null || v === undefined || v === "" ? "(пусто)" : `«${String(v).slice(0, 60)}»`); + +async function analyze(pool: Pool, s: Source, from: Date, minRepeat: number): Promise { + const t = await pool.query<{ total: number; unchanged: number }>( + `select count(*)::int as total, count(*) filter (where not ${CHANGED})::int as unchanged from ${s.table} where closed_at >= $1`, + [from], + ); + const fields = await pool.query<{ field: string; n: number }>( + `select k as field, count(*)::int as n from ${s.table}, jsonb_object_keys(coalesce(changed_fields, '{}'::jsonb)) k + where closed_at >= $1 group by k order by n desc, k limit 8`, + [from], + ); + const vendors = await pool.query<{ vendor: string; changed: number; total: number }>( + `select ${s.vendor} as vendor, (count(*) filter (where ${CHANGED}))::int as changed, count(*)::int as total + from ${s.table} where closed_at >= $1 group by 1 having count(*) filter (where ${CHANGED}) > 0 order by changed desc, vendor limit 5`, + [from], + ); + const projects = s.project + ? await pool.query<{ project: string; changed: number }>( + `select coalesce((select q.display_name from qbo_customer q where q.id = p.pid limit 1), p.pid, '(не указан)') as project, count(*)::int as changed + from (select ${s.project} as pid from ${s.table} where closed_at >= $1 and ${CHANGED}) p + group by p.pid order by changed desc, project limit 5`, + [from], + ) + : { rows: [] as { project: string; changed: number }[] }; + + const candidates: { text: string; n: number }[] = []; + if (s.table === "acc_categorization_review_history") { + const c = await pool.query<{ vendor: string; sub: string; old_v: string | null; new_v: string | null; n: number }>( + `select ${s.vendor} as vendor, sub, changed_fields -> 'suggestion' -> 'old' ->> sub as old_v, changed_fields -> 'suggestion' -> 'new' ->> sub as new_v, count(*)::int as n + from ${s.table} cross join unnest(array['account', 'project_customer_id']) sub + where closed_at >= $1 and changed_fields ? 'suggestion' + and changed_fields -> 'suggestion' -> 'old' ->> sub is distinct from changed_fields -> 'suggestion' -> 'new' ->> sub + group by 1, 2, 3, 4 having count(*) >= $2 order by n desc limit 10`, + [from, minRepeat], + ); + for (const r of c.rows) { + const what = r.sub === "account" ? "счёт" : "проект"; + candidates.push({ n: r.n, text: `у «${r.vendor}» автомат ставит ${what} ${quote(r.old_v)}, люди исправляют на ${quote(r.new_v)} (${r.n} раз): правило для промпта категоризации` }); + } + } else { + const c = await pool.query<{ vendor: string; field: string; new_v: string | null; n: number }>( + `select ${s.vendor} as vendor, k as field, changed_fields -> k ->> 'new' as new_v, count(*)::int as n + from ${s.table}, jsonb_object_keys(coalesce(changed_fields, '{}'::jsonb)) k + where closed_at >= $1 group by 1, 2, 3 having count(*) >= $2 order by n desc limit 10`, + [from, minRepeat], + ); + for (const r of c.rows) candidates.push({ n: r.n, text: `у «${r.vendor}» поле ${r.field} исправляют на ${quote(r.new_v)} (${r.n} раз): правило распознавания` }); + } + return { label: s.label, total: t.rows[0]!.total, unchanged: t.rows[0]!.unchanged, fields: fields.rows, vendors: vendors.rows, projects: projects.rows, candidates }; +} + +export async function buildHistoryReport(pool: Pool, now: Date, opts: { days?: number; minRepeat?: number } = {}): Promise { + const days = opts.days ?? 7; + const from = new Date(now.getTime() - days * 86_400_000); + const stats: HistoryStats[] = []; + for (const s of SOURCES) stats.push(await analyze(pool, s, from, opts.minRepeat ?? 3)); + const fromIso = from.toISOString().slice(0, 10); + const toIso = now.toISOString().slice(0, 10); + + const total = stats.reduce((a, x) => a + x.total, 0); + const unchanged = stats.reduce((a, x) => a + x.unchanged, 0); + const lines: string[] = [`Разбор истории правок за неделю ${ru(fromIso)} - ${ru(toIso)}.`]; + if (total === 0) { + lines.push("За неделю не закрыто ни одной записи ручного разбора: анализировать нечего."); + } else { + lines.push(`Закрыто записей: ${total}, принято без изменений: ${unchanged} (${pct(unchanged, total)}%).`); + for (const x of stats) { + if (x.total === 0) continue; + lines.push("", `${x.label}: закрыто ${x.total}, без изменений ${x.unchanged} (${pct(x.unchanged, x.total)}%).`); + if (x.fields.length) lines.push(` Чаще всего правят поля: ${x.fields.map((f) => `${f.field} (${f.n})`).join(", ")}.`); + if (x.vendors.length) lines.push(` Вендоры с правками: ${x.vendors.map((v) => `${v.vendor} (${v.changed} из ${v.total})`).join(", ")}.`); + if (x.projects.length) lines.push(` Проекты с правками: ${x.projects.map((p) => `${p.project} (${p.changed})`).join(", ")}.`); + } + const all = stats.flatMap((x) => x.candidates.map((c) => ({ label: x.label, ...c }))).sort((a, b) => b.n - a.n); + lines.push(""); + if (all.length === 0) lines.push("Кандидатов в правила нет: повторяющихся правок не найдено."); + else { + lines.push("Кандидаты в правила (повторяющиеся правки):"); + for (const c of all) lines.push(`- ${c.label}: ${c.text}`); + lines.push("Решить, что принять: править промпт категоризации в Google Drive или правила распознавания."); + } + } + return { from: fromIso, to: toIso, text: lines.join("\n"), stats }; +} + +export interface HistoryWeeklyDeps { + pool: Pool; + slack: SlackPoster; + channelId: string; + now?: () => Date; +} + +export async function runHistoryWeekly(deps: HistoryWeeklyDeps): Promise<{ sent: true; total: number; candidates: number }> { + const rep = await buildHistoryReport(deps.pool, (deps.now ?? (() => new Date()))()); + await deps.slack.post(deps.channelId, rep.text); + return { sent: true, total: rep.stats.reduce((a, x) => a + x.total, 0), candidates: rep.stats.reduce((a, x) => a + x.candidates.length, 0) }; +} diff --git a/packages/accounting_automation/src/http-api.ts b/packages/accounting_automation/src/http-api.ts index 147d66c..5496fe6 100644 --- a/packages/accounting_automation/src/http-api.ts +++ b/packages/accounting_automation/src/http-api.ts @@ -1,5 +1,6 @@ import Fastify, { type FastifyInstance } from "fastify"; import type { Pool } from "khb_common"; +import { registerChargebackRoutes } from "./chargeback-http.js"; import { registerMcp } from "./mcp.js"; import type { AccountingSettings } from "./settings.js"; @@ -18,8 +19,17 @@ export interface JobHandlers { "receipt-search": () => Promise; /** Раз в неделю: отчёт Анастасии о непринесённых чеках. */ "receipt-weekly-report": () => Promise; + /** Этап 2 (необязательные: не настроенное задание отвечает 404). */ + /** Страховые сертификаты: сроки, запросы подрядчикам, отметка «нет страховки» (раз в день). */ + certificates?: () => Promise; + /** Ежемесячная сверка выписок из Drive с QuickBooks. */ + "reconcile-monthly"?: () => Promise; + /** Еженедельный разбор истории правок -> отчёт Анастасии. */ + "history-weekly"?: () => Promise; + /** Еженедельное напоминание о незакрытых fraud по картам. */ + "fraud-weekly"?: () => Promise; } -export const JOB_NAMES = ["invoices-mail", "finalize", "categorize", "summary", "fraud-flags", "invoice-check", "invoice-paid", "receipts-slack", "receipt-search", "receipt-weekly-report"] as const; +export const JOB_NAMES = ["invoices-mail", "finalize", "categorize", "summary", "fraud-flags", "invoice-check", "invoice-paid", "receipts-slack", "receipt-search", "receipt-weekly-report", "certificates", "reconcile-monthly", "history-weekly", "fraud-weekly"] as const; export interface ApiDeps { pool: Pool; @@ -52,7 +62,7 @@ export function buildApi(deps: ApiDeps): FastifyInstance { */ app.post<{ Params: { name: string }; Querystring: { wait?: string } }>("/jobs/:name", async (req, reply) => { const name = req.params.name as keyof JobHandlers; - const handler = Object.prototype.hasOwnProperty.call(deps.jobs, name) ? deps.jobs[name] : undefined; + const handler = Object.prototype.hasOwnProperty.call(deps.jobs, name) && (JOB_NAMES as readonly string[]).includes(name) ? deps.jobs[name] : undefined; if (!handler) return reply.code(404).send({ error: "unknown_job" }); if (running.has(name)) return reply.code(409).send({ error: "already_running" }); running.add(name); @@ -77,6 +87,9 @@ export function buildApi(deps: ApiDeps): FastifyInstance { return reply.code(202).send({ job: name, started: true }); }); + // --- ручки chargeback для ассистента менеджера (под токеном сервиса) + registerChargebackRoutes(app, { pool: deps.pool }); + // --- MCP для Claude сотрудников (Streamable HTTP, без сессий) if (deps.settings.mcp.enabled) { const base = deps.settings.mcp.publicUrl?.replace(/\/$/, ""); diff --git a/packages/accounting_automation/src/invoices-mail.ts b/packages/accounting_automation/src/invoices-mail.ts index fe59ff5..ab1290b 100644 --- a/packages/accounting_automation/src/invoices-mail.ts +++ b/packages/accounting_automation/src/invoices-mail.ts @@ -5,6 +5,8 @@ import { join } from "node:path"; import type { Logger, Pool } from "khb_common"; import type { ClaudeRunner } from "./claude-runner.js"; import type { DriveStore } from "./drive.js"; +import { ingestCertificate } from "./certificates-ingest.js"; +import { normalizeVendorName } from "./vendor-name.js"; import type { MailAttachment, MailMessage, MailSource } from "./gmail.js"; export interface InvoiceIngestDeps { @@ -27,10 +29,17 @@ export interface InvoiceIngestResult { /** Писем без инвойса. */ skipped: number; errors: number; + /** Страховых сертификатов сохранено (только если были; процесс «Страховые сертификаты подрядчиков», шаг 2). */ + certificates?: number; } export interface RecognizedInvoice { is_invoice: boolean; + /** invoice, certificate (страховой сертификат), other. Нет в ответе агента - выводится из is_invoice. */ + document_type?: "invoice" | "certificate" | "other"; + /** Для сертификата: страховая компания и дата окончания полиса (YYYY-MM-DD); vendor_name - застрахованный подрядчик. */ + insurer?: string | null; + valid_until?: string | null; vendor_name: string | null; invoice_number: string | null; invoice_date: string | null; @@ -41,19 +50,7 @@ export interface RecognizedInvoice { // ----------------------------------------------------------------- нормализация и разбор -const COMPANY_SUFFIX = new Set(["llc", "inc", "corp", "co", "ltd", "company", "corporation", "incorporated", "lp", "llp", "pllc"]); - -/** Имя вендора для сравнения: регистр, знаки, юридические суффиксы. */ -export function normalizeVendorName(s: string | null | undefined): string { - const words = (s ?? "") - .toLowerCase() - .replace(/&/g, " and ") - .replace(/[^a-z0-9а-яё]+/g, " ") - .split(" ") - .filter(Boolean); - while (words.length > 1 && COMPANY_SUFFIX.has(words[words.length - 1]!)) words.pop(); - return words.join(" "); -} +export { normalizeVendorName }; const STREET_WORDS: Record = { street: "st", avenue: "ave", road: "rd", drive: "dr", lane: "ln", court: "ct", boulevard: "blvd", place: "pl", terrace: "ter", circle: "cir", way: "way" }; @@ -102,14 +99,19 @@ export function parseRecognition(stdout: string): RecognizedInvoice { } catch (e) { throw new Error(`агент вернул невалидный JSON: ${(e as Error).message}`); } - if (typeof j.is_invoice !== "boolean") throw new Error("в JSON агента нет поля is_invoice"); + const docType = j.document_type === "invoice" || j.document_type === "certificate" || j.document_type === "other" ? j.document_type : undefined; + if (typeof j.is_invoice !== "boolean" && !docType) throw new Error("в JSON агента нет поля is_invoice"); + const isInvoice = typeof j.is_invoice === "boolean" ? j.is_invoice && docType !== "certificate" : docType === "invoice"; const lines = Array.isArray(j.lines) ? j.lines .filter((l): l is Record => !!l && typeof l === "object") .map((l) => ({ description: str(l.description) ?? "", amount: parseAmount(l.amount) })) : null; return { - is_invoice: j.is_invoice, + is_invoice: isInvoice, + document_type: docType ?? (isInvoice ? "invoice" : "other"), + insurer: str(j.insurer), + valid_until: parseDate(j.valid_until), vendor_name: str(j.vendor_name), invoice_number: str(j.invoice_number) ?? (typeof j.invoice_number === "number" ? String(j.invoice_number) : null), invoice_date: parseDate(j.invoice_date), @@ -132,6 +134,8 @@ export function buildRecognitionPrompt(pdfPath: string, mail: { from: string; su `Прочитай PDF-файл ${pdfPath} (письмо от ${mail.from}, тема «${mail.subject}») и верни ТОЛЬКО один JSON-объект, без пояснений и без markdown.`, "Поля JSON:", '- is_invoice: true, если документ - счёт/инвойс подрядчика к оплате; false для всего остального (КП, чек, страховка, реклама и т.п.)', + '- document_type: "invoice" (счёт к оплате), "certificate" (страховой сертификат, например ACORD certificate of liability insurance) или "other"', + "- для certificate: vendor_name - застрахованный подрядчик (Insured), insurer - страховая компания, valid_until - дата окончания действия полиса YYYY-MM-DD (если полисов несколько, самая ранняя дата окончания); остальные поля инвойса можно оставить null", "- vendor_name: название компании, которая выставила счёт (не получатель)", "- invoice_number: номер счёта", "- invoice_date: дата счёта в формате YYYY-MM-DD", @@ -236,17 +240,31 @@ async function recognize(deps: InvoiceIngestDeps, msg: MailMessage, att: MailAtt } /** Результат по одному вложению: created - новая запись; existing - запись уже есть; none - не инвойс. */ -async function processAttachment(deps: InvoiceIngestDeps, msg: MailMessage, att: MailAttachment, index: number): Promise<"created" | "existing" | "none"> { +async function processAttachment(deps: InvoiceIngestDeps, msg: MailMessage, att: MailAttachment, index: number): Promise<"created" | "existing" | "certificate" | "none"> { const { pool } = deps; const id = invoiceReviewId(msg.id, index, att.filename); const ex = await pool.query( - "select 1 from acc_invoices_review where id = $1 union all select 1 from acc_invoices_review_history where id = $1 union all select 1 from acc_invoices where id = $1", + `select 1 from acc_invoices_review where id = $1 union all select 1 from acc_invoices_review_history where id = $1 union all select 1 from acc_invoices where id = $1 + union all select 1 from acc_insurance_certificates where id = $1 union all select 1 from acc_certificates_review where id = $1 + union all select 1 from acc_certificates_review_history where id = $1`, [id], ); if (ex.rowCount) return "existing"; const bytes = await att.getBytes(); const rec = await recognize(deps, msg, att, bytes); + if (rec.document_type === "certificate") { + // Процесс «Страховые сертификаты подрядчиков», шаг 2: файл в папку «Страховки», запись в acc_insurance_certificates + const vendor = await resolveVendor(pool, rec.vendor_name); + const refDate = rec.valid_until ? new Date(`${rec.valid_until}T00:00:00Z`) : msg.receivedAt; + const folder = await deps.drive.ensureFolder(["Страховки", safeName(rec.vendor_name ?? "Без вендора"), ym(refDate)]); + const file = await deps.drive.upload(att.filename, att.mime || "application/pdf", bytes, folder); + await ingestCertificate(pool, { + id, messageId: msg.id, driveFileId: file.id, vendorName: rec.vendor_name, vendorQboId: vendor.id, insurer: rec.insurer ?? null, + validUntil: rec.valid_until ?? null, now: deps.now(), + }); + return "certificate"; + } if (!rec.is_invoice) return "none"; const resolved = await resolveAll(pool, rec); @@ -277,7 +295,7 @@ async function processAttachment(deps: InvoiceIngestDeps, msg: MailMessage, att: return "created"; } -async function markMail(pool: Pool, messageId: string, result: "invoice" | "skipped" | "error", details: unknown): Promise { +async function markMail(pool: Pool, messageId: string, result: "invoice" | "certificate" | "skipped" | "error", details: unknown): Promise { await pool.query( `insert into acc_mail_processed (message_id, result, details) values ($1,$2,$3::jsonb) on conflict (message_id) do update set result = excluded.result, details = excluded.details, processed_at = now()`, @@ -298,15 +316,22 @@ export async function runInvoiceIngest(deps: InvoiceIngestDeps): Promise a.mime.toLowerCase() === "application/pdf" || a.filename.toLowerCase().endsWith(".pdf")); let invoices = 0; let created = 0; + let certificates = 0; for (const [i, att] of pdfs.entries()) { const r = await processAttachment(deps, msg, att, i); + if (r === "certificate") { + certificates++; + out.certificates = (out.certificates ?? 0) + 1; + continue; + } if (r !== "none") invoices++; if (r === "created") { created++; out.created++; } } - if (invoices > 0) await markMail(pool, msg.id, "invoice", { attachments: pdfs.length, invoices, created }); + if (invoices > 0) await markMail(pool, msg.id, "invoice", { attachments: pdfs.length, invoices, created, certificates }); + else if (certificates > 0) await markMail(pool, msg.id, "certificate", { attachments: pdfs.length, certificates }); else { out.skipped++; await markMail(pool, msg.id, "skipped", { attachments: pdfs.length, reason: pdfs.length ? "не инвойс" : "нет PDF" }); diff --git a/packages/accounting_automation/src/main.ts b/packages/accounting_automation/src/main.ts index 1fe131b..8b9729e 100644 --- a/packages/accounting_automation/src/main.ts +++ b/packages/accounting_automation/src/main.ts @@ -1,6 +1,8 @@ import { readFileSync } from "node:fs"; import { createLogger, createPool, itNotify, loadServiceSettings } from "khb_common"; import { runCategorization } from "./categorize.js"; +import { runFraudWeekly } from "./chargeback.js"; +import { manualMessenger, runCertificates } from "./certificates.js"; import { makeClaudeRunner } from "./claude-runner.js"; import { DriveClient } from "./drive.js"; import { runFinalize } from "./finalize.js"; @@ -9,6 +11,8 @@ import { runInvoiceCheck } from "./invoice-check.js"; import { runInvoicePaid } from "./invoice-paid.js"; import { GmailClient } from "./gmail.js"; import { GoogleAuth } from "./google.js"; +import { runHistoryWeekly } from "./history-report.js"; +import { makeClaudeStatementReader, runMonthlyReconcile } from "./reconcile.js"; import { buildApi } from "./http-api.js"; import { instructionsFromFile } from "./mcp.js"; import { runInvoiceIngest } from "./invoices-mail.js"; @@ -50,6 +54,12 @@ async function realmId(): Promise { const nonWorkdays = (): Promise> => loadNonWorkdays(pool); +/** Куда слать отчёты Анастасии (сверка, разбор правок, fraud). */ +function reportSlack(): { slack: NonNullable; channelId: string } { + if (!slack || !s.slack) throw new Error("не настроен slack (botToken, accountingChannelId)"); + return { slack, channelId: s.slack.reportChannelId ?? s.slack.accountingChannelId }; +} + let mcpInstructions: string | undefined; try { mcpInstructions = instructionsFromFile(readFileSync(`${process.env.KHB_REPO_ROOT ?? process.cwd()}/docs/proposed/modules/quickbooks_bookkeeper/p-mcp-instructions.md`, "utf8")); @@ -96,6 +106,31 @@ const app = buildApi({ "fraud-flags": async () => runFraudFlags(pool, { settings: s.fraud, realmId: await realmId() }), "invoice-check": () => runInvoiceCheck({ pool }), "invoice-paid": async () => runInvoicePaid({ pool, realmId: await realmId() }), + certificates: () => + runCertificates({ + pool, + log, + // реальной отправки в JobTread пока нет (data_collector только читает): письмо готовится, Юля отправляет вручную + messenger: manualMessenger, + autoSend: s.stage2.certificateAutoSend, + loadTemplate: s.stage2.certificateTemplateDocId && drive ? () => drive.exportDocText(s.stage2.certificateTemplateDocId!) : undefined, + }), + "reconcile-monthly": async () => { + if (!drive) throw new Error("не настроены google (ключ сервисного аккаунта, rootFolderId)"); + return runMonthlyReconcile({ + pool, + log, + ...reportSlack(), + realmId, + toleranceDays: s.stage2.statementDateToleranceDays, + reader: makeClaudeStatementReader({ claude }), + source: { + list: async () => (await drive.listPdfFiles([s.stage2.statementsFolder])).map((f) => ({ id: f.id, name: f.name, getBytes: () => drive.download(f.id) })), + }, + }); + }, + "history-weekly": () => runHistoryWeekly({ pool, ...reportSlack() }), + "fraud-weekly": () => runFraudWeekly({ pool, ...reportSlack() }), 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-ui.ts b/packages/accounting_automation/src/mcp-ui.ts index 3ebf647..e1e5839 100644 --- a/packages/accounting_automation/src/mcp-ui.ts +++ b/packages/accounting_automation/src/mcp-ui.ts @@ -48,6 +48,12 @@ export function toRow(t: Json): ReviewRow { what = [s(review.invoice_number) ? `№ ${String(review.invoice_number)}` : null, review.project_customer_id ? `проект ${String(review.project_customer_id)}` : null].filter(Boolean).join(", ") || null; confidence = null; + } else if (kind === "chargeback") { + date = day(review.created_at); + amount = s(review.retained_amount); + who = s(review.fix_vendor_name) ?? s(review.feed_txn_id); + what = review.kind === "card_fraud" ? `fraud: ${String(review.status)}` : `chargeback: ${String(review.status)}${review.defect_description ? `, ${String(review.defect_description)}` : ""}`; + confidence = null; } else if (kind === "certificate") { date = day(review.expires_on); who = s(review.vendor_name); diff --git a/packages/accounting_automation/src/mcp.int.test.ts b/packages/accounting_automation/src/mcp.int.test.ts index 96c867b..790be1a 100644 --- a/packages/accounting_automation/src/mcp.int.test.ts +++ b/packages/accounting_automation/src/mcp.int.test.ts @@ -294,8 +294,8 @@ d("MCP бухгалтерии (временная БД)", () => { expect((await post(bearer(TOKEN_A), { jsonrpc: "2.0", method: "notifications/initialized" })).statusCode).toBe(202); 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_receipt_allow_without", "acc_review_batch", "acc_review_snooze", "acc_invoice_to_approve", "acc_invoice_decide", + expect(l.result.tools.map((t: { name: string }) => t.name).slice(0, 8)).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", ]); 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 75538cc..66873d3 100644 --- a/packages/accounting_automation/src/mcp.ts +++ b/packages/accounting_automation/src/mcp.ts @@ -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): 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, t: Task, suffix = "", lock = false): Promise { + 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; сервис подставляет файл, если он доступен). */ diff --git a/packages/accounting_automation/src/reconcile.int.test.ts b/packages/accounting_automation/src/reconcile.int.test.ts new file mode 100644 index 0000000..b70ce5a --- /dev/null +++ b/packages/accounting_automation/src/reconcile.int.test.ts @@ -0,0 +1,166 @@ +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 { buildStatementPrompt, compareTransactions, makeClaudeStatementReader, parseStatement, runMonthlyReconcile, type ParsedStatement, type StatementFile, type StatementReader } from "./reconcile.js"; + +const url = testDatabaseUrl(); +const d = url ? describe : describe.skip; +const log = createLogger("test", "silent"); + +describe("сверка выписки (чистые функции)", () => { + const p = (id: string, date: string, amt: number, name = "V") => ({ id, txn_date: date, total_amt: amt, entity_name: name }); + it("сопоставление: пропущенные, лишние, дубли; допуск по датам", () => { + const stmt = [ + { date: "2026-10-05", description: "HOME DEPOT", amount: 120.5 }, + { date: "2026-10-10", description: "LOWES", amount: 80 }, + { date: "2026-10-12", description: "SALARY", amount: -3000 }, // поступление не сверяется + { date: "2026-10-20", description: "NO QBO", amount: 45 }, + ]; + const qbo = [p("1", "2026-10-07", 120.5), p("2", "2026-10-10", 80), p("3", "2026-10-10", 80), p("4", "2026-10-25", 999, "Extra")]; + const f = compareTransactions(stmt, qbo, "2026-10-01", "2026-10-31", 3); + expect(f.map((x) => x.description)).toEqual([ + "Операция из выписки не найдена в QuickBooks: 2026-10-20 NO QBO 45.00", + "Возможный дубль в QuickBooks: 2026-10-10 V 80.00 (такая же операция 2 уже сверена с выпиской)", + "Операция есть в QuickBooks, но нет в выписке: 2026-10-25 Extra 999.00", + ]); + expect(f[1]!.qboRef).toBe("3"); + }); + it("операции вне периода выписки и вне допуска не считаются совпадением", () => { + const f = compareTransactions([{ date: "2026-10-05", description: "A", amount: 10 }], [p("1", "2026-10-15", 10)], "2026-10-01", "2026-10-31", 3); + expect(f).toHaveLength(2); + }); + it("parseStatement: обёртка, битые операции пропускаются", () => { + const s = parseStatement('Вот:\n```json\n{"bank":"Chase","account_hint":1234,"account_kind":"credit_card","period_start":"2026-10-01","period_end":"2026-10-31","ending_balance":"$1,250.40","transactions":[{"date":"2026-10-02","description":"A","amount":"10.5"},{"date":"bad","amount":1},{"date":"2026-10-03","amount":null}]}\n```'); + expect(s).toMatchObject({ bank: "Chase", accountHint: "1234", accountKind: "credit_card", periodStart: "2026-10-01", endingBalance: 1250.4 }); + expect(s.transactions).toEqual([{ date: "2026-10-02", description: "A", amount: 10.5 }]); + expect(() => parseStatement("нет json")).toThrow(); + }); + it("Claude-читатель пишет PDF во временный файл и разбирает ответ", async () => { + const { readFileSync } = await import("node:fs"); + let seen = ""; + const claude: ClaudeRunner = async (o) => { + const path = /(\S+statement\.pdf)/.exec(o.prompt)![1]!; + seen = readFileSync(path, "utf8"); + return { ok: true, stdout: '{"bank":"B","period_start":"2026-10-01","period_end":"2026-10-31","transactions":[]}', stderr: "", exitCode: 0, timedOut: false }; + }; + const r = await makeClaudeStatementReader({ claude }).read({ name: "s.pdf", bytes: Buffer.from("PDFDATA") }); + expect(seen).toBe("PDFDATA"); + expect(r.bank).toBe("B"); + expect(buildStatementPrompt("/x/statement.pdf")).toContain("ending_balance"); + const failing: ClaudeRunner = async () => ({ ok: false, stdout: "", stderr: "boom", exitCode: 1, timedOut: false }); + await expect(makeClaudeStatementReader({ claude: failing }).read({ name: "s.pdf", bytes: Buffer.from("x") })).rejects.toThrow(/Claude не отработал/); + }); +}); + +d("ежемесячная сверка (временная БД)", () => { + let db: TestDb; + let posted: { channel: string; text: string }[]; + let parsed: Record; + let files: StatementFile[]; + let reads: number; + + const stmt = (over: Partial = {}): ParsedStatement => ({ + bank: "Chase", accountHint: "1234", accountKind: "bank", periodStart: "2026-10-01", periodEnd: "2026-10-31", endingBalance: 9000, + transactions: [{ date: "2026-10-05", description: "HOME DEPOT", amount: 100 }, { date: "2026-10-09", description: "ORPHAN", amount: 50 }], ...over, + }); + const file = (id: string): StatementFile => ({ id, name: `${id}.pdf`, getBytes: async () => Buffer.from(id) }); + const reader: StatementReader = { + async read({ name }) { + reads++; + const r = parsed[name.replace(".pdf", "")]; + if (!r) throw new Error("нет ответа"); + if (r instanceof Error) throw r; + return r; + }, + }; + const run = () => + runMonthlyReconcile({ + pool: db.pool, source: { list: async () => files }, reader, realmId: async () => "r", log, + slack: { post: async (channel, text) => { posted.push({ channel, text }); } }, channelId: "CANASTASIA", + }); + const disc = async () => (await db.pool.query("select kind, qbo_ref, description, amount_diff::float8 as amount_diff from acc_discrepancies order by description")).rows; + + beforeAll(async () => { db = await createTestDb(url!); }); + afterAll(async () => { await db?.drop(); }); + beforeEach(async () => { + posted = []; parsed = {}; files = []; reads = 0; + await db.pool.query("truncate acc_discrepancies, acc_mail_processed, qbo_account, qbo_purchase cascade"); + await db.pool.query(`insert into qbo_account (realm_id, id, name, account_type, current_balance, raw) values + ('r','A1','Chase Checking 1234','Bank', 9100,'{}'), ('r','A2','Amex Card 9999','Credit Card', 400,'{}'), ('r','A3','Other 5555','Bank', 0,'{}')`); + // расходы по счёту A1: одна совпадает с выпиской, одна лишняя в периоде, одна после периода (для восстановления остатка) + await db.pool.query(`insert into qbo_purchase (realm_id, id, txn_date, account_id, entity_name, total_amt, raw) values + ('r','P1','2026-10-06','A1','Home Depot',100,'{}'), ('r','P2','2026-10-15','A1','Lowes',70,'{}'), ('r','P3','2026-11-03','A1','Later',100,'{}')`); + }); + + it("расхождения: пропущенная в QuickBooks, лишняя, остаток; отчёт Анастасии; повторный запуск пропускает файл", async () => { + files = [file("oct")]; + parsed.oct = stmt(); + const r = await run(); + expect(r).toEqual({ statements: 1, discrepancies: 3, errors: 0, skipped: 0 }); + const rows = await disc(); + expect(rows.every((x) => x.kind === "statement_vs_qbo")).toBe(true); + const text = rows.map((x) => x.description).join("\n"); + expect(text).toContain("Операция из выписки не найдена в QuickBooks: 2026-10-09 ORPHAN 50.00"); + expect(text).toContain("Операция есть в QuickBooks, но нет в выписке: 2026-10-15 Lowes 70.00"); + // остаток QuickBooks на 31.10: 9100 + 100 (расход после периода) = 9200; в выписке 9000 -> -200 + const bal = rows.find((x) => x.description.includes("Конечный остаток"))!; + expect(bal.amount_diff).toBe(-200); + expect(bal.qbo_ref).toBe("A1"); + expect(bal.description).toContain("в выписке 9000.00"); + expect(posted).toHaveLength(1); + expect(posted[0]!.channel).toBe("CANASTASIA"); + expect(posted[0]!.text).toContain("расхождений 3"); + expect((await db.pool.query("select result from acc_mail_processed")).rows).toEqual([{ result: "statement" }]); + const again = await run(); + expect(again).toEqual({ statements: 0, discrepancies: 0, errors: 0, skipped: 1 }); + expect(reads).toBe(1); + expect(posted).toHaveLength(1); + expect((await disc())).toHaveLength(3); + }); + + it("всё сходится: расхождений нет", async () => { + files = [file("oct")]; + parsed.oct = stmt({ endingBalance: 9200, transactions: [{ date: "2026-10-05", description: "HD", amount: 100 }, { date: "2026-10-15", description: "L", amount: 70 }] }); + expect(await run()).toMatchObject({ statements: 1, discrepancies: 0 }); + expect(posted[0]!.text).toContain("расхождений нет"); + }); + + it("кредитная карта: остаток считается как задолженность", async () => { + await db.pool.query("insert into qbo_purchase (realm_id, id, txn_date, account_id, entity_name, total_amt, raw) values ('r','C1','2026-10-10','A2','Shop',60,'{}'), ('r','C2','2026-11-02','A2','Later',40,'{}')"); + files = [file("amex")]; + // долг сейчас 400, после периода потрачено 40 -> на 31.10 было 360 + parsed.amex = stmt({ accountHint: "9999", accountKind: "credit_card", endingBalance: 360, transactions: [{ date: "2026-10-10", description: "SHOP", amount: 60 }] }); + expect(await run()).toMatchObject({ statements: 1, discrepancies: 0 }); + }); + + it("счёт не определён и период не распознан - расхождение «сверка не выполнена»", async () => { + files = [file("x"), file("y")]; + parsed.x = stmt({ accountHint: "0000" }); + parsed.y = stmt({ periodStart: null }); + const r = await run(); + expect(r.discrepancies).toBe(2); + const text = (await disc()).map((x) => x.description).join("\n"); + expect(text).toContain("счёт QuickBooks не найден"); + expect(text).toContain("Период выписки не распознан"); + }); + + it("ошибка чтения не роняет остальные файлы; файл с ошибкой повторяется", async () => { + files = [file("bad"), file("oct")]; + parsed.bad = new Error("PDF не читается"); + parsed.oct = stmt({ endingBalance: 9200, transactions: [{ date: "2026-10-05", description: "HD", amount: 100 }, { date: "2026-10-15", description: "L", amount: 70 }] }); + const r = await run(); + expect(r).toMatchObject({ statements: 1, errors: 1 }); + expect(posted[0]!.text).toContain("не удалось прочитать"); + expect((await db.pool.query("select message_id, result from acc_mail_processed order by 1")).rows).toEqual([ + { message_id: "statement:bad", result: "error" }, { message_id: "statement:oct", result: "statement" }, + ]); + parsed.bad = stmt({ endingBalance: 9200, transactions: [{ date: "2026-10-05", description: "HD", amount: 100 }, { date: "2026-10-15", description: "L", amount: 70 }] }); + const r2 = await run(); + expect(r2).toMatchObject({ statements: 1, errors: 0, skipped: 1 }); + }); + + it("без новых выписок в Slack ничего не уходит", async () => { + expect(await run()).toEqual({ statements: 0, discrepancies: 0, errors: 0, skipped: 0 }); + expect(posted).toHaveLength(0); + }); +}); diff --git a/packages/accounting_automation/src/reconcile.ts b/packages/accounting_automation/src/reconcile.ts new file mode 100644 index 0000000..cd51913 --- /dev/null +++ b/packages/accounting_automation/src/reconcile.ts @@ -0,0 +1,311 @@ +import { createHash } from "node:crypto"; +import { mkdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { withTx, type Logger, type Pool } from "khb_common"; +import type { ClaudeRunner } from "./claude-runner.js"; +import { parseAmount } from "./invoices-mail.js"; +import type { SlackPoster } from "./slack.js"; + +/** + * Процесс «Ежемесячная сверка банковских счетов» (шаги 3-4, задание `reconcile-monthly`): + * PDF выписки из Google Drive (папка «Выписки») -> Claude извлекает конечный остаток и операции -> сравнение с зеркалом + * QuickBooks (qbo_account, qbo_purchase) -> расхождения в acc_discrepancies (kind statement_vs_qbo) -> отчёт Анастасии в Slack. + * + * Ограничения: в зеркале только расходы (Purchase). Поэтому сверяются расходные операции выписки (списания, платежи по карте), + * а остаток на конец периода восстанавливается из текущего остатка счёта вычитанием расходов после периода (приближённо: + * поступления и переводы после периода зеркало не знает, расхождение остатка - повод посмотреть, а не диагноз). + */ + +export interface StatementTxn { + date: string; // YYYY-MM-DD + description: string; + /** Положительная - расход (списание, покупка по карте), отрицательная - поступление, возврат. */ + amount: number; +} +export interface ParsedStatement { + bank: string | null; + /** Последние цифры номера счёта или карты, либо название счёта, как в выписке. */ + accountHint: string | null; + accountKind: "bank" | "credit_card" | null; + periodStart: string | null; + periodEnd: string | null; + /** Конечный остаток; для кредитной карты - сумма задолженности (положительная). */ + endingBalance: number | null; + transactions: StatementTxn[]; +} + +export interface StatementFile { + id: string; + name: string; + getBytes(): Promise; +} +/** Источник выписок (в боевом режиме - Drive); в тестах подменяется. */ +export interface StatementSource { + list(): Promise; +} +/** Чтение PDF выписки (в боевом режиме - Claude); в тестах подменяется. */ +export interface StatementReader { + read(file: { name: string; bytes: Buffer }): Promise; +} + +// ----------------------------------------------------------------- Claude + +export function buildStatementPrompt(pdfPath: string): string { + return [ + "Ты читаешь банковскую выписку (PDF) строительной компании.", + `Прочитай файл ${pdfPath} и верни ТОЛЬКО один JSON-объект, без пояснений и без markdown.`, + "Поля JSON:", + "- bank: название банка", + "- account_hint: последние 4 цифры номера счёта или карты (строкой) или название счёта, как в выписке", + '- account_kind: "bank" (расчётный счёт) или "credit_card" (кредитная карта)', + "- period_start, period_end: границы периода выписки, YYYY-MM-DD", + "- ending_balance: конечный остаток на конец периода, число в долларах; для кредитной карты - сумма задолженности (положительное число)", + '- transactions: все операции периода [{"date": "YYYY-MM-DD", "description": "описание", "amount": число}]; amount положительное для расходов (списания со счёта, покупки и платежи по карте), отрицательное для поступлений и возвратов', + "Если значение не найдено, ставь null (не выдумывай).", + ].join("\n"); +} + +const str = (v: unknown): string | null => (typeof v === "string" && v.trim() ? v.trim() : null); +const isoDate = (v: unknown): string | null => { + if (typeof v !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(v)) return null; + const d = new Date(`${v}T00:00:00Z`); + return Number.isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== v ? null : v; +}; + +export function parseStatement(stdout: string): ParsedStatement { + const a = stdout.indexOf("{"); + const b = stdout.lastIndexOf("}"); + if (a < 0 || b <= a) throw new Error("агент не вернул JSON"); + let j: Record; + try { + j = JSON.parse(stdout.slice(a, b + 1)) as Record; + } catch (e) { + throw new Error(`агент вернул невалидный JSON: ${(e as Error).message}`); + } + const txns: StatementTxn[] = []; + if (Array.isArray(j.transactions)) { + for (const t of j.transactions) { + if (!t || typeof t !== "object") continue; + const r = t as Record; + const date = isoDate(r.date); + const amount = parseAmount(r.amount); + if (date && amount !== null) txns.push({ date, description: str(r.description) ?? "", amount }); + } + } + const kind = j.account_kind === "bank" || j.account_kind === "credit_card" ? j.account_kind : null; + const hint = typeof j.account_hint === "number" ? String(j.account_hint) : str(j.account_hint); + return { bank: str(j.bank), accountHint: hint, accountKind: kind, periodStart: isoDate(j.period_start), periodEnd: isoDate(j.period_end), endingBalance: parseAmount(j.ending_balance), transactions: txns }; +} + +export function makeClaudeStatementReader(o: { claude: ClaudeRunner; tmpDir?: string }): StatementReader { + return { + async read({ name, bytes }) { + const dir = join(o.tmpDir ?? tmpdir(), `acc-statement-${createHash("sha1").update(`${name}${Date.now()}${Math.random()}`).digest("hex").slice(0, 12)}`); + await mkdir(dir, { recursive: true }); + try { + const path = join(dir, "statement.pdf"); + await writeFile(path, bytes); + const res = await o.claude({ prompt: buildStatementPrompt(path), cwd: dir }); + if (!res.ok) throw new Error(`Claude не отработал (код ${res.exitCode}${res.timedOut ? ", таймаут" : ""}): ${res.stderr.slice(0, 200)}`); + return parseStatement(res.stdout); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }, + }; +} + +// ----------------------------------------------------------------- сверка + +export interface Finding { + description: string; + amountDiff: number | null; + qboRef: string | null; +} + +interface Purchase { + id: string; + txn_date: string; + total_amt: number; + entity_name: string | null; +} + +const DAY = 86_400_000; +const dayDiff = (a: string, b: string): number => Math.abs(Math.round((Date.parse(`${a}T00:00:00Z`) - Date.parse(`${b}T00:00:00Z`)) / DAY)); +const money = (n: number): string => n.toFixed(2); +const cents = (n: number): number => Math.round(n * 100); + +/** Чистое сравнение операций выписки (расходы) с расходами QuickBooks: пропущенные, лишние и возможные дубли. */ +export function compareTransactions(stmtTxns: StatementTxn[], purchases: Purchase[], start: string, end: string, tolDays: number): Finding[] { + const out: Finding[] = []; + const outflows = stmtTxns.filter((t) => t.amount > 0 && t.date >= start && t.date <= end).sort((a, b) => a.date.localeCompare(b.date)); + const used = new Set(); + const matched: Purchase[] = []; + for (const t of outflows) { + let best: Purchase | null = null; + let bestD = Infinity; + for (const p of purchases) { + if (used.has(p.id) || cents(p.total_amt) !== cents(t.amount)) continue; + const d = dayDiff(p.txn_date, t.date); + if (d <= tolDays && d < bestD) { + best = p; + bestD = d; + } + } + if (best) { + used.add(best.id); + matched.push(best); + } else out.push({ description: `Операция из выписки не найдена в QuickBooks: ${t.date} ${t.description} ${money(t.amount)}`.trim(), amountDiff: t.amount, qboRef: null }); + } + for (const p of purchases) { + if (used.has(p.id) || p.txn_date < start || p.txn_date > end) continue; + const dup = matched.find((q) => cents(q.total_amt) === cents(p.total_amt) && dayDiff(q.txn_date, p.txn_date) <= tolDays); + out.push({ + description: dup + ? `Возможный дубль в QuickBooks: ${p.txn_date} ${p.entity_name ?? ""} ${money(p.total_amt)} (такая же операция ${dup.id} уже сверена с выпиской)`.replace(/\s+/g, " ") + : `Операция есть в QuickBooks, но нет в выписке: ${p.txn_date} ${p.entity_name ?? ""} ${money(p.total_amt)}`.replace(/\s+/g, " "), + amountDiff: p.total_amt, + qboRef: p.id, + }); + } + return out; +} + +export interface ReconcileDeps { + pool: Pool; + source: StatementSource; + reader: StatementReader; + slack: SlackPoster; + channelId: string; + realmId: () => Promise; + log?: Logger; + /** Допуск по датам операций, дней (по умолчанию 3). */ + toleranceDays?: number; + /** Сколько строк расхождений показывать в отчёте на выписку (по умолчанию 15). */ + reportLines?: number; +} + +export interface ReconcileResult { + statements: number; + discrepancies: number; + errors: number; + skipped: number; +} + +interface Account { + id: string; + name: string; + account_type: string | null; + current_balance: number | null; +} + +async function findAccount(pool: Pool, realm: string, s: ParsedStatement): Promise<{ account?: Account; problem?: string }> { + const hint = s.accountHint ?? ""; + const digits = hint.replace(/\D/g, ""); + const { rows } = await pool.query( + `select id, name, account_type, current_balance::float8 as current_balance from qbo_account + where realm_id = $1 and active and account_type in ('Bank', 'Credit Card')`, + [realm], + ); + const cand = rows.filter((a) => { + const hay = `${a.name} ${a.id}`.toLowerCase(); + if (digits.length >= 3) return hay.includes(digits.slice(-4)); + return hint.length >= 3 && hay.includes(hint.toLowerCase()); + }); + const typed = s.accountKind ? cand.filter((a) => (s.accountKind === "credit_card") === (a.account_type === "Credit Card")) : cand; + const use = typed.length ? typed : cand; + if (use.length === 1) return { account: use[0] }; + return { problem: use.length === 0 ? `счёт QuickBooks не найден по выписке (${s.bank ?? "банк ?"}, «${hint || "номер не распознан"}»)` : `счёт QuickBooks неоднозначен (${use.map((a) => a.name).join("; ")})` }; +} + +async function reconcileOne(deps: ReconcileDeps, file: StatementFile, parsed: ParsedStatement): Promise<{ findings: Finding[]; header: string }> { + const { pool } = deps; + const tol = deps.toleranceDays ?? 3; + const header = `${file.name} (${parsed.bank ?? "банк ?"}, ${parsed.accountHint ?? "счёт ?"}, ${parsed.periodStart ?? "?"} - ${parsed.periodEnd ?? "?"})`; + const findings: Finding[] = []; + if (!parsed.periodStart || !parsed.periodEnd) { + return { header, findings: [{ description: "Период выписки не распознан: сверку нужно сделать вручную", amountDiff: null, qboRef: null }] }; + } + const realm = await deps.realmId(); + const { account, problem } = await findAccount(pool, realm, parsed); + if (!account) return { header, findings: [{ description: `Сверка не выполнена: ${problem}`, amountDiff: null, qboRef: null }] }; + + const { rows: purchases } = await pool.query( + `select id, to_char(txn_date, 'YYYY-MM-DD') as txn_date, total_amt::float8 as total_amt, entity_name from qbo_purchase + where realm_id = $1 and account_id = $2 and txn_date between ($3::date - $5::int) and ($4::date + $5::int)`, + [realm, account.id, parsed.periodStart, parsed.periodEnd, tol], + ); + findings.push(...compareTransactions(parsed.transactions, purchases, parsed.periodStart, parsed.periodEnd, tol)); + if (parsed.transactions.length === 0) findings.push({ description: "В выписке не распознано ни одной операции: проверьте чтение файла", amountDiff: null, qboRef: null }); + + if (parsed.endingBalance !== null && account.current_balance !== null) { + const { rows: after } = await pool.query<{ s: number }>( + "select coalesce(sum(total_amt), 0)::float8 as s from qbo_purchase where realm_id = $1 and account_id = $2 and txn_date > $3::date", + [realm, account.id, parsed.periodEnd], + ); + const spentAfter = after[0]!.s; + const card = account.account_type === "Credit Card"; + const qboEnd = card ? account.current_balance - spentAfter : account.current_balance + spentAfter; + const diff = Math.round((parsed.endingBalance - qboEnd) * 100) / 100; + if (Math.abs(diff) > 0.01) { + findings.push({ + description: `Конечный остаток не сходится: в выписке ${money(parsed.endingBalance)}, в QuickBooks на ${parsed.periodEnd} около ${money(qboEnd)} (счёт «${account.name}»; расчёт приближённый: в зеркале только расходы)`, + amountDiff: diff, + qboRef: account.id, + }); + } + } + return { header, findings }; +} + +export async function runMonthlyReconcile(deps: ReconcileDeps): Promise { + const res: ReconcileResult = { statements: 0, discrepancies: 0, errors: 0, skipped: 0 }; + const { pool } = deps; + const blocks: string[] = []; + const files = await deps.source.list(); + for (const f of files) { + const marker = `statement:${f.id}`; + const prev = await pool.query<{ result: string }>("select result from acc_mail_processed where message_id = $1", [marker]); + if (prev.rows[0] && prev.rows[0].result !== "error") { + res.skipped++; + continue; + } + try { + const parsed = await deps.reader.read({ name: f.name, bytes: await f.getBytes() }); + const { header, findings } = await reconcileOne(deps, f, parsed); + await withTx(pool, async (c) => { + for (const x of findings) { + await c.query("insert into acc_discrepancies (kind, qbo_ref, description, amount_diff) values ('statement_vs_qbo', $1, $2, $3)", [ + x.qboRef, + `[${f.name}] ${x.description}`, + x.amountDiff, + ]); + } + await c.query( + `insert into acc_mail_processed (message_id, result, details) values ($1, 'statement', $2::jsonb) + on conflict (message_id) do update set result = 'statement', details = excluded.details, processed_at = now()`, + [marker, JSON.stringify({ file: f.name, discrepancies: findings.length, transactions: parsed.transactions.length })], + ); + }); + res.statements++; + res.discrepancies += findings.length; + const shown = findings.slice(0, deps.reportLines ?? 15).map((x) => ` - ${x.description}`); + const more = findings.length > shown.length ? [` ...и ещё ${findings.length - shown.length} (таблица acc_discrepancies)`] : []; + blocks.push([`Выписка ${header}: ${findings.length === 0 ? "расхождений нет" : `расхождений ${findings.length}`}`, ...shown, ...more].join("\n")); + } catch (e) { + res.errors++; + deps.log?.error({ err: String(e), file: f.name }, "ошибка сверки выписки"); + await pool.query( + `insert into acc_mail_processed (message_id, result, details) values ($1, 'error', $2::jsonb) + on conflict (message_id) do update set result = 'error', details = excluded.details, processed_at = now()`, + [marker, JSON.stringify({ file: f.name, message: (e as Error).message })], + ); + blocks.push(`Выписка ${f.name}: не удалось прочитать или сверить (${(e as Error).message.slice(0, 200)}); повтор при следующем запуске`); + } + } + if (blocks.length) { + await deps.slack.post(deps.channelId, `Ежемесячная сверка банковских счетов. Расхождения записаны в acc_discrepancies; закрывает месяц в QuickBooks Анастасия.\n\n${blocks.join("\n\n")}`); + } + return res; +} diff --git a/packages/accounting_automation/src/settings.ts b/packages/accounting_automation/src/settings.ts index 73dd2de..071538d 100644 --- a/packages/accounting_automation/src/settings.ts +++ b/packages/accounting_automation/src/settings.ts @@ -37,7 +37,27 @@ export const accountingSchema = z.object({ rootFolderId: z.string().optional(), }) .optional(), - slack: z.object({ botToken: z.string(), accountingChannelId: z.string() }).optional(), + slack: z + .object({ + botToken: z.string(), + accountingChannelId: z.string(), + /** Куда слать отчёты Анастасии (сверка, разбор правок, fraud): канал или её user id; не задан - канал бухгалтерии. */ + reportChannelId: z.string().optional(), + }) + .optional(), + /** Этап 2: страховые сертификаты, сверка выписок. */ + stage2: z + .object({ + /** Документ Google Docs «Шаблон запроса сертификата» (плейсхолдеры {{vendor}}, {{valid_until}}); не задан - встроенный текст. */ + certificateTemplateDocId: z.string().optional(), + /** Отправлять запросы сертификатов без подтверждения Юли (включает Анастасия; по умолчанию нет). */ + certificateAutoSend: z.boolean().default(false), + /** Папка «Выписки» в корне Drive (имя), PDF выписок по счетам и картам. */ + statementsFolder: z.string().default("Выписки"), + /** Сколько дней допускается расхождение дат операции в выписке и QuickBooks. */ + statementDateToleranceDays: z.number().default(3), + }) + .default({}), /** Порог суммы, с которого подтверждает Анастасия (USD). */ approvalThresholdUsd: z.number().default(5000), /** Красные флажки fraud по операциям с карты: множитель к медиане прошлых платежей вендору и минимум платежей в истории. */ diff --git a/packages/accounting_automation/src/stage2-api.test.ts b/packages/accounting_automation/src/stage2-api.test.ts new file mode 100644 index 0000000..9698cee --- /dev/null +++ b/packages/accounting_automation/src/stage2-api.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from "vitest"; +import type { Pool } from "khb_common"; +import { buildApi, JOB_NAMES, type JobHandlers } from "./http-api.js"; + +const settings = { http: { host: "127.0.0.1", port: 0, token: "svc-token" }, reviewers: [], mcp: { enabled: false, staticTokens: [] } }; +const auth = { authorization: "Bearer svc-token" }; +const base: JobHandlers = { + "invoices-mail": async () => 1, + finalize: async () => 1, + categorize: async () => 1, + summary: async () => 1, +}; + +describe("задания этапа 2 в служебном API", () => { + it("JOB_NAMES содержит новые задания", () => { + expect(JOB_NAMES).toEqual(expect.arrayContaining(["certificates", "reconcile-monthly", "history-weekly", "fraud-weekly"])); + }); + + it("зарегистрированное задание запускается, не зарегистрированное - 404", async () => { + const calls: string[] = []; + const app = buildApi({ + pool: {} as Pool, + settings, + jobs: { ...base, certificates: async () => { calls.push("certificates"); return { vendorsChecked: 2 }; }, "history-weekly": async () => { calls.push("history"); return { sent: true }; } }, + }); + const r = await app.inject({ method: "POST", url: "/jobs/certificates?wait=true", headers: auth }); + expect(r.statusCode).toBe(200); + expect(r.json()).toEqual({ job: "certificates", result: { vendorsChecked: 2 } }); + expect((await app.inject({ method: "POST", url: "/jobs/history-weekly?wait=true", headers: auth })).statusCode).toBe(200); + expect((await app.inject({ method: "POST", url: "/jobs/fraud-weekly", headers: auth })).statusCode).toBe(404); + expect((await app.inject({ method: "POST", url: "/jobs/reconcile-monthly", headers: auth })).statusCode).toBe(404); + expect(calls).toEqual(["certificates", "history"]); + }); + + it("ошибка нового задания - 502, как у остальных", async () => { + const app = buildApi({ pool: {} as Pool, settings, jobs: { ...base, "reconcile-monthly": async () => { throw new Error("Drive недоступен"); } } }); + const r = await app.inject({ method: "POST", url: "/jobs/reconcile-monthly?wait=true", headers: auth }); + expect(r.statusCode).toBe(502); + expect(r.json().message).toContain("Drive недоступен"); + }); + + it("ручки chargeback закрыты токеном и проверяют вход до обращения к БД", async () => { + const app = buildApi({ pool: {} as Pool, settings, jobs: base }); + expect((await app.inject({ method: "POST", url: "/chargeback/start", payload: {} })).statusCode).toBe(401); + const bad = await app.inject({ method: "POST", url: "/chargeback/find", headers: auth, payload: {} }); + expect(bad.statusCode).toBe(400); + expect(bad.json()).toMatchObject({ error: "bad_request" }); + expect((await app.inject({ method: "POST", url: "/chargeback/add-log", headers: auth, payload: { chargeback_id: "zz" } })).statusCode).toBe(400); + }); +}); diff --git a/packages/accounting_automation/src/stage2-tool-defs.ts b/packages/accounting_automation/src/stage2-tool-defs.ts new file mode 100644 index 0000000..eb71732 --- /dev/null +++ b/packages/accounting_automation/src/stage2-tool-defs.ts @@ -0,0 +1,76 @@ +/** Описания MCP-инструментов этапа 2 (отдельный файл без зависимостей от mcp.ts: нет циклического импорта). */ +type Json = Record; + +const obj = (properties: Json, required: string[] = []): Json => ({ type: "object", properties, required, additionalProperties: false }); +const idP = { type: "string", description: "id строки chargeback (первые 8+ символов или полный uuid) либо id её задачи из acc_review_list" }; +const write = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }; + +export const STAGE2_TOOLS: { name: string; description: string; inputSchema: Json; annotations?: Json }[] = [ + { + name: "acc_certificate_request_approve", + annotations: write, + description: + "Юля (accountant): подтвердить отправку подрядчику запроса нового страхового сертификата по задаче вида certificate. Письмо готовится по шаблону при ближайшем ежедневном запуске (отправляется в JobTread; если автоотправки нет, Юля получит текст для ручной отправки), повторный запрос уйдёт через 5 дней, если сертификата нет.", + inputSchema: obj({ id: { type: "string", description: "id задачи-сертификата: первые 8 символов из acc_review_list (или полный uuid)" } }, ["id"]), + }, + { + name: "acc_chargeback_list", + annotations: { readOnlyHint: true, openWorldHint: false }, + description: + "Дела chargeback (к контракту подрядчика) и fraud по карте. По умолчанию незакрытые. Для каждого контракта видны сумма, удержания, оплачено и остаток. Используй при разборе инвойса подрядчика Б (есть ли одобренный chargeback на этом проекте: project_customer_id) и для вопросов про дефекты и удержания.", + inputSchema: obj({ + kind: { type: "string", enum: ["contract", "card_fraud"] }, + status: { type: "string", description: "contract: claimed, approved, fix_invoiced, applied, rejected, closed; card_fraud: collecting, filed, refunded, rejected, closed" }, + project_customer_id: { type: "string", description: "проект QuickBooks (id клиента-проекта)" }, + include_closed: { type: "boolean" }, + }), + }, + { + name: "acc_contract_balance", + annotations: { readOnlyHint: true, openWorldHint: false }, + description: "Остаток к оплате по контракту подрядчика с учётом удержаний: сумма контракта - удержания - уже оплачено. По названию подрядчика (часть названия) и, при необходимости, проекту.", + inputSchema: obj({ vendor_name: { type: "string" }, contract_id: { type: "string" }, project_customer_id: { type: "string" } }), + }, + { + name: "acc_chargeback_decide", + annotations: write, + description: + "Анастасия (cfo), chargeback к контракту, шаг 4: решение по дефекту. decision=approve - нанять другого подрядчика (fix_vendor_name) и удержать его стоимость с подрядчика А; reject - отклонить (строка закрывается, comment - причина). Только для статуса claimed.", + inputSchema: obj({ id: idP, decision: { type: "string", enum: ["approve", "reject"] }, fix_vendor_name: { type: "string", description: "подрядчик Б, исправляющий дефект" }, comment: { type: "string" } }, ["id", "decision"]), + }, + { + name: "acc_chargeback_link_invoice", + annotations: write, + description: + "Юля, chargeback к контракту, шаг 6: привязать к одобренному chargeback инвойс подрядчика Б из acc_invoices (invoice_id, он же id записи реестра инвойсов) и сумму удержания (по умолчанию весь инвойс; не больше суммы инвойса). Статус станет fix_invoiced, задача уйдёт Анастасии на подтверждение суммы.", + inputSchema: obj({ id: idP, invoice_id: { type: "string", description: "uuid инвойса в acc_invoices" }, retained_amount: { type: "number", description: "сумма удержания, USD; по умолчанию сумма инвойса" } }, ["id", "invoice_id"]), + }, + { + name: "acc_chargeback_confirm", + annotations: write, + description: + "Анастасия (cfo), chargeback к контракту, шаг 7: подтвердить сумму удержания (можно исправить retained_amount). Статус applied; остаток по контракту пересчитывается автоматически: сумма контракта - удержания - оплачено. Дальше Юля сообщает подрядчику А в JobTread.", + inputSchema: obj({ id: idP, retained_amount: { type: "number", description: "исправленная сумма удержания, если отличается" } }, ["id"]), + }, + { + name: "acc_chargeback_close", + annotations: write, + description: "Анастасия (cfo): закрыть строку chargeback или fraud вручную с причиной (раньше автоматического закрытия по остатку контракта).", + inputSchema: obj({ id: idP, reason: { type: "string" } }, ["id", "reason"]), + }, + { + name: "acc_fraud_create", + annotations: write, + description: + "Fraud по карте: завести дело по операции ленты банка (feed_txn_id из acc_review_list). Собирается комплект: операция из разбора, чек или отметка «чека нет». Повторный вызов по той же операции вернёт существующее дело. После этого Юля подаёт заявку в банке (вне системы).", + inputSchema: obj({ feed_txn_id: { type: "string" }, reason: { type: "string", description: "чужое, дубль, товар не получен, неверная сумма" }, bank: { type: "string" }, file_by: { type: "string", description: "срок подачи YYYY-MM-DD" } }, ["feed_txn_id"]), + }, + { + name: "acc_fraud_update", + annotations: write, + description: "Fraud по карте: сменить статус (collecting -> filed -> refunded или rejected -> closed) и записать решение банка. Если банк вернул деньги, возврат придёт в ленту QuickBooks и пройдёт обычную категоризацию.", + inputSchema: obj({ id: idP, status: { type: "string", enum: ["filed", "refunded", "rejected", "closed"] }, bank_decision: { type: "string" }, bank: { type: "string" }, file_by: { type: "string" } }, ["id", "status"]), + }, +]; + +export const STAGE2_TOOL_NAMES = new Set(STAGE2_TOOLS.map((t) => t.name)); diff --git a/packages/accounting_automation/src/stage2-tools.ts b/packages/accounting_automation/src/stage2-tools.ts new file mode 100644 index 0000000..7b85a2b --- /dev/null +++ b/packages/accounting_automation/src/stage2-tools.ts @@ -0,0 +1,90 @@ +import type { Pool } from "khb_common"; +import { + ChargebackError, closeChargebackManually, confirmChargeback, contractBalance, createFraud, decideChargeback, linkFixInvoice, listChargebacks, setFraudStatus, +} from "./chargeback.js"; +import { McpToolError, type ReviewRole } from "./mcp.js"; + +/** + * MCP-инструменты этапа 2 для Юли (accountant) и Анастасии (cfo): сертификаты подрядчиков, chargeback к контракту, fraud по карте. + * Подключаются в ReviewTools.call (mcp.ts); проверка роли - здесь. + */ + +type Json = Record; + +export interface Stage2Deps { + pool: Pool; + rolesOf: (personId: string) => ReviewRole[]; + now: () => Date; +} + +export class Stage2Tools { + constructor(private readonly d: Stage2Deps) {} + + private need(personId: string, role?: ReviewRole): ReviewRole[] { + const roles = this.d.rolesOf(personId); + if (role && !roles.includes(role)) throw new McpToolError(`Нужна роль ${role}.`); + return roles; + } + + /** acc_certificate_request_approve: Юля подтверждает отправку запроса нового сертификата подрядчику (процесс «Страховые сертификаты», шаг 4). */ + private async approveRequest(personId: string, a: Json): Promise { + this.need(personId, "accountant"); + const v = a.id; + if (typeof v !== "string" || !/^[0-9a-f]{8,}(-[0-9a-f-]+)?$/i.test(v)) throw new McpToolError("id: первые 8 символов (или полный uuid) задачи-сертификата из acc_review_list"); + const like = `${v.toLowerCase()}%`; + const { rows } = await this.d.pool.query( + `select r.id, r.vendor_name, r.request_count, r.request_approved_at, r.done from acc_certificates_review r + where r.id::text like $1 or r.id in (select ref_id::uuid from acc_manual_review where ref_table = 'acc_certificates_review' and id::text like $1) limit 2`, + [like], + ); + if (rows.length === 0) throw new McpToolError("Задача по сертификату не найдена (возможно, уже завершена)."); + if (rows.length > 1) throw new McpToolError("Префикс id неоднозначен: укажите больше символов."); + const r = rows[0] as { id: string; vendor_name: string; request_count: number; request_approved_at: Date | null; done: boolean }; + if (r.done) throw new McpToolError("Запись уже отмечена выполненной."); + if (r.request_approved_at) return { ok: true, message: `Отправка запроса подрядчику ${r.vendor_name} уже подтверждена ранее.`, request_count: r.request_count }; + await this.d.pool.query("update acc_certificates_review set request_approved_by = $2, request_approved_at = $3 where id = $1", [r.id, personId, this.d.now()]); + return { ok: true, message: `Запрос нового сертификата подрядчику ${r.vendor_name} подтверждён: он будет подготовлен при ближайшем ежедневном запуске.`, vendor_name: r.vendor_name }; + } + + private async call2(personId: string, name: string, a: Json): Promise { + switch (name) { + case "acc_certificate_request_approve": + return this.approveRequest(personId, a); + case "acc_chargeback_list": + this.need(personId); + return { ...(await listChargebacks(this.d.pool, a)) }; + case "acc_contract_balance": + this.need(personId); + return { ...(await contractBalance(this.d.pool, a)) }; + case "acc_chargeback_decide": + this.need(personId, "cfo"); + return { ok: true, chargeback: await decideChargeback(this.d.pool, personId, a) }; + case "acc_chargeback_link_invoice": + this.need(personId); + return { ok: true, chargeback: await linkFixInvoice(this.d.pool, personId, a) }; + case "acc_chargeback_confirm": + this.need(personId, "cfo"); + return { ok: true, chargeback: await confirmChargeback(this.d.pool, personId, a) }; + case "acc_chargeback_close": + this.need(personId, "cfo"); + return { ok: true, chargeback: await closeChargebackManually(this.d.pool, a) }; + case "acc_fraud_create": + this.need(personId); + return { ok: true, ...(await createFraud(this.d.pool, personId, a)) }; + case "acc_fraud_update": + this.need(personId); + return { ok: true, chargeback: await setFraudStatus(this.d.pool, a) }; + default: + throw new McpToolError(`Неизвестный инструмент ${name}`); + } + } + + async call(personId: string, name: string, a: Json): Promise { + try { + return await this.call2(personId, name, a); + } catch (e) { + if (e instanceof ChargebackError) throw new McpToolError(e.message); + throw e; + } + } +} diff --git a/packages/accounting_automation/src/vendor-name.ts b/packages/accounting_automation/src/vendor-name.ts new file mode 100644 index 0000000..df3a903 --- /dev/null +++ b/packages/accounting_automation/src/vendor-name.ts @@ -0,0 +1,14 @@ +/** Имя вендора для сравнения (общее для инвойсов, сертификатов и сверок). */ +const COMPANY_SUFFIX = new Set(["llc", "inc", "corp", "co", "ltd", "company", "corporation", "incorporated", "lp", "llp", "pllc"]); + +/** Регистр, знаки, юридические суффиксы. */ +export function normalizeVendorName(s: string | null | undefined): string { + const words = (s ?? "") + .toLowerCase() + .replace(/&/g, " and ") + .replace(/[^a-z0-9а-яё]+/g, " ") + .split(" ") + .filter(Boolean); + while (words.length > 1 && COMPANY_SUFFIX.has(words[words.length - 1]!)) words.pop(); + return words.join(" "); +} diff --git a/packages/khb_common/migrations/061_acc_certificates_stage2.sql b/packages/khb_common/migrations/061_acc_certificates_stage2.sql new file mode 100644 index 0000000..81614e3 --- /dev/null +++ b/packages/khb_common/migrations/061_acc_certificates_stage2.sql @@ -0,0 +1,20 @@ +-- Этап 2, страховые сертификаты подрядчиков (процесс «Страховые сертификаты подрядчиков»): только добавления. +-- Описание: docs/proposed/data_objects/accounting_automation/acc_certificates_review.md, acc_invoices.md. + +-- Отметка «нет страховки» в реестре инвойсов (шаг 6): ставит ежедневное задание certificates, согласование не блокирует. +alter table acc_invoices add column if not exists no_insurance boolean not null default false; + +-- Колонки разбора сертификата; _original и _history получают те же колонки в том же порядке (триггер копирует строку целиком). +do $$ +declare + t text; +begin + foreach t in array array['acc_certificates_review', 'acc_certificates_review_original', 'acc_certificates_review_history'] loop + execute format('alter table %I add column if not exists alert_kind text', t); -- expiring_30, expiring_5, expired, missing, new_certificate + execute format('alter table %I add column if not exists drive_file_id text', t); -- файл, если срок не распознан и записи в acc_insurance_certificates ещё нет + execute format('alter table %I add column if not exists request_count smallint not null default 0', t); + execute format('alter table %I add column if not exists request_approved_by text', t); -- кто подтвердил отправку запроса подрядчику + execute format('alter table %I add column if not exists request_approved_at timestamptz', t); + execute format('alter table %I add column if not exists request_log jsonb', t); -- журнал запросов: [{at, delivered, channel, text}] + end loop; +end $$; diff --git a/packages/khb_common/migrations/062_acc_chargeback_contract.sql b/packages/khb_common/migrations/062_acc_chargeback_contract.sql new file mode 100644 index 0000000..0bb13ba --- /dev/null +++ b/packages/khb_common/migrations/062_acc_chargeback_contract.sql @@ -0,0 +1,82 @@ +-- Этап 2: chargeback к контракту подрядчика и fraud по карте (процессы «Chargeback к контракту подрядчика», «Подозрительные операции по карте (fraud)»). +-- Расширяет acc_chargeback (только добавления; ограничение статуса заменяется более широким). Описание: data_objects/accounting_automation/acc_chargeback.md, acc_contracts.md. + +alter table acc_chargeback add column if not exists kind text not null default 'card_fraud'; +alter table acc_chargeback alter column feed_txn_id drop not null; +alter table acc_chargeback alter column reason drop not null; + +alter table acc_chargeback add column if not exists contract_id uuid references acc_contracts (id); +alter table acc_chargeback add column if not exists defect_daily_log_id text; +alter table acc_chargeback add column if not exists defect_daily_log_url text; +alter table acc_chargeback add column if not exists defect_description text; +alter table acc_chargeback add column if not exists extra_daily_logs text[] not null default '{}'; +alter table acc_chargeback add column if not exists reported_by uuid references person (id); +alter table acc_chargeback add column if not exists decided_by uuid references person (id); +alter table acc_chargeback add column if not exists decided_at timestamptz; +alter table acc_chargeback add column if not exists fix_vendor_name text; +alter table acc_chargeback add column if not exists fix_invoice_id uuid references acc_invoices (id); +alter table acc_chargeback add column if not exists retained_amount numeric(14,2); +alter table acc_chargeback add column if not exists close_reason text; +alter table acc_chargeback add column if not exists confirmed_by uuid references person (id); +alter table acc_chargeback add column if not exists confirmed_at timestamptz; +-- fraud: комплект документов (операция, чек или отметка «чека нет») и кто завёл +alter table acc_chargeback add column if not exists kit jsonb; +alter table acc_chargeback add column if not exists created_by uuid references person (id); + +alter table acc_chargeback drop constraint if exists acc_chargeback_status_check; +alter table acc_chargeback drop constraint if exists acc_chargeback_kind_status_check; +alter table acc_chargeback add constraint acc_chargeback_kind_status_check check ( + (kind = 'card_fraud' and status in ('collecting', 'filed', 'refunded', 'rejected', 'closed')) + or (kind = 'contract' and status in ('claimed', 'approved', 'fix_invoiced', 'applied', 'rejected', 'closed'))); +alter table acc_chargeback drop constraint if exists acc_chargeback_kind_fields_check; +alter table acc_chargeback add constraint acc_chargeback_kind_fields_check check ( + (kind = 'card_fraud' and feed_txn_id is not null) or (kind = 'contract' and contract_id is not null)); + +-- Один Daily Log - один дефект: повторный запрос ассистента менеджера не создаёт дубль. +create unique index if not exists acc_chargeback_daily_log_uq on acc_chargeback (defect_daily_log_id) where defect_daily_log_id is not null; +create index if not exists acc_chargeback_contract_idx on acc_chargeback (contract_id); +create index if not exists acc_chargeback_fraud_txn_idx on acc_chargeback (feed_txn_id) where kind = 'card_fraud'; + +alter table acc_contracts add column if not exists retained_amount numeric(14,2) not null default 0; + +-- Пересчёт удержаний контракта: сумма retained_amount строк contract в статусе applied; строка, закрытая после подтверждения суммы +-- (confirmed_at заполнено), продолжает учитываться, иначе закрытие в шаге 12 вернуло бы остаток. +create or replace function acc_contract_retained_recalc(p_contract uuid) returns void language plpgsql as $$ +declare + v numeric(14,2); +begin + if p_contract is null then return; end if; + select coalesce(sum(retained_amount), 0) into v from acc_chargeback + where contract_id = p_contract and kind = 'contract' and (status = 'applied' or (status = 'closed' and confirmed_at is not null)); + update acc_contracts set retained_amount = v where id = p_contract and retained_amount is distinct from v; +end $$; + +create or replace function acc_chargeback_after_change() returns trigger language plpgsql as $$ +begin + if tg_op <> 'DELETE' then + perform acc_contract_retained_recalc(new.contract_id); + if new.status = 'closed' then + delete from acc_manual_review where ref_table = 'acc_chargeback' and ref_id = new.id::text; + end if; + end if; + if tg_op = 'DELETE' or (tg_op = 'UPDATE' and old.contract_id is distinct from new.contract_id) then + perform acc_contract_retained_recalc(old.contract_id); + end if; + return null; +end $$; + +drop trigger if exists acc_chargeback_change on acc_chargeback; +create trigger acc_chargeback_change after insert or update or delete on acc_chargeback for each row execute function acc_chargeback_after_change(); + +-- Шаг 12: остаток к оплате (total - retained - paid) исчерпан - строки applied закрываются. +create or replace function acc_contract_settle() returns trigger language plpgsql as $$ +begin + if new.total_amount - new.retained_amount - new.paid_amount <= 0 then + update acc_chargeback set status = 'closed', close_reason = coalesce(close_reason, 'остаток по контракту оплачен') + where contract_id = new.id and kind = 'contract' and status = 'applied'; + end if; + return null; +end $$; + +drop trigger if exists acc_contract_settle_trg on acc_contracts; +create trigger acc_contract_settle_trg after update of total_amount, paid_amount, retained_amount on acc_contracts for each row execute function acc_contract_settle();