Миграция 071: acc_discrepancies.reason и уникальный индекс открытых расхождений, уникальный открытый card_fraud по операции, insurer в разборе сертификатов. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
66 lines
4.0 KiB
TypeScript
66 lines
4.0 KiB
TypeScript
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;
|
||
}
|