Files
odoo_source/addons/analytic/models/analytic_mixin.py
T
williamandh4818 dc696c8ed4 [IMP] analytic: allow cross analytics
Purpose
=======

Make it possible to compare analytic values between plans by inputting
up to one account per plan on each line.
For instance, if we have 2 plans: "Country" and "Product Type", with the
following accounts

| Country | Product Type |
| ------- | ------------ |
| BE      | Drinks       |
| LU      | Food         |

And the following invoices:
* 1000€ of drinks in Belgium
* 2000€ of food in Belgium
* 3000€ of food in Luxemburg

We want to be able to display the following pivot tables:

|     | Drinks | Food | Total |
| --- | ------ | ---- | ----- |
| BE  |   1000 | 2000 |  3000 |
| LU  |      0 | 3000 |  3000 |
| Tot |   1000 | 5000 |  6000 |

|        | Total |
| ------ | ----- |
| Food   |  5000 |
| * BE   |  2000 |
| * LU   |  3000 |
| Drinks |  1000 |
| * BE   |  1000 |
| Total  |  6000 |

Implementation
==============

* `ir.fields` are added/removed dynamically on `account.analytic.line`
* Each analytic plan corresponds to one field on `account.analytic.line`
* The fields are added dynamically in the views.
* `account.analytic.plan` doesn't have a `company_id` field anymore,
  meaning that all the companies have access to all the plans. This
  means that the applicability fields and lines are now company
  dependent, and those can be used to know which fields/plans to display
  for which company.
* There can no longer be one "Project" plan per company, even if the
  accounts of that project can still be owned by only one company.
* There is now only one method to get the default (or "Project" plan),
  which is `_get_plan_columns`

task-3497653

closes odoo/odoo#139225

Related: odoo/upgrade#5306
Related: odoo/enterprise#49226
Signed-off-by: William André (wan) <wan@odoo.com>
Co-authored-by: william <wan@odoo.com>
Co-authored-by: h4818 <ayh@odoo.com>
2023-10-25 18:10:57 +00:00

116 lines
5.7 KiB
Python

# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, api, _
from odoo.tools.float_utils import float_round, float_compare
from odoo.exceptions import UserError, ValidationError
class AnalyticMixin(models.AbstractModel):
_name = 'analytic.mixin'
_description = 'Analytic Mixin'
analytic_distribution = fields.Json(
'Analytic Distribution',
compute="_compute_analytic_distribution", store=True, copy=True, readonly=False,
precompute=True
)
# Json non stored to be able to search on analytic_distribution.
analytic_distribution_search = fields.Json(
store=False,
search="_search_analytic_distribution"
)
analytic_precision = fields.Integer(
store=False,
default=lambda self: self.env['decimal.precision'].precision_get("Percentage Analytic"),
)
def init(self):
# Add a gin index for json search on the keys, on the models that actually have a table
query = ''' SELECT table_name
FROM information_schema.tables
WHERE table_name=%s '''
self.env.cr.execute(query, [self._table])
if self.env.cr.dictfetchone() and self._fields['analytic_distribution'].store:
query = f"""
CREATE INDEX IF NOT EXISTS {self._table}_analytic_distribution_gin_index
ON {self._table} USING gin(analytic_distribution);
"""
self.env.cr.execute(query)
super().init()
@api.model
def fields_get(self, allfields=None, attributes=None):
""" Hide analytic_distribution_search from filterable/searchable fields"""
res = super().fields_get(allfields, attributes)
if res.get('analytic_distribution_search'):
res['analytic_distribution_search']['searchable'] = False
return res
def _compute_analytic_distribution(self):
pass
def _search_analytic_distribution(self, operator, value):
if operator not in ['=', '!=', 'ilike', 'not ilike'] or not isinstance(value, (str, bool)):
raise UserError(_('Operation not supported'))
operator_name_search = '=' if operator in ('=', '!=') else 'ilike'
account_ids = list(self.env['account.analytic.account']._name_search(name=value, operator=operator_name_search))
query = f"""
SELECT id
FROM {self._table}
WHERE analytic_distribution ?| array[%s]
"""
operator_inselect = 'inselect' if operator in ('=', 'ilike') else 'not inselect'
return [('id', operator_inselect, (query, [[str(account_id) for account_id in account_ids]]))]
@api.model
def _search(self, domain, offset=0, limit=None, order=None, access_rights_uid=None):
domain = self._apply_analytic_distribution_domain(domain)
return super()._search(domain, offset, limit, order, access_rights_uid)
@api.model
def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
domain = self._apply_analytic_distribution_domain(domain)
return super().read_group(domain, fields, groupby, offset, limit, orderby, lazy)
def write(self, vals):
""" Format the analytic_distribution float value, so equality on analytic_distribution can be done """
decimal_precision = self.env['decimal.precision'].precision_get('Percentage Analytic')
vals = self._sanitize_values(vals, decimal_precision)
return super().write(vals)
@api.model_create_multi
def create(self, vals_list):
""" Format the analytic_distribution float value, so equality on analytic_distribution can be done """
decimal_precision = self.env['decimal.precision'].precision_get('Percentage Analytic')
vals_list = [self._sanitize_values(vals, decimal_precision) for vals in vals_list]
return super().create(vals_list)
def _validate_distribution(self, **kwargs):
if self.env.context.get('validate_analytic', False):
mandatory_plans_ids = [plan['id'] for plan in self.env['account.analytic.plan'].sudo().get_relevant_plans(**kwargs) if plan['applicability'] == 'mandatory']
if not mandatory_plans_ids:
return
decimal_precision = self.env['decimal.precision'].precision_get('Percentage Analytic')
distribution_by_root_plan = {}
for analytic_account_ids, percentage in (self.analytic_distribution or {}).items():
for analytic_account in self.env['account.analytic.account'].browse(map(int, analytic_account_ids.split(","))):
root_plan = analytic_account.root_plan_id
distribution_by_root_plan[root_plan.id] = distribution_by_root_plan.get(root_plan.id, 0) + percentage
for plan_id in mandatory_plans_ids:
if float_compare(distribution_by_root_plan.get(plan_id, 0), 100, precision_digits=decimal_precision) != 0:
raise ValidationError(_("One or more lines require a 100% analytic distribution."))
def _sanitize_values(self, vals, decimal_precision):
""" Normalize the float of the distribution """
if 'analytic_distribution' in vals:
vals['analytic_distribution'] = vals.get('analytic_distribution') and {
account_id: float_round(distribution, decimal_precision) for account_id, distribution in vals['analytic_distribution'].items()}
return vals
def _apply_analytic_distribution_domain(self, domain):
return [
('analytic_distribution_search', leaf[1], leaf[2]) if len(leaf) == 3 and leaf[0] == 'analytic_distribution' and isinstance(leaf[2], str) else leaf
for leaf in domain
]