Commit Graph
896 Commits
Author SHA1 Message Date
Rémy Voet (ryv) 3c7db87ade [IMP] core: add warning for malformed aggregate specification
_read_group doesn't raise an error when we have an aggregate
specification like `order_id.create_date:min`, instead it silently
ignores the `.create_date` part.

We only add a warning in the stable version to avoid breaking any
change.

closes odoo/odoo#158777

Signed-off-by: Rémy Voet (ryv) <ryv@odoo.com>
2024-03-22 16:49:49 +00:00
Rémy Voet (ryv) b9bfc0bb6e [FIX] core: sorted of new records + prefetch
BaseModel's sorted() has two problems:
- It breaks the prefetch of self for no reason
- When it is called without an argument, it filters out new records
because the search() used in sorted() doesn't return new records.

Keep the same prefetch as self to fix the first problem.
We partially fix/support the second issue, we just avoid filtering out
new records (but we don't actually sort them)

closes odoo/odoo#157145

X-original-commit: 0551c3b7e8e1469dabdb19d6420c544a1654fec5
Signed-off-by: Rémy Voet (ryv) <ryv@odoo.com>
2024-03-12 10:34:51 +00:00
Rémy Voet (ryv) 86dd313d10 [FIX] core: fix read_group with groupby=['id']
Use read_group with groupby=['id'] raise a Exception:
```
  File "/home/odoo/Documents/dev/odoo/odoo/models.py", line 2386, in _read_group_format_result
    m2x_records = self.env[field.comodel_name].browse(ids).union()
  File "/home/odoo/Documents/dev/odoo/odoo/api.py", line 521, in __getitem__
    return self.registry[model_name](self, (), ())
  File "/home/odoo/Documents/dev/odoo/odoo/modules/registry.py", line 190, in __getitem__
    return self.models[model_name]
KeyError: None
```
Even if it doesn't make lot of sense to do that (mostly equivalent to
search), it is preferable to manage the case correctly.

closes odoo/odoo#154799

X-original-commit: 75a259365989d469972c0616dba22a56bf218bb5
Signed-off-by: Rémy Voet (ryv) <ryv@odoo.com>
2024-02-21 09:41:26 +00:00
Alvaro Fuentes b5e74f47c9 [FIX] core: fix recursion check
Prevent an infinite loop when the cycle in the parents does not contain
the starting id: `3->2->1->2->1...`

Example:
```
>>> m=self.env['ir.module.category']
>>> c1,c2,c3 = map(m.browse,[1,2,3])
>>> c2.parent_id = False
>>> c3.parent_id = False
>>> c1.parent_id = c2
>>> (c3|c2).parent_id = c1  # this never ends
```

With current patch the call to `_check_recursion` successfully detects
the new cycle.

closes odoo/odoo#152080

X-original-commit: e7c6445dd1896bb182b44af768814f297027d3a4
Signed-off-by: Raphael Collet <rco@odoo.com>
Signed-off-by: Alvaro Fuentes Suarez (afu) <afu@odoo.com>
2024-02-05 08:34:51 +00:00
Achraf 29eb854e89 [FIX] base/models: Fix typos in _read_group_format_result
Since https://github.com/odoo/odoo/pull/1432[FIX] base/models: Prevent incorrect behavior in `_read_group_format_result`

To reproduce the problem, you need to ensure that a read_group returns several groups,
with the first element being a group with no value if you choose to group on a many2many (see test).

Here's an example to reproduce in website_sale:

- Install `website_sale` without demo-data
- Go to `eCommerce/Products`
- Create a new product
- Go to `Sales` tab in the product form view
	- Set a new `eCommerce shop/Categories` like `Sales`
	- Save
- Return to `eCommerce/Products`
- Remove default filters
- Group by `Website Product Categories`
- There are two group: `None` and Sales`
- Click on None
- Traceback

In this case, the orderby is website_sequence:sum ASC,
and will therefore return as first group None containing `Delivery Product`
and as second group `Sales` containing the newly created product.

What happens is that `read_group` will build `rows_dict` thanks to `_read_group`.

https://github.com/odoo/odoo/blob/cb67b4e1472ae6689e943ade1e27cb43e8d87025/odoo/models.py#L2724

this `rows_dict` will be ordered according to `orderby`and then passed as an argument to the `_read_group_format_result` function

https://github.com/odoo/odoo/blob/cb67b4e1472ae6689e943ade1e27cb43e8d87025/odoo/models.py#L2759

For each row, this function will convert `row[group]` (group in this case is the many2many field)
into a tuple containing (id, displayname) in case the value (`row[group]`)
is found which will be used to build the domain `[(field_name, =, value)]`.

So, for example, replacing
```py
rows_dict = [
  groupbyField': odoo.model(1),
  groupbyField': odoo.model(4),
]

