def uninstall_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) env['product.template'].search([('service_type', '=', 'timesheet') ]).write({'service_type': 'manual'}) env['product.product'].search([('service_type', '=', 'timesheet') ]).write({'service_type': 'manual'})
def send_notifications(): db_registry = registry(dbname) with api.Environment.manage(), db_registry.cursor() as cr: env = api.Environment(cr, SUPERUSER_ID, _context) env['mail.mail'].browse(email_ids).send()
def load_module_graph(cr, graph, status=None, perform_checks=True, skip_modules=None, report=None, models_to_check=None): """Migrates+Updates or Installs all module nodes from ``graph`` :param graph: graph of module nodes to load :param status: deprecated parameter, unused, left to avoid changing signature in 8.0 :param perform_checks: whether module descriptors should be checked for validity (prints warnings for same cases) :param skip_modules: optional list of module names (packages) which have previously been loaded and can be skipped :return: list of modules that were installed or updated """ def load_test(idref, mode): cr.execute("SAVEPOINT load_test_data_file") try: load_data(cr, idref, mode, 'test', package, report) return True except Exception: _test_logger.exception( 'module %s: an exception occurred in a test', package.name) return False finally: cr.execute("ROLLBACK TO SAVEPOINT load_test_data_file") # avoid keeping stale xml_id, etc. in cache eagle.registry(cr.dbname).clear_caches() if models_to_check is None: models_to_check = set() processed_modules = [] loaded_modules = [] registry = eagle.registry(cr.dbname) migrations = eagle.modules.migration.MigrationManager(cr, graph) module_count = len(graph) _logger.info('loading %d modules...', module_count) # register, instantiate and initialize models for each modules t0 = time.time() t0_sql = eagle.sql_db.sql_counter models_updated = set() for index, package in enumerate(graph, 1): module_name = package.name module_id = package.id if skip_modules and module_name in skip_modules: continue _logger.debug('loading module %s (%d/%d)', module_name, index, module_count) needs_update = (hasattr(package, "init") or hasattr(package, "update") or package.state in ("to install", "to upgrade")) if needs_update: if package.name != 'base': registry.setup_models(cr) migrations.migrate_module(package, 'pre') load_openerp_module(package.name) new_install = package.state == 'to install' if new_install: py_module = sys.modules['eagle.addons.%s' % (module_name, )] pre_init = package.info.get('pre_init_hook') if pre_init: getattr(py_module, pre_init)(cr) model_names = registry.load(cr, package) loaded_modules.append(package.name) if needs_update: models_updated |= set(model_names) models_to_check -= set(model_names) registry.setup_models(cr) registry.init_models(cr, model_names, {'module': package.name}) elif package.state != 'to remove': # The current module has simply been loaded. The models extended by this module # and for which we updated the schema, must have their schema checked again. # This is because the extension may have changed the model, # e.g. adding required=True to an existing field, but the schema has not been # updated by this module because it's not marked as 'to upgrade/to install'. models_to_check |= set(model_names) & models_updated idref = {} mode = 'update' if hasattr(package, 'init') or package.state == 'to install': mode = 'init' if needs_update: env = api.Environment(cr, SUPERUSER_ID, {}) # Can't put this line out of the loop: ir.module.module will be # registered by init_models() above. module = env['ir.module.module'].browse(module_id) if perform_checks: module._check() if package.state == 'to upgrade': # upgrading the module information module.write(module.get_values_from_terp(package.data)) load_data(cr, idref, mode, kind='data', package=package, report=report) demo_loaded = package.dbdemo = load_demo(cr, package, idref, mode, report) cr.execute('update ir_module_module set demo=%s where id=%s', (demo_loaded, module_id)) module.invalidate_cache(['demo']) migrations.migrate_module(package, 'post') # Update translations for all installed languages overwrite = eagle.tools.config["overwrite_existing_translations"] module.with_context(overwrite=overwrite)._update_translations() if package.name is not None: registry._init_modules.add(package.name) if new_install: post_init = package.info.get('post_init_hook') if post_init: getattr(py_module, post_init)(cr, registry) if mode == 'update': # validate the views that have not been checked yet env['ir.ui.view']._validate_module_views(module_name) # need to commit any modification the module's installation or # update made to the schema or data so the tests can run # (separately in their own transaction) cr.commit() if demo_loaded: # launch tests only in demo mode, allowing tests to use demo data. if tools.config.options['test_enable']: # Yamel test report.record_result(load_test(idref, mode)) # Python tests env['ir.http']._clear_routing_map( ) # force routing map to be rebuilt report.record_result( eagle.modules.module.run_unit_tests( module_name, cr.dbname)) # tests may have reset the environment env = api.Environment(cr, SUPERUSER_ID, {}) module = env['ir.module.module'].browse(module_id) processed_modules.append(package.name) ver = adapt_version(package.data['version']) # Set new modules and dependencies module.write({'state': 'installed', 'latest_version': ver}) package.load_state = package.state package.load_version = package.installed_version package.state = 'installed' for kind in ('init', 'demo', 'update'): if hasattr(package, kind): delattr(package, kind) if package.name is not None: registry._init_modules.add(package.name) _logger.log(25, "%s modules loaded in %.2fs, %s queries", len(graph), time.time() - t0, eagle.sql_db.sql_counter - t0_sql) return loaded_modules, processed_modules
def load_modules(db, force_demo=False, status=None, update_module=False): initialize_sys_path() force = [] if force_demo: force.append('demo') models_to_check = set() with db.cursor() as cr: if not eagle.modules.db.is_initialized(cr): if not update_module: _logger.error( "Database %s not initialized, you can force it with `-i base`", cr.dbname) return _logger.info("init db") eagle.modules.db.initialize(cr) update_module = True # process auto-installed modules tools.config["init"]["all"] = 1 tools.config['update']['all'] = 1 if not tools.config['without_demo']: tools.config["demo"]['all'] = 1 # This is a brand new registry, just created in # eagle.modules.registry.Registry.new(). registry = eagle.registry(cr.dbname) if 'base' in tools.config['update'] or 'all' in tools.config['update']: cr.execute( "update ir_module_module set state=%s where name=%s and state=%s", ('to upgrade', 'base', 'installed')) # STEP 1: LOAD BASE (must be done before module dependencies can be computed for later steps) graph = eagle.modules.graph.Graph() graph.add_module(cr, 'base', force) if not graph: _logger.critical( 'module base cannot be loaded! (hint: verify addons-path)') raise ImportError( 'Module `base` cannot be loaded! (hint: verify addons-path)') # processed_modules: for cleanup step after install # loaded_modules: to avoid double loading report = registry._assertion_report loaded_modules, processed_modules = load_module_graph( cr, graph, status, perform_checks=update_module, report=report, models_to_check=models_to_check) load_lang = tools.config.pop('load_language') if load_lang or update_module: # some base models are used below, so make sure they are set up registry.setup_models(cr) if load_lang: for lang in load_lang.split(','): tools.load_language(cr, lang) # STEP 2: Mark other modules to be loaded/updated if update_module: env = api.Environment(cr, SUPERUSER_ID, {}) Module = env['ir.module.module'] _logger.info('updating modules list') Module.update_list() _check_module_names( cr, itertools.chain(tools.config['init'], tools.config['update'])) module_names = [k for k, v in tools.config['init'].items() if v] if module_names: modules = Module.search([('state', '=', 'uninstalled'), ('name', 'in', module_names)]) if modules: modules.button_install() module_names = [k for k, v in tools.config['update'].items() if v] if module_names: modules = Module.search([('state', '=', 'installed'), ('name', 'in', module_names)]) if modules: modules.button_upgrade() cr.execute("update ir_module_module set state=%s where name=%s", ('installed', 'base')) Module.invalidate_cache(['state']) # STEP 3: Load marked modules (skipping base which was done in STEP 1) # IMPORTANT: this is done in two parts, first loading all installed or # partially installed modules (i.e. installed/to upgrade), to # offer a consistent system to the second part: installing # newly selected modules. # We include the modules 'to remove' in the first step, because # they are part of the "currently installed" modules. They will # be dropped in STEP 6 later, before restarting the loading # process. # IMPORTANT 2: We have to loop here until all relevant modules have been # processed, because in some rare cases the dependencies have # changed, and modules that depend on an uninstalled module # will not be processed on the first pass. # It's especially useful for migrations. previously_processed = -1 while previously_processed < len(processed_modules): previously_processed = len(processed_modules) processed_modules += load_marked_modules( cr, graph, ['installed', 'to upgrade', 'to remove'], force, status, report, loaded_modules, update_module, models_to_check) if update_module: processed_modules += load_marked_modules( cr, graph, ['to install'], force, status, report, loaded_modules, update_module, models_to_check) registry.loaded = True registry.setup_models(cr) # STEP 3.5: execute migration end-scripts migrations = eagle.modules.migration.MigrationManager(cr, graph) for package in graph: migrations.migrate_module(package, 'end') # STEP 4: Finish and cleanup installations if processed_modules: env = api.Environment(cr, SUPERUSER_ID, {}) cr.execute( """select model,name from ir_model where id NOT IN (select distinct model_id from ir_model_access)""" ) for (model, name) in cr.fetchall(): if model in registry and not registry[ model]._abstract and not registry[model]._transient: _logger.warning( 'The model %s has no access rules, consider adding one. E.g. access_%s,access_%s,model_%s,base.group_user,1,0,0,0', model, model.replace('.', '_'), model.replace('.', '_'), model.replace('.', '_')) # Temporary warning while we remove access rights on osv_memory objects, as they have # been replaced by owner-only access rights cr.execute( """select distinct mod.model, mod.name from ir_model_access acc, ir_model mod where acc.model_id = mod.id""" ) for (model, name) in cr.fetchall(): if model in registry and registry[model]._transient: _logger.warning( 'The transient model %s (%s) should not have explicit access rules!', model, name) cr.execute("SELECT model from ir_model") for (model, ) in cr.fetchall(): if model in registry: env[model]._check_removed_columns(log=True) elif _logger.isEnabledFor( logging.INFO): # more an info that a warning... _logger.warning( "Model %s is declared but cannot be loaded! (Perhaps a module was partially removed or renamed)", model) # Cleanup orphan records env['ir.model.data']._process_end(processed_modules) for kind in ('init', 'demo', 'update'): tools.config[kind] = {} # STEP 5: Uninstall modules to remove if update_module: # Remove records referenced from ir_model_data for modules to be # removed (and removed the references from ir_model_data). cr.execute("SELECT name, id FROM ir_module_module WHERE state=%s", ('to remove', )) modules_to_remove = dict(cr.fetchall()) if modules_to_remove: env = api.Environment(cr, SUPERUSER_ID, {}) pkgs = reversed( [p for p in graph if p.name in modules_to_remove]) for pkg in pkgs: uninstall_hook = pkg.info.get('uninstall_hook') if uninstall_hook: py_module = sys.modules['eagle.addons.%s' % (pkg.name, )] getattr(py_module, uninstall_hook)(cr, registry) Module = env['ir.module.module'] Module.browse(modules_to_remove.values()).module_uninstall() # Recursive reload, should only happen once, because there should be no # modules to remove next time cr.commit() _logger.info( 'Reloading registry once more after uninstalling modules') api.Environment.reset() registry = eagle.modules.registry.Registry.new( cr.dbname, force_demo, status, update_module) registry.check_tables_exist(cr) cr.commit() return registry # STEP 5.5: Verify extended fields on every model # This will fix the schema of all models in a situation such as: # - module A is loaded and defines model M; # - module B is installed/upgraded and extends model M; # - module C is loaded and extends model M; # - module B and C depend on A but not on each other; # The changes introduced by module C are not taken into account by the upgrade of B. if models_to_check: registry.init_models(cr, list(models_to_check), {'models_to_check': True}) # STEP 6: verify custom views on every model if update_module: env = api.Environment(cr, SUPERUSER_ID, {}) View = env['ir.ui.view'] for model in registry: try: View._validate_custom_views(model) except Exception as e: _logger.warning('invalid custom view(s) for model %s: %s', model, tools.ustr(e)) if report.failures: _logger.error('At least one test failed when loading the modules.') else: _logger.info('Modules loaded.') # STEP 8: call _register_hook on every model env = api.Environment(cr, SUPERUSER_ID, {}) for model in env.values(): model._register_hook() # STEP 9: save installed/updated modules for post-install tests registry.updated_modules += processed_modules
def post_init(cr, registry): """Rewrite ICP's to force groups""" from eagle import api, SUPERUSER_ID env = api.Environment(cr, SUPERUSER_ID, {}) env['ir.config_parameter'].init(force=True)
def _set_default_identification_type(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) env['res.partner'].search([]).write({ 'l10n_latam_identification_type_id': env.ref('l10n_latam_base.it_vat').id })
def change_digit(cr): env = api.Environment(cr, SUPERUSER_ID, {}) precision = env['decimal.precision'].precision_get(application) return 16, precision
def load_translations(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) env.ref('l10n_sa.account_arabic_coa_general').process_coa_translations()
def _handle_exception(cls, exception): code = 500 # default code is_website_request = bool( getattr(request, 'is_frontend', False) and getattr(request, 'website', False)) if not is_website_request: # Don't touch non website requests exception handling return super(Http, cls)._handle_exception(exception) else: try: response = super(Http, cls)._handle_exception(exception) if isinstance(response, Exception): exception = response else: # if parent excplicitely returns a plain response, then we don't touch it return response except Exception as e: if 'werkzeug' in config['dev_mode']: raise e exception = e values = dict( exception=exception, traceback=traceback.format_exc(), ) if isinstance(exception, werkzeug.exceptions.HTTPException): if exception.code is None: # Hand-crafted HTTPException likely coming from abort(), # usually for a redirect response -> return it directly return exception else: code = exception.code if isinstance(exception, eagle.exceptions.AccessError): code = 403 if isinstance(exception, QWebException): values.update(qweb_exception=exception) # retro compatibility to remove in 12.2 exception.qweb = dict(message=exception.message, expression=exception.html) if type(exception.error) == eagle.exceptions.AccessError: code = 403 values.update( status_message=werkzeug.http.HTTP_STATUS_CODES[code], status_code=code, ) view_id = code if request.website.is_publisher() and isinstance( exception, werkzeug.exceptions.NotFound): view_id = 'page_404' values['path'] = request.httprequest.path[1:] if not request.uid: cls._auth_method_public() with registry(request.env.cr.dbname).cursor() as cr: env = api.Environment(cr, request.uid, request.env.context) if code == 500: logger.error("500 Internal Server Error:\n\n%s", values['traceback']) View = env["ir.ui.view"] values['views'] = View if 'qweb_exception' in values: if 'load could not load template' in exception.args: # When t-calling an inexisting template, we don't have reference to # the view that did the t-call. We need to find it. values['views'] = View.search( [('type', '=', 'qweb'), '|', ('arch_db', 'ilike', 't-call="%s"' % exception.name), ('arch_db', 'ilike', "t-call='%s'" % exception.name)], order='write_date desc', limit=1) else: try: # exception.name might be int, string exception_template = int(exception.name) except: exception_template = exception.name view = View._view_obj(exception_template) if exception.html in view.arch: values['views'] = view else: # There might be 2 cases where the exception code can't be found # in the view, either the error is in a child view or the code # contains branding (<div t-att-data="request.browse('ok')"/>). et = etree.fromstring( view.with_context( inherit_branding=False).read_combined( ['arch'])['arch']) node = et.find( exception.path.replace( '/templates/t/', './')) line = node is not None and etree.tostring( node, encoding='unicode') if line: values['views'] = View._views_get( exception_template).filtered( lambda v: line in v.arch) # Keep only views that we can reset values['views'] = values['views'].filtered( lambda view: view._get_original_view( ).arch_fs or 'oe_structure' in view.key) # Needed to show reset template on translated pages (`_prepare_qcontext` will set it for main lang) values[ 'editable'] = request.uid and request.website.is_publisher( ) elif code == 403: logger.warn("403 Forbidden:\n\n%s", values['traceback']) try: html = env['ir.ui.view'].render_template( 'website.%s' % view_id, values) except Exception: html = env['ir.ui.view'].render_template( 'website.http_error', values) return werkzeug.wrappers.Response( html, status=code, content_type='text/html;charset=utf-8')
def uninstall_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) teams = env['crm.team'].search([('use_opportunities', '=', False)]) teams.write({'use_opportunities': True})
def finish(self): """ Transfer the data from the temp table to ir.translation """ cr = self._cr # Step 0: insert rows in batch query = """ INSERT INTO %s (name, lang, res_id, src, type, imd_model, module, imd_name, value, state, comments) VALUES """ % self._table for rows in cr.split_for_in_conditions(self._rows): cr.execute(query + ", ".join(["%s"] * len(rows)), rows) _logger.debug("ir.translation.cursor: We have %d entries to process", len(self._rows)) # Step 1: resolve ir.model.data references to res_ids cr.execute(""" UPDATE %s AS ti SET res_id = imd.res_id, noupdate = imd.noupdate FROM ir_model_data AS imd WHERE ti.res_id IS NULL AND ti.module IS NOT NULL AND ti.imd_name IS NOT NULL AND ti.module = imd.module AND ti.imd_name = imd.name AND ti.imd_model = imd.model; """ % self._table) if self._debug: cr.execute(""" SELECT module, imd_name, imd_model FROM %s WHERE res_id IS NULL AND module IS NOT NULL """ % self._table) for row in cr.fetchall(): _logger.info( "ir.translation.cursor: missing res_id for %s.%s <%s> ", *row) # Records w/o res_id must _not_ be inserted into our db, because they are # referencing non-existent data. cr.execute( "DELETE FROM %s WHERE res_id IS NULL AND module IS NOT NULL" % self._table) # detect the xml_translate fields, where the src must be the same env = api.Environment(cr, SUPERUSER_ID, {}) src_relevant_fields = [] for model in env: for field_name, field in env[model]._fields.items(): if hasattr(field, 'translate') and callable(field.translate): src_relevant_fields.append("%s,%s" % (model, field_name)) count = 0 # Step 2: insert new or upsert non-noupdate translations if self._overwrite: cr.execute( """ INSERT INTO %s(name, lang, res_id, src, type, value, module, state, comments) SELECT name, lang, res_id, src, type, value, module, state, comments FROM %s WHERE type = 'code' AND noupdate IS NOT TRUE ON CONFLICT (type, lang, md5(src)) WHERE type = 'code' DO UPDATE SET (name, lang, res_id, src, type, value, module, state, comments) = (EXCLUDED.name, EXCLUDED.lang, EXCLUDED.res_id, EXCLUDED.src, EXCLUDED.type, EXCLUDED.value, EXCLUDED.module, EXCLUDED.state, EXCLUDED.comments) WHERE EXCLUDED.value IS NOT NULL AND EXCLUDED.value != ''; """ % (self._model_table, self._table)) count += cr.rowcount cr.execute( """ INSERT INTO %s(name, lang, res_id, src, type, value, module, state, comments) SELECT name, lang, res_id, src, type, value, module, state, comments FROM %s WHERE type = 'model' AND noupdate IS NOT TRUE ON CONFLICT (type, lang, name, res_id) WHERE type = 'model' DO UPDATE SET (name, lang, res_id, src, type, value, module, state, comments) = (EXCLUDED.name, EXCLUDED.lang, EXCLUDED.res_id, EXCLUDED.src, EXCLUDED.type, EXCLUDED.value, EXCLUDED.module, EXCLUDED.state, EXCLUDED.comments) WHERE EXCLUDED.value IS NOT NULL AND EXCLUDED.value != ''; """ % (self._model_table, self._table)) count += cr.rowcount cr.execute( """ INSERT INTO %s(name, lang, res_id, src, type, value, module, state, comments) SELECT name, lang, res_id, src, type, value, module, state, comments FROM %s WHERE type = 'model_terms' AND noupdate IS NOT TRUE ON CONFLICT (type, name, lang, res_id, md5(src)) DO UPDATE SET (name, lang, res_id, src, type, value, module, state, comments) = (EXCLUDED.name, EXCLUDED.lang, EXCLUDED.res_id, EXCLUDED.src, EXCLUDED.type, EXCLUDED.value, EXCLUDED.module, EXCLUDED.state, EXCLUDED.comments) WHERE EXCLUDED.value IS NOT NULL AND EXCLUDED.value != ''; """ % (self._model_table, self._table)) count += cr.rowcount cr.execute( """ INSERT INTO %s(name, lang, res_id, src, type, value, module, state, comments) SELECT name, lang, res_id, src, type, value, module, state, comments FROM %s WHERE %s ON CONFLICT DO NOTHING; """ % (self._model_table, self._table, 'noupdate IS TRUE' if self._overwrite else 'TRUE')) count += cr.rowcount if self._debug: cr.execute("SELECT COUNT(*) FROM ONLY %s" % self._model_table) total = cr.fetchone()[0] _logger.debug( "ir.translation.cursor: %d entries now in ir.translation, %d common entries with tmp", total, count) # Step 3: cleanup cr.execute("DROP TABLE %s" % self._table) self._rows.clear() return True
def load_translations(cr, registry): """Load template translations.""" env = api.Environment(cr, SUPERUSER_ID, {}) env.ref( 'l10n_lt.account_chart_template_lithuania').process_coa_translations()
def post_init_hook(cr, _): with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) env['res.partner']._install_partner_firstname()
def to_python(self, value): _uid = RequestUID(value=value, converter=self) env = api.Environment(request.cr, _uid, request.context) return env[self.model].browse(int(v) for v in value.split(','))
def post_init(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) load_translations(env) init_settings(env)
def uninstall_test_pylint(cr): env = api.Environment(cr, SUPERUSER_ID, {}) env['ir.module.module'].search([('name', '=', 'test_pylint'), ('state', '=', 'installed') ]).write({'state': 'uninstalled'})
def pre_init_hook(cr): env = api.Environment(cr, SUPERUSER_ID, {}) env['ir.model.data'].search([ ('model', 'like', '%stock%'), ('module', '=', 'stock') ]).unlink()
def _configure_journals(cr, registry): """Setting journal and property field (if needed)""" env = api.Environment(cr, SUPERUSER_ID, {}) # if we already have a coa installed, create journal and set property field company_ids = env['res.company'].search([('chart_template_id', '!=', False) ]) for company_id in company_ids: # Check if property exists for stock account journal exists properties = env['ir.property'].search([ ('name', '=', 'property_stock_journal'), ('company_id', '=', company_id.id) ]) # If not, check if you can find a journal that is already there with the same name, otherwise create one if not properties: journal_id = env['account.journal'].search( [('name', '=', _('Inventory Valuation')), ('company_id', '=', company_id.id), ('type', '=', 'general')], limit=1).id if not journal_id: journal_id = env['account.journal'].create({ 'name': _('Inventory Valuation'), 'type': 'general', 'code': 'STJ', 'company_id': company_id.id, 'show_on_dashboard': False }).id vals = { 'name': 'property_stock_journal', 'fields_id': env['ir.model.fields'].search( [('name', '=', 'property_stock_journal'), ('model', '=', 'product.category'), ('relation', '=', 'account.journal')], limit=1).id, 'company_id': company_id.id, 'value': 'account.journal,' + str(journal_id) } env['ir.property'].create(vals) # Property Stock Accounts todo_list = [ 'property_stock_account_input_categ_id', 'property_stock_account_output_categ_id', 'property_stock_valuation_account_id', ] for record in todo_list: account = getattr(company_id, record) value = account and 'account.account,' + str(account.id) or False if value: field_id = env['ir.model.fields'].search( [('name', '=', record), ('model', '=', 'product.category'), ('relation', '=', 'account.account')], limit=1).id vals = { 'name': record, 'company_id': company_id.id, 'fields_id': field_id, 'value': value, } properties = env['ir.property'].search([ ('name', '=', record), ('company_id', '=', company_id.id), ]) if properties: properties.write(vals) else: # create the property env['ir.property'].create(vals) stock_account = env.ref('account.demo_stock_account', False) if stock_account: account_id = env['account.account'].search( [('tag_ids', '=', stock_account.id)], limit=1).id fields_id = env['ir.model.fields'].search( [('model', '=', 'product.category'), ('name', '=', 'property_stock_valuation_account_id')], limit=1).id if not account_id: account_id = env['account.account'].search( [('user_type_id', '=', env.ref('account.data_account_type_current_assets').id)], limit=1).id if account_id: xml_id = 'stock_account.property_stock_valuation_account_id' vals = { 'name': 'property_stock_valuation_account_id', 'fields_id': fields_id, 'value': 'account.account,' + str(account_id), 'company_id': env.ref('base.main_company').id, } env['ir.property']._load_records( [dict(xml_id=xml_id, values=vals, noupdate=True)])
def add_payment_methods(self): """ Install required payment acquiers, configure them and mark the onboarding step as done.""" if self.payment_method == 'paypal': self._install_module('payment_paypal') if self.payment_method == 'stripe': self._install_module('payment_stripe') if self.payment_method in ('paypal', 'stripe', 'manual', 'other'): self._on_save_payment_acquirer() self.env.company.payment_onboarding_payment_method = self.payment_method # create a new env including the freshly installed module(s) new_env = api.Environment(self.env.cr, self.env.uid, self.env.context) if self.payment_method == 'paypal': new_env.ref('payment.payment_acquirer_paypal').write({ 'paypal_email_account': self.paypal_email_account, 'paypal_seller_account': self.paypal_seller_account, 'paypal_pdt_token': self.paypal_pdt_token, 'state': 'enabled', }) if self.payment_method == 'stripe': new_env.ref('payment.payment_acquirer_stripe').write({ 'stripe_secret_key': self.stripe_secret_key, 'stripe_publishable_key': self.stripe_publishable_key, 'state': 'enabled', }) if self.payment_method == 'manual': manual_acquirer = self._get_manual_payment_acquirer(new_env) if not manual_acquirer: raise UserError( _('No manual payment method could be found for this company. ' + 'Please create one from the Payment Acquirer menu.')) manual_acquirer.name = self.manual_name manual_acquirer.pending_msg = self.manual_post_msg manual_acquirer.state = 'enabled' journal = manual_acquirer.journal_id if journal: journal.name = self.journal_name journal.bank_acc_number = self.acc_number else: raise UserError( _("You have to set a journal for your payment acquirer %s." % (self.manual_name, ))) # delete wizard data immediately to get rid of residual credentials self.unlink() # the user clicked `apply` and not cancel so we can assume this step is done. self._set_payment_acquirer_onboarding_step_done() return {'type': 'ir.actions.act_window_close'}
def load_translations(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) env.ref('l10n_be.l10nbe_chart_template').process_coa_translations()
def _post_init_hook(cr, registry): _preserve_tag_on_taxes(cr, registry) env = api.Environment(cr, SUPERUSER_ID, {}) env.ref('l10n_lu.lu_2011_chart_1').process_coa_translations()