accounting_automation, этап 2 (часть A): роль cfo по сумме, флажки fraud, проверка и оплата инвойсов

- approval.ts: роль подтверждающего при создании задачи категоризации (порог approvalThresholdUsd, первая оплата вендору)
- fraud.ts: красные флажки по картам (первая оплата, рост суммы от медианы), задание fraud-flags
- invoice-check.ts: заключение по инвойсу и задача invoice_approval; задание invoice-check
- invoice-paid.ts: markPaid и задание invoice-paid (paid_on, paid_amount контракта)
- MCP: acc_invoice_to_approve, acc_invoice_decide; миграция 041; документы proposed

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 16:44:33 +03:00
parent f636836f47
commit 9f8bf1932f
21 changed files with 902 additions and 20 deletions

View File

@@ -0,0 +1,53 @@
import { withTx, type Pool } from "khb_common";
/**
* «Согласование и оплата инвойса», шаг 5 (processes.md): подтверждённая проводка оплаты вендору (qbo_purchase) ->
* инвойс получает stage 'paid', paid_on, qbo_txn_id, а сумма добавляется к paid_amount контракта.
* Сопоставление: согласованный инвойс (stage 'approved'), тот же вендор (qbo id или имя), та же сумма,
* проводка не раньше даты решения и не занята другим инвойсом; берётся самая ранняя.
*/
/** Ставит оплату инвойсу и накапливает paid_amount контракта. Возвращает false, если инвойс уже оплачен или не согласован. */
export async function markPaid(pool: Pool, invoiceId: string, paid: { paidOn: string; qboTxnId: string | null }): Promise<boolean> {
return withTx(pool, async (c) => {
const inv = (await c.query("select amount, contract_id, stage from acc_invoices where id = $1 for update", [invoiceId])).rows[0];
if (!inv || inv.stage !== "approved") return false;
await c.query("update acc_invoices set stage = 'paid', paid_on = $2, qbo_txn_id = $3 where id = $1", [invoiceId, paid.paidOn, paid.qboTxnId]);
if (inv.contract_id) await c.query("update acc_contracts set paid_amount = paid_amount + $2 where id = $1", [inv.contract_id, inv.amount]);
return true;
});
}
export interface InvoicePaidResult {
matched: number;
errors: { id: string; message: string }[];
}
export async function runInvoicePaid(deps: { pool: Pool; realmId?: string | null }): Promise<InvoicePaidResult> {
const res: InvoicePaidResult = { matched: 0, errors: [] };
const { rows } = await deps.pool.query("select id from acc_invoices where stage = 'approved' and paid_on is null order by decided_at nulls last, created_at");
for (const { id } of rows as { id: string }[]) {
try {
const m = (
await deps.pool.query(
`select p.id, p.txn_date::text as txn_date
from acc_invoices i
join qbo_purchase p
on (($2::text is null or p.realm_id = $2::text)
and ((i.vendor_qbo_id is not null and p.entity_id = i.vendor_qbo_id) or lower(p.entity_name) = lower(i.vendor_name))
and p.total_amt = i.amount
and p.txn_date >= coalesce(i.decided_at::date, i.invoice_date))
where i.id = $1
and not exists (select 1 from acc_invoices o where o.qbo_txn_id = p.id and o.id <> i.id)
order by p.txn_date, p.id limit 1`,
[id, deps.realmId ?? null],
)
).rows[0] as { id: string; txn_date: string } | undefined;
if (!m) continue;
if (await markPaid(deps.pool, id, { paidOn: m.txn_date, qboTxnId: m.id })) res.matched++;
} catch (e) {
res.errors.push({ id, message: e instanceof Error ? e.message : String(e) });
}
}
return res;
}