def e_method(self, handler, bot, update): db_registry = registry(config['db_name']) with api.Environment.manage(), db_registry.cursor() as cr: env = api.Environment(cr, SUPERUSER_ID, {}) b2c_base = env['b2c.base'] b2c_base.set_actions(handler, self.token, bot, update)
def pre_init_hook(cr): env = api.Environment(cr, SUPERUSER_ID, {}) return True
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 odoo.registry(cr.dbname).clear_caches() if models_to_check is None: models_to_check = set() processed_modules = [] loaded_modules = [] registry = odoo.registry(cr.dbname) migrations = odoo.modules.migration.MigrationManager(cr, graph) module_count = len(graph) _logger.info('loading %d modules...', module_count) registry.clear_caches() # register, instantiate and initialize models for each modules t0 = time.time() t0_sql = odoo.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['odoo.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 = odoo.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( odoo.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, odoo.sql_db.sql_counter - t0_sql) registry.clear_caches() return loaded_modules, processed_modules
def setUpClass(cls): cls.registry = odoo.registry(get_db_name()) cls.cr = cls.registry.cursor() cls.uid = odoo.SUPERUSER_ID cls.env = api.Environment(cls.cr, cls.uid, {})
def post_init(cr, registry): """Rewrite ICP's to force groups""" from odoo import api, SUPERUSER_ID env = api.Environment(cr, SUPERUSER_ID, {}) env['ir.config_parameter'].init(force=True)
def compute_view_render_params(application_id: Application): application_id = application_id.sudo() SUPER_ENV = api.Environment(request.env.cr, SUPERUSER_ID, {}) relationship_types = request.env['school_base.relationship_type'].sudo( ).search([]) marital_status_types = ( AdmissionController._get_values_for_selection_fields( 'res.partner', 'marital_status')) applying_semester_values = ( AdmissionController._get_values_for_selection_fields( 'adm.application', 'applying_semester')) contact_id = AdmissionController.get_user().partner_id contact_time_ids = request.env["adm.contact_time"].search([]) degree_program_ids = request.env["adm.degree_program"].search([]) gender_ids = request.env['adm.gender'].search([]) application_status_ids = (request.env["adm.application.status"].search( [])) grade_level_ids = ( request.env['school_base.grade_level'].sudo().search([ ('active_admissions', '=', True) ])) school_year_ids = ( request.env['school_base.school_year'].sudo().search([ ('active_admissions', '=', True) ])) language_ids = http.request.env['adm.language'].search([]) language_level_ids = request.env['adm.language.level'].search([]) country_ids = request.env['res.country'].search([]) state_ids = request.env['res.country.state'].search([]) def is_required(fieldname): required_fields_name_list = application_id.get_required_fields( ).get_as_list_of_names() return fieldname in required_fields_name_list application_page_ids = SUPER_ENV['adm.application.page'].search([ ('parent_id', '=', False) ]) return { "country_ids": country_ids, "state_ids": state_ids, 'contact_id': contact_id, 'application_id': application_id, 'application_status_ids': application_status_ids, 'language_ids': language_ids, 'language_level_ids': language_level_ids, 'contact_time_ids': contact_time_ids, "gender_ids": gender_ids, 'degree_program_ids': degree_program_ids, 'current_url': request.httprequest.full_path, "showPendingInformation": False, 'grade_level_ids': grade_level_ids, 'applying_semester_values': applying_semester_values, 'school_year_ids': school_year_ids, 'relationship_types': relationship_types, 'marital_status_types': marital_status_types, 'SUPER_ENV': SUPER_ENV, 'USER_ENV': http.request.env, 'is_required': is_required, 'application_page_ids': application_page_ids, }
def migrate(cr, version): with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) adds = {'active_test': False} env['printnode.action.method'].search([ '|', '|', ('model_id', '=', False), ('name', '=', False), ('method', '=', False), ]).unlink() env['printnode.action.button'].with_context(**adds).search([ '|', '|', ('method_id', '=', False), ('model_id', '=', False), ('report_id', '=', False), ]).unlink() method_duplicates = env['printnode.action.method'].read_group( domain=[], fields=['model_id', 'method'], groupby=['model_id', 'method'], lazy=False) # [{ # '__count': 2, # 'model_id': (462, <odoo.tools.func.lazy object at 0x7f5c210346c0>), # 'method': 'button_validate', # '__domain': ['&', ('model_id', '=', 462), ('method', '=', 'button_validate')], # },] method_dict_list = [ dct for dct in method_duplicates if dct['__count'] > 1 ] injection_methods = [(env.ref(key).id, value[0]) for key, value, in EXTERNAL_IDS.items()] for method_dict in method_dict_list: model_id = method_dict['model_id'][0] method_name = method_dict['method'] method_ids = env['printnode.action.method'].search( method_dict['__domain']).ids primary_method_id = method_ids[-1] if (model_id, method_name) in injection_methods: # Replace matched "action method" external-id to our from EXTERNAL_IDS model = env['ir.model'].browse(model_id) model_external_id = model.get_external_id()[model_id] method_external_id = EXTERNAL_IDS[model_external_id][1] primary_method_id = env.ref(method_external_id).id buttons_to_update = env['printnode.action.button'].with_context( **adds).search([ ('model_id', '=', model_id), ('method_id', 'in', method_ids), ]) buttons_to_update.write({'method_id': primary_method_id}) method_ids.remove(primary_method_id) env['printnode.action.method'].browse(method_ids).unlink()
def _auto_clean_cache_when_installed(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) caches = env['pos.cache.database'].search([]) caches.unlink() _logger.info('!!!!!!! Removed caches !!!!!!!') _logger.info('!!!!!!! THANKS FOR PURCHASED MODULE !!!!!!!')
def add_book_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) book_data1 = {'name': 'Book 1', 'date_release': fields.Date.today()} book_data2 = {'name': 'Book 2', 'date_release': fields.Date.today()} env['library.book'].create([book_data1, book_data2])
def pre_init_hook(cr, registry): with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) env['stock.move'].initializing_stock_segmentation()
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', '=', _('Stock Journal')), ('company_id', '=', company_id.id), ('type', '=', 'general')], limit=1).id if not journal_id: journal_id = env['account.journal'].create({ 'name': _('Stock Journal'), '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)])
def suspend_security(self): return self.with_env( api.Environment(self.env.cr, BaseSuspendSecurityUid(self.env.uid), self.env.context))
def post_init_hook(cr, _): with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) env["res.partner"]._install_l10n_th_partner()
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.sudo().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 assemble_mo_create(self): env = api.Environment(request.cr, SUPERUSER_ID, request.context) vals = request.jsonrequest # print(vals) vin = vals['vin'] if 'vin' in vals else None if not vin: body = json.dumps({ "msg": "Track Number(Serial Number/VIN) not exists in parameters" }) return Response(body, headers=[('Content-Type', 'application/json'), ('Content-Length', len(body))], status=405) mo_name = u'{0}--V001--{1}-{2}-{3}={4}'.format(vals['equipment_name'], vals['factory_name'], vals['year'], vals['pin'], vals['pin_check_code']) count = env['mrp.production'].search_count([('name', '=', mo_name)]) if count > 0: # MO已存在 body = json.dumps( {"msg": "MO name " + mo_name + " already exists"}) return Response(body, headers=[('Content-Type', 'application/json'), ('Content-Length', len(body))], status=405) count = env['mrp.production'].search_count([('vin', '=', vin)]) if count > 0: # MO已存在 body = json.dumps({"msg": "MO vin " + vin + " already exists"}) return Response(body, headers=[('Content-Type', 'application/json'), ('Content-Length', len(body))], status=405) vechile_code = vals['model'] if 'model' in vals else None if not vechile_code: body = json.dumps( {"msg": "Vehicle Type code not exists in parameters"}) return Response(body, headers=[('Content-Type', 'application/json'), ('Content-Length', len(body))], status=405) vals.pop('model') records = env['product.product'].search( [('default_code', 'ilike', vechile_code)], limit=1) if not records: # 找不到对应车型 body = json.dumps( {"msg": "vehicle model " + vechile_code + " not found"}) return Response(body, headers=[('Content-Type', 'application/json'), ('Content-Length', len(body))], status=400) product_id = records[0] assemble_line = vals[ 'assembly_line'] if 'assembly_line' in vals else None if not assemble_line: body = json.dumps( {"msg": "assembly_line not exists in parameters"}) return Response(body, headers=[('Content-Type', 'application/json'), ('Content-Length', len(body))], status=405) vals.pop('assembly_line') records = env['mrp.assemblyline'].search([ '|', ('name', 'ilike', assemble_line), ('code', 'ilike', assemble_line) ], limit=1) if not records: # 找不到对应装配线 records = env['mrp.assemblyline'].create({ 'name': assemble_line, 'code': assemble_line }) # Response.status = "400 Bad Request" # return {"msg": "Assembly line " + assemble_line + " not found"} assembly_line_id = records[0] vals.update({'name': mo_name}) vals.update({ 'product_id': product_id.id, 'bom_id': product_id.active_bom_id.id, 'product_tmpl_id': product_id.product_tmpl_id.id, 'product_uom_id': product_id.active_bom_id.product_uom_id.id, 'routing_id': product_id.active_bom_id.routing_id.id, 'assembly_line_id': assembly_line_id.id }) prs = vals['prs'] vals.pop('prs') vals.update({'production_routings': json.dumps(prs)}) if 'date_planned_start' in vals: _t = parser.parse(vals['date_planned_start'] ) if vals['date_planned_start'] else None if _t: vals.update({ 'date_planned_start': fields.Datetime.to_string((_t - _t.utcoffset())) }) production = env['mrp.production'].create(vals) production.plan_by_prs() ### 模拟点击安排,自动生成工单 if not production: body = json.dumps({"msg": "create MO failed"}) return Response(body, headers=[('Content-Type', 'application/json'), ('Content-Length', len(body))], status=400) # 创建MO成功 vals = { 'id': production.id, 'vin': production.vin, 'knr': production.knr, 'product_id': production.product_id.id, 'assembly_line_id': production.assembly_line_id.id, 'result_ids': production.result_ids.ids if production.result_ids else [], 'workorder_ids': production.workorder_ids.ids if production.workorder_ids else [], } body = json.dumps(vals) return Response(body, headers=[('Content-Type', 'application/json'), ('Content-Length', len(body))], status=201)
def _postprocess_restored_db(self, dbname): """ Do some postprocessing after DB restored from backup The reason for this method, is to ensure that yodoo_client is installed on database and if needed updated. Also, we check installed addons and compare them with thats are available on disk, and if needed run update for them. """ to_update_modules = set() to_install_modules = set() modules_in_db = {} modules_on_disk = { mod: odoo.modules.module.load_information_from_description_file(mod) for mod in odoo.modules.module.get_modules() } auto_install_addons = odoo.tools.config.get( 'yodoo_auto_install_addons', '') auto_install_addons = [ a.strip() for a in auto_install_addons.split(',') if a.strip() ] with closing(db_connect(dbname).cursor()) as cr: cr.execute(""" SELECT name, latest_version FROM ir_module_module WHERE state = 'installed'; """) modules_in_db = dict(cr.fetchall()) if 'yodoo_client' not in modules_in_db: _logger.info("yodoo_client not installed, adding to install list") to_install_modules.add('yodoo_client') elif modules_in_db['yodoo_client'] != get_yodoo_client_version(): _logger.info( "yodoo_client not up to date (%s != %s), " "adding to update list", modules_in_db['yodoo_client'], get_yodoo_client_version()) to_update_modules.add('yodoo_client') for module_name in auto_install_addons: if module_name not in modules_on_disk: continue if module_name not in modules_in_db: _logger.info( "Module %s is mentioned in auto_install_addons list, " "but is not installed in database. Installing.", module_name) to_install_modules.add(module_name) for module_name, db_version in modules_in_db.items(): if module_name not in modules_on_disk: continue if db_version != modules_on_disk[module_name]['version']: _logger.info( "Module %s is not up to data, adding to update list.", module_name) to_update_modules.add(module_name) if to_install_modules or to_update_modules: _logger.info( "There are addons to install %s and to update %s found.", tuple(to_install_modules), tuple(to_update_modules)) with registry(dbname).cursor() as cr: env = api.Environment(cr, SUPERUSER_ID, context={}) env['ir.module.module'].update_list() if to_install_modules: env['ir.module.module'].search([ ('name', 'in', list(to_install_modules)), ('state', 'in', ('uninstalled', 'to_install')) ]).button_immediate_install() if to_update_modules: env['ir.module.module'].search([ ('name', 'in', list(to_update_modules)), ('state', 'in', ('uninstalled', 'to_install')) ]).button_immediate_upgrade()
def set_xml_format_in_pdf_invoice_to_ubl(cr, registry): with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) companies = env['res.company'].search([]) companies.write({'xml_format_in_pdf_invoice': 'ubl'}) return
def client_db_configure_mail(self, incoming, outgoing, db=None, test_and_confirm=False, **params): # pylint: disable=too-many-locals, too-many-branches """ Configure mail servers for database :param dict incoming: dict with config of incoming mail server :param dict outgoing: dict with config of outgoing mail server :param bool test_and_confirm: if set to True, test if odoo can use specified mail servers :return: 200 OK if everythning is ok. in case of errors, 500 code will be returned Required params for incoming mail server: - host - user - password Required params for outgoing mail server: - host - user - password """ test_and_confirm = str2bool(test_and_confirm) incoming = json.loads(incoming) outgoing = json.loads(outgoing) incoming_data = { 'name': 'Yodoo Incoming Mail', 'server_type': 'imap', 'is_ssl': True, 'port': 993, 'server': incoming['host'], 'user': incoming['user'], 'password': incoming['password'], 'active': incoming.get('active', True), 'state': 'draft', } outgoing_data = { 'name': 'Yodoo Outgoing Mail', 'smtp_encryption': 'starttls', 'smtp_port': 587, 'smtp_host': outgoing['host'], 'smtp_user': outgoing['user'], 'smtp_pass': outgoing['password'], 'active': outgoing.get('active', True), } with registry(db).cursor() as cr: env = api.Environment(cr, SUPERUSER_ID, context={}) incoming_srv = env.ref('yodoo_client.yodoo_incoming_mail', raise_if_not_found=False) if incoming_srv: incoming_srv.write(incoming_data) else: incoming_srv = env['fetchmail.server'].create(incoming_data) env['ir.model.data'].create({ 'name': 'yodoo_incoming_mail', 'module': 'yodoo_client', 'model': incoming_srv._name, 'res_id': incoming_srv.id, 'noupdate': True, }) if test_and_confirm: incoming_srv.button_confirm_login() if incoming_srv.state != 'done': raise werkzeug.exceptions.InternalServerError( "Cannot configure incoming mail server") outgoing_srv = env.ref('yodoo_client.yodoo_outgoing_mail', raise_if_not_found=False) if outgoing_srv: outgoing_srv.write(outgoing_data) else: catchall_domain = outgoing['user'].split('@') if len(catchall_domain) > 1: catchall_domain = catchall_domain[1] res_users = env['res.users'].sudo().with_context( active_test=False) res_users.browse(SUPERUSER_ID).partner_id.write( {'email': 'odoobot@%s' % catchall_domain}) env['ir.config_parameter'].sudo().set_param( 'mail.catchall.domain', catchall_domain) env['ir.mail_server'].search([('active', '=', True) ]).write({'active': False}) outgoing_srv = env['ir.mail_server'].create(outgoing_data) env['ir.model.data'].create({ 'name': 'yodoo_outgoing_mail', 'module': 'yodoo_client', 'model': outgoing_srv._name, 'res_id': outgoing_srv.id, 'noupdate': True, }) if test_and_confirm: try: smtp = outgoing_srv.connect(mail_server_id=outgoing_srv.id) except Exception: _logger.error("Cannot configure outgoing mail server", exc_info=True) raise werkzeug.exceptions.InternalServerError( "Cannot configure outgoing mail server") finally: try: if smtp: smtp.quit() except Exception: # pylint: disable=except-pass # ignored, just a consequence of the previous exception pass return http.Response('OK', status=200)
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 _update_street_format(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) env['res.partner'].search([])._split_street()
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 IN ('selection', 'constraint', 'sql_constraint') AND noupdate IS NOT TRUE ON CONFLICT (type, lang, name, md5(src)) WHERE type IN ('selection', 'constraint', 'sql_constraint') 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 l10n_eu_service_post_init(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) env['res.company']._map_all_eu_companies_taxes()
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_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): env = api.Environment(cr, SUPERUSER_ID, {}) return True
def finish(self): """ Transfer the data from the temp table to ir.translation """ cr = self._cr if self._debug: cr.execute("SELECT count(*) FROM %s" % self._table) count = cr.fetchone()[0] _logger.debug("ir.translation.cursor: We have %d entries to process", count) # 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)) find_expr = """ irt.lang = ti.lang AND irt.type = ti.type AND irt.name = ti.name AND ( (ti.type = 'model' AND ti.res_id = irt.res_id AND ti.name IN %s AND irt.src = ti.src) OR (ti.type = 'model' AND ti.res_id = irt.res_id AND ti.name NOT IN %s) OR (ti.type = 'view' AND (irt.res_id IS NULL OR ti.res_id = irt.res_id) AND irt.src = ti.src) OR (ti.type = 'field') OR (ti.type = 'help') OR (ti.type NOT IN ('model', 'view', 'field', 'help') AND irt.src = ti.src) ) """ # Step 2: update existing (matching) translations if self._overwrite: cr.execute(""" UPDATE ONLY %s AS irt SET value = ti.value, src = ti.src, state = 'translated' FROM %s AS ti WHERE %s AND ti.value IS NOT NULL AND ti.value != '' AND noupdate IS NOT TRUE """ % (self._model_table, self._table, find_expr), (tuple(src_relevant_fields), tuple(src_relevant_fields))) # Step 3: insert new translations 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 AS ti WHERE NOT EXISTS(SELECT 1 FROM ONLY %s AS irt WHERE %s); """ % (self._model_table, self._table, self._model_table, find_expr), (tuple(src_relevant_fields), tuple(src_relevant_fields))) if self._debug: cr.execute("SELECT COUNT(*) FROM ONLY %s" % self._model_table) total = cr.fetchone()[0] cr.execute("SELECT COUNT(*) FROM ONLY %s AS irt, %s AS ti WHERE %s" % \ (self._model_table, self._table, find_expr), (tuple(src_relevant_fields), tuple(src_relevant_fields))) count = cr.fetchone()[0] _logger.debug("ir.translation.cursor: %d entries now in ir.translation, %d common entries with tmp", total, count) # Step 4: cleanup cr.execute("DROP TABLE %s" % self._table) return True
def uninstall_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) access = env.ref("base.access_ir_module_module_group_user", raise_if_not_found=False) access.write({'active': True})
def on_message(self, unused_channel, basic_deliver, properties, body): new_cr = sql_db.db_connect(self.env.cr.dbname).cursor() uid, context = self.env.uid, self.env.context with api.Environment.manage(): self.env = api.Environment(new_cr, uid, context) try: LOGGER.info("-------------------------------------------") LOGGER.info(body) jdata = json.loads(body) if jdata: _logger.info(jdata) output = "" status = "error" log_response = "" odoo = jdata['odoo'] oss = jdata['oss'] status = jdata['status'] message = jdata['message'] log_id = jdata['log'] if log_id: log = self.env['cb.logs'].browse(int(log_id)) LOGGER.info( "-------------------------------------------") LOGGER.info(log) object_id = self.env[log.model].browse( int(log.object_id)) if object_id: send_rabbit = object_id.send_rabbit + 1 if log: if status == 1 or status == '1': object_id.with_context({ 'from_rest_api': True }).write({ 'send_rabbit': 0, 'external_id': oss, 'external_type': 'OSS' }) status = 'success' else: if send_rabbit < 2: LOGGER.info( "-------------------send_rabbit------------------------" ) LOGGER.info(send_rabbit) if log.model == 'sale.order': object_id.create_update_order( object_id.id, 'sale.order', log.action) if log.model == 'res.partner': object_id.create_update_partner( object_id.id, 'res.partner', log.action) if log.model == 'stock.picking': object_id.create_update_picking( object_id.id, 'stock.picking', log.action) if log.model == 'account.invoice': object_id.create_update_invoice( object_id.id, 'account.invoice', log.action) else: send_rabbit = 0 object_id.with_context({ 'from_rest_api': True }).write({'send_rabbit': send_rabbit}) status = 'error' LOGGER.info(status) LOGGER.info(message) log.write({ 'status': status, 'response': message }) new_cr.commit() else: output = "Load data fail" status = "error" self.env['cb.logs'].create({ 'name': 'wholesale_oss_respone_msg', 'model': 'consume', 'action': '', 'request': '', 'response': '', 'object_id': '', 'output': output, 'status': status, 'url': '' }) new_cr.commit() LOGGER.info('Received message # %s from %s: %s', basic_deliver.delivery_tag, properties.app_id, body) except Exception, e: _logger.info(e) finally:
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 odoo.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") odoo.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 # odoo.modules.registry.Registry.new(). registry = odoo.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 = odoo.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 = odoo.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['odoo.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 = odoo.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 _uninstall_force_storage(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) config = env['ir.config_parameter'].sudo() config.set_param('ir_attachment.location', 'file') attachment = env['ir.attachment'] attachment.sudo().force_storage()