SELECT trim(to_char(date_trunc('month', ao.invoice_date), 'Month')) || to_char(date_trunc('month', ao.invoice_date), ' YYYY') AS "Month"
    ,s.code AS "Seller code"
    ,s.description AS "Seller description"
    ,c.code AS "Customer code"
    ,c.description AS "Customer description"
    ,ca.code AS "Customer Account code"
    ,ca.description AS "Customer Account description"
    ,ba.code AS "Billing Account code"
    ,ba.description AS "Billing Account description"
    ,to_char(sum(CASE 
                WHEN ao.transaction_category = 'DEBIT'
                    THEN ao.amount
                ELSE 0
                END), '99999999990.00') AS "Amount DEBIT"
    ,to_char(sum(CASE 
                WHEN ao.transaction_category = 'CREDIT'
                    THEN ao.amount
                ELSE 0
                END), '99999999990.00') AS "Amount CREDIT"
    ,to_char(sum(CASE 
                WHEN ao.transaction_category = 'DEBIT'
                    THEN ao.amount
                ELSE - ao.amount
                END), '99999999990.00') AS "Balance"
FROM crm_seller s
    INNER JOIN crm_customer c ON c.seller_id = s.id
    INNER JOIN ar_customer_account ca ON ca.customer_id = c.id
    INNER JOIN billing_billing_account ba ON ba.customer_account_id = ca.id
    INNER JOIN billing_invoice i ON i.billing_account_id = ba.id
    INNER JOIN ar_account_operation ao ON ao.customer_account_id = ca.id
        AND ao.reference = i.invoice_number
        AND ao.invoice_date = i.invoice_date
        AND ao.amount = abs(i.amount_with_tax)
WHERE ao.invoice_date IS NOT NULL
    AND ao.invoice_date > (date_trunc('month', CURRENT_DATE) - CAST(:MONTH_INTERVAL || ' month' AS INTERVAL))
    AND (
        s.code ilike '%' || :SEARCH_CRITERION || '%'
        OR s.description ilike '%' || :SEARCH_CRITERION || '%'
        OR c.code ilike '%' || :SEARCH_CRITERION || '%'
        OR c.description ilike '%' || :SEARCH_CRITERION || '%'
        OR ca.code ilike '%' || :SEARCH_CRITERION || '%'
        OR ca.description ilike '%' || :SEARCH_CRITERION || '%'
        OR ba.code ilike '%' || :SEARCH_CRITERION || '%'
        OR ba.description ilike '%' || :SEARCH_CRITERION || '%'
        )
GROUP BY date_trunc('month', ao.invoice_date)
    ,s.code
    ,s.description
    ,c.code
    ,c.description
    ,ca.code
    ,ca.description
    ,ba.code
    ,ba.description
ORDER BY date_trunc('month', ao.invoice_date) DESC
    ,s.code
    ,c.code
    ,ca.code
    ,ba.code