def post(self, path, vals): config = self.instance() payload = simplejson.dumps(vals) url = config.get('cenit_url') + API_PATH + path headers = self.headers(config) try: _logger.info("[POST] %s ? %s {%s}", url, payload, headers) r = requests.post(url, data=payload, headers=headers) except Exception as e: _logger.error(e) raise exceptions.AccessError("Error trying to connect to Cenit.") if 200 <= r.status_code < 300: return r.json() try: error = r.json() _logger.error(error) except Exception as e: _logger.error(e) raise exceptions.ValidationError("Cenit returned with errors") if 400 <= error.get('code', 400) < 500: raise exceptions.AccessError("Error trying to connect to Cenit.") raise exceptions.ValidationError("Cenit returned with errors")
def get(self, path, params=None): config = self.instance() url = config.get('cenit_url') + API_PATH + path headers = self.headers(config) try: _logger.info("[GET] %s ? %s {%s}", url, params, headers) r = requests.get(url, params=params, headers=self.headers(config)) except Exception as e: _logger.error(e) raise exceptions.AccessError("Error trying to connect to Cenit.") if 200 <= r.status_code < 300: return r.json() try: error = r.json() _logger.error(error) except Exception as e: _logger.error(e) _logger.info("\n\n%s\n", r.content) raise exceptions.ValidationError("Cenit returned with errors") if 400 <= error.get('code', 400) < 500: raise exceptions.AccessError("Error trying to connect to Cenit.") raise exceptions.ValidationError("Cenit returned with errors")
def delete(self, path): config = self.instance() url = config.get('cenit_url') + API_PATH + path headers = self.headers(config) try: _logger.info("[DEL] %s ? {%s}", url, headers) r = requests.delete(url, headers=headers) except Exception as e: _logger.error(e) raise exceptions.AccessError("Error trying to connect to Cenit.") if 200 <= r.status_code < 300: return True try: error = r.json() _logger.error(error) except Exception as e: _logger.error(e) raise exceptions.ValidationError("Cenit returned with errors") if 400 <= error.get('code', 400) < 500: raise exceptions.AccessError("Error trying to connect to Cenit.") raise exceptions.ValidationError("Cenit returned with errors")
def create(self, vals): res = super(OpFeesTerms, self).create(vals) if not res.line_ids: raise exceptions.AccessError(_("Fees Terms must be Required!")) total = 0.0 for line in res.line_ids: if line.value: total += line.value if total != 100.0: raise exceptions.AccessError(_("Fees terms must be divided \ as such sum up in 100%")) return res
def set_rejected(self): if not self.user_can_moderate: raise exceptions.AccessError("Nie masz uprawnień aby dezaktywować ten sklep!") if self.state in ('proposed', 'chain', 'activated'): raise exceptions.AccessError("Uprzednio proponowany sklep nie może zostać odrzucony!") if self.state == 'waiting_bank': self.send( template='bestja_stores.msg_in_project_rejected', recipients=self.project.responsible_user, ) self.sudo().state = 'rejected'
def check( self, cr, uid, model, mode='read', raise_exception=True, context=None): if isinstance(model, BaseModel): assert model._name == 'ir.model', 'Invalid model object' model_name = model.model else: model_name = model if mode != 'read' and model_name in [ 'product.template', 'product.product']: if self.pool['res.users'].has_group( cr, uid, 'product_management_group.group_products_management'): return True elif raise_exception: raise exceptions.AccessError(_( "Sorry, you are not allowed to manage products." "Only users with 'Products Management' level are currently" " allowed to do that")) else: return False return super(IrModelAccess, self).check( cr, uid, model, mode=mode, raise_exception=raise_exception, context=context)
def change_state(self): for store in self.stores: if not self.user_has_groups('bestja_base.instance_admin'): raise exceptions.AccessError( "Nie masz uprawnień do zmiany statusu!") if self.state == 'activated' and store.state not in [ 'chain', 'proposed' ]: raise exceptions.ValidationError( u"""Można aktywować tylko sklepy proponowane lub wysłane do sieci. Jednak sklep "{store}" ma status {state}.""".format( store=store.store.name_get()[0][1], state=store.display_state(), )) elif self.state == 'chain' and store.state != 'proposed': raise exceptions.ValidationError( u"""Można wysłać do sieci tylko proponowane sklepy. Jednak sklep "{store}" ma status {state}.""".format( store=store.store.name_get()[0][1], state=store.display_state(), )) elif self.state not in ['activated', 'chain']: raise exceptions.ValidationError( "Wybrano nieprawidłowy status") store.sudo().state = self.state
def delete_account(self): if not (self.env.uid == SUPERUSER_ID or self.user_has_groups('bestja_base.instance_admin')): raise exceptions.AccessError("Nie masz uprawnień do usuwania użytkowników!") self.sudo().write({ 'login': uuid.uuid1(), 'name': 'Konto usunięte', 'street_gov': '', 'street_number_gov': '', 'apt_number_gov': '', 'zip_code_gov': '', 'email': '', 'phone': '', 'street': '', 'street_number': '', 'apt_number': '', 'zip_code': '', 'curriculum_vitae': None, 'cv_filename': '', 'active_state': 'deleted', 'active': False, 'pesel': '', 'document_id_kind': None, 'document_id': '', })
def schedule_exam(self): for exam in self: if exam.total_student > exam.room_capacity: raise exceptions.AccessError( _("Room capacity must be greater than total number \ of student")) student_ids = [] for student in exam.student_ids: student_ids.append(student.id) for room in exam.room_ids: for i in range(room.capacity): if not student_ids: continue self.env['op.exam.attendees'].create({ 'exam_id': exam.exam_id.id, 'student_id': student_ids[0], 'status': 'present', 'course_id': exam.course_id.id, 'batch_id': exam.batch_id.id, 'room_id': room.id }) student_ids.remove(student_ids[0]) exam.exam_id.state = 'schedule' return True
def run_manually(self): """Run a job from the cron form view.""" if self.env.uid != SUPERUSER_ID and (not self.active or not self.numbercall): raise exceptions.AccessError( _('Only the admin user is allowed to ' 'execute inactive cron jobs manually')) try: # Try to grab an exclusive lock on the job row # until the end of the transaction self.env.cr.execute("""SELECT * FROM ir_cron WHERE id=%s FOR UPDATE NOWAIT""", (self.id, ), log_exceptions=False) except OperationalError as e: # User friendly error if the lock could not be claimed if getattr(e, "pgcode", None) == '55P03': raise exceptions.Warning( _('Another process/thread is already busy ' 'executing this job')) raise _logger.info('Job `%s` triggered from form', self.name) # Execute the cron job method = getattr( self.sudo(self.user_id).env[self.model], self.function) args = safe_eval('tuple(%s)' % (self.args or '')) return method(*args)
def unlock_lot(self): if not self.user_has_groups('stock_lock_by_lot.group_lock_unlock_lot'): raise exceptions.AccessError( _('You are not allowed to unlock Serial Numbers/Lots')) body = _('Serial Number/Lot unlocked') for lot in self: lot.message_post(body=body) return self.write({'locked_lot': False})
def unlink(self, **kwargs): rc = True try: rc = self.drop_from_cenit() except requests.ConnectionError as e: _logger.exception(e) raise exceptions.AccessError("Error trying to connect to Cenit.") except exceptions.AccessError: raise exceptions.AccessError("Error trying to connect to Cenit.") except Exception as e: _logger.exception(e) raise exceptions.ValidationError("Cenit returned with errors") if not rc: raise exceptions.ValidationError("Cenit returned with errors") rc = super(CenitApi, self).unlink(**kwargs) return rc
def set_deactivated(self): if not self.user_can_moderate: raise exceptions.AccessError("Nie masz uprawnień aby dezaktywować ten sklep!") self.send( template='bestja_stores.msg_in_project_deactivated', recipients=self.top_project.responsible_user, ) self.sudo().state = 'deactivated' self.sudo().time_deactivated = fields.Datetime.now()
def fields_view_get(self, view_id=None, view_type='tree', context=None, toolbar=False): rc = super(CenitAccountSettings, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar) arch = rc['arch'] if not arch.startswith('<form string="Cenit Hub account settings">'): return rc #icp = self.pool.get("ir.config_parameter") icp = self.env['ir.config_parameter'] hub_host = icp.get_param("odoo_cenit.cenit_url", default='https://cenit.io') if hub_host.endswith("/"): hub_host = hub_host[:-1] hub_hook = "captcha" hub_url = "{}/{}".format(hub_host, hub_hook) try: r = requests.get(hub_url) except Exception as e: _logger.error("\n\Error: %s\n", e) raise exceptions.AccessError("Error trying to connect to Cenit.") captcha_data = simplejson.loads(r.content) token = captcha_data.get('token', False) if not token: raise exceptions.AccessError("Error trying to connect to Cenit.") icp.set_param('cenit.captcha.token', token) arch = arch.replace('img_data_here', '{}/{}'.format(hub_url, token)) rc['arch'] = arch return rc
def _check_field_permissions(self, vals, permitted_vals=None): if permitted_vals is None: permitted_vals = {} if not self._is_permitted(): for field_name in self._protected_fields: if field_name in vals \ and permitted_vals.get(field_name) != vals[field_name]: raise exceptions.AccessError( "You don't have permissions to modify the {} field!". format(field_name))
def set_default_select_date(self): """Set default sale and purchase taxes for products""" if self.env.user.id != SUPERUSER_ID and not self.env.user.\ has_group('base.group_erp_manager'): raise exceptions.AccessError( _("Only administrators can change the settings")) config_parameters = self.env["ir.config_parameter"] for record in self: company_id = str(record.company_id and record.company_id.id or self._default_company()) key_by_company_id = "acc_invoice.date_invoice_type_" + company_id config_parameters.set_param(key_by_company_id, record.select_date or '')
def set_activated(self): if not self.user_can_moderate: raise exceptions.AccessError("Nie masz uprawnień aby aktywować ten sklep!") self.sudo().state = 'activated' if self.is_bank(): self.sudo().activated_by = self.project.parent.organization elif self.is_owner(): self.sudo().activated_by = self.project.organization else: # This shouldn't really happen, but we can't forbid super user # from doing anything, so theoretically speaking it might... self.sudo().activated_by = False
def delete(self, path): config = self.instance() r = requests.delete(config.get('cenit_url') + API_PATH + path, headers=self.headers(config)) if 200 <= r.status_code < 300: return True error = simplejson.loads(r.content) if 400 <= error.get('code', 400) < 500: raise exceptions.AccessError("Error trying to connect to Cenit.") raise exceptions.ValidationError("Cenit returned with errors")
def deactivate(self): for store in self.stores: if store.state not in ['chain', 'proposed', 'activated']: raise exceptions.ValidationError( u"""Można dezaktywować tylko sklepy zaakceptowane, proponowane lub wysłane do sieci. Jednak sklep "{store}" ma status {state}.""".format( store=store.store.name_get()[0][1], state=store.display_state(), )) if not store.user_can_moderate: raise exceptions.AccessError( u"Nie masz uprawnień do deazktywacji sklepu \"{}\"!". format(store.store.name_get()[0][1])) store.sudo().state = 'deactivated'
def create(self, vals): obj = super(CenitApi, self).create(vals) local = self.env.context.get('local', False) if local: return obj rc = False try: rc = obj.push_to_cenit() except requests.ConnectionError as e: _logger.exception(e) raise exceptions.AccessError("Error trying to connect to Cenit.") except exceptions.AccessError: raise exceptions.AccessError("Error trying to connect to Cenit.") except Exception as e: _logger.exception(e) raise exceptions.ValidationError("Cenit returned with errors") if not rc: raise exceptions.ValidationError("Cenit returned with errors") return obj
def run_manually(self): """Run a job from the cron form view.""" if self.env.uid != SUPERUSER_ID and (not self.active or not self.numbercall): raise exceptions.AccessError( _('Only the admin user is allowed to execute inactive cron jobs manually' )) try: # Try to grab an exclusive lock on the job row # until the end of the transaction self.env.cr.execute("""SELECT * FROM ir_cron WHERE id=%s FOR UPDATE NOWAIT""", (self.id, ), log_exceptions=False) except OperationalError as e: # User friendly error if the lock could not be claimed if getattr(e, "pgcode", None) == '55P03': raise exceptions.Warning( _('Another process/thread is already busy executing this job' )) raise _logger.info('Job `%s` triggered from form', self.name) # Do not propagate active_test to the method to execute ctx = dict(self.env.context) ctx.pop('active_test', None) # Execute the cron job method = getattr( self.with_context(ctx).sudo(self.user_id).env[self.model], self.function) args = safe_eval('tuple(%s)' % (self.args or '')) log = self.env['ir.cron.log'].start(self.name) try: ret = method(*args) openerp.modules.registry.RegistryManager.signal_caches_change( self.env.cr.dbname) except Exception as e: log.stop(error=traceback.format_exc()) self.env.cr.commit() raise e log.stop() return ret
def create(self, vals): record = super(StoreInProject, self).create(vals) if record.organization.level == 1 and record.is_owner(): # Middle organization adding for itself record.sudo().state = 'activated' record.sudo().activated_by = record.project.organization.id elif record.organization.level == 2: if record.is_bank(): # Middle organization adding for its child record.sudo().state = 'waiting_partner' else: record.sudo().state = 'waiting_bank' else: raise exceptions.AccessError("Nie masz uprawnień aby przypisać ten sklep!") return record
def put(self, path, vals): config = self.instance() payload = simplejson.dumps(vals) r = requests.put(config.get('cenit_url') + API_PATH + path, data=payload, headers=self.headers(config)) if 200 <= r.status_code < 300: return simplejson.loads(r.content) error = simplejson.loads(r.content) if 400 <= error.get('code', 400) < 500: raise exceptions.AccessError("Error trying to connect to Cenit.") raise exceptions.ValidationError("Cenit returned with errors")
def write(self, vals): res = super(CenitApi, self).write(vals) local = self.env.context.get('local', False) if local: return res cp = vals.copy() if cp.pop('cenitID', False): if len(cp.keys()) == 0: return res try: self.push_to_cenit() except requests.ConnectionError as e: _logger.exception(e) raise exceptions.AccessError("Error trying to connect to Cenit.") except exceptions.AccessError: raise exceptions.AccessError("Error trying to connect to Cenit.") except Exception as e: _logger.exception(e) raise exceptions.ValidationError("Cenit returned with errors") return res
def lock_lot(self): if not self.user_has_groups('stock_lock_by_lot.group_lock_unlock_lot'): raise exceptions.AccessError( _('You are not allowed to lock Serial Numbers/Lots')) domain = [ ('lot_id', 'in', self.ids), ('reservation_id', '!=', False), ('reservation_id.state', 'not in', ('cancel', 'done')), ] reserved_quants = self.env['stock.quant'].search(domain) reserved_quants.mapped("reservation_id").do_unreserve() body = _('Serial Number/Lot locked') for lot in self: lot.message_post(body=body) return self.write({'locked_lot': True})
def button_lock(self): """"Block the lot If the lot has reservations, they will be undone to lock the lot.""" if not self.user_has_groups('stock_lock_lot.group_lock_lot'): raise exceptions.AccessError( _('You are not allowed to block Serial Numbers/Lots')) reserved_quants = self.env['stock.quant'].search([ ('lot_id', 'in', self.ids), ('reservation_id', '!=', False), ('reservation_id.state', 'not in', ('cancel', 'done')), ('reservation_id.location_dest_id.allow_locked', '=', False) ]) reserved_quants.mapped("reservation_id").do_unreserve() # Block the lot return self.write({'locked': True})
def create(self, vals): record = super(StoreInProject, self).create(vals) if record.organization.level == 1 and record.is_owner(): # Middle organization adding for itself record.sudo().state = 'proposed' record.sudo().proposed_time = fields.Datetime.now() record.sudo().proposed_by = record.project.organization.id elif record.organization.level == 2: if record.is_bank(): # Middle organization adding for its child record.sudo().state = 'waiting_partner' else: record.sudo().state = 'waiting_bank' else: raise exceptions.AccessError("Nie masz uprawnień aby przypisać ten sklep!") if not record.days: # No days defined. Add the default set. record.add_days() return record
def check(self, mode, values=None): """Restricts the access to a workflow task, according to referred model. """ res_ids = {} if self._ids: self._cr.execute( """SELECT DISTINCT res_type, res_id FROM workflow_task WHERE id = ANY (%s)""", (list(self._ids), )) for rmod, rid in self._cr.fetchall(): res_ids.setdefault(rmod, set()).add(rid) if values: if values.get('res_type') and values.get('res_id'): res_ids.setdefault(values['res_type'], set())\ .add(values['res_id']) for model, mids in res_ids.items(): existing_ids = self.pool[model].exists(self._cr, self._uid, mids) self.check_base_security(model, existing_ids, mode) if not self._uid == SUPERUSER_ID and\ not self.env['res.users'].has_group('base.group_user'): raise exceptions.AccessError( _("Sorry, you are not allowed to access this document."))
def write(self, cr, uid, ids, vals, context=None): if any([ k in vals for k in [ 'street', 'street2', 'zip_id', 'street3', 'city', 'state_id', 'zip', 'country_id' ] ]): for partner_id in ids: partner = self.browse(cr, uid, partner_id) moves = self.pool.get('account.move').search( cr, uid, [('partner_id', '=', partner_id)]) invoices = self.pool.get('account.invoice').search( cr, uid, [('partner_id', '=', partner.id), ('state', '!=', 'cancel')]) if moves or invoices: if not self.pool['res.users'].has_group( cr, uid, 'partner_maintainer.group_partner_maintainer'): raise exceptions.AccessError( _("Only administrators can change partner addresses" )) return super(ResPartner, self).write(cr, uid, ids, vals, context)
def check_action_security(self, res_type, res_id): if not self._check_action_security(res_type, res_id): raise exceptions.AccessError( _("""The requested operation cannot be completed due to security restrictions. Please contact your system administrator."""))