# -*- coding: utf-8 -*-
##############################################################################
#
#    Odoo, Open Source Management Solution
#    Copyright (C) 2016-TODAY Prime Consulting SA, Cape Verde (<http://prime.cv>).
#
##############################################################################

from odoo import models, fields, api

class AccountInvoice(models.Model):
    _inherit = "account.invoice"
    
    @api.model
    def _prepare_refund(self, invoice, date_invoice=None, date=None, description=None, journal_id=None):
        """Reset Journal of refund invoice to Source Invoice Journal's Counterpart Journal
        """
        result = super(AccountInvoice, self)._prepare_refund(invoice, date_invoice, date, description, journal_id)
        if journal_id:
            journal = self.env['account.journal'].search([('id','=',journal_id)])[0]
            if journal.counterpart_journal_id:
                journal_id = journal.counterpart_journal_id.id

        result['journal_id'] = journal_id

        return result
            
class AccountJournal(models.Model):
    _inherit = "account.journal"

    counterpart_journal_id = fields.Many2one('account.journal', 'Credit Note Journal', help='Used when credit note invoice is generated.\nKeep empty to use same journal.')
