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:
129
packages/accounting_automation/src/invoice-check.ts
Normal file
129
packages/accounting_automation/src/invoice-check.ts
Normal file
@@ -0,0 +1,129 @@
|
||||
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 при переводе инвойса «на согласование»).
|
||||
* Инвойс система не согласует.
|
||||
*/
|
||||
|
||||
export interface Conclusion {
|
||||
checked_at: string;
|
||||
contract: { found: boolean; 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;
|
||||
duplicateIds: string[];
|
||||
insuranceValidUntil: 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;
|
||||
if (!c) 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, 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 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 for update skip locked", [id])).rows[0];
|
||||
if (!inv) return null;
|
||||
// контракт: указанный в инвойсе, иначе по вендору и проекту
|
||||
const contractRow = (
|
||||
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 = $1::uuid) desc nulls last, id limit 1`,
|
||||
[inv.contract_id, inv.vendor_qbo_id, inv.vendor_name, inv.project_customer_id],
|
||||
)
|
||||
).rows[0];
|
||||
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, duplicateIds: (dup.rows as { id: string }[]).map((r) => r.id),
|
||||
insuranceValidUntil: cert.rows[0]?.v ?? null, today, now,
|
||||
});
|
||||
await c.query(
|
||||
"update acc_invoices set conclusion = $2::jsonb, contract_id = coalesce(contract_id, $3::uuid) where id = $1",
|
||||
[id, JSON.stringify(concl), contract?.id ?? null],
|
||||
);
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user