Debian Codegraph @

addons/project_sale_expense/models/hr_expense.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 from odoo import models
4
5
6 class HrExpense(models.Model):
7 _inherit = "hr.expense"
8
9 def _compute_analytic_distribution(self):
10 super()._compute_analytic_distribution()
11 if not self.env.context.get('project_id'):
12 expenses_to_recompute = self.env['hr.expense']
13 prefetch_ids = set()
14 for expense in self.filtered('sale_order_id'):
15 expenses_to_recompute += expense
16 prefetch_ids.update(self.env['analytic.mixin']._get_analytic_account_ids_from_distributions(expense.analytic_distribution))
17 prefetch_ids.update(self.env['analytic.mixin']._get_analytic_account_ids_from_distributions(expense.sale_order_id.project_id._get_analytic_distribution()))
18
19 if expenses_to_recompute:
20 analytic_account_model = self.env['account.analytic.account'].with_prefetch(prefetch_ids)
21 for expense in expenses_to_recompute:
22 expense_account_ids = self.env['analytic.mixin']._get_analytic_account_ids_from_distributions(expense.analytic_distribution)
23 project_analytic_distribution = expense.sale_order_id.project_id._get_analytic_distribution()
24 project_account_ids = self.env['analytic.mixin']._get_analytic_account_ids_from_distributions(project_analytic_distribution)
25
26 project_analytic_distribution_accounts = self.env['account.analytic.account'].browse(project_account_ids)
27 expense_analytic_accounts = analytic_account_model.browse(expense_account_ids)
28
29 if not any(project_account.root_plan_id in expense_analytic_accounts.root_plan_id for project_account in project_analytic_distribution_accounts):
30 # If it is possible we keep both analytic distributions
31 expense.analytic_distribution = {
32 **(expense.analytic_distribution or {}),
33 **(project_analytic_distribution or {})
34 }
35 else:
36 # If not we keep the most prioritized one -> project
37 expense.analytic_distribution = expense.sale_order_id.project_id._get_analytic_distribution() or expense.analytic_distribution or {}
38
39 def action_post(self):
40 """ When creating the move of the expense, if the AA is given in the project of the SO, we take it as reference in the distribution.
41 Otherwise, we create a AA for the project of the SO and set the distribution to it.
42 """
43 for expense in self:
44 project = expense.sale_order_id.project_id
45 if not project or expense.analytic_distribution:
46 continue
47 if not project.account_id:
48 project._create_analytic_account()
49 expense.analytic_distribution = project._get_analytic_distribution()
50 return super().action_post()