def oea(self, **kw): """login user via Coffice Account provider""" dbname = kw.pop('db', None) if not dbname: dbname = db_monodb() if not dbname: return BadRequest() if not http.db_filter([dbname]): return BadRequest() registry = registry_get(dbname) with registry.cursor() as cr: try: env = api.Environment(cr, SUPERUSER_ID, {}) provider = env.ref('auth_oauth.provider_openerp') except ValueError: return set_cookie_and_redirect('/web?db=%s' % dbname) assert provider._name == 'auth.oauth.provider' state = { 'd': dbname, 'p': provider.id, 'c': { 'no_user_creation': True }, } kw['state'] = json.dumps(state) return self.signin(**kw)
def _button_immediate_function(self, function): try: # This is done because the installation/uninstallation/upgrade can modify a currently # running cron job and prevent it from finishing, and since the ir_cron table is locked # during execution, the lock won't be released until timeout. self._cr.execute("SELECT * FROM ir_cron FOR UPDATE NOWAIT") except psycopg2.OperationalError: raise UserError( _("The server is busy right now, module operations are not possible at" " this time, please try again later.")) function(self) self._cr.commit() api.Environment.reset() modules.registry.Registry.new(self._cr.dbname, update_module=True) self._cr.commit() env = api.Environment(self._cr, self._uid, self._context) # pylint: disable=next-method-called config = env['ir.module.module'].next() or {} if config.get('type') not in ('ir.actions.act_window_close', ): return config # reload the client; open the first available root menu menu = env['ir.ui.menu'].search([('parent_id', '=', False)])[:1] return { 'type': 'ir.actions.client', 'tag': 'reload', 'params': { 'menu_id': menu.id }, }
def _auto_install_enterprise_dependencies(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) module_list = ['account_accountant'] module_ids = env['ir.module.module'].search([('name', 'in', module_list), ('state', '=', 'uninstalled') ]) module_ids.sudo().button_install()
def load_demo(cr, package, idref, mode, report=None): """ Loads demo data for the specified package. """ if not package.should_have_demo(): return False try: _logger.info("Module %s: loading demo", package.name) with cr.savepoint(flush=False): load_data(cr, idref, mode, kind='demo', package=package, report=report) return True except Exception as e: # If we could not install demo data for this module _logger.warning( "Module %s demo data failed to install, installed without demo data", package.name, exc_info=True) env = api.Environment(cr, SUPERUSER_ID, {}) todo = env.ref('base.demo_failure_todo', raise_if_not_found=False) Failure = env.get('ir.demo_failure') if todo and Failure is not None: todo.state = 'open' Failure.create({'module_id': package.id, 'error': str(e)}) return False
def _serve_attachment(cls): env = api.Environment(request.cr, SUPERUSER_ID, request.context) attach = env['ir.attachment'].get_serve_attachment( request.httprequest.path, extra_fields=['name', 'checksum']) if attach: wdate = attach[0]['__last_update'] datas = attach[0]['datas'] or b'' name = attach[0]['name'] checksum = attach[0]['checksum'] or hashlib.sha1(datas).hexdigest() if (not datas and name != request.httprequest.path and name.startswith(('http://', 'https://', '/'))): return werkzeug.utils.redirect(name, 301) response = werkzeug.wrappers.Response() response.last_modified = wdate response.set_etag(checksum) response.make_conditional(request.httprequest) if response.status_code == 304: return response response.mimetype = attach[0][ 'mimetype'] or 'application/octet-stream' response.data = base64.b64decode(datas) return response
def log_xml(self, xml_string, func): self.ensure_one() if self.debug_logging: self.flush() db_name = self._cr.dbname # Use a new cursor to avoid rollback that could be caused by an upper method try: db_registry = registry(db_name) with db_registry.cursor() as cr: env = api.Environment(cr, SUPERUSER_ID, {}) IrLogging = env['ir.logging'] IrLogging.sudo().create({ 'name': 'delivery.carrier', 'type': 'server', 'dbname': db_name, 'level': 'DEBUG', 'message': xml_string, 'path': self.delivery_type, 'func': func, 'line': 1 }) except psycopg2.Error: pass
def uninstall_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) env['delivery.carrier'].search([('delivery_type', '=', 'temando')]).write({ 'delivery_type': 'fixed', 'fixed_price': 0 })
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 _create_warehouse_data(cr, registry): """ This hook is used to add a default manufacture_pull_id, manufacture picking_type on every warehouse. It is necessary if the mrp module is installed after some warehouses were already created. """ env = api.Environment(cr, SUPERUSER_ID, {}) warehouse_ids = env['stock.warehouse'].search([('manufacture_pull_id', '=', False)]) warehouse_ids.write({'manufacture_to_resupply': True})
def to_python(self, value): matching = re.match(self.regex, value) _uid = RequestUID(value=value, match=matching, converter=self) record_id = int(matching.group(2)) env = api.Environment(request.cr, _uid, request.context) if record_id < 0: # limited support for negative IDs due to our slug pattern, assume abs() if not found if not env[self.model].browse(record_id).exists(): record_id = abs(record_id) return env[self.model].browse(record_id)
def _create_buy_rules(cr, registry): """ This hook is used to add a default buy_pull_id on every warehouse. It is necessary if the purchase_stock module is installed after some warehouses were already created. """ env = api.Environment(cr, SUPERUSER_ID, {}) warehouse_ids = env['stock.warehouse'].search([('buy_pull_id', '=', False) ]) for warehouse_id in warehouse_ids: warehouse_id._create_or_update_global_routes_rules()
def _setup_inalterability(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) # enable ping for this module env['publisher_warranty.contract'].update_notification(cron_mode=True) fr_companies = env['res.company'].search([ ('partner_id.country_id.code', 'in', env['res.company']._get_unalterable_country()) ]) if fr_companies: fr_companies._create_secure_sequence(['l10n_fr_pos_cert_sequence_id'])
def setUpClass(cls): super(TestAllL10n, cls).setUpClass() l10n_mods = cls.env['ir.module.module'].search([ ('name', 'like', 'l10n%'), ('state', '=', 'uninstalled'), ]) _logger.info("Modules to install: %s" % [x.name for x in l10n_mods]) l10n_mods.button_immediate_install() # Now that new modules are installed, we have to reset the environment api.Environment.reset() cls.env = api.Environment(cls.cr, coffice.SUPERUSER_ID, {})
def _setup_inalterability(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) # enable ping for this module env['publisher_warranty.contract'].update_notification(cron_mode=True) fr_companies = env['res.company'].search([('partner_id.country_id.code', 'in', env['res.company']._get_unalterable_country())]) if fr_companies: fr_companies._create_secure_sequence(['l10n_fr_closing_sequence_id']) for fr_company in fr_companies: fr_journals = env['account.journal'].search([('company_id', '=', fr_company.id)]) fr_journals.filtered(lambda x: not x.secure_sequence_id)._create_secure_sequence(['secure_sequence_id'])
def _assign_default_nomeclature_id(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) company_ids_without_default_nomenclature_id = env['res.company'].search([ ('nomenclature_id', '=', False) ]) default_nomenclature_id = env.ref('barcodes.default_barcode_nomenclature', raise_if_not_found=False) if default_nomenclature_id: company_ids_without_default_nomenclature_id.write({ 'nomenclature_id': default_nomenclature_id.id, })
def signin(self, **kw): state = json.loads(kw['state']) dbname = state['d'] if not http.db_filter([dbname]): return BadRequest() provider = state['p'] context = state.get('c', {}) registry = registry_get(dbname) with registry.cursor() as cr: try: env = api.Environment(cr, SUPERUSER_ID, context) credentials = env['res.users'].sudo().auth_oauth(provider, kw) cr.commit() action = state.get('a') menu = state.get('m') redirect = werkzeug.url_unquote_plus( state['r']) if state.get('r') else False url = '/web' if redirect: url = redirect elif action: url = '/web#action=%s' % action elif menu: url = '/web#menu_id=%s' % menu resp = login_and_redirect(*credentials, redirect_url=url) # Since /web is hardcoded, verify user has right to land on it if werkzeug.urls.url_parse( resp.location ).path == '/web' and not request.env.user.has_group( 'base.group_user'): resp.location = '/' return resp except AttributeError: # auth_signup is not installed _logger.error( "auth_signup not installed on database %s: oauth sign up cancelled." % (dbname, )) url = "/web/login?oauth_error=1" except AccessDenied: # oauth credentials not valid, user could be on a temporary session _logger.info( 'OAuth2: access denied, redirect to main page in case a valid session exists, without setting cookies' ) url = "/web/login?oauth_error=3" redirect = werkzeug.utils.redirect(url, 303) redirect.autocorrect_location_header = False return redirect except Exception as e: # signup error _logger.exception("OAuth2: %s" % str(e)) url = "/web/login?oauth_error=2" return set_cookie_and_redirect(url)
def _assign_default_mail_template_picking_id(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) company_ids_without_default_mail_template_id = env['res.company'].search([ ('stock_mail_confirmation_template_id', '=', False) ]) default_mail_template_id = env.ref( 'stock.mail_template_data_delivery_confirmation', raise_if_not_found=False) if default_mail_template_id: company_ids_without_default_mail_template_id.write({ 'stock_mail_confirmation_template_id': default_mail_template_id.id, })
def receive(self, req): """ End-point to receive mail from an external SMTP server. """ dbs = req.jsonrequest.get('databases') for db in dbs: message = base64.b64decode(dbs[db]) try: db_registry = registry(db) with db_registry.cursor() as cr: env = api.Environment(cr, SUPERUSER_ID, {}) env['mail.thread'].message_process(None, message) except psycopg2.Error: pass return True
def _process_job(cls, job_cr, job, cron_cr): """ Run a given job taking care of the repetition. :param job_cr: cursor to use to execute the job, safe to commit/rollback :param job: job to be run (as a dictionary). :param cron_cr: cursor holding lock on the cron job row, to use to update the next exec date, must not be committed/rolled back! """ try: with api.Environment.manage(): cron = api.Environment( job_cr, job['user_id'], {'lastcall': fields.Datetime.from_string(job['lastcall']) })[cls._name] # Use the user's timezone to compare and compute datetimes, # otherwise unexpected results may appear. For instance, adding # 1 month in UTC to July 1st at midnight in GMT+2 gives July 30 # instead of August 1st! now = fields.Datetime.context_timestamp(cron, datetime.now()) nextcall = fields.Datetime.context_timestamp( cron, fields.Datetime.from_string(job['nextcall'])) numbercall = job['numbercall'] ok = False while nextcall < now and numbercall: if numbercall > 0: numbercall -= 1 if not ok or job['doall']: cron._callback(job['cron_name'], job['ir_actions_server_id'], job['id']) if numbercall: nextcall += _intervalTypes[job['interval_type']]( job['interval_number']) ok = True addsql = '' if not numbercall: addsql = ', active=False' cron_cr.execute( "UPDATE ir_cron SET nextcall=%s, numbercall=%s, lastcall=%s" + addsql + " WHERE id=%s", (fields.Datetime.to_string(nextcall.astimezone( pytz.UTC)), numbercall, fields.Datetime.to_string(now.astimezone( pytz.UTC)), job['id'])) cron.flush() cron.invalidate_cache() finally: job_cr.commit() cron_cr.commit()
def force_demo(cr): """ Forces the `demo` flag on all modules, and installs demo data for all installed modules. """ graph = coffice.modules.graph.Graph() cr.execute('UPDATE ir_module_module SET demo=True') cr.execute( "SELECT name FROM ir_module_module WHERE state IN ('installed', 'to upgrade', 'to remove')" ) module_list = [name for (name, ) in cr.fetchall()] graph.add_modules(cr, module_list, ['demo']) for package in graph: load_demo(cr, package, {}, 'init') env = api.Environment(cr, SUPERUSER_ID, {}) env['ir.module.module'].invalidate_cache(['demo'])
def _handle_exception(cls, exception): is_frontend_request = bool(getattr(request, 'is_frontend', False)) if not is_frontend_request: # Don't touch non frontend requests exception handling return super(IrHttp, cls)._handle_exception(exception) try: response = super(IrHttp, 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 code, values = cls._get_exception_code_values(exception) if code is None: # Hand-crafted HTTPException likely coming from abort(), # usually for a redirect response -> return it directly return exception 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']) values = cls._get_values_500_error(env, values, exception) elif code == 403: _logger.warn("403 Forbidden:\n\n%s", values['traceback']) elif code == 400: _logger.warn("400 Bad Request:\n\n%s", values['traceback']) try: html = cls._get_error_html(env, code, values) except Exception: html = env['ir.ui.view'].render_template( 'http_routing.http_error', values) return werkzeug.wrappers.Response( html, status=code, content_type='text/html;charset=utf-8')
def _login(cls, db, login, password): try: return super(Users, cls)._login(db, login, password) except AccessDenied as e: with registry(db).cursor() as cr: cr.execute("SELECT id FROM res_users WHERE lower(login)=%s", (login, )) res = cr.fetchone() if res: raise e env = api.Environment(cr, SUPERUSER_ID, {}) Ldap = env['res.company.ldap'] for conf in Ldap._get_ldap_dicts(): entry = Ldap._authenticate(conf, login, password) if entry: return Ldap._get_or_create_user(conf, login, entry) raise e
def post_init(cr, registry): """ Set the timesheet project and task on existing leave type. Do it in post_init to be sure the internal project/task of res.company are set. (Since timesheet_generate field is true by default, those 2 fields are required on the leave type). """ from coffice import api, SUPERUSER_ID env = api.Environment(cr, SUPERUSER_ID, {}) for hr_leave_type in env['hr.leave.type'].search([ ('timesheet_generate', '=', True), ('timesheet_project_id', '=', False) ]): company = hr_leave_type.company_id or env.company hr_leave_type.write({ 'timesheet_project_id': company.leave_timesheet_project_id.id, 'timesheet_task_id': company.leave_timesheet_task_id.id, })
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()
def pre_init_hook(cr): env = api.Environment(cr, SUPERUSER_ID, {}) env['ir.model.data'].search([('model', 'like', '%stock%'), ('module', '=', 'stock')]).unlink()
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(cr, registry): """Rewrite ICP's to force groups""" from coffice import api, SUPERUSER_ID env = api.Environment(cr, SUPERUSER_ID, {}) env['ir.config_parameter'].init(force=True)
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 load_translations(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) env.ref('l10n_sa.account_arabic_coa_general').process_coa_translations()
def uninstall_test_pylint(cr): env = api.Environment(cr, SUPERUSER_ID, {}) env['ir.module.module'].search([ ('name', '=', 'test_pylint'), ('state', '=', 'installed') ]).write({'state': 'uninstalled'})