Beispiel #1
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 #2
0
 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
        """
        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 #4
0
 def unlink(self):
     for inspection in self:
         if inspection.auto_generated:
             raise exceptions.UserError(
                 _("You cannot remove an auto-generated inspection."))
         if inspection.state != 'draft':
             raise exceptions.UserError(
                 _("You cannot remove an inspection that is not in draft "
                   "state."))
     return super(QcInspection, self).unlink()
Beispiel #5
0
    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)))

        record = self.env[self.mailing_id.mailing_model_real].search([],
                                                                     limit=1)
        body = self.mailing_id.body_plaintext
        if record:
            # Returns a proper error if there is a syntax error with jinja
            body = self.env['mail.render.mixin']._render_template(
                body, self.mailing_id.mailing_model_real,
                record.ids)[record.id]

        self.env['sms.api']._send_sms_batch([{
            'res_id': 0,
            'number': number,
            'content': body,
        } for number in sanitized_numbers])
        return True
Beispiel #6
0
 def _ir_mail_server_connect(model, *args, **kwargs):
     if sim_error and sim_error == 'connect_smtp_notfound':
         raise exceptions.UserError(
             "Missing SMTP Server\nPlease define at least one SMTP server, or provide the SMTP parameters explicitly.")
     if sim_error and sim_error == 'connect_failure':
         raise Exception("Some exception")
     return None
Beispiel #7
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
 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 #9
0
 def _get_manufacture_route_id(self):
     manufacture_route = self.env.ref('mrp.route_warehouse0_manufacture', raise_if_not_found=False)
     if not manufacture_route:
         manufacture_route = self.env['stock.location.route'].search([('name', 'like', _('Manufacture'))], limit=1)
     if not manufacture_route:
         raise exceptions.UserError(_('Can\'t find any generic Manufacture route.'))
     return manufacture_route.id
Beispiel #10
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 #11
0
 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)
Beispiel #12
0
 def action_confirm(self):
     for inspection in self:
         for line in inspection.inspection_lines:
             if line.question_type == 'qualitative':
                 if not line.qualitative_value:
                     raise exceptions.UserError(
                         _("You should provide an answer for all "
                           "qualitative questions."))
             else:
                 if not line.uom_id:
                     raise exceptions.UserError(
                         _("You should provide a unit of measure for "
                           "quantitative questions."))
         if inspection.success:
             inspection.state = 'success'
         else:
             inspection.state = 'waiting'
Beispiel #13
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 #14
0
 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')
Beispiel #15
0
 def _purchase_request_line_check(self):
     for po in self:
         for line in po.order_line:
             for request_line in line.purchase_request_lines:
                 if request_line.sudo().purchase_state == 'done':
                     raise exceptions.UserError(
                         _('Purchase Request %s has already '
                           'been completed') % request_line.request_id.name)
     return True
Beispiel #16
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 #17
0
 def _check_recursion(self):
     ids = self.ids
     level = 100
     while ids:
         parents = self.search([('id', 'in', ids),
                                ('parent_id', '!=', False)])
         ids = list(set([x.parent_id.id for x in parents]))
         if not level:
             raise exceptions.UserError(
                 _('Error! You can not create recursive categories.'))
         level -= 1
Beispiel #18
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 #19
0
    def payment_token_json(self, order_id, pm_id=None, **kwargs):
        order = request.env['sale.order'].sudo().browse(order_id)
        if not order or not order.order_line or pm_id is None:
            raise exceptions.UserError(_('Nothing to pay/no token selected'))

        # try to convert pm_id into an integer, if it doesn't work redirect the user to the quote
        try:
            pm_id = int(pm_id)
        except ValueError:
            raise exceptions.UserError(_('Faulty token value'))

        # retrieve the token from its id
        token = request.env['payment.token'].sudo().browse(pm_id)
        if not token:
            raise exceptions.UserError(_('Cannot find token'))

        # find an already existing transaction
        tx = request.env['payment.transaction'].sudo().search(
            [('reference', '=', order.name)], limit=1)
        # set the transaction type to server2server
        tx_type = 'server2server'
        # check if the transaction exists, if not then it create one
        tx = tx._check_or_create_sale_tx(order,
                                         token.acquirer_id,
                                         payment_token=token,
                                         tx_type=tx_type)
        # set the transaction id into the session
        request.session['quote_%s_transaction_id' % order_id] = tx.id
        # proceed to try the payment
        tx.with_context(off_session=False).confirm_sale_token()
        # send result in json
        tx_info = tx._get_json_info()
        return {
            'tx_info': tx_info,
            'redirect': '/quote/%s/%s' % (order_id, order.access_token),
        }
Beispiel #20
0
    def _open_connection(self, raise_on_error=False):
        self.ensure_one()
        connection = False
        try:
            connection = cups.Connection(host=self.address, port=self.port)
        except:
            message = _("Failed to connect to the CUPS server on %s:%s. "
                        "Check that the CUPS server is running and that "
                        "you can reach it from the flectra server.") % (
                            self.address, self.port)
            _logger.warning(message)
            if raise_on_error:
                raise exceptions.UserError(message)

        return connection
Beispiel #21
0
    def print_label(self, printer, record, page_count=1, **extra):
        for label in self:
            if record._name != label.model_id.model:
                raise exceptions.UserError(
                    _('This label cannot be used on {model}').format(
                        model=record._name))

            # Send the label to printer
            label_contents = label._generate_zpl2_data(record,
                                                       page_count=page_count,
                                                       **extra)
            printer.print_document(report=None,
                                   content=label_contents,
                                   doc_format='raw')

        return True
Beispiel #22
0
 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(HrEmployee, self).read_group(domain,
                                               fields,
                                               groupby,
                                               offset=offset,
                                               limit=limit,
                                               orderby=orderby,
                                               lazy=lazy)
Beispiel #23
0
 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)
Beispiel #24
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 #25
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 #26
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
    def test_ignore_exceptions(self):
        config = {
            'sentry_enabled': True,
            'sentry_dsn': 'http://*****:*****@example.com/1',
            'sentry_ignore_exceptions': 'flectra.exceptions.UserError',
        }
        level, msg = logging.WARNING, 'Test UserError'
        client = initialize_raven(config, client_cls=InMemoryClient)

        handlers = list(
            log_handler_by_class(logging.getLogger(), FlectraSentryHandler))
        self.assertTrue(handlers)
        handler = handlers[0]
        try:
            raise exceptions.UserError(msg)
        except exceptions.UserError:
            exc_info = sys.exc_info()
        record = logging.LogRecord(__name__, level, __file__, 42, msg, (),
                                   exc_info)
        handler.emit(record)
        self.assertEventNotCaptured(client, level, msg)
Beispiel #28
0
 def copy(self):
     raise exceptions.UserError(_('You cannot duplicate an attendance.'))
Beispiel #29
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
Beispiel #30
0
 def _check_capacity(self):
     if any(workcenter.capacity <= 0.0 for workcenter in self):
         raise exceptions.UserError(_('The capacity must be strictly positive.'))