api.py 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. """The Odoo API module defines Odoo Environments and method decorators.
  4. .. todo:: Document this module
  5. """
  6. __all__ = [
  7. 'Environment',
  8. 'Meta',
  9. 'model',
  10. 'constrains', 'depends', 'onchange', 'returns',
  11. 'call_kw',
  12. ]
  13. import logging
  14. import warnings
  15. from collections import defaultdict
  16. from collections.abc import Mapping
  17. from contextlib import contextmanager
  18. from inspect import signature
  19. from pprint import pformat
  20. from weakref import WeakSet
  21. try:
  22. from decorator import decoratorx as decorator
  23. except ImportError:
  24. from decorator import decorator
  25. from .exceptions import AccessError, CacheMiss
  26. from .tools import classproperty, frozendict, lazy_property, OrderedSet, Query, StackMap
  27. from .tools.translate import _
  28. _logger = logging.getLogger(__name__)
  29. # The following attributes are used, and reflected on wrapping methods:
  30. # - method._constrains: set by @constrains, specifies constraint dependencies
  31. # - method._depends: set by @depends, specifies compute dependencies
  32. # - method._returns: set by @returns, specifies return model
  33. # - method._onchange: set by @onchange, specifies onchange fields
  34. # - method.clear_cache: set by @ormcache, used to clear the cache
  35. # - method._ondelete: set by @ondelete, used to raise errors for unlink operations
  36. #
  37. # On wrapping method only:
  38. # - method._api: decorator function, used for re-applying decorator
  39. #
  40. INHERITED_ATTRS = ('_returns',)
  41. class Params(object):
  42. def __init__(self, args, kwargs):
  43. self.args = args
  44. self.kwargs = kwargs
  45. def __str__(self):
  46. params = []
  47. for arg in self.args:
  48. params.append(repr(arg))
  49. for item in sorted(self.kwargs.items()):
  50. params.append("%s=%r" % item)
  51. return ', '.join(params)
  52. class Meta(type):
  53. """ Metaclass that automatically decorates traditional-style methods by
  54. guessing their API. It also implements the inheritance of the
  55. :func:`returns` decorators.
  56. """
  57. def __new__(meta, name, bases, attrs):
  58. # dummy parent class to catch overridden methods decorated with 'returns'
  59. parent = type.__new__(meta, name, bases, {})
  60. for key, value in list(attrs.items()):
  61. if not key.startswith('__') and callable(value):
  62. # make the method inherit from decorators
  63. value = propagate(getattr(parent, key, None), value)
  64. attrs[key] = value
  65. return type.__new__(meta, name, bases, attrs)
  66. def attrsetter(attr, value):
  67. """ Return a function that sets ``attr`` on its argument and returns it. """
  68. return lambda method: setattr(method, attr, value) or method
  69. def propagate(method1, method2):
  70. """ Propagate decorators from ``method1`` to ``method2``, and return the
  71. resulting method.
  72. """
  73. if method1:
  74. for attr in INHERITED_ATTRS:
  75. if hasattr(method1, attr) and not hasattr(method2, attr):
  76. setattr(method2, attr, getattr(method1, attr))
  77. return method2
  78. def constrains(*args):
  79. """Decorate a constraint checker.
  80. Each argument must be a field name used in the check::
  81. @api.constrains('name', 'description')
  82. def _check_description(self):
  83. for record in self:
  84. if record.name == record.description:
  85. raise ValidationError("Fields name and description must be different")
  86. Invoked on the records on which one of the named fields has been modified.
  87. Should raise :exc:`~odoo.exceptions.ValidationError` if the
  88. validation failed.
  89. .. warning::
  90. ``@constrains`` only supports simple field names, dotted names
  91. (fields of relational fields e.g. ``partner_id.customer``) are not
  92. supported and will be ignored.
  93. ``@constrains`` will be triggered only if the declared fields in the
  94. decorated method are included in the ``create`` or ``write`` call.
  95. It implies that fields not present in a view will not trigger a call
  96. during a record creation. A override of ``create`` is necessary to make
  97. sure a constraint will always be triggered (e.g. to test the absence of
  98. value).
  99. One may also pass a single function as argument. In that case, the field
  100. names are given by calling the function with a model instance.
  101. """
  102. if args and callable(args[0]):
  103. args = args[0]
  104. return attrsetter('_constrains', args)
  105. def ondelete(*, at_uninstall):
  106. """
  107. Mark a method to be executed during :meth:`~odoo.models.BaseModel.unlink`.
  108. The goal of this decorator is to allow client-side errors when unlinking
  109. records if, from a business point of view, it does not make sense to delete
  110. such records. For instance, a user should not be able to delete a validated
  111. sales order.
  112. While this could be implemented by simply overriding the method ``unlink``
  113. on the model, it has the drawback of not being compatible with module
  114. uninstallation. When uninstalling the module, the override could raise user
  115. errors, but we shouldn't care because the module is being uninstalled, and
  116. thus **all** records related to the module should be removed anyway.
  117. This means that by overriding ``unlink``, there is a big chance that some
  118. tables/records may remain as leftover data from the uninstalled module. This
  119. leaves the database in an inconsistent state. Moreover, there is a risk of
  120. conflicts if the module is ever reinstalled on that database.
  121. Methods decorated with ``@ondelete`` should raise an error following some
  122. conditions, and by convention, the method should be named either
  123. ``_unlink_if_<condition>`` or ``_unlink_except_<not_condition>``.
  124. .. code-block:: python
  125. @api.ondelete(at_uninstall=False)
  126. def _unlink_if_user_inactive(self):
  127. if any(user.active for user in self):
  128. raise UserError("Can't delete an active user!")
  129. # same as above but with _unlink_except_* as method name
  130. @api.ondelete(at_uninstall=False)
  131. def _unlink_except_active_user(self):
  132. if any(user.active for user in self):
  133. raise UserError("Can't delete an active user!")
  134. :param bool at_uninstall: Whether the decorated method should be called if
  135. the module that implements said method is being uninstalled. Should
  136. almost always be ``False``, so that module uninstallation does not
  137. trigger those errors.
  138. .. danger::
  139. The parameter ``at_uninstall`` should only be set to ``True`` if the
  140. check you are implementing also applies when uninstalling the module.
  141. For instance, it doesn't matter if when uninstalling ``sale``, validated
  142. sales orders are being deleted because all data pertaining to ``sale``
  143. should be deleted anyway, in that case ``at_uninstall`` should be set to
  144. ``False``.
  145. However, it makes sense to prevent the removal of the default language
  146. if no other languages are installed, since deleting the default language
  147. will break a lot of basic behavior. In this case, ``at_uninstall``
  148. should be set to ``True``.
  149. """
  150. return attrsetter('_ondelete', at_uninstall)
  151. def onchange(*args):
  152. """Return a decorator to decorate an onchange method for given fields.
  153. In the form views where the field appears, the method will be called
  154. when one of the given fields is modified. The method is invoked on a
  155. pseudo-record that contains the values present in the form. Field
  156. assignments on that record are automatically sent back to the client.
  157. Each argument must be a field name::
  158. @api.onchange('partner_id')
  159. def _onchange_partner(self):
  160. self.message = "Dear %s" % (self.partner_id.name or "")
  161. .. code-block:: python
  162. return {
  163. 'warning': {'title': "Warning", 'message': "What is this?", 'type': 'notification'},
  164. }
  165. If the type is set to notification, the warning will be displayed in a notification.
  166. Otherwise it will be displayed in a dialog as default.
  167. .. warning::
  168. ``@onchange`` only supports simple field names, dotted names
  169. (fields of relational fields e.g. ``partner_id.tz``) are not
  170. supported and will be ignored
  171. .. danger::
  172. Since ``@onchange`` returns a recordset of pseudo-records,
  173. calling any one of the CRUD methods
  174. (:meth:`create`, :meth:`read`, :meth:`write`, :meth:`unlink`)
  175. on the aforementioned recordset is undefined behaviour,
  176. as they potentially do not exist in the database yet.
  177. Instead, simply set the record's field like shown in the example
  178. above or call the :meth:`update` method.
  179. .. warning::
  180. It is not possible for a ``one2many`` or ``many2many`` field to modify
  181. itself via onchange. This is a webclient limitation - see `#2693 <https://github.com/odoo/odoo/issues/2693>`_.
  182. """
  183. return attrsetter('_onchange', args)
  184. def depends(*args):
  185. """ Return a decorator that specifies the field dependencies of a "compute"
  186. method (for new-style function fields). Each argument must be a string
  187. that consists in a dot-separated sequence of field names::
  188. pname = fields.Char(compute='_compute_pname')
  189. @api.depends('partner_id.name', 'partner_id.is_company')
  190. def _compute_pname(self):
  191. for record in self:
  192. if record.partner_id.is_company:
  193. record.pname = (record.partner_id.name or "").upper()
  194. else:
  195. record.pname = record.partner_id.name
  196. One may also pass a single function as argument. In that case, the
  197. dependencies are given by calling the function with the field's model.
  198. """
  199. if args and callable(args[0]):
  200. args = args[0]
  201. elif any('id' in arg.split('.') for arg in args):
  202. raise NotImplementedError("Compute method cannot depend on field 'id'.")
  203. return attrsetter('_depends', args)
  204. def depends_context(*args):
  205. """ Return a decorator that specifies the context dependencies of a
  206. non-stored "compute" method. Each argument is a key in the context's
  207. dictionary::
  208. price = fields.Float(compute='_compute_product_price')
  209. @api.depends_context('pricelist')
  210. def _compute_product_price(self):
  211. for product in self:
  212. if product.env.context.get('pricelist'):
  213. pricelist = self.env['product.pricelist'].browse(product.env.context['pricelist'])
  214. else:
  215. pricelist = self.env['product.pricelist'].get_default_pricelist()
  216. product.price = pricelist._get_products_price(product).get(product.id, 0.0)
  217. All dependencies must be hashable. The following keys have special
  218. support:
  219. * `company` (value in context or current company id),
  220. * `uid` (current user id and superuser flag),
  221. * `active_test` (value in env.context or value in field.context).
  222. """
  223. return attrsetter('_depends_context', args)
  224. def returns(model, downgrade=None, upgrade=None):
  225. """ Return a decorator for methods that return instances of ``model``.
  226. :param model: a model name, or ``'self'`` for the current model
  227. :param downgrade: a function ``downgrade(self, value, *args, **kwargs)``
  228. to convert the record-style ``value`` to a traditional-style output
  229. :param upgrade: a function ``upgrade(self, value, *args, **kwargs)``
  230. to convert the traditional-style ``value`` to a record-style output
  231. The arguments ``self``, ``*args`` and ``**kwargs`` are the ones passed
  232. to the method in the record-style.
  233. The decorator adapts the method output to the api style: ``id``, ``ids`` or
  234. ``False`` for the traditional style, and recordset for the record style::
  235. @model
  236. @returns('res.partner')
  237. def find_partner(self, arg):
  238. ... # return some record
  239. # output depends on call style: traditional vs record style
  240. partner_id = model.find_partner(cr, uid, arg, context=context)
  241. # recs = model.browse(cr, uid, ids, context)
  242. partner_record = recs.find_partner(arg)
  243. Note that the decorated method must satisfy that convention.
  244. Those decorators are automatically *inherited*: a method that overrides
  245. a decorated existing method will be decorated with the same
  246. ``@returns(model)``.
  247. """
  248. return attrsetter('_returns', (model, downgrade, upgrade))
  249. def downgrade(method, value, self, args, kwargs):
  250. """ Convert ``value`` returned by ``method`` on ``self`` to traditional style. """
  251. spec = getattr(method, '_returns', None)
  252. if not spec:
  253. return value
  254. _, convert, _ = spec
  255. if convert and len(signature(convert).parameters) > 1:
  256. return convert(self, value, *args, **kwargs)
  257. elif convert:
  258. return convert(value)
  259. else:
  260. return value.ids
  261. def split_context(method, args, kwargs):
  262. """ Extract the context from a pair of positional and keyword arguments.
  263. Return a triple ``context, args, kwargs``.
  264. """
  265. # altering kwargs is a cause of errors, for instance when retrying a request
  266. # after a serialization error: the retry is done without context!
  267. kwargs = kwargs.copy()
  268. return kwargs.pop('context', None), args, kwargs
  269. def autovacuum(method):
  270. """
  271. Decorate a method so that it is called by the daily vacuum cron job (model
  272. ``ir.autovacuum``). This is typically used for garbage-collection-like
  273. tasks that do not deserve a specific cron job.
  274. """
  275. assert method.__name__.startswith('_'), "%s: autovacuum methods must be private" % method.__name__
  276. method._autovacuum = True
  277. return method
  278. def model(method):
  279. """ Decorate a record-style method where ``self`` is a recordset, but its
  280. contents is not relevant, only the model is. Such a method::
  281. @api.model
  282. def method(self, args):
  283. ...
  284. """
  285. if method.__name__ == 'create':
  286. return model_create_single(method)
  287. method._api = 'model'
  288. return method
  289. _create_logger = logging.getLogger(__name__ + '.create')
  290. @decorator
  291. def _model_create_single(create, self, arg):
  292. # 'create' expects a dict and returns a record
  293. if isinstance(arg, Mapping):
  294. return create(self, arg)
  295. if len(arg) > 1:
  296. _create_logger.debug("%s.create() called with %d dicts", self, len(arg))
  297. return self.browse().concat(*(create(self, vals) for vals in arg))
  298. def model_create_single(method):
  299. """ Decorate a method that takes a dictionary and creates a single record.
  300. The method may be called with either a single dict or a list of dicts::
  301. record = model.create(vals)
  302. records = model.create([vals, ...])
  303. """
  304. _create_logger.warning("The model %s is not overriding the create method in batch", method.__module__)
  305. wrapper = _model_create_single(method) # pylint: disable=no-value-for-parameter
  306. wrapper._api = 'model_create'
  307. return wrapper
  308. @decorator
  309. def _model_create_multi(create, self, arg):
  310. # 'create' expects a list of dicts and returns a recordset
  311. if isinstance(arg, Mapping):
  312. return create(self, [arg])
  313. return create(self, arg)
  314. def model_create_multi(method):
  315. """ Decorate a method that takes a list of dictionaries and creates multiple
  316. records. The method may be called with either a single dict or a list of
  317. dicts::
  318. record = model.create(vals)
  319. records = model.create([vals, ...])
  320. """
  321. wrapper = _model_create_multi(method) # pylint: disable=no-value-for-parameter
  322. wrapper._api = 'model_create'
  323. return wrapper
  324. def _call_kw_model(method, self, args, kwargs):
  325. context, args, kwargs = split_context(method, args, kwargs)
  326. recs = self.with_context(context or {})
  327. _logger.debug("call %s.%s(%s)", recs, method.__name__, Params(args, kwargs))
  328. result = method(recs, *args, **kwargs)
  329. return downgrade(method, result, recs, args, kwargs)
  330. def _call_kw_model_create(method, self, args, kwargs):
  331. # special case for method 'create'
  332. context, args, kwargs = split_context(method, args, kwargs)
  333. recs = self.with_context(context or {})
  334. _logger.debug("call %s.%s(%s)", recs, method.__name__, Params(args, kwargs))
  335. result = method(recs, *args, **kwargs)
  336. return result.id if isinstance(args[0], Mapping) else result.ids
  337. def _call_kw_multi(method, self, args, kwargs):
  338. ids, args = args[0], args[1:]
  339. context, args, kwargs = split_context(method, args, kwargs)
  340. recs = self.with_context(context or {}).browse(ids)
  341. _logger.debug("call %s.%s(%s)", recs, method.__name__, Params(args, kwargs))
  342. result = method(recs, *args, **kwargs)
  343. return downgrade(method, result, recs, args, kwargs)
  344. def call_kw(model, name, args, kwargs):
  345. """ Invoke the given method ``name`` on the recordset ``model``. """
  346. method = getattr(type(model), name)
  347. api = getattr(method, '_api', None)
  348. if api == 'model':
  349. result = _call_kw_model(method, model, args, kwargs)
  350. elif api == 'model_create':
  351. result = _call_kw_model_create(method, model, args, kwargs)
  352. else:
  353. result = _call_kw_multi(method, model, args, kwargs)
  354. model.env.flush_all()
  355. return result
  356. class Environment(Mapping):
  357. """ The environment stores various contextual data used by the ORM:
  358. - :attr:`cr`: the current database cursor (for database queries);
  359. - :attr:`uid`: the current user id (for access rights checks);
  360. - :attr:`context`: the current context dictionary (arbitrary metadata);
  361. - :attr:`su`: whether in superuser mode.
  362. It provides access to the registry by implementing a mapping from model
  363. names to models. It also holds a cache for records, and a data
  364. structure to manage recomputations.
  365. """
  366. @classproperty
  367. def envs(cls):
  368. raise NotImplementedError(
  369. "Since Odoo 15.0, Environment.envs no longer works; "
  370. "use cr.transaction or env.transaction instead."
  371. )
  372. @classmethod
  373. @contextmanager
  374. def manage(cls):
  375. warnings.warn(
  376. "Since Odoo 15.0, Environment.manage() is useless.",
  377. DeprecationWarning, stacklevel=2,
  378. )
  379. yield
  380. def reset(self):
  381. """ Reset the transaction, see :meth:`Transaction.reset`. """
  382. self.transaction.reset()
  383. def __new__(cls, cr, uid, context, su=False):
  384. if uid == SUPERUSER_ID:
  385. su = True
  386. assert context is not None
  387. args = (cr, uid, context, su)
  388. # determine transaction object
  389. transaction = cr.transaction
  390. if transaction is None:
  391. transaction = cr.transaction = Transaction(Registry(cr.dbname))
  392. # if env already exists, return it
  393. for env in transaction.envs:
  394. if env.args == args:
  395. return env
  396. # otherwise create environment, and add it in the set
  397. self = object.__new__(cls)
  398. args = (cr, uid, frozendict(context), su)
  399. self.cr, self.uid, self.context, self.su = self.args = args
  400. self.transaction = self.all = transaction
  401. self.registry = transaction.registry
  402. self.cache = transaction.cache
  403. self._cache_key = {} # memo {field: cache_key}
  404. self._protected = transaction.protected
  405. transaction.envs.add(self)
  406. return self
  407. #
  408. # Mapping methods
  409. #
  410. def __contains__(self, model_name):
  411. """ Test whether the given model exists. """
  412. return model_name in self.registry
  413. def __getitem__(self, model_name):
  414. """ Return an empty recordset from the given model. """
  415. return self.registry[model_name](self, (), ())
  416. def __iter__(self):
  417. """ Return an iterator on model names. """
  418. return iter(self.registry)
  419. def __len__(self):
  420. """ Return the size of the model registry. """
  421. return len(self.registry)
  422. def __eq__(self, other):
  423. return self is other
  424. def __ne__(self, other):
  425. return self is not other
  426. def __hash__(self):
  427. return object.__hash__(self)
  428. def __call__(self, cr=None, user=None, context=None, su=None):
  429. """ Return an environment based on ``self`` with modified parameters.
  430. :param cr: optional database cursor to change the current cursor
  431. :type cursor: :class:`~odoo.sql_db.Cursor`
  432. :param user: optional user/user id to change the current user
  433. :type user: int or :class:`res.users record<~odoo.addons.base.models.res_users.Users>`
  434. :param dict context: optional context dictionary to change the current context
  435. :param bool su: optional boolean to change the superuser mode
  436. :returns: environment with specified args (new or existing one)
  437. :rtype: :class:`Environment`
  438. """
  439. cr = self.cr if cr is None else cr
  440. uid = self.uid if user is None else int(user)
  441. context = self.context if context is None else context
  442. su = (user is None and self.su) if su is None else su
  443. return Environment(cr, uid, context, su)
  444. def ref(self, xml_id, raise_if_not_found=True):
  445. """ Return the record corresponding to the given ``xml_id``.
  446. :param str xml_id: record xml_id, under the format ``<module.id>``
  447. :param bool raise_if_not_found: whether the method should raise if record is not found
  448. :returns: Found record or None
  449. :raise ValueError: if record wasn't found and ``raise_if_not_found`` is True
  450. """
  451. res_model, res_id = self['ir.model.data']._xmlid_to_res_model_res_id(
  452. xml_id, raise_if_not_found=raise_if_not_found
  453. )
  454. if res_model and res_id:
  455. record = self[res_model].browse(res_id)
  456. if record.exists():
  457. return record
  458. if raise_if_not_found:
  459. raise ValueError('No record found for unique ID %s. It may have been deleted.' % (xml_id))
  460. return None
  461. def is_superuser(self):
  462. """ Return whether the environment is in superuser mode. """
  463. return self.su
  464. def is_admin(self):
  465. """ Return whether the current user has group "Access Rights", or is in
  466. superuser mode. """
  467. return self.su or self.user._is_admin()
  468. def is_system(self):
  469. """ Return whether the current user has group "Settings", or is in
  470. superuser mode. """
  471. return self.su or self.user._is_system()
  472. @lazy_property
  473. def user(self):
  474. """Return the current user (as an instance).
  475. :returns: current user - sudoed
  476. :rtype: :class:`res.users record<~odoo.addons.base.models.res_users.Users>`"""
  477. return self(su=True)['res.users'].browse(self.uid)
  478. @lazy_property
  479. def company(self):
  480. """Return the current company (as an instance).
  481. If not specified in the context (`allowed_company_ids`),
  482. fallback on current user main company.
  483. :raise AccessError: invalid or unauthorized `allowed_company_ids` context key content.
  484. :return: current company (default=`self.user.company_id`), with the current environment
  485. :rtype: :class:`res.company record<~odoo.addons.base.models.res_company.Company>`
  486. .. warning::
  487. No sanity checks applied in sudo mode !
  488. When in sudo mode, a user can access any company,
  489. even if not in his allowed companies.
  490. This allows to trigger inter-company modifications,
  491. even if the current user doesn't have access to
  492. the targeted company.
  493. """
  494. company_ids = self.context.get('allowed_company_ids', [])
  495. if company_ids:
  496. if not self.su:
  497. user_company_ids = self.user._get_company_ids()
  498. if set(company_ids) - set(user_company_ids):
  499. raise AccessError(_("Access to unauthorized or invalid companies."))
  500. return self['res.company'].browse(company_ids[0])
  501. return self.user.company_id.with_env(self)
  502. @lazy_property
  503. def companies(self):
  504. """Return a recordset of the enabled companies by the user.
  505. If not specified in the context(`allowed_company_ids`),
  506. fallback on current user companies.
  507. :raise AccessError: invalid or unauthorized `allowed_company_ids` context key content.
  508. :return: current companies (default=`self.user.company_ids`), with the current environment
  509. :rtype: :class:`res.company recordset<~odoo.addons.base.models.res_company.Company>`
  510. .. warning::
  511. No sanity checks applied in sudo mode !
  512. When in sudo mode, a user can access any company,
  513. even if not in his allowed companies.
  514. This allows to trigger inter-company modifications,
  515. even if the current user doesn't have access to
  516. the targeted company.
  517. """
  518. company_ids = self.context.get('allowed_company_ids', [])
  519. user_company_ids = self.user._get_company_ids()
  520. if company_ids:
  521. if not self.su:
  522. if set(company_ids) - set(user_company_ids):
  523. raise AccessError(_("Access to unauthorized or invalid companies."))
  524. return self['res.company'].browse(company_ids)
  525. # By setting the default companies to all user companies instead of the main one
  526. # we save a lot of potential trouble in all "out of context" calls, such as
  527. # /mail/redirect or /web/image, etc. And it is not unsafe because the user does
  528. # have access to these other companies. The risk of exposing foreign records
  529. # (wrt to the context) is low because all normal RPCs will have a proper
  530. # allowed_company_ids.
  531. # Examples:
  532. # - when printing a report for several records from several companies
  533. # - when accessing to a record from the notification email template
  534. # - when loading an binary image on a template
  535. return self['res.company'].browse(user_company_ids)
  536. @property
  537. def lang(self):
  538. """Return the current language code.
  539. :rtype: str
  540. """
  541. lang = self.context.get('lang')
  542. # _lang_get_id is cached and used to validate lang before return,
  543. # because 'env.lang' may be injected in SQL queries
  544. return lang if lang and self['res.lang']._lang_get_id(lang) else None
  545. def clear(self):
  546. """ Clear all record caches, and discard all fields to recompute.
  547. This may be useful when recovering from a failed ORM operation.
  548. """
  549. lazy_property.reset_all(self)
  550. self.transaction.clear()
  551. def clear_upon_failure(self):
  552. """ Context manager that rolls back the environments (caches and pending
  553. computations and updates) upon exception.
  554. """
  555. warnings.warn(
  556. "Since Odoo 15.0, use cr.savepoint() instead of env.clear_upon_failure().",
  557. DeprecationWarning, stacklevel=2,
  558. )
  559. return self.cr.savepoint()
  560. def invalidate_all(self, flush=True):
  561. """ Invalidate the cache of all records.
  562. :param flush: whether pending updates should be flushed before invalidation.
  563. It is ``True`` by default, which ensures cache consistency.
  564. Do not use this parameter unless you know what you are doing.
  565. """
  566. if flush:
  567. self.flush_all()
  568. self.cache.invalidate()
  569. def _recompute_all(self):
  570. """ Process all pending computations. """
  571. for field in list(self.fields_to_compute()):
  572. self[field.model_name]._recompute_field(field)
  573. def flush_all(self):
  574. """ Flush all pending computations and updates to the database. """
  575. self._recompute_all()
  576. for model_name in OrderedSet(field.model_name for field in self.cache.get_dirty_fields()):
  577. self[model_name].flush_model()
  578. def is_protected(self, field, record):
  579. """ Return whether `record` is protected against invalidation or
  580. recomputation for `field`.
  581. """
  582. return record.id in self._protected.get(field, ())
  583. def protected(self, field):
  584. """ Return the recordset for which ``field`` should not be invalidated or recomputed. """
  585. return self[field.model_name].browse(self._protected.get(field, ()))
  586. @contextmanager
  587. def protecting(self, what, records=None):
  588. """ Prevent the invalidation or recomputation of fields on records.
  589. The parameters are either:
  590. - ``what`` a collection of fields and ``records`` a recordset, or
  591. - ``what`` a collection of pairs ``(fields, records)``.
  592. """
  593. protected = self._protected
  594. try:
  595. protected.pushmap()
  596. if records is not None: # Handle first signature
  597. ids_by_field = {field: records._ids for field in what}
  598. else: # Handle second signature
  599. ids_by_field = defaultdict(list)
  600. for fields, what_records in what:
  601. for field in fields:
  602. ids_by_field[field].extend(what_records._ids)
  603. for field, rec_ids in ids_by_field.items():
  604. ids = protected.get(field)
  605. protected[field] = ids.union(rec_ids) if ids else frozenset(rec_ids)
  606. yield
  607. finally:
  608. protected.popmap()
  609. def fields_to_compute(self):
  610. """ Return a view on the field to compute. """
  611. return self.all.tocompute.keys()
  612. def records_to_compute(self, field):
  613. """ Return the records to compute for ``field``. """
  614. ids = self.all.tocompute.get(field, ())
  615. return self[field.model_name].browse(ids)
  616. def is_to_compute(self, field, record):
  617. """ Return whether ``field`` must be computed on ``record``. """
  618. return record.id in self.all.tocompute.get(field, ())
  619. def not_to_compute(self, field, records):
  620. """ Return the subset of ``records`` for which ``field`` must not be computed. """
  621. ids = self.all.tocompute.get(field, ())
  622. return records.browse(id_ for id_ in records._ids if id_ not in ids)
  623. def add_to_compute(self, field, records):
  624. """ Mark ``field`` to be computed on ``records``. """
  625. if not records:
  626. return records
  627. assert field.store and field.compute, "Cannot add to recompute no-store or no-computed field"
  628. self.all.tocompute[field].update(records._ids)
  629. def remove_to_compute(self, field, records):
  630. """ Mark ``field`` as computed on ``records``. """
  631. if not records:
  632. return
  633. ids = self.all.tocompute.get(field, None)
  634. if ids is None:
  635. return
  636. ids.difference_update(records._ids)
  637. if not ids:
  638. del self.all.tocompute[field]
  639. @contextmanager
  640. def norecompute(self):
  641. """ Delay recomputations (deprecated: this is not the default behavior). """
  642. yield
  643. def cache_key(self, field):
  644. """ Return the cache key of the given ``field``. """
  645. try:
  646. return self._cache_key[field]
  647. except KeyError:
  648. def get(key, get_context=self.context.get):
  649. if key == 'company':
  650. return self.company.id
  651. elif key == 'uid':
  652. return (self.uid, self.su)
  653. elif key == 'lang':
  654. return get_context('lang') or None
  655. elif key == 'active_test':
  656. return get_context('active_test', field.context.get('active_test', True))
  657. else:
  658. val = get_context(key)
  659. if type(val) is list:
  660. val = tuple(val)
  661. try:
  662. hash(val)
  663. except TypeError:
  664. raise TypeError(
  665. "Can only create cache keys from hashable values, "
  666. "got non-hashable value {!r} at context key {!r} "
  667. "(dependency of field {})".format(val, key, field)
  668. ) from None # we don't need to chain the exception created 2 lines above
  669. else:
  670. return val
  671. result = tuple(get(key) for key in self.registry.field_depends_context[field])
  672. self._cache_key[field] = result
  673. return result
  674. class Transaction:
  675. """ A object holding ORM data structures for a transaction. """
  676. def __init__(self, registry):
  677. self.registry = registry
  678. # weak set of environments
  679. self.envs = WeakSet()
  680. # cache for all records
  681. self.cache = Cache()
  682. # fields to protect {field: ids}
  683. self.protected = StackMap()
  684. # pending computations {field: ids}
  685. self.tocompute = defaultdict(OrderedSet)
  686. def flush(self):
  687. """ Flush pending computations and updates in the transaction. """
  688. env_to_flush = None
  689. for env in self.envs:
  690. if isinstance(env.uid, int) or env.uid is None:
  691. env_to_flush = env
  692. if env.uid is not None:
  693. break
  694. if env_to_flush is not None:
  695. env_to_flush.flush_all()
  696. def clear(self):
  697. """ Clear the caches and pending computations and updates in the translations. """
  698. self.cache.clear()
  699. self.tocompute.clear()
  700. def reset(self):
  701. """ Reset the transaction. This clears the transaction, and reassigns
  702. the registry on all its environments. This operation is strongly
  703. recommended after reloading the registry.
  704. """
  705. self.registry = Registry(self.registry.db_name)
  706. for env in self.envs:
  707. env.registry = self.registry
  708. lazy_property.reset_all(env)
  709. self.clear()
  710. # sentinel value for optional parameters
  711. NOTHING = object()
  712. EMPTY_DICT = frozendict()
  713. class Cache(object):
  714. """ Implementation of the cache of records.
  715. For most fields, the cache is simply a mapping from a record and a field to
  716. a value. In the case of context-dependent fields, the mapping also depends
  717. on the environment of the given record. For the sake of performance, the
  718. cache is first partitioned by field, then by record. This makes some
  719. common ORM operations pretty fast, like determining which records have a
  720. value for a given field, or invalidating a given field on all possible
  721. records.
  722. The cache can also mark some entries as "dirty". Dirty entries essentially
  723. marks values that are different from the database. They represent database
  724. updates that haven't been done yet. Note that dirty entries only make
  725. sense for stored fields. Note also that if a field is dirty on a given
  726. record, and the field is context-dependent, then all the values of the
  727. record for that field are considered dirty. For the sake of consistency,
  728. the values that should be in the database must be in a context where all
  729. the field's context keys are ``None``.
  730. """
  731. def __init__(self):
  732. # {field: {record_id: value}, field: {context_key: {record_id: value}}}
  733. self._data = defaultdict(dict)
  734. # {field: set[id]} stores the fields and ids that are changed in the
  735. # cache, but not yet written in the database; their changed values are
  736. # in `_data`
  737. self._dirty = defaultdict(OrderedSet)
  738. def __repr__(self):
  739. # for debugging: show the cache content and dirty flags as stars
  740. data = {}
  741. for field, field_cache in sorted(self._data.items(), key=lambda item: str(item[0])):
  742. dirty_ids = self._dirty.get(field, ())
  743. if field_cache and isinstance(next(iter(field_cache)), tuple):
  744. data[field] = {
  745. key: {
  746. Starred(id_) if id_ in dirty_ids else id_: val if field.type != 'binary' else '<binary>'
  747. for id_, val in key_cache.items()
  748. }
  749. for key, key_cache in field_cache.items()
  750. }
  751. else:
  752. data[field] = {
  753. Starred(id_) if id_ in dirty_ids else id_: val if field.type != 'binary' else '<binary>'
  754. for id_, val in field_cache.items()
  755. }
  756. return repr(data)
  757. def _get_field_cache(self, model, field):
  758. """ Return the field cache of the given field, but not for modifying it. """
  759. field_cache = self._data.get(field, EMPTY_DICT)
  760. if field_cache and model.pool.field_depends_context[field]:
  761. field_cache = field_cache.get(model.env.cache_key(field), EMPTY_DICT)
  762. return field_cache
  763. def _set_field_cache(self, model, field):
  764. """ Return the field cache of the given field for modifying it. """
  765. field_cache = self._data[field]
  766. if model.pool.field_depends_context[field]:
  767. field_cache = field_cache.setdefault(model.env.cache_key(field), {})
  768. return field_cache
  769. def contains(self, record, field):
  770. """ Return whether ``record`` has a value for ``field``. """
  771. field_cache = self._get_field_cache(record, field)
  772. if field.translate:
  773. cache_value = field_cache.get(record.id, EMPTY_DICT)
  774. if cache_value is None:
  775. return True
  776. lang = record.env.lang or 'en_US'
  777. return lang in cache_value
  778. return record.id in field_cache
  779. def contains_field(self, field):
  780. """ Return whether ``field`` has a value for at least one record. """
  781. cache = self._data.get(field)
  782. if not cache:
  783. return False
  784. # 'cache' keys are tuples if 'field' is context-dependent, record ids otherwise
  785. if isinstance(next(iter(cache)), tuple):
  786. return any(value for value in cache.values())
  787. return True
  788. def get(self, record, field, default=NOTHING):
  789. """ Return the value of ``field`` for ``record``. """
  790. try:
  791. field_cache = self._get_field_cache(record, field)
  792. cache_value = field_cache[record._ids[0]]
  793. if field.translate and cache_value is not None:
  794. lang = record.env.lang or 'en_US'
  795. return cache_value[lang]
  796. return cache_value
  797. except KeyError:
  798. if default is NOTHING:
  799. raise CacheMiss(record, field)
  800. return default
  801. def set(self, record, field, value, dirty=False, check_dirty=True):
  802. """ Set the value of ``field`` for ``record``.
  803. One can normally make a clean field dirty but not the other way around.
  804. Updating a dirty field without ``dirty=True`` is a programming error and
  805. raises an exception.
  806. :param dirty: whether ``field`` must be made dirty on ``record`` after
  807. the update
  808. :param check_dirty: whether updating a dirty field without making it
  809. dirty must raise an exception
  810. """
  811. field_cache = self._set_field_cache(record, field)
  812. if field.translate and value is not None:
  813. lang = record.env.lang or 'en_US'
  814. cache_value = field_cache.get(record._ids[0]) or {}
  815. cache_value[lang] = value
  816. value = cache_value
  817. field_cache[record._ids[0]] = value
  818. if not check_dirty:
  819. return
  820. if dirty:
  821. assert field.column_type and field.store and record.id
  822. self._dirty[field].add(record.id)
  823. if record.pool.field_depends_context[field]:
  824. # put the values under conventional context key values {'context_key': None},
  825. # in order to ease the retrieval of those values to flush them
  826. context_none = dict.fromkeys(record.pool.field_depends_context[field])
  827. record = record.with_env(record.env(context=context_none))
  828. field_cache = self._set_field_cache(record, field)
  829. field_cache[record._ids[0]] = value
  830. elif record.id in self._dirty.get(field, ()):
  831. _logger.error("cache.set() removing flag dirty on %s.%s", record, field.name, stack_info=True)
  832. def update(self, records, field, values, dirty=False, check_dirty=True):
  833. """ Set the values of ``field`` for several ``records``.
  834. One can normally make a clean field dirty but not the other way around.
  835. Updating a dirty field without ``dirty=True`` is a programming error and
  836. raises an exception.
  837. :param dirty: whether ``field`` must be made dirty on ``record`` after
  838. the update
  839. :param check_dirty: whether updating a dirty field without making it
  840. dirty must raise an exception
  841. """
  842. if field.translate:
  843. lang = records.env.lang or 'en_US'
  844. field_cache = self._get_field_cache(records, field)
  845. cache_values = []
  846. for id_, value in zip(records._ids, values):
  847. if value is None:
  848. cache_values.append(None)
  849. else:
  850. cache_value = field_cache.get(id_) or {}
  851. cache_value[lang] = value
  852. cache_values.append(cache_value)
  853. values = cache_values
  854. self.update_raw(records, field, values, dirty, check_dirty)
  855. def update_raw(self, records, field, values, dirty=False, check_dirty=True):
  856. """ This is a variant of method :meth:`~update` without the logic for
  857. translated fields.
  858. """
  859. field_cache = self._set_field_cache(records, field)
  860. field_cache.update(zip(records._ids, values))
  861. if not check_dirty:
  862. return
  863. if dirty:
  864. assert field.column_type and field.store and all(records._ids)
  865. self._dirty[field].update(records._ids)
  866. if records.pool.field_depends_context[field]:
  867. # put the values under conventional context key values {'context_key': None},
  868. # in order to ease the retrieval of those values to flush them
  869. context_none = dict.fromkeys(records.pool.field_depends_context[field])
  870. records = records.with_env(records.env(context=context_none))
  871. field_cache = self._set_field_cache(records, field)
  872. field_cache.update(zip(records._ids, values))
  873. else:
  874. dirty_ids = self._dirty.get(field)
  875. if dirty_ids and not dirty_ids.isdisjoint(records._ids):
  876. _logger.error("cache.update() removing flag dirty on %s.%s", records, field.name, stack_info=True)
  877. def insert_missing(self, records, field, values):
  878. """ Set the values of ``field`` for the records in ``records`` that
  879. don't have a value yet. In other words, this does not overwrite
  880. existing values in cache.
  881. """
  882. field_cache = self._set_field_cache(records, field)
  883. if field.translate:
  884. lang = records.env.lang or 'en_US'
  885. for id_, val in zip(records._ids, values):
  886. if val is None:
  887. field_cache.setdefault(id_, None)
  888. else:
  889. cache_value = field_cache.setdefault(id_, {})
  890. if cache_value is not None:
  891. cache_value.setdefault(lang, val)
  892. else:
  893. for id_, val in zip(records._ids, values):
  894. field_cache.setdefault(id_, val)
  895. def remove(self, record, field):
  896. """ Remove the value of ``field`` for ``record``. """
  897. assert record.id not in self._dirty.get(field, ())
  898. try:
  899. field_cache = self._set_field_cache(record, field)
  900. del field_cache[record._ids[0]]
  901. except KeyError:
  902. pass
  903. def get_values(self, records, field):
  904. """ Return the cached values of ``field`` for ``records``. """
  905. field_cache = self._get_field_cache(records, field)
  906. for record_id in records._ids:
  907. try:
  908. yield field_cache[record_id]
  909. except KeyError:
  910. pass
  911. def get_until_miss(self, records, field):
  912. """ Return the cached values of ``field`` for ``records`` until a value is not found. """
  913. field_cache = self._get_field_cache(records, field)
  914. if field.translate:
  915. lang = records.env.lang or 'en_US'
  916. def get_value(id_):
  917. cache_value = field_cache[id_]
  918. return None if cache_value is None else cache_value[lang]
  919. else:
  920. get_value = field_cache.__getitem__
  921. vals = []
  922. for record_id in records._ids:
  923. try:
  924. vals.append(get_value(record_id))
  925. except KeyError:
  926. break
  927. return vals
  928. def get_records_different_from(self, records, field, value):
  929. """ Return the subset of ``records`` that has not ``value`` for ``field``. """
  930. field_cache = self._get_field_cache(records, field)
  931. if field.translate:
  932. lang = records.env.lang or 'en_US'
  933. def get_value(id_):
  934. cache_value = field_cache[id_]
  935. return None if cache_value is None else cache_value[lang]
  936. else:
  937. get_value = field_cache.__getitem__
  938. ids = []
  939. for record_id in records._ids:
  940. try:
  941. val = get_value(record_id)
  942. except KeyError:
  943. ids.append(record_id)
  944. else:
  945. if val != value:
  946. ids.append(record_id)
  947. return records.browse(ids)
  948. def get_fields(self, record):
  949. """ Return the fields with a value for ``record``. """
  950. for name, field in record._fields.items():
  951. if name != 'id' and record.id in self._get_field_cache(record, field):
  952. yield field
  953. def get_records(self, model, field):
  954. """ Return the records of ``model`` that have a value for ``field``. """
  955. field_cache = self._get_field_cache(model, field)
  956. return model.browse(field_cache)
  957. def get_missing_ids(self, records, field):
  958. """ Return the ids of ``records`` that have no value for ``field``. """
  959. field_cache = self._get_field_cache(records, field)
  960. if field.translate:
  961. lang = records.env.lang or 'en_US'
  962. for record_id in records._ids:
  963. cache_value = field_cache.get(record_id, False)
  964. if cache_value is False or not (cache_value is None or lang in cache_value):
  965. yield record_id
  966. else:
  967. for record_id in records._ids:
  968. if record_id not in field_cache:
  969. yield record_id
  970. def get_dirty_fields(self):
  971. """ Return the fields that have dirty records in cache. """
  972. return self._dirty.keys()
  973. def get_dirty_records(self, model, field):
  974. """ Return the records that for which ``field`` is dirty in cache. """
  975. return model.browse(self._dirty.get(field, ()))
  976. def has_dirty_fields(self, records, fields=None):
  977. """ Return whether any of the given records has dirty fields.
  978. :param fields: a collection of fields or ``None``; the value ``None`` is
  979. interpreted as any field on ``records``
  980. """
  981. if fields is None:
  982. return any(
  983. not ids.isdisjoint(records._ids)
  984. for field, ids in self._dirty.items()
  985. if field.model_name == records._name
  986. )
  987. else:
  988. return any(
  989. field in self._dirty and not self._dirty[field].isdisjoint(records._ids)
  990. for field in fields
  991. )
  992. def clear_dirty_field(self, field):
  993. """ Make the given field clean on all records, and return the ids of the
  994. formerly dirty records for the field.
  995. """
  996. return self._dirty.pop(field, ())
  997. def invalidate(self, spec=None):
  998. """ Invalidate the cache, partially or totally depending on ``spec``.
  999. If a field is context-dependent, invalidating it for a given record
  1000. actually invalidates all the values of that field on the record. In
  1001. other words, the field is invalidated for the record in all
  1002. environments.
  1003. This operation is unsafe by default, and must be used with care.
  1004. Indeed, invalidating a dirty field on a record may lead to an error,
  1005. because doing so drops the value to be written in database.
  1006. spec = [(field, ids), (field, None), ...]
  1007. """
  1008. if spec is None:
  1009. self._data.clear()
  1010. elif spec:
  1011. for field, ids in spec:
  1012. if ids is None:
  1013. self._data.pop(field, None)
  1014. continue
  1015. cache = self._data.get(field)
  1016. if not cache:
  1017. continue
  1018. caches = cache.values() if isinstance(next(iter(cache)), tuple) else [cache]
  1019. for field_cache in caches:
  1020. for id_ in ids:
  1021. field_cache.pop(id_, None)
  1022. def clear(self):
  1023. """ Invalidate the cache and its dirty flags. """
  1024. self._data.clear()
  1025. self._dirty.clear()
  1026. def check(self, env):
  1027. """ Check the consistency of the cache for the given environment. """
  1028. depends_context = env.registry.field_depends_context
  1029. invalids = []
  1030. def process(model, field, field_cache):
  1031. # ignore new records and records to flush
  1032. dirty_ids = self._dirty.get(field, ())
  1033. ids = [id_ for id_ in field_cache if id_ and id_ not in dirty_ids]
  1034. if not ids:
  1035. return
  1036. # select the column for the given ids
  1037. query = Query(env.cr, model._table, model._table_query)
  1038. qname = model._inherits_join_calc(model._table, field.name, query)
  1039. if field.type == 'binary' and (
  1040. model.env.context.get('bin_size') or model.env.context.get('bin_size_' + field.name)
  1041. ):
  1042. qname = f'pg_size_pretty(length({qname})::bigint)'
  1043. query.add_where(f'"{model._table}".id IN %s', [tuple(ids)])
  1044. query_str, params = query.select(f'"{model._table}".id', qname)
  1045. env.cr.execute(query_str, params)
  1046. # compare returned values with corresponding values in cache
  1047. for id_, value in env.cr.fetchall():
  1048. cached = field_cache[id_]
  1049. if value == cached or (not value and not cached):
  1050. continue
  1051. invalids.append((model.browse(id_), field, {'cached': cached, 'fetched': value}))
  1052. for field, field_cache in self._data.items():
  1053. # check column fields only
  1054. if not field.store or not field.column_type or callable(field.translate):
  1055. continue
  1056. model = env[field.model_name]
  1057. if depends_context[field]:
  1058. for context_keys, inner_cache in field_cache.items():
  1059. context = dict(zip(depends_context[field], context_keys))
  1060. if 'company' in context:
  1061. # the cache key 'company' actually comes from context
  1062. # key 'allowed_company_ids' (see property env.company
  1063. # and method env.cache_key())
  1064. context['allowed_company_ids'] = [context.pop('company')]
  1065. process(model.with_context(context), field, inner_cache)
  1066. else:
  1067. process(model, field, field_cache)
  1068. if invalids:
  1069. _logger.warning("Invalid cache: %s", pformat(invalids))
  1070. class Starred:
  1071. """ Simple helper class to ``repr`` a value with a star suffix. """
  1072. __slots__ = ['value']
  1073. def __init__(self, value):
  1074. self.value = value
  1075. def __repr__(self):
  1076. return f"{self.value!r}*"
  1077. # keep those imports here in order to handle cyclic dependencies correctly
  1078. from odoo import SUPERUSER_ID
  1079. from odoo.modules.registry import Registry