def action_grant_badge(self):
        """Wizard action for sending a badge to a chosen employee"""
        if not self.user_id:
            raise UserError(
                _('You can send badges only to employees linked to a user.'))

        if self.env.uid == self.user_id.id:
            raise UserError(_('You can not send a badge to yourself.'))

        values = {
            'user_id': self.user_id.id,
            'sender_id': self.env.uid,
            'badge_id': self.badge_id.id,
            'employee_id': self.employee_id.id,
            'comment': self.comment,
        }

        return self.env['gamification.badge.user'].create(values)._send_badge()
예제 #2
0
 def reset_expense_sheets(self):
     if not self.can_reset:
         raise UserError(
             _("Only HR Officers or the concerned employee can reset to draft."
               ))
     self.mapped('expense_line_ids').write({'is_refused': False})
     self.write({'state': 'draft'})
     self.activity_update()
     return True
예제 #3
0
 def create(self, vals_list):
     active_picking_id = self.env.context.get('active_picking_id', False)
     if active_picking_id:
         picking_id = self.env['stock.picking'].browse(active_picking_id)
         if picking_id and not picking_id.picking_type_id.use_create_lots:
             raise UserError(
                 _('You are not allowed to create a lot or serial number with this operation type. To change this, go on the operation type and tick the box "Create New Lots/Serial Numbers".'
                   ))
     return super(ProductionLot, self).create(vals_list)
예제 #4
0
 def _check_create(self):
     active_mo_id = self.env.context.get('active_mo_id')
     if active_mo_id:
         active_mo = self.env['mrp.production'].browse(active_mo_id)
         if not active_mo.picking_type_id.use_create_components_lots:
             raise UserError(
                 _('You are not allowed to create or edit a lot or serial number for the components with the operation type "Manufacturing". To change this, go on the operation type and tick the box "Create New Lots/Serial Numbers for Components".'
                   ))
     return super(StockProductionLot, self)._check_create()
예제 #5
0
 def cancel_repair(self):
     if not self._context.get('active_id'):
         return {'type': 'ir.actions.act_window_close'}
     repair = self.env['repair.order'].browse(self._context['active_id'])
     if repair.invoiced or repair.invoice_method == 'none':
         repair.action_cancel()
     else:
         raise UserError(_('Repair order is not invoiced.'))
     return {'type': 'ir.actions.act_window_close'}
예제 #6
0
 def _get_production_location(self):
     location = self.env.ref('stock.location_production',
                             raise_if_not_found=False)
     if not location:
         location = self.env['stock.location'].search(
             [('usage', '=', 'production')], limit=1)
     if not location:
         raise UserError(_('Can\'t find any production location.'))
     return location
예제 #7
0
 def do_signup(self, qcontext):
     """ Shared helper that creates a res.partner out of a token """
     values = {
         key: qcontext.get(key)
         for key in ('login', 'name', 'password')
     }
     if not values:
         raise UserError(_("The form was not properly filled in."))
     if values.get('password') != qcontext.get('confirm_password'):
         raise UserError(_("Passwords do not match; please retype them."))
     supported_lang_codes = [
         code for code, _ in request.env['res.lang'].get_installed()
     ]
     lang = request.context.get('lang', '').split('_')[0]
     if lang in supported_lang_codes:
         values['lang'] = lang
     self._signup_with_values(qcontext.get('token'), values)
     request.env.cr.commit()
예제 #8
0
 def restart_db_template(self):
     for obj in self:
         host_server, db_server = obj.server_id.get_server_details()
         response_flag = containers.action(operation="restart",
                                           container_id=obj.container_id,
                                           host_server=host_server,
                                           db_server=db_server)
         if not response_flag:
             raise UserError("Operation Failed! Unknown Error!")
예제 #9
0
 def write(self, vals):
     res = super(PurchaseRequisitionLine, self).write(vals)
     if 'price_unit' in vals:
         if vals['price_unit'] <= 0.0:
             raise UserError(
                 _('You cannot confirm the blanket order without price.'))
         # If the price is updated, we have to update the related SupplierInfo
         self.supplier_info_ids.write({'price': vals['price_unit']})
     return res
 def unlink(self):
     for record in self:
         if record.move_check:
             if record.asset_id.category_id.type == 'purchase':
                 msg = _("You cannot delete posted depreciation lines.")
             else:
                 msg = _("You cannot delete posted installment lines.")
             raise UserError(msg)
     return super(AccountAssetDepreciationLine, self).unlink()
