              AND (aa.exclude_from_opz_stat is NULL OR aa.exclude_from_opz_stat = False)
              AND coalesce(aml.curr_exch_difference,False)= False
              --AND aml."date" <= _date_from -- (_from_date)
-             AND aml.date_maturity <= _date_to  --+ INTERVAL '1 month'
+             AND coalesce(aml.date_maturity, inv.date_due) <= _date_to  --+ INTERVAL '1 month'
              AND am."state" = 'posted'
              --AND account_account.active
             -- AND (_partner_id = 0 OR coalesce(aml.partner_id, -1) = coalesce(_partner_id, -1) ) --speed

                                                     AND (opzl.invoice_id IS nOT NULL AND opzl.invoice_id = d.invoice_id)
                                                     AND opzl.opz_id =_opz_id
                    )
;



        ,open_move_line AS (
           SELECT aml.partner_id
                ,coalesce(inv.date_invoice, aml."date") as date_invoice
                ,coalesce(aml.date_maturity, inv.date_due) as date_due
                ,inv."id" as invoice_id
                ,coalesce(inv."number", aml."name") as invoice_number
                ,coalesce(inv.amount_untaxed,0.0) as invoice_amount
