Files
khb_microservices/packages/accounting_automation/src/invoice-check.ts

142 lines
8.5 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 { withTx, type Pool } from "khb_common";
/**
* «Проверка инвойса перед согласованием» (processes.md): для новых записей acc_invoices (stage 'checking', conclusion пусто)
* сервис считает заключение, пишет его в conclusion и создаёт задачу в acc_manual_review для accountant
* (kind 'invoice_approval', ref_table 'acc_invoices'; дальше задача переходит к cfo при переводе инвойса «на согласование»).
* Инвойс система не согласует.
* Если у вендора на проекте несколько контрактов, а в инвойсе контракт не указан, произвольный не выбирается: в заключении
* «контракт неоднозначен» (contract.ambiguous, candidate_ids) и в problem_highlight. Стадия работ: выводится стадия контракта,
* совпадение со стадией в инвойсе (lines, description) проверяет Юля вручную.
*/
export interface Conclusion {
checked_at: string;
contract: { found: boolean; ambiguous: boolean; candidate_ids: string[]; id: string | null; stage: string | null; total_amount: number | null; paid_amount: number | null; retained_amount: number | null; remaining: number | null };
exceeds_balance: boolean;
duplicate: { found: boolean; invoice_ids: string[] };
insurance: { valid: boolean; valid_until: string | null };
problems: string[];
}
export interface ContractFacts {
id: string;
stage: string | null;
total_amount: number;
paid_amount: number;
retained_amount: number;
}
/** Чистая сборка заключения. */
export function buildConclusion(i: {
amount: number;
contract: ContractFacts | null;
/** Контракты вендора на проекте, если их несколько и инвойс не указывает конкретный (тогда contract = null). */
ambiguousContractIds?: string[];
duplicateIds: string[];
insuranceValidUntil: string | null;
/** Основание вместо договора: invoice - сам инвойс служит основанием (доп. заказ), проблема «нет контракта» не ставится. */
contractBasis?: string | null;
today: string;
now: Date;
}): Conclusion {
const problems: string[] = [];
const c = i.contract;
const remaining = c ? Math.round((c.total_amount - c.retained_amount - c.paid_amount) * 100) / 100 : null;
const ambiguous = i.ambiguousContractIds ?? [];
if (ambiguous.length > 1) problems.push(`контракт неоднозначен: у вендора на этом проекте контрактов ${ambiguous.length}, выберите нужный (сверка стадии работ тоже вручную)`);
else if (!c && i.contractBasis !== "invoice") problems.push("нет контракта с этим вендором на этом проекте");
const exceeds = remaining !== null && i.amount > remaining;
if (exceeds) problems.push(`сумма инвойса ${i.amount.toFixed(2)} больше остатка по контракту ${remaining!.toFixed(2)}`);
if (i.duplicateIds.length > 0) problems.push(`возможный дубль инвойса (${i.duplicateIds.length} шт.: тот же номер или та же сумма и дата)`);
const insured = i.insuranceValidUntil !== null && i.insuranceValidUntil >= i.today;
if (!insured) problems.push(i.insuranceValidUntil ? `нет страховки: сертификат истёк ${i.insuranceValidUntil}` : "нет страховки: сертификата нет");
return {
checked_at: i.now.toISOString(),
contract: {
found: !!c, ambiguous: ambiguous.length > 1, candidate_ids: ambiguous, id: c?.id ?? null, stage: c?.stage ?? null,
total_amount: c?.total_amount ?? null, paid_amount: c?.paid_amount ?? null, retained_amount: c?.retained_amount ?? null, remaining,
},
exceeds_balance: exceeds,
duplicate: { found: i.duplicateIds.length > 0, invoice_ids: i.duplicateIds },
insurance: { valid: insured, valid_until: i.insuranceValidUntil },
problems,
};
}
export interface InvoiceCheckResult {
checked: number;
withProblems: number;
errors: { id: string; message: string }[];
}
export async function runInvoiceCheck(deps: { pool: Pool; now?: () => Date }): Promise<InvoiceCheckResult> {
const now = (deps.now ?? (() => new Date()))();
const today = now.toISOString().slice(0, 10);
const res: InvoiceCheckResult = { checked: 0, withProblems: 0, errors: [] };
const { rows } = await deps.pool.query("select id from acc_invoices where stage = 'checking' and conclusion is null and not is_draft and not cancelled order by created_at");
for (const { id } of rows as { id: string }[]) {
try {
const problems = await withTx(deps.pool, async (c) => {
const inv = (await c.query("select * from acc_invoices where id = $1 and stage = 'checking' and conclusion is null and not is_draft and not cancelled for update skip locked", [id])).rows[0];
if (!inv) return null;
// контракт: указанный в инвойсе, иначе по вендору и проекту (один; если несколько - неоднозначно, не выбираем)
const found = (
await c.query(
`select id, stage, total_amount, paid_amount, retained_amount from acc_contracts
where ($1::uuid is not null and id = $1::uuid)
or ($1::uuid is null and project_customer_id = $4
and (($2::text is not null and vendor_qbo_id = $2) or lower(vendor_name) = lower($3)))
order by id`,
[inv.contract_id, inv.vendor_qbo_id, inv.vendor_name, inv.project_customer_id],
)
).rows;
const ambiguousIds = found.length > 1 ? (found as { id: string }[]).map((r) => r.id) : [];
const contractRow = found.length === 1 ? found[0] : undefined;
const contract: ContractFacts | null = contractRow
? {
id: contractRow.id, stage: contractRow.stage, total_amount: Number(contractRow.total_amount),
paid_amount: Number(contractRow.paid_amount), retained_amount: Number(contractRow.retained_amount ?? 0),
}
: null;
const dup = await c.query(
`select id from acc_invoices
where id <> $1 and stage <> 'rejected'
and (($2::text is not null and vendor_qbo_id = $2) or lower(vendor_name) = lower($3))
and ((nullif(btrim($4::text), '') is not null and lower(btrim(invoice_number)) = lower(btrim($4::text)))
or (amount = $5 and invoice_date = $6))
order by created_at`,
[id, inv.vendor_qbo_id, inv.vendor_name, inv.invoice_number, inv.amount, inv.invoice_date],
);
const cert = await c.query(
`select max(valid_until)::text as v from acc_insurance_certificates
where ($1::text is not null and vendor_qbo_id = $1) or lower(vendor_name) = lower($2)`,
[inv.vendor_qbo_id, inv.vendor_name],
);
const concl = buildConclusion({
amount: Number(inv.amount), contract, ambiguousContractIds: ambiguousIds, duplicateIds: (dup.rows as { id: string }[]).map((r) => r.id),
insuranceValidUntil: cert.rows[0]?.v ?? null, contractBasis: inv.contract_basis ?? null, today, now,
});
await c.query(
// llm_result (сервис acc_invoices): «OK» без замечаний, иначе текст проблем
"update acc_invoices set conclusion = $2::jsonb, contract_id = coalesce(contract_id, $3::uuid), llm_result = $4 where id = $1",
[id, JSON.stringify(concl), contract?.id ?? null, concl.problems.length ? concl.problems.join("; ") : "OK"],
);
const highlight = concl.problems.length > 0 ? concl.problems.join("; ") : null;
await c.query(
`insert into acc_manual_review (kind, ref_table, ref_id, assignee_role, problem_highlight)
values ('invoice_approval', 'acc_invoices', $1, 'accountant', $2) on conflict (ref_table, ref_id) do nothing`,
[id, highlight],
);
return concl.problems.length;
});
if (problems === null) continue;
res.checked++;
if (problems > 0) res.withProblems++;
} catch (e) {
res.errors.push({ id, message: e instanceof Error ? e.message : String(e) });
}
}
return res;
}