예제 #11
0
 def unlink(self):
     for statement in self:
         if statement.state != 'open':
             raise UserError(
                 _('In order to delete a bank statement, you must first cancel it to delete related journal items.'
                   ))
         # Explicitly unlink bank statement lines so it will check that the related journal entries have been deleted first
         statement.line_ids.unlink()
     return super(AccountBankStatement, self).unlink()
 def action_create_invoice(self):
     if not self.sale_order_id and self.sale_order_id.invoice_status != 'to invoice':
         raise UserError(
             _("The selected Sales Order should contain something to invoice."
               ))
     action = self.env.ref(
         'sale.action_view_sale_advance_payment_inv').read()[0]
     action['context'] = {'active_ids': self.sale_order_id.ids}
     return action
예제 #13
0
 def view_init(self, fields):
     """ Check some preconditions before the wizard executes. """
     for lead in self.env['crm.lead'].browse(
             self._context.get('active_ids', [])):
         if lead.probability == 100:
             raise UserError(
                 _("Closed/Dead leads cannot be converted into opportunities."
                   ))
     return False
예제 #14
0
 def _compute_ressource_id(self):
     result = {}
     for record in self:
         word = self._get_key_from_url(record.google_drive_template_url)
         if word:
             record.google_drive_resource_id = word
         else:
             raise UserError(_("Please enter a valid Google Document URL."))
     return result
예제 #15
0
    def action_set_viewed(self, quiz_attempts_inc=False):
        if not all(slide.channel_id.is_member for slide in self):
            raise UserError(
                _('You cannot mark a slide as viewed if you are not among its members.'
                  ))

        return bool(
            self._action_set_viewed(self.env.user.partner_id,
                                    quiz_attempts_inc=quiz_attempts_inc))
예제 #16
0
 def unlink(self):
     for pav in self:
         if pav.is_used_on_products:
             raise UserError(
                 _("You cannot delete the value %s because it is used on the following products:\n%s"
                   ) % (pav.display_name, ", ".join(
                       pav.pav_attribute_line_ids.product_tmpl_id.mapped(
                           'display_name'))))
     return super(ProductAttributeValue, self).unlink()
예제 #17
0
 def _check_if_no_draft_orders(self):
     draft_orders = self.order_ids.filtered(lambda order: order.state == 'draft')
     if draft_orders:
         raise UserError(_(
                 'There are still orders in draft state in the session. '
                 'Pay or cancel the following orders to validate the session:\n%s'
             ) % ', '.join(draft_orders.mapped('name'))
         )
     return True
예제 #18
0
    def _find_additional_data(self, currency_code, account_number):
        """ Look for a res.currency and account.journal using values extracted from the
            statement and make sure it's consistent.
        """
        company_currency = self.env.user.company_id.currency_id
        journal_obj = self.env['account.journal']
        currency = None
        sanitized_account_number = sanitize_account_number(account_number)

        if currency_code:
            currency = self.env['res.currency'].search([('name', '=ilike', currency_code)], limit=1)
            if not currency:
                raise UserError(_("No currency found matching '%s'.") % currency_code)
            if currency == company_currency:
                currency = False

        journal = journal_obj.browse(self.env.context.get('journal_id', []))
        if account_number:
            # No bank account on the journal : create one from the account number of the statement
            if journal and not journal.bank_account_id:
                journal.set_bank_account(account_number)
            # No journal passed to the wizard : try to find one using the account number of the statement
            elif not journal:
                journal = journal_obj.search([('bank_account_id.sanitized_acc_number', '=', sanitized_account_number)])
            # Already a bank account on the journal : check it's the same as on the statement
            else:
                if not self._check_journal_bank_account(journal, sanitized_account_number):
                    raise UserError(_('The account of this statement (%s) is not the same as the journal (%s).') % (account_number, journal.bank_account_id.acc_number))

        # If importing into an existing journal, its currency must be the same as the bank statement
        if journal:
            journal_currency = journal.currency_id
            if currency is None:
                currency = journal_currency
            if currency and currency != journal_currency:
                statement_cur_code = not currency and company_currency.name or currency.name
                journal_cur_code = not journal_currency and company_currency.name or journal_currency.name
                raise UserError(_('The currency of the bank statement (%s) is not the same as the currency of the journal (%s).') % (statement_cur_code, journal_cur_code))

        # If we couldn't find / can't create a journal, everything is lost
        if not journal and not account_number:
            raise UserError(_('Cannot find in which journal import this statement. Please manually select a journal.'))

        return currency, journal
