This is an action inside of the transactions module. Selecting a transaction and clicking Actions and Rebuild Loan Transaction History will execute the following code.


loan_transaction_history = env['loan.transaction.history']

loan_transaction_history.search([]).unlink()

for loan in env['account.loan'].search([]):

    for loan_invoice in loan.loan_inv_ids:

        for invoice in loan_invoice.invoice_id:

            if invoice.state in ['open','paid']:

                for invoice_line in invoice.invoice_line_ids:

                    loan_transaction_history.create({

                        'date': invoice.date_invoice,

                        'loan_id': invoice.loan_id and invoice.loan_id.id or False,

                        'reference': invoice.number and invoice.number or False,

                        'description': invoice_line.product_id.name if invoice_line.product_id else invoice_line.name,

                        'debit': invoice_line.price_subtotal,

                        'invoice_id': invoice.id or False

                    })

    for payment in env['account.payment'].search([('loan_id','=',loan.id)]):

        if payment.state not in ['draft','cancelled']:

            loan_transaction_history.create({

                'date': payment.payment_date,

                'loan_id': payment.loan_id and payment.loan_id.id or False,

                'reference': payment.name,

                'description': 'Payment Received',

                'credit': payment.amount,

                'payment_ids': [(4, payment.id)]

            })




This will delete all of the transaction history items and then rebuild each one for every loan.