```
with
```py
rows_dict = [
  groupbyField': (1, 'First record'),
  groupbyField': (4, 'Fourth record'),
]
```

https://github.com/odoo/odoo/blob/cb67b4e1472ae6689e943ade1e27cb43e8d87025/odoo/models.py#L2460-L2462

If the value is False, we'll use the 'not in' operator instead.
To do this, we need to retrieve the ids of all the other groups to
include in this one all the records that aren't in any group,
either by retrieving the id if it's a model,
or by retrieving the first element of the tuple if it's already been modified,
or by directly retrieving the value of the field if it's not a many2x.

Except that if the first element is directly a group without a value,
it won't be able to retrieve the values of the other groups,
because the condition for checking that it's a `BaseModel` instance contained a typo

https://github.com/odoo/odoo/blob/cb67b4e1472ae6689e943ade1e27cb43e8d87025/odoo/models.py#L2465-L2467

closes odoo/odoo#151497

Signed-off-by: Rémy Voet (ryv) <ryv@odoo.com>
2024-02-01 16:25:38 +00:00
Victor Feyens 9ea17019f6 [FIX] core: default multi-company domain
of check_company=True fields.

Suppose two models

class A:

    company_id = fields.M2O() # not required

class B:
    _check_company_auto = True

    company_id = fields.M2O() # not required
    a_id = fields.M20(check_company=True)

and the following code:

a = A.create({'company_id': 1})
b = B.create({'a_id': a.id, 'company_id': False})

The creation of B will fail because of the multi-company
checks, which is expected.

Nevertheless, since 0d30cc2bc9, the domain
of the field a_id would be:

(company_id and ['|', ('company_id', '=', False), ('company_id', 'in', [company_id])] or []) + ([])

which means that through the interface, if you create a record b following
the example above (no company_id on b), the evaluated domain would be empty,
allowing to select records of class A, even if they belong to another company.
Of course, this would lead to a multi-company error when trying to save the
record.

This commit makes sure that the right domain is applied on
check_company=True fields, even if the current record has no value
in its `company_id` field.

opw-3629374

closes odoo/odoo#151341

X-original-commit: aaddedc3bab4f16747fb0f71ae626d94f3975ee3
Signed-off-by: Victor Feyens (vfe) <vfe@odoo.com>
2024-01-27 00:01:24 +00:00
Denis Ledoux ec0cd75328 [IMP] core: disable x2many manipulation as sudo for sensitive models
This revision adds a flag
`_allow_sudo_commands` to which models can opt-in
to protect themselves against malicious
manipulation of one2many or many2many fields
through an environment using `sudo` or a more priviledged user.

Flagging a model `_allow_sudo_commands = False`
disable `sudo` and `with_user(...)`
when manipulating a one2many or many2many
field targeting this model.

task-3695103
2023-11-01 08:05:16 +00:00
bve-odoo 72c1a4f96a [IMP] *: replace type where possible
do not compare types, for exact checks use `is` / `is not`,
for instance checks use `isinstance()`Flake8(E721)

Signed-off-by: Rémy Voet (ryv) <ryv@odoo.com>
2023-11-07 17:09:34 +00:00
Alvaro Fuentes 4b096631ad [FIX] core: include inactive companies in _check_company
`res.users.company_ids` returns only active companies, while
`res.users.company_id` may be inactive. This leads to a situation where
`self.env.company` is inactive but still associated to `self.env.user`.

Since in multiple cases the default value for relational fields pointing
to `res.users` is `self.env.user`, we may get an error in this check:
`self.env.company` is not in `self.env.user.company_ids`.

See https://github.com/odoo/odoo/blob/5506ca7/odoo/addons/base/models/res_users.py#L281-L282

closes odoo/odoo#147127

Signed-off-by: Raphael Collet <rco@odoo.com>
2024-01-08 20:38:03 +00:00
Rémy Voet (ryv) e0297bdac4 [FIX] core: fix onchange when create new one2many record
When we add a new record N to an one2many tree view from an existing
record X form, during the onchange() on the one2many comodel, the cache
of the N.one2many contains only the new record X (the siblings aren't in
it). Because of this, the result of compute methods may be incorrect
and the form won't be updated accordingly. See
https://github.com/odoo/enterprise/pull/52957 for a concrete example.

Technically, this is due to _update_cache() forcing the inverse field
value to the single value of the new record
("not cache.contains(inv_rec, invf)" is True), instead of also
considering the original values (which is properly done by
Field._update()).

closes odoo/odoo#146778

Related: odoo/enterprise#53298
Signed-off-by: Raphael Collet <rco@odoo.com>
2023-12-22 16:14:45 +00:00
Denis Ledoux 6e8e3e6333 [IMP] core: allow to override model/field manual name rule
At Odoo, we want custom models and fields to start with `x_`.
However, other developers and companies might want to customize
that behavior and be able to change the rule.

This revision targets to factorize the rule `startswith('x_')`
in a dedicated method on `ir.model` and `ir.model.fields`
so they can be overridden to allow the customization
of custom model and fields name in custom modules.

closes odoo/odoo#145270

X-original-commit: edf979c7fddbf05b915393923ed57680b9ba5399
Related: odoo/enterprise#52263
Signed-off-by: Denis Ledoux (dle) <dle@odoo.com>
Signed-off-by: Christophe Simonis (chs) <chs@odoo.com>
2023-12-06 20:39:42 +00:00
Hugo Carlier (Huca) 9048f585c7 [FIX] models, *: make read_group domains coherent with access rights
* = test_read_group

Currently, a search with the following domain `[('m2m_field', '=',
False)]` will return only the records for which the m2m field is actually
empty and not take access rights into account. This means that, for a
given user and depending on access rules, `record.m2m_field` can give an
empty recordset while a search using the previous domain won't return
this record.

This behavior is problematic when such a domain is returned by the
read_group. Indeed, when using read_group to group on a m2m field,
records for which this m2m field appears empty for the current user will
be counted in the column 'False'. However, the domain associated to this
column is not always valid, as this m2m field can appear empty for the
current user but still have records in it that the current user does not
have access to. Such records won't be returned by a search performed
using the domain returned by the read_group for the False column.

closes odoo/odoo#143233

Signed-off-by: Rémy Voet (ryv) <ryv@odoo.com>
2023-11-28 21:20:59 +00:00
Nicolas Lempereur 7c7f927bef [FIX] core,account: no join for grouping by m2o id
When using account.root (through account.account().root_id or
account.move.line().account_root_id) in read_group, we can have
inconsistent results because of how account.root is defined.

account_root is a view with the id field computed out of account codes,
but there can be the same account for several companies, so we can have
several same ID for different rows => this is not expected by the ORM
who expects one record by ID => in result, we get for example the values
in the pivot table of journal items be multiplied by the number of
companies if we group by "Account Root".

With this changeset, we add a small optimisation in ORM so if a group by
is ordered by a many2one, if the order of the many2one is "id" we don't
add a left join for ordering.

note: without the change, the added tests failed:

- in account, with 1000 as balance, and 2 as number of root with id=90090
- in test_read_group with a query containing a left join to o2m table
- in test_new_api with a query containing a left join to o2m table

opw-2282699
opw-2289440
opw-3288390

closes odoo/odoo#143257

X-original-commit: 674bdd1ac2cf9a4a3748b85f71ebbd01137485ce
Signed-off-by: Rémy Voet (ryv) <ryv@odoo.com>
2023-11-27 12:39:55 +00:00
Chong Wang (cwg) 9e32ac4292 [IMP] core: support field.export_string_translation
Some auto-generated field labels don't make sense for translators. For example
field: needed_terms_dirty label: "Needed Terms Dirty"

After this commit, if the field.export_string_translation is False, we don't
export their labels when export translations.

closes odoo/odoo#142329

Signed-off-by: Raphael Collet <rco@odoo.com>
2023-11-27 12:39:51 +00:00
Raphael Collet 425a6054ec [FIX] core: modified() for context-dependent non-stored recursive fields
When recursing on non-stored recursive fields, modified() only considers
the records that have some value in cache.  But when fields are context-
dependent, we may miss some records because we look up for cache values
in the wrong context.  Instead, consider cache values in all contexts
for that matter.

closes odoo/odoo#143644

X-original-commit: f19732c199e6bb2b8bdd55808658cb82c8cd44b4
Signed-off-by: Rémy Voet (ryv) <ryv@odoo.com>
Signed-off-by: Raphael Collet <rco@odoo.com>
2023-11-25 06:43:38 +00:00
Raphael Collet 232f34d226 [FIX] core: modified() on recursive fields before unlink()
The following situation happened with module industry_fsm, when trying
to delete a cancelled sales order corresponding to a task.  When doing
so, the server crashes with error "Could not find all values of X to
flush them", which means that a dirty field (pending update) has lost
its value from cache.

The issue is related to recursive computed fields.  Before deleting a
record, method unlink() invokes modified(), which determines all the
fields that depend on the record to be deleted, and marks them to
recompute.  Those fields should be recomputed after the record is
deleted, and not before.  We found out that the recursive call to
modified() made for recursive fields can force the recomputation of the
recursive field itself before the record is deleted, which causes
unlink() to crash.

The fix consists in marking the fields for recomputation at the very end
of method modified(), after all the fields to recompute have been
determined.  This ensures that the processing of recursive fields always
uses the current value of the field instead of its recomputed value.

X-original-commit: 1f5293bc63ae7b06fd0df8d509dc7fafaa016a22
Part-of: odoo/odoo#143644
2023-11-25 06:43:38 +00:00
Chong Wang (cwg) 7b55483e23 [FIX] core: fix typo for ormcache
fix typo in #119813 for ormcache

closes odoo/odoo#141008

X-original-commit: a242da98b533f5d6c11c68f9d973a26a47f17074
Signed-off-by: Xavier Dollé (xdo) <xdo@odoo.com>
Signed-off-by: Chong Wang (cwg) <cwg@odoo.com>
2023-11-04 09:05:36 +00:00
Chong Wang (cwg) 2d08f97c07 [IMP] core: support delay translation
Jsonb data structure of model_terms translated fields' columns
'{
	"en_US": "<div>Apple</div>"
	"fr_FR": "<div>Pomme</div><div>Banane</div>"
	"_fr_FR": "<div>Pomme</div>"
}'::jsonb

"column" IS NULL OR "column"->>'en_US' IS NOT NULL

"column"->>'lang'
1. stores last confirmed value
2. logically fallbacks to
    COALESCE(
        "column"->>'lang',
        "column"->>'en_US'
    )

"column"->>'_lang'
1. stores translations and the last written html/xml structure
2. shares the same html/xml structure with other "column"->>'_lang'
3. logically fallbacks to
    COALESCE(
        "column"->>'_lang',
        "column"->>'lang',
        "column"->>'_en_US',
        "column"->>'en_US'
    )

Context:
1. `delay_translations`(new) only write values to _langs while keeping
translations for langs when the written value has at least one translatable term
2. `check_translations`(new) read _langs values to create translation mapping
for the translation dialog
3. `edit_translations` read values whose translatable terms are wrapped by
`<span></span>` with term information for the TRANSLATE mode of website

Potential issue
since the record value of a model terms translated field is logical content
dependent (check_translations, edit_translations), all computed field computed
from any model terms translated field should also be marked.
@api.depends_context('lang', 'edit_translations', 'check_translations')

Data flow for column value, cache value and record value
(make sure the window is wide enough to see the graph)

                             +- - - - - - - - - - - - - - - - - - - - - - - - - - - -+
                             ' Record(str):                                          '
                             '                                                       '
                             ' +---------------------------------------------------+ '               +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+
                             ' | "<div><span data-oe-model='model'                 | '               {            read fr_FR             {
                             ' | data-oe-id='id' ...>French</span></div>"          | ' <------------ } context.get('edit_translations')  } <+
                             ' +---------------------------------------------------+ '               +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+  |
                             ' +---------------------------------------------------+ '               +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+  |
                             ' | "<div>French</div>"                               | '               {            read fr_FR             {  |
                             ' |                                                   | ' <------------ } context.get('check_translations') } <+
                             ' +---------------------------------------------------+ '               +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+  |
+~~~~~~~~~~~~+               ' +---------------------------------------------------+ '                                                      |
{ read fr_FR { ------------> ' | "<a>French</a>"                                   | '                                                      |
+~~~~~~~~~~~~+               ' +---------------------------------------------------+ '                                                      |
  ^                          '                                                       '                                                      |
  |                          +- - - - - - - - - - - - - - - - - - - - - - - - - - - -+                                                      |
  |                                                                                                                                         |
  |                                                                                                                                         |
  |                                                                                                                                         |
  |                          +- - - - - - - - - - - - - - - - - - - - - - - - - - - -+                                                      |
  |                          ' Cache(dict):                                          '                                                      |
  |                          '                                                       '                                                      |
  |                          ' +---------------------------------------------------+ '                                                      |
  |                          ' |                                                   | ' -----------------------------------------------------+
  |                          ' | "_fr_FR": "<div>French</div>"                     | '
  |                          ' |                                                   | ' <----------------------------------------------------+
  |                          ' +---------------------------------------------------+ '                                                      |
  |                          ' +---------------------------------------------------+ '               +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+
  +------------------------- ' |                                                   | '               {              fetch fr_FR               {
                             ' | "fr_FR": "<a>French</a>"                          | '               }    context.get('edit_translations')    }
  +------------------------> ' |                                                   | '               {  or context.get('check_translations')  {
  |                          ' +---------------------------------------------------+ '               +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+
+~~~~~~~~~~~~~~~~~+          '                                                       '                                                      ^
{   fetch fr_FR   {          +- - - - - - - - - - - - - - - - - - - - - - - - - - - -+                              COALESCE(               |
+~~~~~~~~~~~~~~~~~+                                                                                                     "c"->>'_fr_FR',     |
  ^                                                                                                                     "c"->>'fr_FR',      |
  | COALESCE(                                                                                                           "c"->>'_en_US',     |
  |     "c"->>'fr_FR',       +- - - - - - - - - - - - - - - - - - - - - - - - - - - -+                                  "c"->>'en_US'       |
  |     "c"->>'en_US'        ' Database(jsonb):                                      '                              )                       |
  | )                        '                                                       '                                                      |
  |                          ' +---------------------------------------------------+ '                                                      |
  |                          ' | "_fr_FR": "<div>French</div>"                     | ' -----------------------------------------------------+
  |                          ' +---------------------------------------------------+ '                                                      |
  |                          ' +---------------------------------------------------+ '                                                      |
  +------------------------- ' | "fr_FR": "<a>French</a>"                          | ' -----------------------------------------------------+
  |                          ' +---------------------------------------------------+ '                                                      |
  |                          ' +---------------------------------------------------+ '                                                      |
  |                          ' | "_en_US": "<div>English</div>"                    | ' -----------------------------------------------------+
  |                          ' +---------------------------------------------------+ '                                                      |
  |                          ' +---------------------------------------------------+ '                                                      |
  +------------------------- ' | "en_US": "<div>English1</div><div>English2</div>" | ' -----------------------------------------------------+
                             ' +---------------------------------------------------+ '
                             '                                                       '
                             +- - - - - - - - - - - - - - - - - - - - - - - - - - - -+

Task: 3043340
Part-of: odoo/odoo#139819
2023-10-27 11:35:03 +00:00
Rémy Voet (ryv)andPolymorphe57 e6f501bea5 [FIX] web: fix domain_selector to handle false as display_name
Since https://github.com/odoo/odoo/pull/137098, `display_name`
can be false (from the default behavior in BaseModel). It isn't
handle correctly in domain_selector Component, which trigger a
traceback trying to `split` false.

closes odoo/odoo#139450

X-original-commit: 06f3cbb95b2e4cfb271039a19660991c743c2ba8
Signed-off-by: Mathieu Duckerts-Antoine (dam) <dam@odoo.com>
Signed-off-by: Rémy Voet (ryv) <ryv@odoo.com>
Co-authored-by: Polymorphe57 <dam@odoo.com>
2023-10-26 13:41:14 +00:00
Raphael Collet f6b7899a06 [IMP] core: use SQL wrapper in _read_group()
Part-of: odoo/odoo#138019
2023-10-20 09:35:18 +00:00
Raphael Collet c041919f1b [IMP] core: introduce _order_to_sql() to replace _generate_order_by()
The new method should be used to generate an SQL object that represents
how to order by a field in an SQL query.  We introduced the auxiliary
method _order_field_to_sql() so that one can specify some SQL for
ordering by a given field with a simple method override.

Part-of: odoo/odoo#138019
2023-10-20 09:35:18 +00:00
Raphael Collet 2c09f5ed68 [IMP] core: introduce _field_to_sql() to replace _inherits_join_calc()
The new method should be used to generate an SQL object that represents
the value of a field in an SQL query.  Later this method will add
metadata to SQL objects, and that metadata will be used to determine
which fields to flush before executing some SQL code.

Part-of: odoo/odoo#138019
2023-10-20 09:35:18 +00:00
Raphael Collet 31caff2834 [IMP] core: add named parameters to SQL wrapper
For very large bits of SQL code with potentially repeated terms, it is
useful to use named parameters instead of positional parameters:

    sql = SQL(
        "SELECT %(column)s FROM %(table)s WHERE %(column)s IS NOT NULL",
        table=SQL.identifier("foo"),
        column=SQL.identifier("foo", "bar"),
    )

Part-of: odoo/odoo#138019
2023-10-20 09:35:17 +00:00
Rémy Voet (ryv) b67df70b8a [REV] core: remove ORM display_name fallback
This reverts commit 4573ca0c83eb63785016f4389a5157efb21fa9a4.

Because now, `display_name` is implicitly on every form (last breadcrumb
item). Then it will be queried by `onchange` calls. When we create a
new record, `_rec_name` can be `False` and the display_name will be a
technical one: '<model_name>,<NewId0x...>' which is uglier than the
previous situation showing 'New'.

Part-of: odoo/odoo#138061
2023-10-10 12:35:01 +00:00
Rémy Voet (ryv) eb0ba7f79b [IMP] core: check field groups for search domain and order
In order to boost the read security of groups on field, we now
check groups of field used in search domain and search order.

Part-of: odoo/odoo#135111
2023-09-29 14:48:09 +00:00
Mahdi Cheikh Rouhou (macr) efea7e13c5 [FIX] base, test_read_group : process duplicated groupbys without lazy
Issue:
======
When you have duplicate groupbys with `lazy=False` you will get an error.

Steps to reproduce the error:
=============================
- Install timesheet
- Go to timesheet / reporting / By Employee
- Add a groupby by month for one employee
- I will show an error.

Origin of the issue:
====================
The timesheet component will the send a request for read_group having
`['date:month', 'date:month']` so we will have duplicated groupby which
will be processed later in `_read_group_format_result` which update the
value of `row[group]` for each group so the first group will have the
original values which is ok but the second one will have the updated
values by the first iteration which will result in error.

Solution:
=========
We need to check that the value is of class BaseModel to update it , it
means that's the first time encountered.

opw-3497803

closes odoo/odoo#137000

X-original-commit: 91d6dc7ed56f67d41adab90ec0019fbb920d9042
Signed-off-by: Rémy Voet (ryv) <ryv@odoo.com>
2023-09-29 08:07:02 +00:00
Raphael Collet 758780c03b [IMP] core: remove parameter 'extra' from Query.join() and Query.left_join()
Part-of: odoo/odoo#134677
2023-09-27 03:01:45 +00:00
Raphael Collet 66a0cdd637 [IMP] core: make an API to get rid of Query._raw_joins
Part-of: odoo/odoo#134677
2023-09-27 03:01:45 +00:00
Raphael Collet b622ffc373 [IMP] core: use SQL wrapper in models.py
Part-of: odoo/odoo#134677
2023-09-27 03:01:45 +00:00
Bastien PIERRE 3192051806 [IMP] web: Add duplicate action on view list
Include the 'duplicate' action in the action menu in list view. The copy_batch
method will call the copy method with a loop to keep any existing override.

closes odoo/odoo#133977

Task-id: 3456679
Signed-off-by: Aaron Bohy (aab) <aab@odoo.com>
2023-09-22 15:06:01 +00:00
abd-msyukyu-odoo ed0bf2baec [FIX] base: filled week groups should be dependent on the locale
How to reproduce:
- open CRM > Forecast
- group by Expected Closing > Week

Current behavior:
- some week numbers appear multiple times

Expected behavior:
- each week should only appear once

Technical explanation:
Since [1], week groups are dependent on the locale, but the
`_read_group_fill_temporal` method was not updated to also produce groups
dependent on the locale.

[1]: https://github.com/odoo/odoo/pull/93053

task-3478451

closes odoo/odoo#135952

X-original-commit: 980786e301bdf80a9a39260a95359431c5cb5e86
Signed-off-by: Damien Abeloos (abd) <abd@odoo.com>
Signed-off-by: Rémy Voet (ryv) <ryv@odoo.com>
2023-09-20 08:36:40 +00:00
Chong Wang (cwg) 506d0cc4ec [FIX] core: fix cached translations
before this commit:
translations updated by `update_field_translation` api cannot be detected by
t-cache and some cached data whose model overrides `write` with an extra
'clear_caches()'

Step to reproduce:
- Create a mega menu, select any template, `Odoo Menu` for the example
- Install another language on the website
- Go to the translated version of your website and enter translate mode
- Change "Camera" in the mega menu to something else
- Save

The change won't be replicated, looking like it did nothing.
From there, removing or adding `edit_translations=1` in the URL will
use different cache version of the page's views and you will see the
outdated value on one and the correct on the other one.

after this commit:
`update_field_translation` will call `write`
it does the following 4 important things
1. mark field as modified
2. execute logics in the override `write` method
3. update write_date if needed to support t-cache

opw-3305117

X-original-commit: 2beb466668e4eb80d7c3ca3947445fb1cb141cff
Part-of: odoo/odoo#135277
2023-09-13 12:19:10 +00:00
Miquel Raïch c93a57ccab [IMP] models: only log "long name constraint" when the constraint is added
This way, we avoid spamming the log each time new constraints are added in the constraint's table.

closes odoo/odoo#132681

Signed-off-by: Rémy Voet (ryv) <ryv@odoo.com>
2023-09-12 22:12:53 +00:00
Chong Wang (cwg) ddfdba9424 [FIX] core: update model terms for en_US and other
For model_terms translated fields if a translation for a lang(fr_FR) has never
been defined

before this commit
when update translations for both en_US and fr_FR, the new translation for fr_FR
cannot be saved.

after this commit
new translations can be correctly saved when en_US and fr_FR are updated at the
same time.

closes odoo/odoo#135103

X-original-commit: ef4b195eeac178a14eb47f4e6cc61ddc97f78866
Signed-off-by: Raphael Collet <rco@odoo.com>
Signed-off-by: Chong Wang (cwg) <cwg@odoo.com>
2023-09-11 23:59:51 +00:00
std-odoo 15353f06d7 [IMP] base, web: allow to group by properties
Purpose
=======
Allow to group records by their property values,
like we can do with normal fields.

Technical
=========
Because there's no foreign key, when we group by a relational property
we need to check the existence of the ids in the query (and same for
selection and tags, because we might have value of a deleted
option / tag in database).

Task-3032464

Part-of: odoo/odoo#103510
2023-09-08 09:46:56 +00:00
std-odoo 6c566c2814 [IMP] base: properties, better name verification
Purpose
=======
Currently, it is possible to use some bad characters in a property name
by writing directly on the parent (not via the child).

It's possible only with RPC call and it wasn't an issue because we
recheck the name anyway before using it in SQL query (but it should be
cleaned).

We also restrict the maximum length (there's nor reason to use
huge property names).

Task-3032464

Part-of: odoo/odoo#103510
2023-09-08 09:46:56 +00:00
Raphael Collet b28265dbb2 [FIX] core: _create() should not set non-stored field to None in cache
When _create() is invoked, it inserts rows into the database, and sets
the cache of the corresponding records to the values that are inserted.
If a field is not passed to _create(), we assume that its database value
will be NULL (or falsy, at least) and put None in cache, in order to
avoid fetching that value.  However, this only makes sense for stored
fields.

Part-of: odoo/odoo#133021
2023-09-04 09:19:06 +00:00
Xavier Morel 46178afee0 [IMP] core: precompute (company_id parent_of $x)
There are cases where the result of `check_company_domain_parent_of`
is used in in a loop, leading to the parent_of relation being
recomputed once or even multiple times per iteration during SQL
evaluation.

Computing the parent relationship turns out to be fairly expensive in
worst case scenarios (e.g. lots of companies), so while precomputing
doesn't save much for a 1:1 situation (though it does make the job of
the expressions compiler a bit simpler), the ability to compute it
just once instead of say 140 times does make a huge difference in
e.g. some report renderings.

Nota: apparently `_check_company_domain` can be called with a string
because lol, so there's a special case for that.

closes odoo/odoo#133530

X-original-commit: 2f9ae135c9dd7cb09fa83fda7a9b304993cb3edc
Related: odoo/enterprise#46518
Signed-off-by: Raphael Collet <rco@odoo.com>
Signed-off-by: Xavier Morel (xmo) <xmo@odoo.com>
2023-09-04 08:03:36 +00:00
Rémy Voet (ryv) 013332d791 [FIX] core: add display_name fallback
Since 3c62ca1eb9, if the `_rec_name` value
is False, `name_search` and `name_create` will return a tuple of
(<id>, False). This is an invalid response for the web client,
which triggers a JS traceback.

Instead of using the old behavior (returning an empty string, resulting
in a partially invisible row in the Many2one selection),
use the same fallback as when the `_rec_name` doesn't exist.

Since `display_name` should never be Falsy anymore, remove part of the
test_mail_message_values_fromto_long_name that covers the
Falsy `display_name` case.

task-3424154

closes odoo/odoo#133691

X-original-commit: 0cb9e66edd9b7142a6e56bc6ee6491e6d6047e51
Signed-off-by: Raphael Collet <rco@odoo.com>
Signed-off-by: Rémy Voet (ryv) <ryv@odoo.com>
2023-08-31 09:05:02 +00:00
Raphael Collet 132e9f72ed [REF] *: rename onchange2 to onchange
closes odoo/odoo#133049

Related: odoo/enterprise#46240
Signed-off-by: Raphael Collet <rco@odoo.com>
2023-08-31 05:11:44 +00:00
Raphael Collet 109935dbc1 [REM] *: discard old implementation of onchange
Part-of: odoo/odoo#133049
2023-08-31 05:11:44 +00:00
Merel Geens (mege) 29acbe8230 [FIX] odoo: import was broken for non-admin users
A check was added to prevent importing records with prefixes of existing
modules: https://github.com/odoo/odoo/pull/130825 . This queries the
known modules, but non-admin users don't have access to that by default,
causing the import to fail for them. Allow the module query regardless
of access rights.

closes odoo/odoo#133405

X-original-commit: e1dcf886129f47fdc121f121df15a2c4724bb0e2
Signed-off-by: Raphael Collet <rco@odoo.com>
Signed-off-by: Merel Geens <mege@odoo.com>
2023-08-29 06:31:37 +00:00
std-odoo 5a23c4dd1e [FIX] web: fix the unity read with relational properties
Bug
===
Since 7d2baaa0c7 , we read the field
with `web_read`. We don't load the display name when calling read,
but instead we load them after.

But, since this change, the display names of the relational
properties are not loaded.

To fix that, we always load the display name of the relational
properties because it's a purely frontend field.

Task-3460126

Part-of: odoo/odoo#131394
2023-08-28 16:42:03 +00:00
Merel Geens (mege) c65fb9d198 [IMP] odoo: prevent unsafe import from file
It's possible to specify an existing module as the xml id prefix when
importing records from a file. This will result in `ir_module_data`
records being created with `noupdate` set to False. When the module is
upgraded, these records will be deleted.

This can lead to undesired side effects like journal items for
accounts imported this way being deleted.

This change prevents creating new records linked to existing modules
when importing from a file. Instead, the user should either use no
prefix or the name of a non-existent module, like `__import__`.

opw-3231987

closes odoo/odoo#133263

X-original-commit: 8f12d14c4c4354a63c94f14e7a89abc6048525f9
Signed-off-by: Merel Geens <mege@odoo.com>
2023-08-28 09:34:05 +00:00
Rémy Voet (ryv) 160acc0200 [FIX] core: fix inconsistencies between _apply_ir_rule and check_access_rule
Issues
======
- `_apply_ir_rule` applies `ir.rule` of the current model and also
`ir.rule` from the inherited model (via inherits). But
`check_access_rule` doesn't check the later one.
- `_flush_search` doesn't flush fields coming from the `ir.rule` of
the inherited model (via inherits). Then the filtering done by
`_apply_ir_rule` may be inconsistent with cached values.

Changes
=======
Because of https://github.com/odoo/odoo/blob/6ddcb448612f5d784c8e9ebb90f19077e65be3e1/odoo/osv/expression.py#L1073-L1073,
and https://github.com/odoo/odoo/blob/00e86b1552d1e5541a8dbf9411de5cfdb8990cc4/odoo/fields.py#L2895
leaf like `('<many2one_delegate>', 'any', [<sub-domain>])`,
will be translated in the same way as `_inherits_join_add` does.
We can remove `_inherits_join_add` and its usage in `_apply_ir_rule`
and change `ir.rule._compute_domain` to also return the inherited
(via inherits) `ir.rule` domain (with the new 'any' operator).
Since `_compute_domain` is used by `_apply_ir_rule` and
`_filter_access_rules_python`, everything is consistent.

Also fix `BaseModel._flush_search` to take in account 'any'/'not any'
operators (compulsory in order to flush correctly new domain
from `ir.rule._compute_domain` generated).

Part-of: odoo/odoo#125916
2023-08-21 19:56:55 +02:00
Rémy Voet (ryv) fcb092af12 [FIX] core: add test to ensure correct call of _compute_display_name
Add test to ensure that `_compute_display_name` is called once with
the correct recordset during `read_group`. Also
fix and small typo in the documentation of `read_group`.

closes odoo/odoo#132261

X-original-commit: 60477586f11ca7eb698240a6bd3f565b5a9e3279
Signed-off-by: Julien Castiaux (juc) <juc@odoo.com>
Signed-off-by: Raphael Collet <rco@odoo.com>
Signed-off-by: Rémy Voet (ryv) <ryv@odoo.com>
2023-08-18 12:17:57 +02:00
Gorash 75a105f46a [REF] base/all: Update modifier syntax: remove 'states' from fields
These changes are made as a result of simplifying attrs and 'states' in
views. However, they should have remained in a separate commit. When
applying the script making the xml changes (used later for the migration
script), the script checked the definition of the python fields in order
to convert the information into a python expression. Therefore, this
commit is not applied when the script is applied to xml changes.

During this attribute deletion pre-existing errors were found. Part of
the code was using the boolean values of 'states' and another part of
the code was not. The behavior could therefore be different (in cases
where readonly on the field had the same value as the ballan in
'states').

Following the deletion of 'states' and without the application of the
view migration, the js tests (tower) were no longer functional. Tests
using the Form view suffered the same effect. There are few tests that
had to be adapted, including two tests in business accounting (updated
by the accounting team). A test for column_invisible did not work. Test
checking if the test system triggers an error if we try to write on an
invisible field. It turns out that Form was testing on the value of
invisible but not taking into account if the column was invisible. The
test system fix is applied separately because there were a lot of tests
that were incorrect.

Part-of: odoo/odoo#104741
2023-08-18 09:49:11 +02:00
Gorash cdaa761ced [REF] base: Update modifier syntax (invisible, required, readonly)
Goal:
* Simplified modifiers to only have one way to define modifiers;
* Remove states attributes on python field;
* Use python expression in view `required`, `readonly`, `invisible`;
* More accurate validation of xml views.

This commit change the syntax to python expression. The next commit
will update/convert all xml views.

Before this commit:
* the `required`, `readonly` and `invisible` attributes can only have
values of `True`, `False`, 1, 0 or a python expression to use the
context;
* the `attrs` attribute define a dict. The key of this dict was
`required`, `readonly` and `invisible` and the values are the domain or
a string representing a domain to be evaluate as python expression.
This python expressions was evaluate by the javascript with view fields
and other contextual values as: context, uid, parent, active_id,
active_ids, active_model, allowed_company_ids, current_company_id.
* the `states` attribute in the view was a comma separated list of the
state. This list was combined with the `invisible` attribute;
* the `invisible` attribute on python field is used as default value;
* the `states` attribute on python field was dictionnary with state as
key and list of tuple. This structure was combined with `readonly` view
attribute.
* After combining, the resulting domains of the different attributes
`required`, `readonly` and `invisible` are evaluated with the values of
the fields. The `invisible` attributes is splitted into two use:
`invisible` and `column_invisible`.

After this commit:
* The attributes `required`, `readonly`, `invisible` and
`column_invisible` define python expression. This python expressions
are evaluate by the javascript with view fields and other contextual
values as: context, uid, parent, active_id, active_ids, active_model,
allowed_company_ids, current_company_id.

The domains can contains contextual value and will be evaluate by the
javascript.

```xml
    <field name="field_a" readonly="not context.get('show_a')" attrs="{'readonly': [('field_b', '!=', False), ('field_c', '=', parent.c)]}"/>
    <field name="field_b" states="draft"/>
