
drop table if exists migrate_payment;

create table migrate_payment as select ai.id invoice_id, ap.id, ap.state payment_status, ap.payment_date , ap.air_bill_number ,  ai.product_type , ai.amount_total, trim(dd.name) district_name, trim(ru.login) email, ap.create_date
                                    from account_invoice ai , account_invoice_payment_rel aipr, account_payment ap, district_district dd, res_users ru, account_move_line aml
                                    where ai.id = aipr.invoice_id
                                    and aipr.payment_id  = ap.id
                                    and ru.id = ap.write_uid
                                    and ap.district  = dd.id
                                    and aipr.payment_id = aml.payment_id
                                    and aml.reconciled = true
                                    and ap.state  = 'posted';

create index migrate_payment_invoice_idx on migrate_payment(invoice_id);

create index account_invoice_line_inv_idx on account_invoice_line(invoice_id);
