ir_module.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. import base64
  4. from collections import defaultdict, OrderedDict
  5. from decorator import decorator
  6. from operator import attrgetter
  7. import io
  8. import logging
  9. import os
  10. import shutil
  11. import tempfile
  12. import threading
  13. import zipfile
  14. import requests
  15. import werkzeug.urls
  16. from docutils import nodes
  17. from docutils.core import publish_string
  18. from docutils.transforms import Transform, writer_aux
  19. from docutils.writers.html4css1 import Writer
  20. import lxml.html
  21. import psycopg2
  22. import odoo
  23. from odoo import api, fields, models, modules, tools, _
  24. from odoo.addons.base.models.ir_model import MODULE_UNINSTALL_FLAG
  25. from odoo.exceptions import AccessDenied, UserError
  26. from odoo.osv import expression
  27. from odoo.tools.parse_version import parse_version
  28. from odoo.tools.misc import topological_sort
  29. from odoo.tools.translate import TranslationImporter
  30. from odoo.http import request
  31. from odoo.modules import get_module_path, get_module_resource
  32. _logger = logging.getLogger(__name__)
  33. ACTION_DICT = {
  34. 'view_mode': 'form',
  35. 'res_model': 'base.module.upgrade',
  36. 'target': 'new',
  37. 'type': 'ir.actions.act_window',
  38. }
  39. def backup(path, raise_exception=True):
  40. path = os.path.normpath(path)
  41. if not os.path.exists(path):
  42. if not raise_exception:
  43. return None
  44. raise OSError('path does not exists')
  45. cnt = 1
  46. while True:
  47. bck = '%s~%d' % (path, cnt)
  48. if not os.path.exists(bck):
  49. shutil.move(path, bck)
  50. return bck
  51. cnt += 1
  52. def assert_log_admin_access(method):
  53. """Decorator checking that the calling user is an administrator, and logging the call.
  54. Raises an AccessDenied error if the user does not have administrator privileges, according
  55. to `user._is_admin()`.
  56. """
  57. def check_and_log(method, self, *args, **kwargs):
  58. user = self.env.user
  59. origin = request.httprequest.remote_addr if request else 'n/a'
  60. log_data = (method.__name__, self.sudo().mapped('display_name'), user.login, user.id, origin)
  61. if not self.env.is_admin():
  62. _logger.warning('DENY access to module.%s on %s to user %s ID #%s via %s', *log_data)
  63. raise AccessDenied()
  64. _logger.info('ALLOW access to module.%s on %s to user %s #%s via %s', *log_data)
  65. return method(self, *args, **kwargs)
  66. return decorator(check_and_log, method)
  67. class ModuleCategory(models.Model):
  68. _name = "ir.module.category"
  69. _description = "Application"
  70. _order = 'name'
  71. @api.depends('module_ids')
  72. def _compute_module_nr(self):
  73. self.env['ir.module.module'].flush_model(['category_id'])
  74. self.flush_model(['parent_id'])
  75. cr = self._cr
  76. cr.execute('SELECT category_id, COUNT(*) \
  77. FROM ir_module_module \
  78. WHERE category_id IN %(ids)s \
  79. OR category_id IN (SELECT id \
  80. FROM ir_module_category \
  81. WHERE parent_id IN %(ids)s) \
  82. GROUP BY category_id', {'ids': tuple(self.ids)}
  83. )
  84. result = dict(cr.fetchall())
  85. for cat in self.filtered('id'):
  86. cr.execute('SELECT id FROM ir_module_category WHERE parent_id=%s', (cat.id,))
  87. cat.module_nr = sum([result.get(c, 0) for (c,) in cr.fetchall()], result.get(cat.id, 0))
  88. name = fields.Char(string='Name', required=True, translate=True, index=True)
  89. parent_id = fields.Many2one('ir.module.category', string='Parent Application', index=True)
  90. child_ids = fields.One2many('ir.module.category', 'parent_id', string='Child Applications')
  91. module_nr = fields.Integer(string='Number of Apps', compute='_compute_module_nr')
  92. module_ids = fields.One2many('ir.module.module', 'category_id', string='Modules')
  93. description = fields.Text(string='Description', translate=True)
  94. sequence = fields.Integer(string='Sequence')
  95. visible = fields.Boolean(string='Visible', default=True)
  96. exclusive = fields.Boolean(string='Exclusive')
  97. xml_id = fields.Char(string='External ID', compute='_compute_xml_id')
  98. def _compute_xml_id(self):
  99. xml_ids = defaultdict(list)
  100. domain = [('model', '=', self._name), ('res_id', 'in', self.ids)]
  101. for data in self.env['ir.model.data'].sudo().search_read(domain, ['module', 'name', 'res_id']):
  102. xml_ids[data['res_id']].append("%s.%s" % (data['module'], data['name']))
  103. for cat in self:
  104. cat.xml_id = xml_ids.get(cat.id, [''])[0]
  105. class MyFilterMessages(Transform):
  106. """
  107. Custom docutils transform to remove `system message` for a document and
  108. generate warnings.
  109. (The standard filter removes them based on some `report_level` passed in
  110. the `settings_override` dictionary, but if we use it, we can't see them
  111. and generate warnings.)
  112. """
  113. default_priority = 870
  114. def apply(self):
  115. for node in self.document.traverse(nodes.system_message):
  116. _logger.warning("docutils' system message present: %s", str(node))
  117. node.parent.remove(node)
  118. class MyWriter(Writer):
  119. """
  120. Custom docutils html4ccs1 writer that doesn't add the warnings to the
  121. output document.
  122. """
  123. def get_transforms(self):
  124. return [MyFilterMessages, writer_aux.Admonitions]
  125. STATES = [
  126. ('uninstallable', 'Uninstallable'),
  127. ('uninstalled', 'Not Installed'),
  128. ('installed', 'Installed'),
  129. ('to upgrade', 'To be upgraded'),
  130. ('to remove', 'To be removed'),
  131. ('to install', 'To be installed'),
  132. ]
  133. XML_DECLARATION = (
  134. '<?xml version='.encode('utf-8'),
  135. '<?xml version='.encode('utf-16-be'),
  136. '<?xml version='.encode('utf-16-le'),
  137. )
  138. class Module(models.Model):
  139. _name = "ir.module.module"
  140. _rec_name = "shortdesc"
  141. _rec_names_search = ['name', 'shortdesc', 'summary']
  142. _description = "Module"
  143. _order = 'application desc,sequence,name'
  144. @api.model
  145. def get_views(self, views, options=None):
  146. res = super().get_views(views, options)
  147. if res['views'].get('form', {}).get('toolbar'):
  148. install_id = self.env.ref('base.action_server_module_immediate_install').id
  149. action = [rec for rec in res['views']['form']['toolbar']['action'] if rec.get('id', False) != install_id]
  150. res['views']['form']['toolbar'] = {'action': action}
  151. return res
  152. @classmethod
  153. def get_module_info(cls, name):
  154. try:
  155. return modules.get_manifest(name)
  156. except Exception:
  157. _logger.debug('Error when trying to fetch information for module %s', name, exc_info=True)
  158. return {}
  159. @api.depends('name', 'description')
  160. def _get_desc(self):
  161. for module in self:
  162. if not module.name:
  163. module.description_html = False
  164. continue
  165. module_path = modules.get_module_path(module.name, display_warning=False) # avoid to log warning for fake community module
  166. if module_path:
  167. path = modules.check_resource_path(module_path, 'static/description/index.html')
  168. if module_path and path:
  169. with tools.file_open(path, 'rb') as desc_file:
  170. doc = desc_file.read()
  171. if not doc.startswith(XML_DECLARATION):
  172. try:
  173. doc = doc.decode('utf-8')
  174. except UnicodeDecodeError:
  175. pass
  176. html = lxml.html.document_fromstring(doc)
  177. for element, attribute, link, pos in html.iterlinks():
  178. if element.get('src') and not '//' in element.get('src') and not 'static/' in element.get('src'):
  179. element.set('src', "/%s/static/description/%s" % (module.name, element.get('src')))
  180. module.description_html = tools.html_sanitize(lxml.html.tostring(html))
  181. else:
  182. overrides = {
  183. 'embed_stylesheet': False,
  184. 'doctitle_xform': False,
  185. 'output_encoding': 'unicode',
  186. 'xml_declaration': False,
  187. 'file_insertion_enabled': False,
  188. }
  189. output = publish_string(source=module.description if not module.application and module.description else '', settings_overrides=overrides, writer=MyWriter())
  190. module.description_html = tools.html_sanitize(output)
  191. @api.depends('name')
  192. def _get_latest_version(self):
  193. default_version = modules.adapt_version('1.0')
  194. for module in self:
  195. module.installed_version = self.get_module_info(module.name).get('version', default_version)
  196. @api.depends('name', 'state')
  197. def _get_views(self):
  198. IrModelData = self.env['ir.model.data'].with_context(active_test=True)
  199. dmodels = ['ir.ui.view', 'ir.actions.report', 'ir.ui.menu']
  200. for module in self:
  201. # Skip uninstalled modules below, no data to find anyway.
  202. if module.state not in ('installed', 'to upgrade', 'to remove'):
  203. module.views_by_module = ""
  204. module.reports_by_module = ""
  205. module.menus_by_module = ""
  206. continue
  207. # then, search and group ir.model.data records
  208. imd_models = defaultdict(list)
  209. imd_domain = [('module', '=', module.name), ('model', 'in', tuple(dmodels))]
  210. for data in IrModelData.sudo().search(imd_domain):
  211. imd_models[data.model].append(data.res_id)
  212. def browse(model):
  213. # as this method is called before the module update, some xmlid
  214. # may be invalid at this stage; explictly filter records before
  215. # reading them
  216. return self.env[model].browse(imd_models[model]).exists()
  217. def format_view(v):
  218. return '%s%s (%s)' % (v.inherit_id and '* INHERIT ' or '', v.name, v.type)
  219. module.views_by_module = "\n".join(sorted(format_view(v) for v in browse('ir.ui.view')))
  220. module.reports_by_module = "\n".join(sorted(r.name for r in browse('ir.actions.report')))
  221. module.menus_by_module = "\n".join(sorted(m.complete_name for m in browse('ir.ui.menu')))
  222. @api.depends('icon')
  223. def _get_icon_image(self):
  224. for module in self:
  225. module.icon_image = ''
  226. if module.icon:
  227. path_parts = module.icon.split('/')
  228. path = modules.get_module_resource(path_parts[1], *path_parts[2:])
  229. elif module.id:
  230. path = modules.module.get_module_icon_path(module)
  231. else:
  232. path = ''
  233. if path:
  234. with tools.file_open(path, 'rb') as image_file:
  235. module.icon_image = base64.b64encode(image_file.read())
  236. name = fields.Char('Technical Name', readonly=True, required=True)
  237. category_id = fields.Many2one('ir.module.category', string='Category', readonly=True, index=True)
  238. shortdesc = fields.Char('Module Name', readonly=True, translate=True)
  239. summary = fields.Char('Summary', readonly=True, translate=True)
  240. description = fields.Text('Description', readonly=True, translate=True)
  241. description_html = fields.Html('Description HTML', compute='_get_desc')
  242. author = fields.Char("Author", readonly=True)
  243. maintainer = fields.Char('Maintainer', readonly=True)
  244. contributors = fields.Text('Contributors', readonly=True)
  245. website = fields.Char("Website", readonly=True)
  246. # attention: Incorrect field names !!
  247. # installed_version refers the latest version (the one on disk)
  248. # latest_version refers the installed version (the one in database)
  249. # published_version refers the version available on the repository
  250. installed_version = fields.Char('Latest Version', compute='_get_latest_version')
  251. latest_version = fields.Char('Installed Version', readonly=True)
  252. published_version = fields.Char('Published Version', readonly=True)
  253. url = fields.Char('URL', readonly=True)
  254. sequence = fields.Integer('Sequence', default=100)
  255. dependencies_id = fields.One2many('ir.module.module.dependency', 'module_id',
  256. string='Dependencies', readonly=True)
  257. exclusion_ids = fields.One2many('ir.module.module.exclusion', 'module_id',
  258. string='Exclusions', readonly=True)
  259. auto_install = fields.Boolean('Automatic Installation',
  260. help='An auto-installable module is automatically installed by the '
  261. 'system when all its dependencies are satisfied. '
  262. 'If the module has no dependency, it is always installed.')
  263. state = fields.Selection(STATES, string='Status', default='uninstallable', readonly=True, index=True)
  264. demo = fields.Boolean('Demo Data', default=False, readonly=True)
  265. license = fields.Selection([
  266. ('GPL-2', 'GPL Version 2'),
  267. ('GPL-2 or any later version', 'GPL-2 or later version'),
  268. ('GPL-3', 'GPL Version 3'),
  269. ('GPL-3 or any later version', 'GPL-3 or later version'),
  270. ('AGPL-3', 'Affero GPL-3'),
  271. ('LGPL-3', 'LGPL Version 3'),
  272. ('Other OSI approved licence', 'Other OSI Approved License'),
  273. ('OEEL-1', 'Odoo Enterprise Edition License v1.0'),
  274. ('OPL-1', 'Odoo Proprietary License v1.0'),
  275. ('Other proprietary', 'Other Proprietary')
  276. ], string='License', default='LGPL-3', readonly=True)
  277. menus_by_module = fields.Text(string='Menus', compute='_get_views', store=True)
  278. reports_by_module = fields.Text(string='Reports', compute='_get_views', store=True)
  279. views_by_module = fields.Text(string='Views', compute='_get_views', store=True)
  280. application = fields.Boolean('Application', readonly=True)
  281. icon = fields.Char('Icon URL')
  282. icon_image = fields.Binary(string='Icon', compute='_get_icon_image')
  283. to_buy = fields.Boolean('Odoo Enterprise Module', default=False)
  284. has_iap = fields.Boolean(compute='_compute_has_iap')
  285. _sql_constraints = [
  286. ('name_uniq', 'UNIQUE (name)', 'The name of the module must be unique!'),
  287. ]
  288. def _compute_has_iap(self):
  289. for module in self:
  290. module.has_iap = bool(module.id) and 'iap' in module.upstream_dependencies(exclude_states=('',)).mapped('name')
  291. @api.ondelete(at_uninstall=False)
  292. def _unlink_except_installed(self):
  293. for module in self:
  294. if module.state in ('installed', 'to upgrade', 'to remove', 'to install'):
  295. raise UserError(_('You are trying to remove a module that is installed or will be installed.'))
  296. def unlink(self):
  297. self.clear_caches()
  298. return super(Module, self).unlink()
  299. def _get_modules_to_load_domain(self):
  300. """ Domain to retrieve the modules that should be loaded by the registry. """
  301. return [('state', '=', 'installed')]
  302. @classmethod
  303. def check_external_dependencies(cls, module_name, newstate='to install'):
  304. terp = cls.get_module_info(module_name)
  305. try:
  306. modules.check_manifest_dependencies(terp)
  307. except Exception as e:
  308. if newstate == 'to install':
  309. msg = _('Unable to install module "%s" because an external dependency is not met: %s')
  310. elif newstate == 'to upgrade':
  311. msg = _('Unable to upgrade module "%s" because an external dependency is not met: %s')
  312. else:
  313. msg = _('Unable to process module "%s" because an external dependency is not met: %s')
  314. raise UserError(msg % (module_name, e.args[0]))
  315. def _state_update(self, newstate, states_to_update, level=100):
  316. if level < 1:
  317. raise UserError(_('Recursion error in modules dependencies !'))
  318. # whether some modules are installed with demo data
  319. demo = False
  320. for module in self:
  321. if module.state not in states_to_update:
  322. demo = demo or module.demo
  323. continue
  324. # determine dependency modules to update/others
  325. update_mods, ready_mods = self.browse(), self.browse()
  326. for dep in module.dependencies_id:
  327. if dep.state == 'unknown':
  328. raise UserError(_("You try to install module '%s' that depends on module '%s'.\nBut the latter module is not available in your system.") % (module.name, dep.name,))
  329. if dep.depend_id.state == newstate:
  330. ready_mods += dep.depend_id
  331. else:
  332. update_mods += dep.depend_id
  333. # update dependency modules that require it, and determine demo for module
  334. update_demo = update_mods._state_update(newstate, states_to_update, level=level-1)
  335. module_demo = module.demo or update_demo or any(mod.demo for mod in ready_mods)
  336. demo = demo or module_demo
  337. if module.state in states_to_update:
  338. # check dependencies and update module itself
  339. self.check_external_dependencies(module.name, newstate)
  340. module.write({'state': newstate, 'demo': module_demo})
  341. return demo
  342. @assert_log_admin_access
  343. def button_install(self):
  344. # domain to select auto-installable (but not yet installed) modules
  345. auto_domain = [('state', '=', 'uninstalled'), ('auto_install', '=', True)]
  346. # determine whether an auto-install module must be installed:
  347. # - all its dependencies are installed or to be installed,
  348. # - at least one dependency is 'to install'
  349. install_states = frozenset(('installed', 'to install', 'to upgrade'))
  350. def must_install(module):
  351. states = {dep.state for dep in module.dependencies_id if dep.auto_install_required}
  352. return states <= install_states and 'to install' in states
  353. modules = self
  354. while modules:
  355. # Mark the given modules and their dependencies to be installed.
  356. modules._state_update('to install', ['uninstalled'])
  357. # Determine which auto-installable modules must be installed.
  358. modules = self.search(auto_domain).filtered(must_install)
  359. # the modules that are installed/to install/to upgrade
  360. install_mods = self.search([('state', 'in', list(install_states))])
  361. # check individual exclusions
  362. install_names = {module.name for module in install_mods}
  363. for module in install_mods:
  364. for exclusion in module.exclusion_ids:
  365. if exclusion.name in install_names:
  366. msg = _('Modules "%s" and "%s" are incompatible.')
  367. raise UserError(msg % (module.shortdesc, exclusion.exclusion_id.shortdesc))
  368. # check category exclusions
  369. def closure(module):
  370. todo = result = module
  371. while todo:
  372. result |= todo
  373. todo = todo.dependencies_id.depend_id
  374. return result
  375. exclusives = self.env['ir.module.category'].search([('exclusive', '=', True)])
  376. for category in exclusives:
  377. # retrieve installed modules in category and sub-categories
  378. categories = category.search([('id', 'child_of', category.ids)])
  379. modules = install_mods.filtered(lambda mod: mod.category_id in categories)
  380. # the installation is valid if all installed modules in categories
  381. # belong to the transitive dependencies of one of them
  382. if modules and not any(modules <= closure(module) for module in modules):
  383. msg = _('You are trying to install incompatible modules in category "%s":')
  384. labels = dict(self.fields_get(['state'])['state']['selection'])
  385. raise UserError("\n".join([msg % category.name] + [
  386. "- %s (%s)" % (module.shortdesc, labels[module.state])
  387. for module in modules
  388. ]))
  389. return dict(ACTION_DICT, name=_('Install'))
  390. @assert_log_admin_access
  391. def button_immediate_install(self):
  392. """ Installs the selected module(s) immediately and fully,
  393. returns the next res.config action to execute
  394. :returns: next res.config item to execute
  395. :rtype: dict[str, object]
  396. """
  397. _logger.info('User #%d triggered module installation', self.env.uid)
  398. # We use here the request object (which is thread-local) as a kind of
  399. # "global" env because the env is not usable in the following use case.
  400. # When installing a Chart of Account, I would like to send the
  401. # allowed companies to configure it on the correct company.
  402. # Otherwise, the SUPERUSER won't be aware of that and will try to
  403. # configure the CoA on his own company, which makes no sense.
  404. if request:
  405. request.allowed_company_ids = self.env.companies.ids
  406. return self._button_immediate_function(type(self).button_install)
  407. @assert_log_admin_access
  408. def button_install_cancel(self):
  409. self.write({'state': 'uninstalled', 'demo': False})
  410. return True
  411. @assert_log_admin_access
  412. def module_uninstall(self):
  413. """ Perform the various steps required to uninstall a module completely
  414. including the deletion of all database structures created by the module:
  415. tables, columns, constraints, etc.
  416. """
  417. modules_to_remove = self.mapped('name')
  418. self.env['ir.model.data']._module_data_uninstall(modules_to_remove)
  419. # we deactivate prefetching to not try to read a column that has been deleted
  420. self.with_context(prefetch_fields=False).write({'state': 'uninstalled', 'latest_version': False})
  421. return True
  422. def _remove_copied_views(self):
  423. """ Remove the copies of the views installed by the modules in `self`.
  424. Those copies do not have an external id so they will not be cleaned by
  425. `_module_data_uninstall`. This is why we rely on `key` instead.
  426. It is important to remove these copies because using them will crash if
  427. they rely on data that don't exist anymore if the module is removed.
  428. """
  429. domain = expression.OR([[('key', '=like', m.name + '.%')] for m in self])
  430. orphans = self.env['ir.ui.view'].with_context(**{'active_test': False, MODULE_UNINSTALL_FLAG: True}).search(domain)
  431. orphans.unlink()
  432. @api.returns('self')
  433. def downstream_dependencies(self, known_deps=None,
  434. exclude_states=('uninstalled', 'uninstallable', 'to remove')):
  435. """ Return the modules that directly or indirectly depend on the modules
  436. in `self`, and that satisfy the `exclude_states` filter.
  437. """
  438. if not self:
  439. return self
  440. self.flush_model(['name', 'state'])
  441. self.env['ir.module.module.dependency'].flush_model(['module_id', 'name'])
  442. known_deps = known_deps or self.browse()
  443. query = """ SELECT DISTINCT m.id
  444. FROM ir_module_module_dependency d
  445. JOIN ir_module_module m ON (d.module_id=m.id)
  446. WHERE
  447. d.name IN (SELECT name from ir_module_module where id in %s) AND
  448. m.state NOT IN %s AND
  449. m.id NOT IN %s """
  450. self._cr.execute(query, (tuple(self.ids), tuple(exclude_states), tuple(known_deps.ids or self.ids)))
  451. new_deps = self.browse([row[0] for row in self._cr.fetchall()])
  452. missing_mods = new_deps - known_deps
  453. known_deps |= new_deps
  454. if missing_mods:
  455. known_deps |= missing_mods.downstream_dependencies(known_deps, exclude_states)
  456. return known_deps
  457. @api.returns('self')
  458. def upstream_dependencies(self, known_deps=None,
  459. exclude_states=('installed', 'uninstallable', 'to remove')):
  460. """ Return the dependency tree of modules of the modules in `self`, and
  461. that satisfy the `exclude_states` filter.
  462. """
  463. if not self:
  464. return self
  465. self.flush_model(['name', 'state'])
  466. self.env['ir.module.module.dependency'].flush_model(['module_id', 'name'])
  467. known_deps = known_deps or self.browse()
  468. query = """ SELECT DISTINCT m.id
  469. FROM ir_module_module_dependency d
  470. JOIN ir_module_module m ON (d.module_id=m.id)
  471. WHERE
  472. m.name IN (SELECT name from ir_module_module_dependency where module_id in %s) AND
  473. m.state NOT IN %s AND
  474. m.id NOT IN %s """
  475. self._cr.execute(query, (tuple(self.ids), tuple(exclude_states), tuple(known_deps.ids or self.ids)))
  476. new_deps = self.browse([row[0] for row in self._cr.fetchall()])
  477. missing_mods = new_deps - known_deps
  478. known_deps |= new_deps
  479. if missing_mods:
  480. known_deps |= missing_mods.upstream_dependencies(known_deps, exclude_states)
  481. return known_deps
  482. def next(self):
  483. """
  484. Return the action linked to an ir.actions.todo is there exists one that
  485. should be executed. Otherwise, redirect to /web
  486. """
  487. Todos = self.env['ir.actions.todo']
  488. _logger.info('getting next %s', Todos)
  489. active_todo = Todos.search([('state', '=', 'open')], limit=1)
  490. if active_todo:
  491. _logger.info('next action is "%s"', active_todo.name)
  492. return active_todo.action_launch()
  493. return {
  494. 'type': 'ir.actions.act_url',
  495. 'target': 'self',
  496. 'url': '/web',
  497. }
  498. def _button_immediate_function(self, function):
  499. if not self.env.registry.ready or self.env.registry._init:
  500. raise UserError(_('The method _button_immediate_install cannot be called on init or non loaded registries. Please use button_install instead.'))
  501. if getattr(threading.current_thread(), 'testing', False):
  502. raise RuntimeError(
  503. "Module operations inside tests are not transactional and thus forbidden.\n"
  504. "If you really need to perform module operations to test a specific behavior, it "
  505. "is best to write it as a standalone script, and ask the runbot/metastorm team "
  506. "for help."
  507. )
  508. try:
  509. # This is done because the installation/uninstallation/upgrade can modify a currently
  510. # running cron job and prevent it from finishing, and since the ir_cron table is locked
  511. # during execution, the lock won't be released until timeout.
  512. self._cr.execute("SELECT * FROM ir_cron FOR UPDATE NOWAIT")
  513. except psycopg2.OperationalError:
  514. raise UserError(_("Odoo is currently processing a scheduled action.\n"
  515. "Module operations are not possible at this time, "
  516. "please try again later or contact your system administrator."))
  517. function(self)
  518. self._cr.commit()
  519. registry = modules.registry.Registry.new(self._cr.dbname, update_module=True)
  520. self._cr.commit()
  521. if request and request.registry is self.env.registry:
  522. request.env.cr.reset()
  523. request.registry = request.env.registry
  524. assert request.env.registry is registry
  525. self._cr.reset()
  526. assert self.env.registry is registry
  527. # pylint: disable=next-method-called
  528. config = self.env['ir.module.module'].next() or {}
  529. if config.get('type') not in ('ir.actions.act_window_close',):
  530. return config
  531. # reload the client; open the first available root menu
  532. menu = self.env['ir.ui.menu'].search([('parent_id', '=', False)])[:1]
  533. return {
  534. 'type': 'ir.actions.client',
  535. 'tag': 'reload',
  536. 'params': {'menu_id': menu.id},
  537. }
  538. @assert_log_admin_access
  539. def button_immediate_uninstall(self):
  540. """
  541. Uninstall the selected module(s) immediately and fully,
  542. returns the next res.config action to execute
  543. """
  544. _logger.info('User #%d triggered module uninstallation', self.env.uid)
  545. return self._button_immediate_function(type(self).button_uninstall)
  546. @assert_log_admin_access
  547. def button_uninstall(self):
  548. un_installable_modules = set(odoo.conf.server_wide_modules) & set(self.mapped('name'))
  549. if un_installable_modules:
  550. raise UserError(_("Those modules cannot be uninstalled: %s", ', '.join(un_installable_modules)))
  551. if any(state not in ('installed', 'to upgrade') for state in self.mapped('state')):
  552. raise UserError(_(
  553. "One or more of the selected modules have already been uninstalled, if you "
  554. "believe this to be an error, you may try again later or contact support."
  555. ))
  556. deps = self.downstream_dependencies()
  557. (self + deps).write({'state': 'to remove'})
  558. return dict(ACTION_DICT, name=_('Uninstall'))
  559. @assert_log_admin_access
  560. def button_uninstall_wizard(self):
  561. """ Launch the wizard to uninstall the given module. """
  562. return {
  563. 'type': 'ir.actions.act_window',
  564. 'target': 'new',
  565. 'name': _('Uninstall module'),
  566. 'view_mode': 'form',
  567. 'res_model': 'base.module.uninstall',
  568. 'context': {'default_module_id': self.id},
  569. }
  570. def button_uninstall_cancel(self):
  571. self.write({'state': 'installed'})
  572. return True
  573. @assert_log_admin_access
  574. def button_immediate_upgrade(self):
  575. """
  576. Upgrade the selected module(s) immediately and fully,
  577. return the next res.config action to execute
  578. """
  579. return self._button_immediate_function(type(self).button_upgrade)
  580. @assert_log_admin_access
  581. def button_upgrade(self):
  582. if not self:
  583. return
  584. Dependency = self.env['ir.module.module.dependency']
  585. self.update_list()
  586. todo = list(self)
  587. if 'base' in self.mapped('name'):
  588. # If an installed module is only present in the dependency graph through
  589. # a new, uninstalled dependency, it will not have been selected yet.
  590. # An update of 'base' should also update these modules, and as a consequence,
  591. # install the new dependency.
  592. todo.extend(self.search([
  593. ('state', '=', 'installed'),
  594. ('name', '!=', 'studio_customization'),
  595. ('id', 'not in', self.ids),
  596. ]))
  597. i = 0
  598. while i < len(todo):
  599. module = todo[i]
  600. i += 1
  601. if module.state not in ('installed', 'to upgrade'):
  602. raise UserError(_("Can not upgrade module '%s'. It is not installed.") % (module.name,))
  603. if self.get_module_info(module.name).get("installable", True):
  604. self.check_external_dependencies(module.name, 'to upgrade')
  605. for dep in Dependency.search([('name', '=', module.name)]):
  606. if (
  607. dep.module_id.state == 'installed'
  608. and dep.module_id not in todo
  609. and dep.module_id.name != 'studio_customization'
  610. ):
  611. todo.append(dep.module_id)
  612. self.browse(module.id for module in todo).write({'state': 'to upgrade'})
  613. to_install = []
  614. for module in todo:
  615. if not self.get_module_info(module.name).get("installable", True):
  616. continue
  617. for dep in module.dependencies_id:
  618. if dep.state == 'unknown':
  619. raise UserError(_('You try to upgrade the module %s that depends on the module: %s.\nBut this module is not available in your system.') % (module.name, dep.name,))
  620. if dep.state == 'uninstalled':
  621. to_install += self.search([('name', '=', dep.name)]).ids
  622. self.browse(to_install).button_install()
  623. return dict(ACTION_DICT, name=_('Apply Schedule Upgrade'))
  624. @assert_log_admin_access
  625. def button_upgrade_cancel(self):
  626. self.write({'state': 'installed'})
  627. return True
  628. @staticmethod
  629. def get_values_from_terp(terp):
  630. return {
  631. 'description': terp.get('description', ''),
  632. 'shortdesc': terp.get('name', ''),
  633. 'author': terp.get('author', 'Unknown'),
  634. 'maintainer': terp.get('maintainer', False),
  635. 'contributors': ', '.join(terp.get('contributors', [])) or False,
  636. 'website': terp.get('website', ''),
  637. 'license': terp.get('license', 'LGPL-3'),
  638. 'sequence': terp.get('sequence', 100),
  639. 'application': terp.get('application', False),
  640. 'auto_install': terp.get('auto_install', False) is not False,
  641. 'icon': terp.get('icon', False),
  642. 'summary': terp.get('summary', ''),
  643. 'url': terp.get('url') or terp.get('live_test_url', ''),
  644. 'to_buy': False
  645. }
  646. @api.model_create_multi
  647. def create(self, vals_list):
  648. modules = super().create(vals_list)
  649. module_metadata_list = [{
  650. 'name': 'module_%s' % module.name,
  651. 'model': 'ir.module.module',
  652. 'module': 'base',
  653. 'res_id': module.id,
  654. 'noupdate': True,
  655. } for module in modules]
  656. self.env['ir.model.data'].create(module_metadata_list)
  657. return modules
  658. # update the list of available packages
  659. @assert_log_admin_access
  660. @api.model
  661. def update_list(self):
  662. res = [0, 0] # [update, add]
  663. default_version = modules.adapt_version('1.0')
  664. known_mods = self.with_context(lang=None).search([])
  665. known_mods_names = {mod.name: mod for mod in known_mods}
  666. # iterate through detected modules and update/create them in db
  667. for mod_name in modules.get_modules():
  668. mod = known_mods_names.get(mod_name)
  669. terp = self.get_module_info(mod_name)
  670. values = self.get_values_from_terp(terp)
  671. if mod:
  672. updated_values = {}
  673. for key in values:
  674. old = getattr(mod, key)
  675. if (old or values[key]) and values[key] != old:
  676. updated_values[key] = values[key]
  677. if terp.get('installable', True) and mod.state == 'uninstallable':
  678. updated_values['state'] = 'uninstalled'
  679. if parse_version(terp.get('version', default_version)) > parse_version(mod.latest_version or default_version):
  680. res[0] += 1
  681. if updated_values:
  682. mod.write(updated_values)
  683. else:
  684. mod_path = modules.get_module_path(mod_name)
  685. if not mod_path or not terp:
  686. continue
  687. state = "uninstalled" if terp.get('installable', True) else "uninstallable"
  688. mod = self.create(dict(name=mod_name, state=state, **values))
  689. res[1] += 1
  690. mod._update_dependencies(terp.get('depends', []), terp.get('auto_install'))
  691. mod._update_exclusions(terp.get('excludes', []))
  692. mod._update_category(terp.get('category', 'Uncategorized'))
  693. return res
  694. @assert_log_admin_access
  695. def download(self, download=True):
  696. return []
  697. @assert_log_admin_access
  698. @api.model
  699. def install_from_urls(self, urls):
  700. if not self.env.user.has_group('base.group_system'):
  701. raise AccessDenied()
  702. # One-click install is opt-in - cfr Issue #15225
  703. ad_dir = tools.config.addons_data_dir
  704. if not os.access(ad_dir, os.W_OK):
  705. msg = (_("Automatic install of downloaded Apps is currently disabled.") + "\n\n" +
  706. _("To enable it, make sure this directory exists and is writable on the server:") +
  707. "\n%s" % ad_dir)
  708. _logger.warning(msg)
  709. raise UserError(msg)
  710. apps_server = werkzeug.urls.url_parse(self.get_apps_server())
  711. OPENERP = odoo.release.product_name.lower()
  712. tmp = tempfile.mkdtemp()
  713. _logger.debug('Install from url: %r', urls)
  714. try:
  715. # 1. Download & unzip missing modules
  716. for module_name, url in urls.items():
  717. if not url:
  718. continue # nothing to download, local version is already the last one
  719. up = werkzeug.urls.url_parse(url)
  720. if up.scheme != apps_server.scheme or up.netloc != apps_server.netloc:
  721. raise AccessDenied()
  722. try:
  723. _logger.info('Downloading module `%s` from OpenERP Apps', module_name)
  724. response = requests.get(url)
  725. response.raise_for_status()
  726. content = response.content
  727. except Exception:
  728. _logger.exception('Failed to fetch module %s', module_name)
  729. raise UserError(_('The `%s` module appears to be unavailable at the moment, please try again later.', module_name))
  730. else:
  731. zipfile.ZipFile(io.BytesIO(content)).extractall(tmp)
  732. assert os.path.isdir(os.path.join(tmp, module_name))
  733. # 2a. Copy/Replace module source in addons path
  734. for module_name, url in urls.items():
  735. if module_name == OPENERP or not url:
  736. continue # OPENERP is special case, handled below, and no URL means local module
  737. module_path = modules.get_module_path(module_name, downloaded=True, display_warning=False)
  738. bck = backup(module_path, False)
  739. _logger.info('Copy downloaded module `%s` to `%s`', module_name, module_path)
  740. shutil.move(os.path.join(tmp, module_name), module_path)
  741. if bck:
  742. shutil.rmtree(bck)
  743. # 2b. Copy/Replace server+base module source if downloaded
  744. if urls.get(OPENERP):
  745. # special case. it contains the server and the base module.
  746. # extract path is not the same
  747. base_path = os.path.dirname(modules.get_module_path('base'))
  748. # copy all modules in the SERVER/odoo/addons directory to the new "odoo" module (except base itself)
  749. for d in os.listdir(base_path):
  750. if d != 'base' and os.path.isdir(os.path.join(base_path, d)):
  751. destdir = os.path.join(tmp, OPENERP, 'addons', d) # XXX 'odoo' subdirectory ?
  752. shutil.copytree(os.path.join(base_path, d), destdir)
  753. # then replace the server by the new "base" module
  754. server_dir = tools.config['root_path'] # XXX or dirname()
  755. bck = backup(server_dir)
  756. _logger.info('Copy downloaded module `odoo` to `%s`', server_dir)
  757. shutil.move(os.path.join(tmp, OPENERP), server_dir)
  758. #if bck:
  759. # shutil.rmtree(bck)
  760. self.update_list()
  761. with_urls = [module_name for module_name, url in urls.items() if url]
  762. downloaded = self.search([('name', 'in', with_urls)])
  763. installed = self.search([('id', 'in', downloaded.ids), ('state', '=', 'installed')])
  764. to_install = self.search([('name', 'in', list(urls)), ('state', '=', 'uninstalled')])
  765. post_install_action = to_install.button_immediate_install()
  766. if installed or to_install:
  767. # in this case, force server restart to reload python code...
  768. self._cr.commit()
  769. odoo.service.server.restart()
  770. return {
  771. 'type': 'ir.actions.client',
  772. 'tag': 'home',
  773. 'params': {'wait': True},
  774. }
  775. return post_install_action
  776. finally:
  777. shutil.rmtree(tmp)
  778. @api.model
  779. def get_apps_server(self):
  780. return tools.config.get('apps_server', 'https://apps.odoo.com/apps')
  781. def _update_dependencies(self, depends=None, auto_install_requirements=()):
  782. self.env['ir.module.module.dependency'].flush_model()
  783. existing = set(dep.name for dep in self.dependencies_id)
  784. needed = set(depends or [])
  785. for dep in (needed - existing):
  786. self._cr.execute('INSERT INTO ir_module_module_dependency (module_id, name) values (%s, %s)', (self.id, dep))
  787. for dep in (existing - needed):
  788. self._cr.execute('DELETE FROM ir_module_module_dependency WHERE module_id = %s and name = %s', (self.id, dep))
  789. self._cr.execute('UPDATE ir_module_module_dependency SET auto_install_required = (name = any(%s)) WHERE module_id = %s',
  790. (list(auto_install_requirements or ()), self.id))
  791. self.env['ir.module.module.dependency'].invalidate_model(['auto_install_required'])
  792. self.invalidate_recordset(['dependencies_id'])
  793. def _update_exclusions(self, excludes=None):
  794. self.env['ir.module.module.exclusion'].flush_model()
  795. existing = set(excl.name for excl in self.exclusion_ids)
  796. needed = set(excludes or [])
  797. for name in (needed - existing):
  798. self._cr.execute('INSERT INTO ir_module_module_exclusion (module_id, name) VALUES (%s, %s)', (self.id, name))
  799. for name in (existing - needed):
  800. self._cr.execute('DELETE FROM ir_module_module_exclusion WHERE module_id=%s AND name=%s', (self.id, name))
  801. self.invalidate_recordset(['exclusion_ids'])
  802. def _update_category(self, category='Uncategorized'):
  803. current_category = self.category_id
  804. current_category_path = []
  805. while current_category:
  806. current_category_path.insert(0, current_category.name)
  807. current_category = current_category.parent_id
  808. categs = category.split('/')
  809. if categs != current_category_path:
  810. cat_id = modules.db.create_categories(self._cr, categs)
  811. self.write({'category_id': cat_id})
  812. def _update_translations(self, filter_lang=None, overwrite=False):
  813. if not filter_lang:
  814. langs = self.env['res.lang'].get_installed()
  815. filter_lang = [code for code, _ in langs]
  816. elif not isinstance(filter_lang, (list, tuple)):
  817. filter_lang = [filter_lang]
  818. update_mods = self.filtered(lambda r: r.state in ('installed', 'to install', 'to upgrade'))
  819. mod_dict = {
  820. mod.name: mod.dependencies_id.mapped('name')
  821. for mod in update_mods
  822. }
  823. mod_names = topological_sort(mod_dict)
  824. self.env['ir.module.module']._load_module_terms(mod_names, filter_lang, overwrite)
  825. def _check(self):
  826. for module in self:
  827. if not module.description_html:
  828. _logger.warning('module %s: description is empty !', module.name)
  829. def _get(self, name):
  830. """ Return the (sudoed) `ir.module.module` record with the given name.
  831. The result may be an empty recordset if the module is not found.
  832. """
  833. model_id = self._get_id(name) if name else False
  834. return self.browse(model_id).sudo()
  835. @tools.ormcache('name')
  836. def _get_id(self, name):
  837. self.flush_model(['name'])
  838. self.env.cr.execute("SELECT id FROM ir_module_module WHERE name=%s", (name,))
  839. return self.env.cr.fetchone()
  840. @api.model
  841. @tools.ormcache()
  842. def _installed(self):
  843. """ Return the set of installed modules as a dictionary {name: id} """
  844. return {
  845. module.name: module.id
  846. for module in self.sudo().search([('state', '=', 'installed')])
  847. }
  848. @api.model
  849. def search_panel_select_range(self, field_name, **kwargs):
  850. if field_name == 'category_id':
  851. enable_counters = kwargs.get('enable_counters', False)
  852. domain = [('parent_id', '=', False), ('child_ids.module_ids', '!=', False)]
  853. excluded_xmlids = [
  854. 'base.module_category_website_theme',
  855. 'base.module_category_theme',
  856. ]
  857. if not self.user_has_groups('base.group_no_one'):
  858. excluded_xmlids.append('base.module_category_hidden')
  859. excluded_category_ids = []
  860. for excluded_xmlid in excluded_xmlids:
  861. categ = self.env.ref(excluded_xmlid, False)
  862. if not categ:
  863. continue
  864. excluded_category_ids.append(categ.id)
  865. if excluded_category_ids:
  866. domain = expression.AND([
  867. domain,
  868. [('id', 'not in', excluded_category_ids)],
  869. ])
  870. records = self.env['ir.module.category'].search_read(domain, ['display_name'], order="sequence")
  871. values_range = OrderedDict()
  872. for record in records:
  873. record_id = record['id']
  874. if enable_counters:
  875. model_domain = expression.AND([
  876. kwargs.get('search_domain', []),
  877. kwargs.get('category_domain', []),
  878. kwargs.get('filter_domain', []),
  879. [('category_id', 'child_of', record_id), ('category_id', 'not in', excluded_category_ids)]
  880. ])
  881. record['__count'] = self.env['ir.module.module'].search_count(model_domain)
  882. values_range[record_id] = record
  883. return {
  884. 'parent_field': 'parent_id',
  885. 'values': list(values_range.values()),
  886. }
  887. return super(Module, self).search_panel_select_range(field_name, **kwargs)
  888. @api.model
  889. def _load_module_terms(self, modules, langs, overwrite=False):
  890. """ Load PO files of the given modules for the given languages. """
  891. # load i18n files
  892. translation_importer = TranslationImporter(self.env.cr, verbose=False)
  893. for module_name in modules:
  894. modpath = get_module_path(module_name)
  895. if not modpath:
  896. continue
  897. for lang in langs:
  898. lang_code = tools.get_iso_codes(lang)
  899. base_lang_code = None
  900. if '_' in lang_code:
  901. base_lang_code = lang_code.split('_')[0]
  902. # Step 1: for sub-languages, load base language first (e.g. es_CL.po is loaded over es.po)
  903. if base_lang_code:
  904. base_trans_file = get_module_resource(module_name, 'i18n', base_lang_code + '.po')
  905. if base_trans_file:
  906. _logger.info('module %s: loading base translation file %s for language %s', module_name, base_lang_code, lang)
  907. translation_importer.load_file(base_trans_file, lang)
  908. # i18n_extra folder is for additional translations handle manually (eg: for l10n_be)
  909. base_trans_extra_file = get_module_resource(module_name, 'i18n_extra', base_lang_code + '.po')
  910. if base_trans_extra_file:
  911. _logger.info('module %s: loading extra base translation file %s for language %s', module_name, base_lang_code, lang)
  912. translation_importer.load_file(base_trans_extra_file, lang)
  913. # Step 2: then load the main translation file, possibly overriding the terms coming from the base language
  914. trans_file = get_module_resource(module_name, 'i18n', lang_code + '.po')
  915. if trans_file:
  916. _logger.info('module %s: loading translation file %s for language %s', module_name, lang_code, lang)
  917. translation_importer.load_file(trans_file, lang)
  918. elif lang_code != 'en_US':
  919. _logger.info('module %s: no translation for language %s', module_name, lang_code)
  920. trans_extra_file = get_module_resource(module_name, 'i18n_extra', lang_code + '.po')
  921. if trans_extra_file:
  922. _logger.info('module %s: loading extra translation file %s for language %s', module_name, lang_code, lang)
  923. translation_importer.load_file(trans_extra_file, lang)
  924. translation_importer.save(overwrite=overwrite)
  925. DEP_STATES = STATES + [('unknown', 'Unknown')]
  926. class ModuleDependency(models.Model):
  927. _name = "ir.module.module.dependency"
  928. _description = "Module dependency"
  929. _log_access = False # inserts are done manually, create and write uid, dates are always null
  930. # the dependency name
  931. name = fields.Char(index=True)
  932. # the module that depends on it
  933. module_id = fields.Many2one('ir.module.module', 'Module', ondelete='cascade')
  934. # the module corresponding to the dependency, and its status
  935. depend_id = fields.Many2one('ir.module.module', 'Dependency',
  936. compute='_compute_depend', search='_search_depend')
  937. state = fields.Selection(DEP_STATES, string='Status', compute='_compute_state')
  938. auto_install_required = fields.Boolean(
  939. default=True,
  940. help="Whether this dependency blocks automatic installation "
  941. "of the dependent")
  942. @api.depends('name')
  943. def _compute_depend(self):
  944. # retrieve all modules corresponding to the dependency names
  945. names = list(set(dep.name for dep in self))
  946. mods = self.env['ir.module.module'].search([('name', 'in', names)])
  947. # index modules by name, and assign dependencies
  948. name_mod = dict((mod.name, mod) for mod in mods)
  949. for dep in self:
  950. dep.depend_id = name_mod.get(dep.name)
  951. def _search_depend(self, operator, value):
  952. assert operator == 'in'
  953. modules = self.env['ir.module.module'].browse(set(value))
  954. return [('name', 'in', modules.mapped('name'))]
  955. @api.depends('depend_id.state')
  956. def _compute_state(self):
  957. for dependency in self:
  958. dependency.state = dependency.depend_id.state or 'unknown'
  959. class ModuleExclusion(models.Model):
  960. _name = "ir.module.module.exclusion"
  961. _description = "Module exclusion"
  962. # the exclusion name
  963. name = fields.Char(index=True)
  964. # the module that excludes it
  965. module_id = fields.Many2one('ir.module.module', 'Module', ondelete='cascade')
  966. # the module corresponding to the exclusion, and its status
  967. exclusion_id = fields.Many2one('ir.module.module', 'Exclusion Module',
  968. compute='_compute_exclusion', search='_search_exclusion')
  969. state = fields.Selection(DEP_STATES, string='Status', compute='_compute_state')
  970. @api.depends('name')
  971. def _compute_exclusion(self):
  972. # retrieve all modules corresponding to the exclusion names
  973. names = list(set(excl.name for excl in self))
  974. mods = self.env['ir.module.module'].search([('name', 'in', names)])
  975. # index modules by name, and assign dependencies
  976. name_mod = {mod.name: mod for mod in mods}
  977. for excl in self:
  978. excl.exclusion_id = name_mod.get(excl.name)
  979. def _search_exclusion(self, operator, value):
  980. assert operator == 'in'
  981. modules = self.env['ir.module.module'].browse(set(value))
  982. return [('name', 'in', modules.mapped('name'))]
  983. @api.depends('exclusion_id.state')
  984. def _compute_state(self):
  985. for exclusion in self:
  986. exclusion.state = exclusion.exclusion_id.state or 'unknown'