예제 #19
0
    def action_create_sale_order(self):
        # if project linked to SO line or at least on tasks with SO line, then we consider project as billable.
        if self.project_id.sale_line_id:
            raise UserError(
                _("The project is already linked to a sales order item."))

        if self.billable_type == 'employee_rate':
            # at least one line
            if not self.line_ids:
                raise UserError(_("At least one line should be filled."))

            # all employee having timesheet should be in the wizard map
            timesheet_employees = self.env['account.analytic.line'].search([
                ('task_id', 'in', self.project_id.tasks.ids)
            ]).mapped('employee_id')
            map_employees = self.line_ids.mapped('employee_id')
            missing_meployees = timesheet_employees - map_employees
            if missing_meployees:
                raise UserError(
                    _('The Sales Order cannot be created because you did not enter some employees that entered timesheets on this project. Please list all the relevant employees before creating the Sales Order.\nMissing employee(s): %s'
                      ) % (', '.join(missing_meployees.mapped('name'))))

        # check here if timesheet already linked to SO line
        timesheet_with_so_line = self.env[
            'account.analytic.line'].search_count([('task_id', 'in',
                                                    self.project_id.tasks.ids),
                                                   ('so_line', '!=', False)])
        if timesheet_with_so_line:
            raise UserError(
                _('The sales order cannot be created because some timesheets of this project are already linked to another sales order.'
                  ))

        # create SO according to the chosen billable type
        sale_order = self._create_sale_order()

        view_form_id = self.env.ref('sale.view_order_form').id
        action = self.env.ref('sale.action_orders').read()[0]
        action.update({
            'views': [(view_form_id, 'form')],
            'view_mode': 'form',
            'name': sale_order.name,
            'res_id': sale_order.id,
        })
        return action
예제 #20
0
    def _create_bank_statements(self, stmts_vals):
        """ Create new bank statements from imported values, filtering out already imported transactions, and returns data used by the reconciliation widget """
        BankStatement = self.env['account.bank.statement']
        BankStatementLine = self.env['account.bank.statement.line']

        # Filter out already imported transactions and create statements
        statement_line_ids = []
        ignored_statement_lines_import_ids = []
        for st_vals in stmts_vals:
            filtered_st_lines = []
            for line_vals in st_vals['transactions']:
                if 'unique_import_id' not in line_vals \
                   or not line_vals['unique_import_id'] \
                   or not bool(BankStatementLine.sudo().search([('unique_import_id', '=', line_vals['unique_import_id'])], limit=1)):
                    filtered_st_lines.append(line_vals)
                else:
                    ignored_statement_lines_import_ids.append(
                        line_vals['unique_import_id'])
                    if 'balance_start' in st_vals:
                        st_vals['balance_start'] += float(line_vals['amount'])

            if len(filtered_st_lines) > 0:
                # Remove values that won't be used to create records
                st_vals.pop('transactions', None)
                # Create the statement
                st_vals['line_ids'] = [[0, False, line]
                                       for line in filtered_st_lines]
                statement_line_ids.extend(
                    BankStatement.create(st_vals).line_ids.ids)
        if len(statement_line_ids) == 0:
            raise UserError(_('You already have imported that file.'))

        # Prepare import feedback
        notifications = []
        num_ignored = len(ignored_statement_lines_import_ids)
        if num_ignored > 0:
            notifications += [{
                'type':
                'warning',
                'message':
                _("%d transactions had already been imported and were ignored."
                  ) % num_ignored if num_ignored > 1 else
                _("1 transaction had already been imported and was ignored."),
                'details': {
                    'name':
                    _('Already imported items'),
                    'model':
                    'account.bank.statement.line',
                    'ids':
                    BankStatementLine.search([
                        ('unique_import_id', 'in',
                         ignored_statement_lines_import_ids)
                    ]).ids
                }
            }]
        return statement_line_ids, notifications
예제 #21
0
    def action_validate(self):
        current_employee = self.env['hr.employee'].search(
            [('user_id', '=', self.env.uid)], limit=1)
        if any(holiday.state not in ['confirm', 'validate1']
               for holiday in self):
            raise UserError(
                _('Leave request must be confirmed in order to approve it.'))

        self.write({'state': 'validate'})
        self.filtered(lambda holiday: holiday.validation_type == 'both').write(
            {'second_approver_id': current_employee.id})
        self.filtered(lambda holiday: holiday.validation_type != 'both').write(
            {'first_approver_id': current_employee.id})

        for holiday in self.filtered(
                lambda holiday: holiday.holiday_type != 'employee'):
            if holiday.holiday_type == 'category':
                employees = holiday.category_id.employee_ids
            elif holiday.holiday_type == 'company':
                employees = self.env['hr.employee'].search([
                    ('company_id', '=', holiday.mode_company_id.id)
                ])
            else:
                employees = holiday.department_id.member_ids

            if self.env['hr.leave'].search_count([
                ('date_from', '<=', holiday.date_to),
                ('date_to', '>', holiday.date_from),
                ('state', 'not in', ['cancel', 'refuse']),
                ('holiday_type', '=', 'employee'),
                ('employee_id', 'in', employees.ids)
            ]):
                raise ValidationError(
                    _('You can not have 2 leaves that overlaps on the same day.'
                      ))

            values = [
                holiday._prepare_holiday_values(employee)
                for employee in employees
            ]
            leaves = self.env['hr.leave'].with_context(
                tracking_disable=True,
                mail_activity_automation_skip=True,
                leave_fast_create=True,
            ).create(values)
            leaves.action_approve()
            # FIXME RLi: This does not make sense, only the parent should be in validation_type both
            if leaves and leaves[0].validation_type == 'both':
                leaves.action_validate()

        employee_requests = self.filtered(
            lambda hol: hol.holiday_type == 'employee')
        employee_requests._validate_leave_request()
        if not self.env.context.get('leave_fast_create'):
            employee_requests.activity_update()
        return True
