-- Vendor payments with no bill were posted to Accounts Payable (coa_account_id
-- null + vendor → Dr A/P / Cr Bank), leaving A/P negative and the expense never
-- recognized. Per the rule (expense at payment date when no bill present), set
-- their expense account so post_transaction_gl re-posts them Dr Expense / Cr Bank.
-- Excludes bill payments ('Bill Payment%'), payments already linked to an
-- auto-bill, and imported-GL (non-gl_managed) companies.
update accounting.transactions t
set coa_account_id = coalesce(
      (select a.id from accounting.accounts a
        where a.company_id = t.company_id and a.name = t.category and a.type = 'expense'
        limit 1),
      accounting.coa_default_expense(t.company_id))
where t.type = 'debit'
  and t.vendor_id is not null
  and t.coa_account_id is null
  and t.transfer_id is null and t.deposit_id is null
  and coalesce(t.description, '') not ilike 'Bill Payment%'
  and not exists (select 1 from accounting.bills b where b.source_payment_id = t.id)
  and accounting.gl_managed(t.company_id);
