def get_report_values(self, docids, data=None): if not data.get('form'): raise UserError( _("Form content is missing, this report cannot be printed.")) return { 'data': data['form'], 'lines': self.get_lines(data.get('form')), }
def action_cancel(self): group_id = self.sudo().env.ref('purchase.group_purchase_manager') if self._uid != self.create_uid.id \ and self._uid not in group_id.users.ids: raise Warning( _("Can't cancel purchase indent which is \ requested by %s!") % (self.create_uid.name)) self.state = 'cancel'
def unlink(self): for indent_id in self: if indent_id.state not in ['draft', 'cancel']: raise Warning( _("Invalid Action!\n You cannot delete a \ Purchase Indent which is not in 'Draft' or 'Cancel' State!")) indent_id.indent_line.unlink() return super(PurchaseIndent, self).unlink()
def action_confirm_request(self): self.ensure_one() if not self.rma_line: raise UserError(_('You must select rma lines!')) if not self.is_website: for line in self.rma_line: line._onchange_qty_return() self.state = 'confirmed'
def button_cancel(self): if any('done' in event.mapped('registration_ids.state') for event in self): raise UserError( _("There are already attendees who attended this event. Please reset it to draft if you want to cancel this event." )) self.registration_ids.write({'state': 'cancel'}) self.state = 'cancel'
def _create_welcome_message(self): self.ensure_one() if not self.has_group('base.group_user'): return False company_name = self.company_id.name if self.company_id else '' body = _('%s has joined the %s network.') % (self.name, company_name) # TODO change SUPERUSER_ID into user.id but catch errors return self.partner_id.sudo().message_post(body=body)
def partner_interested(self, comment=False): message = _('<p>I am interested by this lead.</p>') if comment: message += '<p>%s</p>' % comment for lead in self: lead.message_post(body=message, subtype="mail.mt_note") lead.sudo().convert_opportunity( lead.partner_id.id) # sudo required to convert partner data
def _default_content(self): return ''' <section class="s_text_block"> <div class="container"> <div class="row"> <div class="col-md-12 mb16 mt16"> <p class="o_default_snippet_text">''' + _( "Start writing here...") + '''</p>
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()
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 _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_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) for line_vals in filtered_st_lines: line_vals.pop('account_number', None) # Create the satement st_vals['line_ids'] = [[0, False, line] for line in filtered_st_lines] statement_ids.append(BankStatement.create(st_vals).id) if len(statement_ids) == 0: raise UserError(_('You have already 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_ids, notifications
def submit_expenses(self): if any(expense.state != 'draft' for expense in self): raise UserError(_("You cannot report twice the same line!")) if len(self.mapped('employee_id')) != 1: raise UserError( _("You cannot report expenses for different employees in the same report!" )) return { 'type': 'ir.actions.act_window', 'view_mode': 'form', 'res_model': 'hr.expense.sheet', 'target': 'current', 'context': { 'default_expense_line_ids': [line.id for line in self], 'default_employee_id': self[0].employee_id.id, 'default_name': self[0].name if len(self.ids) == 1 else '' } }
def create(self, vals): 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 for this picking type" )) return super(ProductionLot, self).create(vals)
def cancel(self): """ cancel one or more order.line, update order status and unlink existing cashmoves """ if self.user_has_groups("lunch.group_lunch_manager"): self.state = 'cancelled' self.cashmove.unlink() else: raise AccessError(_("Only your lunch manager cancels the orders."))
def _check_authorize_state(self): failed_tx = self.filtered( lambda tx: tx.state == 'authorized' and tx.acquirer_id. provider not in self.env['payment.acquirer']._get_feature_support( )['authorize']) if failed_tx: raise exceptions.ValidationError( _('The %s payment acquirers are not allowed to manual capture mode!' % failed_tx.mapped('acquirer_id.name')))
def _action_unfollow(self, partner): channel_info = self.channel_info('unsubscribe')[0] # must be computed before leaving the channel (access rights) result = self.write({'channel_partner_ids': [(3, partner.id)]}) self.env['bus.bus'].sendone((self._cr.dbname, 'res.partner', partner.id), channel_info) if not self.email_send: notification = _('<div class="o_mail_notification">left <a href="#" class="o_channel_redirect" data-oe-id="%s">#%s</a></div>') % (self.id, self.name,) # post 'channel left' message as root since the partner just unsubscribed from the channel self.sudo().message_post(body=notification, message_type="notification", subtype="mail.mt_comment", author_id=partner.id) return result
def _check_package(self): default_uom = self.product_id.uom_id pack = self.product_packaging qty = self.product_uom_qty q = default_uom._compute_quantity(pack.qty, self.product_uom) if qty and q and (qty % q): newqty = qty - (qty % q) + q return { 'warning': { 'title': _('Warning'), 'message': _("This product is packaged by %.2f %s. You should sell %.2f %s." ) % (pack.qty, default_uom.name, newqty, self.product_uom.name), }, } return {}
def _check_recursion_associate_member(self): level = 100 while self: self = self.associate_member if not level: raise ValidationError( _('Error ! You cannot create recursive associated members.' )) level -= 1
def cancel_repair(self): if not self._context.get('active_id'): return {'type': 'ir.actions.act_window_close'} repair = self.env['mrp.repair'].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'}
def _check_attribute_value_ids(self): for product in self: attributes = self.env['product.attribute'] for value in product.attribute_value_ids: if value.attribute_id in attributes: raise ValidationError(_('Error! It is not allowed to choose more than one value for a given attribute.')) if value.attribute_id.create_variant: attributes |= value.attribute_id return True
def _alias_check_contact(self, message, message_dict, alias): if alias.alias_contact == 'followers' and self.ids: author = self.env['res.partner'].browse(message_dict.get('author_id', False)) if not author or author not in self.channel_partner_ids: return { 'error_message': _('restricted to channel members'), } return True return super(Channel, self)._alias_check_contact(message, message_dict, alias)
def unlink(self): if self.env['mrp.production'].search( [('bom_id', 'in', self.ids), ('state', 'not in', ['done', 'cancel'])], limit=1): raise UserError( _('You can not delete a Bill of Material with running manufacturing orders.\nPlease close or cancel it first.' )) return super(MrpBom, self).unlink()
def _check_format(self): for lang in self: for pattern in lang._disallowed_datetime_patterns: if (lang.time_format and pattern in lang.time_format) or \ (lang.date_format and pattern in lang.date_format): raise ValidationError( _('Invalid date/time format directive specified. ' 'Please refer to the list of allowed directives, ' 'displayed when you edit a language.'))
def write(self, vals): if 'name' in vals: if vals['name'].startswith('-'): raise UserError(_('The name of the group can not start with "-"')) # invalidate caches before updating groups, since the recomputation of # field 'share' depends on method has_group() self.env['ir.model.access'].call_cache_clearing_methods() self.env['res.users'].has_group.clear_cache(self.env['res.users']) return super(Groups, self).write(vals)
def _check_main_currency_rounding(self): if any(precision.name == 'Account' and tools.float_compare( self.env.user.company_id.currency_id.rounding, 10**-precision.digits, precision_digits=6) == -1 for precision in self): raise ValidationError( _("You cannot define the decimal precision of 'Account' as greater than the rounding factor of the company's main currency" )) return True
def action_cancel(self): # try to set all associated quotations to cancel state for requisition in self: requisition.purchase_ids.button_cancel() for po in requisition.purchase_ids: po.message_post(body=_( 'Cancelled by the agreement associated to this quotation.') ) self.write({'state': 'cancel'})
def _check_company_branch(self): for record in self: if record.branch_id and record.company_id != record.branch_id.company_id: raise ValidationError( _('Configuration Error of Company:\n' 'The Company (%s) in the voucher and ' 'the Company (%s) of Branch must ' 'be the same company!') % (record.company_id.name, record.branch_id.company_id.name))
def _check_date(self): """ Prevents the user to create an order in the past """ date_order = datetime.datetime.strptime(self.date, '%Y-%m-%d') date_today = datetime.datetime.strptime( fields.Date.context_today(self), '%Y-%m-%d') if (date_order < date_today): raise ValidationError(_('The date of your order is in the past.'))
def unlink(self): MailAlias = self.env['mail.alias'] for category in self: if category.equipment_ids or category.maintenance_ids: raise UserError(_("You cannot delete an equipment category containing equipments or maintenance requests.")) MailAlias += category.alias_id res = super(MaintenanceEquipmentCategory, self).unlink() MailAlias.unlink() return res
def order(self): """ The order_line is ordered to the vendor but isn't received yet """ if self.user_has_groups("lunch.group_lunch_manager"): self.state = 'ordered' else: raise AccessError( _("Only your lunch manager processes the orders."))