def _check_access_assignation(self): """ Check assigned user (user_id field) has access to the document. Purpose is to allow assigned user to handle their activities. For that purpose assigned user should be able to at least read the document. We therefore raise an UserError if the assigned user has no access to the document. """ for activity in self: model = self.env[activity.res_model].with_user(activity.user_id).with_context(allowed_company_ids=activity.user_id.company_ids.ids) try: model.check_access_rights('read') except exceptions.AccessError: raise exceptions.UserError( _('Assigned user %s has no access to the document and is not able to handle this activity.') % activity.user_id.display_name) else: try: target_user = activity.user_id target_record = self.env[activity.res_model].browse(activity.res_id) if hasattr(target_record, 'company_id') and ( target_record.company_id != target_user.company_id and ( len(target_user.sudo().company_ids) > 1)): return # in that case we skip the check, assuming it would fail because of the company model.browse(activity.res_id).check_access_rule('read') except exceptions.AccessError: raise exceptions.UserError( _('Assigned user %s has no access to the document and is not able to handle this activity.') % activity.user_id.display_name)
def _attendance_action_change(self): """ Check In/Check Out action Check In: create a new attendance record Check Out: modify check_out field of appropriate attendance record """ self.ensure_one() action_date = fields.Datetime.now() if self.attendance_state != 'checked_in': vals = { 'employee_id': self.id, 'check_in': action_date, } return self.env['hr.attendance'].create(vals) attendance = self.env['hr.attendance'].search( [('employee_id', '=', self.id), ('check_out', '=', False)], limit=1) if attendance: attendance.check_out = action_date else: raise exceptions.UserError( _('Cannot perform check out on %(empl_name)s, could not find corresponding check in. ' 'Your attendances have probably been modified manually by human resources.' ) % { 'empl_name': self.sudo().name, }) return attendance
def action_send_sms(self): self.ensure_one() numbers = [number.strip() for number in self.numbers.split(',')] sanitize_res = phone_validation.phone_sanitize_numbers_w_record( numbers, self.env.user) sanitized_numbers = [ info['sanitized'] for info in sanitize_res.values() if info['sanitized'] ] invalid_numbers = [ number for number, info in sanitize_res.items() if info['code'] ] if invalid_numbers: raise exceptions.UserError( _('Following numbers are not correctly encoded: %s, example : "+32 495 85 85 77, +33 545 55 55 55"' ) % repr(invalid_numbers)) self.env['sms.api']._send_sms_batch([{ 'res_id': 0, 'number': number, 'content': self.mailing_id.body_plaintext, } for number in sanitized_numbers]) return True
def write(self, vals): if vals.get('user_domain'): users = self._get_challenger_users(ustr(vals.get('user_domain'))) if not vals.get('user_ids'): vals['user_ids'] = [] vals['user_ids'].extend((4, user.id) for user in users) write_res = super(Challenge, self).write(vals) if vals.get('report_message_frequency', 'never') != 'never': # _recompute_challenge_users do not set users for challenges with no reports, subscribing them now for challenge in self: challenge.message_subscribe( [user.partner_id.id for user in challenge.user_ids]) if vals.get('state') == 'inprogress': self._recompute_challenge_users() self._generate_goals_from_challenge() elif vals.get('state') == 'done': self._check_challenge_reward(force=True) elif vals.get('state') == 'draft': # resetting progress if self.env['gamification.goal'].search( [('challenge_id', 'in', self.ids), ('state', '=', 'inprogress')], limit=1): raise exceptions.UserError( _("You can not reset a challenge with unfinished goals.")) return write_res
def _check_model_validity(self): """ make sure the selected field and model are usable""" for definition in self: try: if not (definition.model_id and definition.field_id): continue Model = self.env[definition.model_id.model] field = Model._fields.get(definition.field_id.name) if not (field and field.store): raise exceptions.UserError( _("The model configuration for the definition %s seems incorrect, please check it.\n\n%s not stored" ) % (definition.name, definition.field_id.name)) except KeyError as e: raise exceptions.UserError( _("The model configuration for the definition %s seems incorrect, please check it.\n\n%s not found" ) % (definition.name, e))
def write(self, values): if any(rec.provider == 'test' for rec in self) and 'state' in values and values.get( 'state') not in ('test', 'disabled'): raise exceptions.UserError( _('This acquirer should not be used for other purposes than testing.' )) return super(PaymentAcquirerTest, self).write(values)
def _signup_retrieve_partner(self, token, check_validity=False, raise_exception=False): """ find the partner corresponding to a token, and possibly check its validity :param token: the token to resolve :param check_validity: if True, also check validity :param raise_exception: if True, raise exception instead of returning False :return: partner (browse record) or False (if raise_exception is False) """ partner = self.search([('signup_token', '=', token)], limit=1) if not partner: if raise_exception: raise exceptions.UserError(_("Signup token '%s' is not valid") % token) return False if check_validity and not partner.signup_valid: if raise_exception: raise exceptions.UserError(_("Signup token '%s' is no longer valid") % token) return False return partner
def unblock(self): self.ensure_one() if self.working_state != 'blocked': raise exceptions.UserError(_("It has already been unblocked.")) times = self.env['mrp.workcenter.productivity'].search([ ('workcenter_id', '=', self.id), ('date_end', '=', False) ]) times.write({'date_end': fields.Datetime.now()}) return {'type': 'ir.actions.client', 'tag': 'reload'}
def _check_access(self): if not self.mail_message_id or not self.mail_message_id.model or not self.mail_message_id.res_id: raise exceptions.UserError( _('You do not have access to the message and/or related document.' )) record = self.env[self.mail_message_id.model].browse( self.mail_message_id.res_id) record.check_access_rights('read') record.check_access_rule('read')
def poll(self, channels, last, options=None): if options is None: options = {} if not dispatch: raise Exception("bus.Bus unavailable") if [c for c in channels if not isinstance(c, str)]: raise Exception("bus.Bus only string channels are allowed.") if request.registry.in_test_mode(): raise exceptions.UserError(_("bus.Bus not available in test mode")) return self._poll(request.db, channels, last, options)
def check_granting(self): """Check the user 'uid' can grant the badge 'badge_id' and raise the appropriate exception if not Do not check for SUPERUSER_ID """ status_code = self._can_grant_badge() if status_code == self.CAN_GRANT: return True elif status_code == self.NOBODY_CAN_GRANT: raise exceptions.UserError(_('This badge can not be sent by users.')) elif status_code == self.USER_NOT_VIP: raise exceptions.UserError(_('You are not in the user allowed list.')) elif status_code == self.BADGE_REQUIRED: raise exceptions.UserError(_('You do not have the required badges.')) elif status_code == self.TOO_MANY: raise exceptions.UserError(_('You have already sent this badge too many time this month.')) else: _logger.error("Unknown badge status code: %s" % status_code) return False
def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True): if 'pin' in groupby or 'pin' in self.env.context.get( 'group_by', '') or self.env.context.get('no_group_by'): raise exceptions.UserError(_('Such grouping is not allowed.')) return super(HrEmployeeBase, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)
def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True): if not self.user_has_groups( 'hr_holidays.group_hr_holidays_user') and 'name' in groupby: raise exceptions.UserError(_('Such grouping is not allowed.')) return super(LeaveReport, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)
def action_grant_badge(self): """Wizard action for sending a badge to a chosen user""" BadgeUser = self.env['gamification.badge.user'] uid = self.env.uid for wiz in self: if uid == wiz.user_id.id: raise exceptions.UserError(_('You can not grant a badge to yourself.')) #create the badge BadgeUser.create({ 'user_id': wiz.user_id.id, 'sender_id': uid, 'badge_id': wiz.badge_id.id, 'comment': wiz.comment, })._send_badge() return True
def write(self, vals): """Overwrite the write method to update the last_update field to today If the current value is changed and the report frequency is set to On change, a report is generated """ vals['last_update'] = fields.Date.today() result = super(Goal, self).write(vals) for goal in self: if goal.state != "draft" and ('definition_id' in vals or 'user_id' in vals): # avoid drag&drop in kanban view raise exceptions.UserError( _('Can not modify the configuration of a started goal')) if vals.get( 'current') and 'no_remind_goal' not in self.env.context: if goal.challenge_id.report_message_frequency == 'onchange': goal.challenge_id.sudo().report_progress( users=goal.user_id) return result
def _check_domain_validity(self): # take admin as should always be present for definition in self: if definition.computation_mode not in ('count', 'sum'): continue Obj = self.env[definition.model_id.model] try: domain = safe_eval( definition.domain, {'user': self.env.user.with_user(self.env.user)}) # dummy search to make sure the domain is valid Obj.search_count(domain) except (ValueError, SyntaxError) as e: msg = e if isinstance(e, SyntaxError): msg = (e.msg + '\n' + e.text) raise exceptions.UserError( _("The domain for the definition %s seems incorrect, please check it.\n\n%s" ) % (definition.name, msg)) return True
def _get_serialized_challenge_lines(self, user=(), restrict_goals=(), restrict_top=0): """Return a serialised version of the goals information if the user has not completed every goal :param user: user retrieving progress (False if no distinction, only for ranking challenges) :param restrict_goals: compute only the results for this subset of gamification.goal ids, if False retrieve every goal of current running challenge :param int restrict_top: for challenge lines where visibility_mode is ``ranking``, retrieve only the best ``restrict_top`` results and itself, if 0 retrieve all restrict_goal_ids has priority over restrict_top format list # if visibility_mode == 'ranking' { 'name': <gamification.goal.description name>, 'description': <gamification.goal.description description>, 'condition': <reach condition {lower,higher}>, 'computation_mode': <target computation {manually,count,sum,python}>, 'monetary': <{True,False}>, 'suffix': <value suffix>, 'action': <{True,False}>, 'display_mode': <{progress,boolean}>, 'target': <challenge line target>, 'own_goal_id': <gamification.goal id where user_id == uid>, 'goals': [ { 'id': <gamification.goal id>, 'rank': <user ranking>, 'user_id': <res.users id>, 'name': <res.users name>, 'state': <gamification.goal state {draft,inprogress,reached,failed,canceled}>, 'completeness': <percentage>, 'current': <current value>, } ] }, # if visibility_mode == 'personal' { 'id': <gamification.goal id>, 'name': <gamification.goal.description name>, 'description': <gamification.goal.description description>, 'condition': <reach condition {lower,higher}>, 'computation_mode': <target computation {manually,count,sum,python}>, 'monetary': <{True,False}>, 'suffix': <value suffix>, 'action': <{True,False}>, 'display_mode': <{progress,boolean}>, 'target': <challenge line target>, 'state': <gamification.goal state {draft,inprogress,reached,failed,canceled}>, 'completeness': <percentage>, 'current': <current value>, } """ Goals = self.env['gamification.goal'] (start_date, end_date) = start_end_date_for_period(self.period) res_lines = [] for line in self.line_ids: line_data = { 'name': line.definition_id.name, 'description': line.definition_id.description, 'condition': line.definition_id.condition, 'computation_mode': line.definition_id.computation_mode, 'monetary': line.definition_id.monetary, 'suffix': line.definition_id.suffix, 'action': True if line.definition_id.action_id else False, 'display_mode': line.definition_id.display_mode, 'target': line.target_goal, } domain = [ ('line_id', '=', line.id), ('state', '!=', 'draft'), ] if restrict_goals: domain.append(('ids', 'in', restrict_goals.ids)) else: # if no subset goals, use the dates for restriction if start_date: domain.append(('start_date', '=', start_date)) if end_date: domain.append(('end_date', '=', end_date)) if self.visibility_mode == 'personal': if not user: raise exceptions.UserError( _("Retrieving progress for personal challenge without user information" )) domain.append(('user_id', '=', user.id)) goal = Goals.search(domain, limit=1) if not goal: continue if goal.state != 'reached': return [] line_data.update( goal.read(['id', 'current', 'completeness', 'state'])[0]) res_lines.append(line_data) continue line_data['own_goal_id'] = False, line_data['goals'] = [] if line.condition == 'higher': goals = Goals.search(domain, order="completeness desc, current desc") else: goals = Goals.search(domain, order="completeness desc, current asc") if not goals: continue for ranking, goal in enumerate(goals): if user and goal.user_id == user: line_data['own_goal_id'] = goal.id elif restrict_top and ranking > restrict_top: # not own goal and too low to be in top continue line_data['goals'].append({ 'id': goal.id, 'user_id': goal.user_id.id, 'name': goal.user_id.name, 'rank': ranking, 'current': goal.current, 'completeness': goal.completeness, 'state': goal.state, }) if len(goals) < 3: # display at least the top 3 in the results missing = 3 - len(goals) for ranking, mock_goal in enumerate([{ 'id': False, 'user_id': False, 'name': '', 'current': 0, 'completeness': 0, 'state': False }] * missing, start=len(goals)): mock_goal['rank'] = ranking line_data['goals'].append(mock_goal) res_lines.append(line_data) return res_lines
def _check_capacity(self): if any(workcenter.capacity <= 0.0 for workcenter in self): raise exceptions.UserError( _('The capacity must be strictly positive.'))
def copy(self): raise exceptions.UserError(_('You cannot duplicate an attendance.'))