Beispiel #1
0
    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
        """
        if len(self) > 1:
            raise exceptions.UserError(
                _('Cannot perform check in or check out on multiple employees.'
                  ))
        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)
        else:
            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.name,
                      })
            return attendance
Beispiel #2
0
    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
Beispiel #3
0
 def _get_manufacture_route_id(self):
     manufacture_route_id = self.env.ref('mrp.route_warehouse0_manufacture').id
     if not manufacture_route_id:
         manufacture_route_id = self.env['stock.location.route'].search([('name', 'like', _('Manufacture'))], limit=1).id
     if not manufacture_route_id:
         raise exceptions.UserError(_('Can\'t find any generic Manufacture route.'))
     return manufacture_route_id
Beispiel #4
0
 def unblock(self):
     self.ensure_one()
     if self.working_state != 'blocked':
         raise exceptions.UserError(_("It has been unblocked already. "))
     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'}
Beispiel #5
0
    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
Beispiel #6
0
    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))
Beispiel #7
0
 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
Beispiel #8
0
 def _action_cancel(self):
     if any(move.quantity_done and (
             move.raw_material_production_id or move.production_id)
            for move in self):
         raise exceptions.UserError(
             _('You cannot cancel a manufacturing order if you have already consumed material.\
          If you want to cancel this MO, please change the consumed quantities to 0.'
               ))
     return super(StockMove, self)._action_cancel()
Beispiel #9
0
 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, pycompat.string_types)]:
         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)
Beispiel #10
0
    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
Beispiel #11
0
    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.sudo(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
Beispiel #12
0
    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
Beispiel #13
0
 def copy(self):
     raise exceptions.UserError(_('You cannot duplicate an attendance.'))
Beispiel #14
0
 def _check_capacity(self):
     if any(workcenter.capacity <= 0.0 for workcenter in self):
         raise exceptions.UserError(_('The capacity must be strictly positive.'))
Beispiel #15
0
    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")
            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 goals:
                res_lines.append(line_data)
        return res_lines