```
will be replaced by
```xml
    <field name="field_a" readonly="not context.get('show_a') or field_b and field_c == parent.c"/>
    <field name="field_b" invisible="state != 'draft'"/>
```

Some inherited views will be modified differently in order to maintain
the previous behavior:

```xml
    <field name="field_a" readonly="not context.get('show_a')" attrs="{'invisible': [('field_b', '!=', False)]}">
```
```xml
    <field name="field_a" position="attributes">
        <attribute name="attrs">{'readonly': [('field_c', '=', False)], 'invisible': [('field_d', '!=', '3')]}<attribute>
    </field>
```
will be replaced by
```xml
    <field name="field_a" readonly="not context.get('show_a')" invisible="field_b">
```
```xml
    <field name="field_a" position="attributes">
        <attribute name="readonly" add="(not field_c)" separator=" or "/>
        <attribute name="invisible">field_d != 3<attribute>
    </field>
```

Validation:
A stricter control is made on the level of the attributes (modifiers)
and the fields necessary for these. The use of the previous attributes
'attr' and 'states' triggers an error (these no longer exist after the
application of the migration script)

task-2495504

Part-of: odoo/odoo#104741
2023-08-18 09:49:08 +02:00
Alvaro Fuentes f7cd412725 [FIX] core: fix remove constraints at uninstall
This patch aims to fix multiple issues with the removal of table
constraints at module uninstall.

1. We cannot remove `ir.model.constraint` records before calling
   `_module_data_uninstall` on them. Otherwise we either won't find them
   when performing the search
   `self.env['ir.model.constraint'].search([('module', 'in',
   modules.ids)]` or, if we somehow keep the ids and use `browse`
   instead, would get an error because `_module_data_uninstall` tries to
   access field values of records already removed. Note, although not an
   issue, the removal is redundant for non FK constraints since
   `_model_data_uninstall` already unlinks the record.
2. When a constraint has a name longer than 63 characters (Postgres
   default) we would fail the check for the existence of the constraint
   since the names are truncated.
3. When checking for the presence of a constraint we assumed its type
   would be `u` in `pg_constraint` because for us that means non FK
   (i.e. not `f` type). That's incorrect since there are many more
   types. Here we propose to handle `c,u,x` types.

For bullet 2 we use `tools.make_identifier` that hashes the name and
ensures it fits in the 63 chars limit.

Revert "[IMP] models: warn if constraint key len exceed 63"

The check from commit 823d9e10dc is no
longer needed since the name is ensured to fit length limit.

[IMP] code: improve uninstall tests

Perform extra checks for removal of SQL constraints. Note the test is
commented out in `__init__.py`. It can be uncommented locally for
testing. It's kept commented out to avoid random errors in runbot.

closes odoo/odoo#129084

X-original-commit: af288b7178c25261329dd85a2e64b9dd635cd9e1
Signed-off-by: Raphael Collet <rco@odoo.com>
2023-08-16 16:04:47 +02:00
william-andre 0d30cc2bc9 [IMP] models: manage sub companies with check_company
Allow some models to be delegated to the main company of the object.
For instance:
* Have company Parent and Child
* Child has access to all the accounts of Parent
* When creating a document in Child using an account of Parent, there
  shouldn't be a consistency error.

In order to do that, a new method `_check_company_domain` has been added.
This method is used when `check_company=True` is set on the field
declaration to:
* filter relational fields in the UI [^1]
* validate relational fields when writing on them in `create` and `write`

That method should also be used in the business code for models likely
to be shared amongst company branches instead of hardcoding the domain
based on `company_id`.
The same applies on domain restriction on the field declaration: the
flag `check_company` should be prefered instead of providing the domain
explicitly based on `company_id`.

Since a lot of validation and filtering will now be done based on
`parent_of`/`child_of` of the company, some support has been added for
that special case in `filtered_domain` in order to avoid doing
additional queries.

task-3371677

[^1]: because of that change, support has been added on the python
interpreter of the client to allow concatenatng domains.

Part-of: odoo/odoo#125642
2023-07-20 11:49:05 +02:00