예제 #22
0
 def write(self, vals):
     if "tax_ids" in vals:
         if self.env["pos.order"].sudo().search_count([("fiscal_position_id", "in", self.ids)]):
             raise UserError(
                 _(
                     "You cannot modify a fiscal position used in a POS order. "
                     + "You should archive it and create a new one."
                 )
             )
     return super(AccountFiscalPosition, self).write(vals)
예제 #23
0
 def confirm_exam(self):
     if len(self.subject_line) < 1:
         raise UserError(_('Please Add Subjects'))
     name = str(self.exam_type.name) + '-' + str(self.start_date)[0:10]
     if self.division_id:
         name = name + ' (' + str(self.division_id.name) + ')'
     elif self.class_id:
         name = name + ' (' + str(self.class_id.name) + ')'
     self.generated_name = name
     self.state = 'ongoing'
 def _print_report(self, data):
     data = self.pre_print_report(data)
     data['form'].update(self.read(['initial_balance', 'sortby'])[0])
     if data['form'].get(
             'initial_balance') and not data['form'].get('date_from'):
         raise UserError(_("You must define a Start Date"))
     records = self.env[data['model']].browse(data.get('ids', []))
     return self.env.ref(
         'accounting_pdf_reports.action_report_general_ledger'
     ).with_context(landscape=True).report_action(records, data=data)
예제 #25
0
    def default_get(self, fields):
        rec = super(account_register_payments, self).default_get(fields)
        active_ids = self._context.get('active_ids')

        if not active_ids:
            raise UserError(
                _("Programming error: wizard action executed without active_ids in context."
                  ))

        return rec
예제 #26
0
 def create(self, vals):
     # restrict the operation in case we are trying to set a forbidden field
     if self.company_id._is_accounting_unalterable():
         if vals.get('update_posted'):
             field_string = self._fields['update_posted'].get_description(
                 self.env)['string']
             raise UserError(
                 _("According to the French law, you cannot modify a journal in order for its posted data to be updated or deleted. Unauthorized field: %s."
                   ) % field_string)
     return super(AccountJournal, self).create(vals)
예제 #27
0
 def write(self, vals):
     if 'active' in vals and not vals.get('active'):
         template_id = self.env['ir.default'].get('sale.order',
                                                  'sale_order_template_id')
         for template in self:
             if template_id and template_id == template.id:
                 raise UserError(
                     'Before archiving "%s" please select another default template in the settings.'
                     % template.name)
     return super(SaleOrderTemplate, self).write(vals)
예제 #28
0
    def _check_parsed_data(self, stmts_vals, account_number):
        """ Basic and structural verifications """
        extra_msg = _(
            'If it contains transactions for more than one account, it must be imported on each of them.'
        )
        if len(stmts_vals) == 0:
            raise UserError(
                _('This file doesn\'t contain any statement for account %s.') %
                (account_number, ) + '\n' + extra_msg)

        no_st_line = True
        for vals in stmts_vals:
            if vals['transactions'] and len(vals['transactions']) > 0:
                no_st_line = False
                break
        if no_st_line:
            raise UserError(
                _('This file doesn\'t contain any transaction for account %s.')
                % (account_number, ) + '\n' + extra_msg)
예제 #29
0
    def _check_leave_type_validity(self):
        for allocation in self:
            if allocation.holiday_status_id.validity_start and allocation.holiday_status_id.validity_stop:
                vstart = allocation.holiday_status_id.validity_start
                vstop = allocation.holiday_status_id.validity_stop
                today = fields.Date.today()

                if vstart > today or vstop < today:
                    raise UserError(_('You can allocate %s only between %s and %s') % (allocation.holiday_status_id.display_name,
                                                                                  allocation.holiday_status_id.validity_start, allocation.holiday_status_id.validity_stop))
    def _get_pos_mercury_config_id(self, config, payment_method_id):
        payment_method = config.current_session_id.payment_method_ids.filtered(
            lambda pm: pm.id == payment_method_id)

        if payment_method and payment_method.pos_mercury_config_id:
            return payment_method.pos_mercury_config_id
        else:
            raise UserError(
                _("No Vantiv configuration associated with the payment method."
                  ))