def oea(self, **kw): """login user via NobleCRM 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_noblecrmerp') 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 poll(self, dbname, channels, last, options=None, timeout=TIMEOUT): if options is None: options = {} # Dont hang ctrl-c for a poll request, we need to bypass private # attribute access because we dont know before starting the thread that # it will handle a longpolling request if not noblecrm.evented: current = threading.current_thread() current._Thread__daemonic = True # PY2 current._daemonic = True # PY3 # rename the thread to avoid tests waiting for a longpolling current.setName("noblecrmerp.longpolling.request.%s" % current.ident) registry = noblecrm.registry(dbname) # immediatly returns if past notifications exist with registry.cursor() as cr: env = api.Environment(cr, SUPERUSER_ID, {}) notifications = env['bus.bus'].poll(channels, last, options) # immediatly returns in peek mode if options.get('peek'): return dict(notifications=notifications, channels=channels) # or wait for future ones if not notifications: if not self.started: # Lazy start of events listener self.start() event = self.Event() for channel in channels: self.channels.setdefault(hashable(channel), []).append(event) try: event.wait(timeout=timeout) with registry.cursor() as cr: env = api.Environment(cr, SUPERUSER_ID, {}) notifications = env['bus.bus'].poll(channels, last, options, force_status=True) except Exception: # timeout pass return notifications
def update_dashboard_graph_model(dbname): db_registry = noblecrm.modules.registry.Registry.new(dbname) with api.Environment.manage(), db_registry.cursor() as cr: env = api.Environment(cr, SUPERUSER_ID, {}) if 'crm.team' in env: recs = env['crm.team'].search([]) for rec in recs: rec._onchange_team_type()
def _set_accounts(cr, registry): #write the default debit account on salary rule having xml_id like 'l10n_be_hr_payroll.1' up to 'l10n_be_hr_payroll.1409' env = api.Environment(cr, SUPERUSER_ID, {}) names = [str(x) for x in range(1,1410)] data = env['ir.model.data'].search([('model', '=', 'hr.salary.rule'), ('module', '=', 'l10n_be_hr_payroll'), ('name', 'in', names)]) account = env['account.account'].search([('code', 'like', '4530%')], limit=1) if account and data: rule_ids = [x['res_id'] for x in data.read(['res_id'])] env['hr.salary.rule'].browse(rule_ids).write({'account_debit': account.id})
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 _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', UNALTERABLE_COUNTRIES)]) if fr_companies: # create the securisation sequence per company fr_companies._create_secure_sequence(['l10n_fr_closing_sequence_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 _auth_method_public(cls): """ If no user logged, set the public user of current website, or default public user as request uid. After this method `request.env` can be called, since the `request.uid` is set. The `env` lazy property of `request` will be correct. """ if not request.session.uid: env = api.Environment(request.cr, SUPERUSER_ID, request.context) website = env['website'].get_current_website() if website and website.user_id: request.uid = website.user_id.id if not request.uid: super(Http, cls)._auth_method_public()
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 _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', UNALTERABLE_COUNTRIES)]) if fr_companies: # create the securisation sequence per company fr_companies._create_secure_sequence(['l10n_fr_secure_sequence_id']) #reset the update_posted field on journals journals = env['account.journal'].search([('company_id', 'in', fr_companies.ids)]) journals.write({'update_posted': False})
def _auto_install_l10n(cr, registry): #check the country of the main company (only) and eventually load some module needed in that country env = api.Environment(cr, SUPERUSER_ID, {}) country_code = env.user.company_id.country_id.code if country_code: #auto install localization module(s) if available module_list = [] if country_code in SYSCOHADA_LIST: #countries using OHADA Chart of Accounts module_list.append('l10n_syscohada') elif country_code == 'GB': module_list.append('l10n_uk') elif country_code == 'DE': module_list.append('l10n_de_skr03') module_list.append('l10n_de_skr04') else: if env['ir.module.module'].search([ ('name', '=', 'l10n_' + country_code.lower()) ]): module_list.append('l10n_' + country_code.lower()) else: module_list.append('l10n_generic_coa') if country_code == 'US': module_list.append('account_plaid') module_list.append('account_check_printing') if country_code in [ 'US', 'AU', 'NZ', 'CA', 'CO', 'EC', 'ES', 'FR', 'IN', 'MX', 'UK' ]: module_list.append('account_yodlee') if country_code in SYSCOHADA_LIST + [ 'AT', 'BE', 'CA', 'CO', 'DE', 'EC', 'ES', 'ET', 'FR', 'GR', 'IT', 'LU', 'MX', 'NL', 'NO', 'PL', 'PT', 'RO', 'SI', 'TR', 'UK', 'VE', 'VN' ]: module_list.append('base_vat') #european countries will be using SEPA europe = env.ref('base.europe', raise_if_not_found=False) if europe: europe_country_codes = [x.code for x in europe.country_ids] if country_code in europe_country_codes: module_list.append('account_sepa') module_ids = env['ir.module.module'].search([ ('name', 'in', module_list), ('state', '=', 'uninstalled') ]) module_ids.sudo().button_install()
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 noblecrm import api, SUPERUSER_ID env = api.Environment(cr, SUPERUSER_ID, {}) for leave_type in env['hr.holidays.status'].search([ ('timesheet_generate', '=', True), ('timesheet_project_id', '=', False) ]): company = leave_type.company_id or env.user.company_id leave_type.write({ 'timesheet_project_id': company.leave_timesheet_project_id.id, 'timesheet_task_id': company.leave_timesheet_task_id.id, })
def _login(cls, db, login, password): user_id = super(Users, cls)._login(db, login, password) if user_id: return user_id with registry(db).cursor() as cr: cr.execute("SELECT id FROM res_users WHERE lower(login)=%s", (login, )) res = cr.fetchone() if res: return False 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: user_id = Ldap.get_or_create_user(conf, login, entry) if user_id: break return user_id
def log_xml(self, xml_string, func): self.ensure_one() if self.debug_logging: 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 create_missing_journal_for_acquirers(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) env['payment.acquirer']._create_missing_journal_for_acquirers()
def load_translations(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) env.ref('l10n_ca.ca_en_chart_template_en').process_coa_translations()
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_translations(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) env.ref('l10n_sa.account_arabic_coa_general').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 post_init(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) load_translations(env) init_settings(env)
def change_digit(cr): env = api.Environment(cr, SUPERUSER_ID, {}) precision = env['decimal.precision'].precision_get(application) return 16, precision
def uninstall_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) teams = env['crm.team'].search([('dashboard_graph_model', '=', 'crm.opportunity.report')]) teams.update({'dashboard_graph_model': None})