75 lines
4.4 KiB
TypeScript
75 lines
4.4 KiB
TypeScript
import { withTx, type Pool } from "khb_common";
|
||
import { paidWithoutApproval, recordDiscrepancy } from "./invoice-reconcile.js";
|
||
|
||
/**
|
||
* «Согласование и оплата инвойса», шаг 5 (processes.md): подтверждённая проводка оплаты вендору (qbo_purchase) ->
|
||
* инвойс получает paid_on и qbo_txn_id, а сумма добавляется к paid_amount контракта.
|
||
* «Согласован» и «оплачен» независимы: оплата проставляется инвойсу в любой стадии, кроме rejected, стадия (stage) не меняется.
|
||
* Оплата без решения (инвойс не согласован либо оплачен раньше решения) попадает в acc_discrepancies как paid_without_approval.
|
||
* Сопоставление: тот же вендор (qbo id или имя), та же сумма, проводка не раньше даты решения (для согласованных)
|
||
* или даты инвойса (для остальных) и не занята другим инвойсом; берётся самая ранняя.
|
||
*/
|
||
|
||
/**
|
||
* Ставит оплату инвойсу и накапливает 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, 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;
|
||
});
|
||
}
|
||
|
||
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 not in ('rejected', 'paid') and paid_on is null and not is_draft and not cancelled 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 >= 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`,
|
||
[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;
|
||
}
|