accounting_automation: сверка инвойсов с QuickBooks (invoice-reconcile), оплата независима от согласования, сумма и вендор из ленты, сводка Анастасии, правки finalize, поиска чека, проверки инвойса, chargeback; документы

Миграция 071: acc_discrepancies.reason и уникальный индекс открытых расхождений, уникальный открытый card_fraud по операции, insurer в разборе сертификатов.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 19:43:58 +03:00
parent 85f781b9fe
commit 74ffe8613b
34 changed files with 999 additions and 85 deletions

View File

@@ -1,5 +1,6 @@
import { readFileSync } from "node:fs";
import { createLogger, createPool, itNotify, loadServiceSettings } from "khb_common";
import { reapplyCategorizationRoles } from "./approval.js";
import { runCategorization } from "./categorize.js";
import { runFraudWeekly } from "./chargeback.js";
import { manualMessenger, runCertificates } from "./certificates.js";
@@ -9,6 +10,7 @@ import { runFinalize } from "./finalize.js";
import { runFraudFlags } from "./fraud.js";
import { runInvoiceCheck } from "./invoice-check.js";
import { runInvoicePaid } from "./invoice-paid.js";
import { runInvoiceReconcile } from "./invoice-reconcile.js";
import { GmailClient } from "./gmail.js";
import { GoogleAuth } from "./google.js";
import { runHistoryWeekly } from "./history-report.js";
@@ -19,7 +21,7 @@ import { runInvoiceIngest } from "./invoices-mail.js";
import { makePromptLoader } from "./prompt-loader.js";
import { accountingSchema } from "./settings.js";
import { createSlackClient } from "./slack.js";
import { postDailySummary } from "./summary.js";
import { postCfoSummary, postDailySummary } from "./summary.js";
import { runReceiptSearch, runReceiptWeeklyReport } from "./receipt-search.js";
import { runReceiptsSlack } from "./receipts.js";
import { loadNonWorkdays } from "./workdays.js";
@@ -86,7 +88,13 @@ const app = buildApi({
});
return runInvoiceIngest({ pool, mail, drive, claude, now: () => new Date(), log });
},
finalize: () => runFinalize({ pool, delaySeconds: s.finalizeDelaySeconds, noReceiptLimitUsd: s.receipts.noReceiptLimitUsd, notify }),
finalize: () => runFinalize({
pool,
delaySeconds: s.finalizeDelaySeconds,
noReceiptLimitUsd: s.receipts.noReceiptLimitUsd,
notify,
notifyPerson: slack ? async (slackUserId, text) => void (await slack.postMessage(slackUserId, text)) : undefined,
}),
categorize: async () =>
runCategorization({
pool,
@@ -103,9 +111,16 @@ const app = buildApi({
log: (msg, extra) => log.warn(extra ?? {}, msg),
}),
}),
"fraud-flags": async () => runFraudFlags(pool, { settings: s.fraud, realmId: await realmId() }),
"fraud-flags": async () => {
const realm = await realmId();
const flags = await runFraudFlags(pool, { settings: s.fraud, realmId: realm });
// роль подтверждающего повторяется для задач, у которых она не проставилась при записи категоризации (идемпотентно)
const roles = await reapplyCategorizationRoles(pool, { threshold: s.approvalThresholdUsd, realmId: realm });
return { ...flags, roles };
},
"invoice-check": () => runInvoiceCheck({ pool }),
"invoice-paid": async () => runInvoicePaid({ pool, realmId: await realmId() }),
"invoice-reconcile": async () => runInvoiceReconcile({ pool, realmId: await realmId() }),
certificates: () =>
runCertificates({
pool,
@@ -133,8 +148,11 @@ const app = buildApi({
"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() } });
return { sent: true, length: text.length };
const options = { nonWorkdays: await nonWorkdays(), mathesarUrl: s.mathesarUrl, bankFeedUrl: s.receipts.qboBankingUrl };
const text = await postDailySummary({ pool, slack, channelId: s.slack.accountingChannelId, tz: "Asia/Nicosia", options });
const cfo = await postCfoSummary({ pool, slack, tz: "Asia/Nicosia", options });
if (!cfo.sent) log.warn({ reason: cfo.reason }, "сводка Анастасии не отправлена");
return { sent: true, length: text.length, cfo };
},
"receipts-slack": async () => {
if (!slack || !drive) throw new Error("не настроены slack (botToken) и google (ключ сервисного аккаунта, rootFolderId)");