accounting_automation, этап 2: страховые сертификаты, сверка выписок, разбор истории правок, chargeback к контракту, fraud

- Миграции 061 (сертификаты: alert_kind, drive_file_id, request_*, acc_invoices.no_insurance) и 062 (acc_chargeback: kind contract|card_fraud,
  колонки contract, триггеры пересчёта acc_contracts.retained_amount и закрытия по остатку).
- Задания certificates, reconcile-monthly, history-weekly, fraud-weekly (JOB_NAMES, main.ts); расписание на сервере не заведено.
- Письма с сертификатами разбирает invoices-mail (document_type certificate); запрос подрядчику - через интерфейс ContractorMessenger
  (пока ручной: текст в request_log, Юля отправляет из JobTread).
- Ручки /chargeback/find|start|close|add-log|fraud для ассистента менеджера; MCP-инструменты acc_chargeback_*, acc_fraud_*,
  acc_contract_balance, acc_certificate_request_approve; очередь показывает задачи вида chargeback.
- Тесты на временной БД (сертификаты, сверка, история правок, chargeback и fraud, служебное API); описание данных в docs/proposed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 16:58:00 +03:00
parent f636836f47
commit 4c99033f13
32 changed files with 2618 additions and 36 deletions

View File

@@ -1,11 +1,15 @@
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";
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";
@@ -47,6 +51,12 @@ async function nonWorkdays(): Promise<ReadonlySet<string>> {
return new Set(rows.map((r) => r.d as string));
}
/** Куда слать отчёты Анастасии (сверка, разбор правок, fraud). */
function reportSlack(): { slack: NonNullable<typeof slack>; 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"));
@@ -87,6 +97,31 @@ const app = buildApi({
log: (msg, extra) => log.warn(extra ?? {}, msg),
}),
}),
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() } });