From 6b14ceb22577faec4fde8454a86c54bd7d7bedc2 Mon Sep 17 00:00:00 2001
From: Nans Lefebvre <len@odoo.com>
Date: Fri, 31 May 2019 11:58:25 +0000
Subject: [PATCH] [FIX] account: select default journal with the correct
 currency

Create a journal J1 of a given type T with no currency.
Create a journal J2 of type T with a currency Y, default currency of company C.

Invoices of type T are created with journal J1 by default.
However, if the currency Y is explicitly set in the context, it will be created
with journal J2, even in company C. In that case J2 will be selected,
because the currency is explicitly set in context.

Now suppose we have a journal J3 of type T with a currency Y', different from
the currency of company C.
Give a lower sequence index to J3 than to J1.
Create an invoice with no currency in context.
Then J3 will be selected despite not being on the correct currency, because
no currency condition has been put in the domain.

We solve these two bugs by always adding the clause in the domain,
and adding that the currency can not be set in the case of the company currency.

opw 2002748

closes odoo/odoo#33795

Signed-off-by: Nans Lefebvre (len) <len@odoo.com>
---
 addons/account/models/account_invoice.py | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)

diff --git a/addons/account/models/account_invoice.py b/addons/account/models/account_invoice.py
index d7d980728fd2..799beaf887ac 100644
--- a/addons/account/models/account_invoice.py
+++ b/addons/account/models/account_invoice.py
@@ -93,11 +93,12 @@ class AccountInvoice(models.Model):
             ('type', 'in', [TYPE2JOURNAL[ty] for ty in inv_types if ty in TYPE2JOURNAL]),
             ('company_id', '=', company_id),
         ]
-        journal_with_currency = False
-        if self._context.get('default_currency_id'):
-            currency_clause = [('currency_id', '=', self._context.get('default_currency_id'))]
-            journal_with_currency = self.env['account.journal'].search(domain + currency_clause, limit=1)
-        return journal_with_currency or self.env['account.journal'].search(domain, limit=1)
+        company_currency_id = self.env['res.company'].browse(company_id).currency_id.id
+        currency_id = self._context.get('default_currency_id') or company_currency_id
+        currency_clause = [('currency_id', '=', currency_id)]
+        if currency_id == company_currency_id:
+            currency_clause = ['|', ('currency_id', '=', False)] + currency_clause
+        return self.env['account.journal'].search(domain + currency_clause, limit=1)
 
     @api.model
     def _default_currency(self):
-- 
GitLab