Files
khb_microservices/packages/accounting_automation/src/approval.ts
Yuri Yaryshev 74ffe8613b accounting_automation: сверка инвойсов с QuickBooks (invoice-reconcile), оплата независима от согласования, сумма и вендор из ленты, сводка Анастасии, правки finalize, поиска чека, проверки инвойса, chargeback; документы
Миграция 071: acc_discrepancies.reason и уникальный индекс открытых расхождений, уникальный открытый card_fraud по операции, insurer в разборе сертификатов.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 19:43:58 +03:00

66 lines
4.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import type { Pool } from "khb_common";
import { loadOperation, queryVendorHistory, suggestionAmount, vendorOf, type Suggestion } from "./fraud.js";
/**
* Роль подтверждающего задачу категоризации (stage2.md п. 3; processes.md «Категоризация банковских операций», шаг 5):
* cfo (Анастасия) - при сумме операции от порога или первой оплате новому вендору; иначе accountant (Юля).
* Задачу по-прежнему может закрыть и пользователь с ролью accountant+cfo; в acc_manual_review.assignee_role пишется основная роль.
* Сумма и вендор берутся из suggestion (amount, vendor_qbo_id, vendor_name) строки acc_categorization_review;
* если suggestion пусто (агент не дал предложения), - из строки acc_feed_txn (amount, vendor_name).
*/
export type AssigneeRole = "accountant" | "cfo";
export function decideAssigneeRole(i: { amount: number | null; threshold: number; firstPayment: boolean }): { role: AssigneeRole; reason: string | null } {
if (i.amount !== null && Math.abs(i.amount) >= i.threshold) return { role: "cfo", reason: `сумма ${Math.abs(i.amount).toFixed(2)} >= порога ${i.threshold}` };
if (i.firstPayment) return { role: "cfo", reason: "первая оплата новому вендору" };
return { role: "accountant", reason: null };
}
/** Определяет роль и обновляет задачу в acc_manual_review; задачу, уже переданную вручную (роль не accountant), не трогает. */
export async function applyCategorizationRole(
pool: Pool,
feedTxnId: string,
opts: { threshold: number; realmId?: string | null },
): Promise<{ role: AssigneeRole; reason: string | null }> {
const row = (await pool.query("select suggestion from acc_categorization_review where feed_txn_id = $1", [feedTxnId])).rows[0] as { suggestion: Suggestion | null } | undefined;
const s = (await loadOperation(pool, feedTxnId, row?.suggestion ?? null)).suggestion;
const v = vendorOf(s);
let firstPayment = false;
if (v.qboId || v.name) {
const h = await queryVendorHistory(pool, { realmId: opts.realmId, vendorQboId: v.qboId, vendorName: v.name, feedTxnId });
firstPayment = h.priorCount === 0;
}
const decision = decideAssigneeRole({ amount: suggestionAmount(s), threshold: opts.threshold, firstPayment });
if (decision.role === "cfo") {
await pool.query(
"update acc_manual_review set assignee_role = 'cfo' where ref_table = 'acc_categorization_review' and ref_id = $1 and assignee_role = 'accountant'",
[feedTxnId],
);
}
return decision;
}
export interface ReapplyResult {
checked: number;
/** Переданы Анастасии (роль cfo). */
toCfo: number;
}
/**
* Повторно определяет роль для открытых задач категоризации, которые всё ещё у accountant (сбой при записи, поздно пришла строка acc_feed_txn).
* Идемпотентно; задачи, переданные вручную (роль не accountant), не трогает: applyCategorizationRole меняет только accountant -> cfo.
*/
export async function reapplyCategorizationRoles(pool: Pool, opts: { threshold: number; realmId?: string | null }): Promise<ReapplyResult> {
const { rows } = await pool.query<{ feed_txn_id: string }>(
`select r.feed_txn_id from acc_categorization_review r join acc_manual_review m on m.ref_table = 'acc_categorization_review' and m.ref_id = r.feed_txn_id
where not r.done and m.assignee_role = 'accountant' order by r.created_at`,
);
const res: ReapplyResult = { checked: 0, toCfo: 0 };
for (const { feed_txn_id } of rows) {
res.checked++;
if ((await applyCategorizationRole(pool, feed_txn_id, opts)).role === "cfo") res.toCfo++;
}
return res;
}