diff --git a/packages/accounting_automation/scripts/old-invoices-link-qbo.sql b/packages/accounting_automation/scripts/old-invoices-link-qbo.sql new file mode 100644 index 0000000..9c10153 --- /dev/null +++ b/packages/accounting_automation/scripts/old-invoices-link-qbo.sql @@ -0,0 +1,16 @@ +-- Привязка перенесённых из Excel инвойсов к проводкам QuickBooks (Purchase): тот же вендор и сумма, дата проводки в окне вокруг даты оплаты (или инвойса). +-- Привязываем только однозначные совпадения (одна проводка на инвойс и одна проводка не занята другим инвойсом). +begin; +with cand as ( + select i.id as inv, p.id as txn, + count(*) over (partition by i.id) as n_for_inv, + count(*) over (partition by p.id) as n_for_txn + from acc_invoices i + join qbo_purchase p on i.vendor_qbo_id is not null and p.entity_id = i.vendor_qbo_id and p.total_amt = i.amount + and p.txn_date between coalesce(i.paid_on, i.invoice_date) - 10 and coalesce(i.paid_on, i.invoice_date) + 21 + where i.conclusion ->> 'imported_from' = 'old_invoices' and i.qbo_txn_id is null + and not exists (select 1 from acc_invoices o where o.qbo_txn_id = p.id) +) +update acc_invoices a set qbo_txn_id = c.txn from cand c where a.id = c.inv and c.n_for_inv = 1 and c.n_for_txn = 1; +select count(*) filter (where qbo_txn_id is not null) as linked, count(*) as total from acc_invoices where conclusion ->> 'imported_from' = 'old_invoices'; +commit;