def _do_payment(self): if self.payment_token_id.acquirer_id.capture_manually: raise ValidationError( _('This feature is not available for payment acquirers set to the "Authorize" mode.\n' 'Please use a token from another provider than %s.') % self.payment_token_id.acquirer_id.name) reference = "P-%s-%s" % ( self.id, datetime.datetime.now().strftime('%y%m%d_%H%M%S')) tx = self.env['payment.transaction'].create({ 'amount': self.amount, 'acquirer_id': self.payment_token_id.acquirer_id.id, 'type': 'server2server', 'currency_id': self.currency_id.id, 'reference': reference, 'payment_token_id': self.payment_token_id.id, 'partner_id': self.partner_id.id, 'partner_country_id': self.partner_id.country_id.id, }) s2s_result = tx.s2s_do_transaction() if not s2s_result or tx.state != 'done': raise ValidationError( _("Payment transaction failed (%s)") % tx.state_message) self.payment_transaction_id = tx
def validate_iban(iban): iban = normalize_iban(iban) if not iban: raise ValidationError(_("No IBAN !")) country_code = iban[:2].lower() if country_code not in _map_iban_template: raise ValidationError( _("The IBAN is invalid, it should begin with the country code")) iban_template = _map_iban_template[country_code] if len(iban) != len(iban_template.replace(' ', '')): raise ValidationError( _("The IBAN does not seem to be correct. You should have entered something like this %s\n" "Where B = National bank code, S = Branch code, C = Account No, k = Check digit" ) % iban_template) check_chars = iban[4:] + iban[:4] digits = int(''.join( str(int(char, 36)) for char in check_chars)) # BASE 36: 0..9,A..Z -> 0..35 if digits % 97 != 1: raise ValidationError( _("This IBAN does not pass the validation check, please verify it." ))
def set(self, model_name, field_name, value, user_id=False, company_id=False, condition=False): """ Defines a default value for the given field. Any entry for the same scope (field, user, company) will be replaced. The value is encoded in JSON to be stored to the database. :param user_id: may be ``False`` for all users, ``True`` for the current user, or any user id :param company_id: may be ``False`` for all companies, ``True`` for the current user's company, or any company id :param condition: optional condition that restricts the applicability of the default value; this is an opaque string, but the client typically uses single-field conditions in the form ``'key=val'``. """ if user_id is True: user_id = self.env.uid if company_id is True: company_id = self.env.user.company_id.id # check consistency of model_name, field_name, and value try: model = self.env[model_name] field = model._fields[field_name] field.convert_to_cache(value, model) json_value = json.dumps(value, ensure_ascii=False) except KeyError: raise ValidationError( _("Invalid field %s.%s") % (model_name, field_name)) except Exception: raise ValidationError( _("Invalid value for %s.%s: %s") % (model_name, field_name, value)) # update existing default for the same scope, or create one field = self.env['ir.model.fields']._get(model_name, field_name) default = self.search([ ('field_id', '=', field.id), ('user_id', '=', user_id), ('company_id', '=', company_id), ('condition', '=', condition), ]) if default: default.write({'json_value': json_value}) else: self.create({ 'field_id': field.id, 'user_id': user_id, 'company_id': company_id, 'condition': condition, 'json_value': json_value, }) return True
def _check_model(self): for action in self: if action.res_model not in self.env: raise ValidationError( _('Invalid model name %r in action definition.') % action.res_model) if action.src_model and action.src_model not in self.env: raise ValidationError( _('Invalid model name %r in action definition.') % action.src_model)
def _check_gstin_format(self): for res in self: if res.state_id and res.vat and res.state_id.l10n_in_tin != \ res.vat[:2]: raise ValidationError(_('Invalid State Code!')) if res.vat and len(res.vat) != 15 and res.gst_type != \ 'unregistered': raise ValidationError( _('GSTIN length must be of 15 ' 'characters!'))
def check_dates(self): if self.sprint_id: start_date = self.sprint_id.start_date end_date = self.sprint_id.end_date if self.start_date and start_date and (self.start_date < start_date): raise ValidationError( "Start date is not valid according to the Sprint.") if self.end_date and end_date and (self.end_date > end_date): raise ValidationError( "End date is not valid according to the Sprint.")
def _check_grouping(self): warning = _( 'The Separator Format should be like [,n] where 0 < n :starting from Unit digit. ' '-1 will end the separation. e.g. [3,2,-1] will represent 106500 to be 1,06,500;' '[1,2,-1] will represent it to be 106,50,0;[3] will represent it as 106,500. ' 'Provided as the thousand separator in each case.') for lang in self: try: if not all( isinstance(x, int) for x in json.loads(lang.grouping)): raise ValidationError(warning) except Exception: raise ValidationError(warning)
def check_complete_move(self, move, theorical_lines): for aml in move.line_ids: line = (aml.name, round(aml.debit, 2), round(aml.credit, 2)) if line in theorical_lines: theorical_lines.remove(line) else: raise ValidationError( 'Unexpected journal item. (label: %s, debit: %s, credit: %s)' % (aml.name, round(aml.debit, 2), round(aml.credit, 2))) if theorical_lines: raise ValidationError('Remaining theorical line (not found). %s)' % ([(aml[0], aml[1], aml[2]) for aml in theorical_lines])) return True
def _check_product_recursion(self): for bom in self: if bom.bom_line_ids.filtered(lambda x: x.product_id.product_tmpl_id == bom.product_tmpl_id): raise ValidationError( _('BoM line product %s should not be same as BoM product.') % bom.display_name)
def action_capture(self): if any(self.mapped(lambda tx: tx.state != 'authorized')): raise ValidationError( _('Only transactions in the Authorized status can be captured.' )) for tx in self: tx.s2s_capture_transaction()
def _check_communication(self, payment_method_id, communication): super(AccountPayment, self)._check_communication(payment_method_id, communication) if payment_method_id == self.env.ref('account_check_printing.account_payment_method_check').id: if not communication: return if len(communication) > 60: raise ValidationError(_("A check memo cannot exceed 60 characters."))
def check_vat(self): if self.env.context.get('company_id'): company = self.env['res.company'].browse( self.env.context['company_id']) else: company = self.env.user.company_id if company.vat_check_vies: # force full VIES online check check_func = self.vies_vat_check else: # quick and partial off-line checksum validation check_func = self.simple_vat_check for partner in self: if not partner.vat: continue #check with country code as prefix of the TIN vat_country, vat_number = self._split_vat(partner.vat) if not check_func(vat_country, vat_number): #if fails, check with country code from country country_code = partner.commercial_partner_id.country_id.code if country_code: if not check_func(country_code.lower(), partner.vat): msg = partner._construct_constraint_msg( country_code.lower()) raise ValidationError(msg)
def invoice_validate(self): """ Apply GST invoice type at the time of invoice validation. """ for invoice in self: partner_location = self.partner_id.partner_location if invoice.partner_id.vat: invoice.write({ 'vat': invoice.partner_id.vat, 'gst_type': invoice.partner_id.gst_type, 'gst_invoice': 'b2b' }) elif invoice.type == 'out_invoice' and partner_location: b2c_limit = self.env['res.company.b2c.limit'].search( [('date_from', '<=', invoice.date_invoice), ('date_to', '>=', invoice.date_invoice), ('company_id', '=', invoice.company_id.id)]) if not b2c_limit: raise ValidationError(_('Please define B2C limit line in ' 'company for current period!')) if partner_location == 'inter_state' and \ invoice.amount_total > b2c_limit.b2cl_limit: invoice.write({'gst_invoice': 'b2cl'}) if partner_location == 'intra_state' or partner_location == \ 'inter_state' and invoice.amount_total < \ b2c_limit.b2cs_limit: invoice.write({'gst_invoice': 'b2cs'}) elif invoice.type == 'in_invoice' and partner_location and \ partner_location != 'inter_country': invoice.write({'gst_invoice': 'b2bur'}) return super(AccountInvoice, self).invoice_validate()
def _check_company_payment(self): if self.env['account.journal'].search_count([ ('id', 'in', self.journal_ids.ids), ('company_id', '!=', self.company_id.id) ]): raise ValidationError( _("The company of a payment method is different than the one of point of sale" ))
def check_users_in_planning_line(self): user_list = [] for user in self.sprint_planning_line: if user.user_id.id not in user_list: user_list.append(user.user_id.id) else: raise ValidationError( "You can't add the same user twice in Sprint Planning!")
def _check_recursion(self): if any(item.base == 'pricelist' and item.pricelist_id and item.pricelist_id == item.base_pricelist_id for item in self): raise ValidationError( _('Error! You cannot assign the Main Pricelist as Other Pricelist in PriceList Item!' )) return True
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 _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_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 _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 _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 _set_check_next_number(self): if self.check_next_number < self.check_sequence_id.number_next_actual: raise ValidationError( _("The last check number was %s. In order to avoid a check being rejected " "by the bank, you can only use a greater number.") % self.check_sequence_id.number_next_actual) if self.check_sequence_id: self.check_sequence_id.sudo( ).number_next_actual = self.check_next_number
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 check_reserved_done_quantity(self): for move_line in self: if move_line.state == 'done' and not float_is_zero( move_line.product_uom_qty, precision_digits=self.env['decimal.precision']. precision_get('Product Unit of Measure')): raise ValidationError( _('A done move line should never have a reserved quantity.' ))
def _check_value(self): pattern = "^[a-z A-Z]*$" for data in self: if re.match(pattern, data.declaration_of_error): return True else: return False if len(self.declaration_of_error) > 200: raise ValidationError(_('Number of characters must on exceed 200')) return {}
def _check_company(self): for order in self: if order.branch_id \ and order.company_id != order.branch_id.company_id: raise ValidationError( _('Configuration Error of Company:\n' 'The Purchase Indent Company (%s) and ' 'the Company (%s) of Branch must ' 'be the same company!') % (order.company_id.name, order.branch_id.company_id.name))
def check_quantity(self): for quant in self: if float_compare( quant.quantity, 1, precision_rounding=quant.product_uom_id.rounding ) > 0 and quant.lot_id and quant.product_id.tracking == 'serial': raise ValidationError( _('A serial number should only be linked to a single product.' ))
def _check_branch(self): dropshipping = self.env.ref("stock_dropshipping.picking_type_dropship") for order in self: warehouse_branch_id = order.picking_type_id.warehouse_id.branch_id if order.branch_id and warehouse_branch_id != order.branch_id and order.picking_type_id != dropshipping: raise ValidationError( _('Configuration Error of Branch:\n' 'The Purchase Order Branch (%s) and ' 'the Warehouse Branch (%s) of Deliver To must ' 'be the same branch!') % (order.branch_id.name, warehouse_branch_id.name))
def _validate_fiscalyear_lock(self, values): if values.get('fiscalyear_lock_date'): nb_draft_entries = self.env['account.move'].search([ ('company_id', 'in', [c.id for c in self]), ('state', '=', 'draft'), ('date', '<=', values['fiscalyear_lock_date']) ]) if nb_draft_entries: raise ValidationError( _('There are still unposted entries in the period you want to lock. You should either post or delete them.' ))
def _check_account_ids(self, vals): # Raise an error to prevent the account.budget.post to have not specified account_ids. # This check is done on create because require=True doesn't work on Many2many fields. if 'account_ids' in vals: account_ids = self.resolve_2many_commands('account_ids', vals['account_ids']) else: account_ids = self.account_ids if not account_ids: raise ValidationError( _('The budget must have at least one account.'))