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,19 +1,38 @@
import { withTx, type Pool } from "khb_common";
import { paidWithoutApproval, recordDiscrepancy } from "./invoice-reconcile.js";
/**
* «Согласование и оплата инвойса», шаг 5 (processes.md): подтверждённая проводка оплаты вендору (qbo_purchase) ->
* инвойс получает stage 'paid', paid_on, qbo_txn_id, а сумма добавляется к paid_amount контракта.
* Сопоставление: согласованный инвойс (stage 'approved'), тот же вендор (qbo id или имя), та же сумма,
* проводка не раньше даты решения и не занята другим инвойсом; берётся самая ранняя.
* инвойс получает paid_on и qbo_txn_id, а сумма добавляется к paid_amount контракта.
* «Согласован» и «оплачен» независимы: оплата проставляется инвойсу в любой стадии, кроме rejected, стадия (stage) не меняется.
* Оплата без решения (инвойс не согласован либо оплачен раньше решения) попадает в acc_discrepancies как paid_without_approval.
* Сопоставление: тот же вендор (qbo id или имя), та же сумма, проводка не раньше даты решения (для согласованных)
* или даты инвойса (для остальных) и не занята другим инвойсом; берётся самая ранняя.
*/
/** Ставит оплату инвойсу и накапливает paid_amount контракта. Возвращает false, если инвойс уже оплачен или не согласован. */
/**
* Ставит оплату инвойсу и накапливает paid_amount контракта. Возвращает false, если инвойс уже оплачен, отклонён или не найден.
* Стадию не меняет. Оплата без решения записывается в acc_discrepancies.
*/
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]);
const inv = (
await c.query(
"select amount, contract_id, stage, paid_on, vendor_name, invoice_number, decided_at::text as decided_at from acc_invoices where id = $1 for update",
[invoiceId],
)
).rows[0];
if (!inv || inv.stage === "rejected" || inv.paid_on || inv.stage === "paid") return false;
await c.query("update acc_invoices set 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]);
const why = paidWithoutApproval({ stage: inv.stage, paid_on: paid.paidOn, decided_at: inv.decided_at });
if (why)
await recordDiscrepancy(c, {
invoiceId,
reason: "paid_without_approval",
description: `Оплата без решения: ${inv.vendor_name}${inv.invoice_number ? ` №${inv.invoice_number}` : ""} $${Number(inv.amount).toFixed(2)}: ${why}`,
qboRef: paid.qboTxnId,
});
return true;
});
}
@@ -25,7 +44,9 @@ export interface InvoicePaidResult {
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");
const { rows } = await deps.pool.query(
"select id from acc_invoices where stage not in ('rejected', 'paid') and paid_on is null order by decided_at nulls last, created_at",
);
for (const { id } of rows as { id: string }[]) {
try {
const m = (
@@ -36,7 +57,7 @@ export async function runInvoicePaid(deps: { pool: Pool; realmId?: string | null
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))
and p.txn_date >= case when i.stage = 'approved' then coalesce(i.decided_at::date, i.invoice_date) else i.invoice_date end)
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`,