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:
@@ -5,11 +5,14 @@ import { withTx, type Pool } from "khb_common";
|
||||
* сервис считает заключение, пишет его в 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; id: string | null; stage: string | null; total_amount: number | null; paid_amount: number | null; retained_amount: number | null; remaining: number | null };
|
||||
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 };
|
||||
@@ -28,6 +31,8 @@ export interface ContractFacts {
|
||||
export function buildConclusion(i: {
|
||||
amount: number;
|
||||
contract: ContractFacts | null;
|
||||
/** Контракты вендора на проекте, если их несколько и инвойс не указывает конкретный (тогда contract = null). */
|
||||
ambiguousContractIds?: string[];
|
||||
duplicateIds: string[];
|
||||
insuranceValidUntil: string | null;
|
||||
today: string;
|
||||
@@ -36,7 +41,9 @@ export function buildConclusion(i: {
|
||||
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 ambiguous = i.ambiguousContractIds ?? [];
|
||||
if (ambiguous.length > 1) problems.push(`контракт неоднозначен: у вендора на этом проекте контрактов ${ambiguous.length}, выберите нужный (сверка стадии работ тоже вручную)`);
|
||||
else 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} шт.: тот же номер или та же сумма и дата)`);
|
||||
@@ -45,7 +52,7 @@ export function buildConclusion(i: {
|
||||
return {
|
||||
checked_at: i.now.toISOString(),
|
||||
contract: {
|
||||
found: !!c, id: c?.id ?? null, stage: c?.stage ?? null,
|
||||
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,
|
||||
@@ -71,17 +78,19 @@ export async function runInvoiceCheck(deps: { pool: Pool; now?: () => Date }): P
|
||||
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 = (
|
||||
// контракт: указанный в инвойсе, иначе по вендору и проекту (один; если несколько - неоднозначно, не выбираем)
|
||||
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 = $1::uuid) desc nulls last, id limit 1`,
|
||||
order by id`,
|
||||
[inv.contract_id, inv.vendor_qbo_id, inv.vendor_name, inv.project_customer_id],
|
||||
)
|
||||
).rows[0];
|
||||
).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),
|
||||
@@ -103,7 +112,7 @@ export async function runInvoiceCheck(deps: { pool: Pool; now?: () => Date }): P
|
||||
[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),
|
||||
amount: Number(inv.amount), contract, ambiguousContractIds: ambiguousIds, duplicateIds: (dup.rows as { id: string }[]).map((r) => r.id),
|
||||
insuranceValidUntil: cert.rows[0]?.v ?? null, today, now,
|
||||
});
|
||||
await c.query(
|
||||
|
||||
Reference in New Issue
Block a user