import type { Pool } from "khb_common"; import { approvedFrom, type InvoiceRow } from "./rules.js"; type Q = Pick; /** Столбцы, которые отдаёт список (с агрегатами для правил). */ const LIST_SQL = ` select i.id, i.invoice_number, i.vendor_name, i.vendor_qbo_id, i.invoice_date::text as invoice_date, i.amount::float8 as amount, i.project_customer_id, i.jt_job_id, i.contract_id, i.pay_method, i.is_draft, i.cancelled, i.is_approved, i.llm_result, i.manual_result, i.invoice_url, i.payment_url, i.sent_to_bank, i.paid_on::text as paid_on, i.is_paid_manual, i.paid_manual_at, i.review_date::text as review_date, i.need_employee_refund, i.is_employee_refunded, i.author, i.target_employee, i.created_at, i.updated_at, (select display_name from person where id = i.author) as author_name, (select display_name from person where id = i.target_employee) as target_name, (select c.display_name from qbo_customer c where c.id = i.project_customer_id limit 1) as project_name, (select sum(d.amount)::float8 from acc_invoices_details d where d.invoice_id = i.id) as details_sum, (select count(*)::int from acc_invoices o where o.id <> i.id and not o.cancelled and o.vendor_name = i.vendor_name and coalesce(o.invoice_number, '') <> '' and o.invoice_number = i.invoice_number and o.amount = i.amount) as duplicates, (select (c.total_amount - coalesce((select sum(o.amount) from acc_invoices o where o.contract_id = c.id and o.id <> i.id and not o.cancelled and not o.is_draft), 0))::float8 from acc_contracts c where c.id = i.contract_id) as contract_remaining, (select count(*)::int from acc_invoices_approves a where a.invoice_id = i.id and a.decision = 'pending') as approves_pending, (select count(*)::int from acc_invoices_approves a where a.invoice_id = i.id and a.decision = 'rejected') as approves_rejected from acc_invoices i`; export interface ListItem extends InvoiceRow { invoice_number: string | null; vendor_name: string; vendor_qbo_id: string | null; invoice_date: string | null; project_customer_id: string | null; jt_job_id: string | null; contract_id: string | null; pay_method: string | null; need_employee_refund: boolean; is_employee_refunded: boolean; author_name: string | null; target_name: string | null; project_name: string | null; created_at: Date; updated_at: Date; } export async function listInvoices(db: Q, opts: { viewerPersonId?: string; limit?: number } = {}): Promise { const params: unknown[] = []; let where = ""; if (opts.viewerPersonId) { params.push(opts.viewerPersonId); where = ` where i.author = $1 or i.target_employee = $1`; } const { rows } = await db.query(`${LIST_SQL}${where} order by i.created_at desc limit ${Math.min(opts.limit ?? 5000, 20000)}`, params); return rows as ListItem[]; } export async function getInvoice(db: Q, id: string): Promise { const { rows } = await db.query(`${LIST_SQL} where i.id = $1`, [id]); return (rows[0] as ListItem) ?? null; } export async function getDetails(db: Q, invoiceId: string) { const { rows } = await db.query( `select id, line_no, description, quantity::float8 as quantity, unit_price::float8 as unit_price, amount::float8 as amount, category_qbo_id, category_name, contract_detail_id from acc_invoices_details where invoice_id = $1 order by line_no`, [invoiceId], ); return rows; } export async function getApproves(db: Q, invoiceId: string) { const { rows } = await db.query( `select a.id, a.approver_person_id, p.display_name as approver_name, a.decision, a.comment, a.requested_at, a.decided_at from acc_invoices_approves a join person p on p.id = a.approver_person_id where a.invoice_id = $1 order by a.requested_at`, [invoiceId], ); return rows; } /** Контракт инвойса: итоги, строки и все инвойсы контракта (правая панель). */ export async function getContractPanel(db: Q, contractId: string | null, currentId: string) { if (!contractId) return null; const c = ( await db.query( `select id, vendor_name, project_customer_id, stage, total_amount::float8 as total_amount, paid_amount::float8 as paid_amount, retained_amount::float8 as retained_amount, drive_file_id from acc_contracts where id = $1`, [contractId], ) ).rows[0]; if (!c) return null; const details = (await db.query("select id, line_no, description, amount::float8 as amount from acc_contract_details where contract_id = $1 order by line_no", [contractId])).rows; const invoices = ( await db.query( `select id, invoice_number, invoice_date::text as invoice_date, amount::float8 as amount, paid_on::text as paid_on, is_paid_manual, is_draft, cancelled, (id = $2) as is_current, case when paid_on is not null or is_paid_manual then amount::float8 else null end as paid_amount from acc_invoices where contract_id = $1 and not cancelled order by invoice_date nulls last, created_at`, [contractId, currentId], ) ).rows; return { ...c, details, invoices }; } export async function recomputeApproved(db: Q, invoiceId: string): Promise { const d = (await db.query("select decision from acc_invoices_approves where invoice_id = $1", [invoiceId])).rows.map((r) => String(r.decision)); const ok = approvedFrom(d); await db.query("update acc_invoices set is_approved = $2, updated_at = now() where id = $1", [invoiceId, ok]); return ok; } export const LOOKUP = { projects: `select id, display_name as name from qbo_customer where is_job and active order by display_name`, vendors: `select id, display_name as name from qbo_vendor where active order by display_name`, people: `select id, display_name as name from person where is_active order by display_name`, categories: `select id, coalesce(fully_qualified_name, name) as name from qbo_account where active and classification in ('Expense','Revenue') order by 2`, contracts: `select id, vendor_name, project_customer_id, total_amount::float8 as total_amount from acc_contracts order by vendor_name`, } as const;