def check_fiscalcode(self, cr, uid, ids, context={}): for partner in self.browse(cr, uid, ids, context): if not partner.fiscalcode: return True if partner.fiscalcode.isdigit() or partner.fiscalcode[2:].isdigit(): return True return isvalid(partner.fiscalcode.upper()) return True
def check_fiscalcode(self, cr, uid, ids, context={}): for partner in self.read(cr, uid, ids, ['fiscalcode'], context): if not partner['fiscalcode']: return True if partner['fiscalcode'].isdigit() or partner['fiscalcode'][2:].isdigit(): return True return isvalid(partner['fiscalcode'].upper()) return True
def test_isvalid(self): invalid = [ None, True, 16, "RCCMNL", # the first 'I' shouldn't be there "CSTNGL22I10D086I" ] for cf in invalid: self.assertFalse(isvalid(cf)) valid = ( 'MRTNTN23M02D969P', 'RCCMNL83S18D969H', 'MRSMSR81D60Z611H', 'CNTCHR83T41D969D', 'XXXXXX77A01Z2P6B', 'FOXDRA26C24H872Y', 'MAILCU91A25F839D' ) for cf in valid: self.assertTrue(isvalid(cf))
def test_isvalid(self): invalid = [ None, True, 16, "RCCMNL", # the first 'I' shouldn't be there "CSTNGL22I10D086I" ] for cf in invalid: self.assertFalse(isvalid(cf)) valid = ('MRTNTN23M02D969P', 'RCCMNL83S18D969H', 'MRSMSR81D60Z611H', 'CNTCHR83T41D969D', 'XXXXXX77A01Z2P6B', 'FOXDRA26C24H872Y', 'MAILCU91A25F839D') for cf in valid: self.assertTrue(isvalid(cf))
def calcoloCodiceFiscale(cod_fisc): # Controlla che che il codice fiscale inserito sia corretto: if cod_fisc == '0': return "Inserire un codice fiscale!" elif not codicefiscale.isvalid(cod_fisc): return "CF errato" else: if verificaEta(cod_fisc): return "OK" else: return "Sei Minorenne!"
def test_isvalid(self): invalid = [ None, True, 16, "RCCMNL", # the first 'I' shouldn't be there "CSTNGL22I10D086I" ] for cf in invalid: self.assertFalse(isvalid(cf)) valid = ( 'MRTNTN23M02D969P', 'RCCMNL83S18D969H', 'MRSMSR81D60Z611H', 'CNTCHR83T41D969D', 'FOXDRA26C24H872Y', 'MAILCU91A25F839D', 'RSSMRA45C12F205C', 'RSSMRA45C12F20RX', 'RSSMRA45C12F2L5N', 'RSSMRA45C12F2LRI', 'RSSMRAQRCMNFNLRG',) for cf in valid: self.assertTrue(isvalid(cf))
def _it_check_fiscalcode(self): if self.fiscalcode: if self.is_individual: if len(self.fiscalcode) != 16: raise ValidationError( _("Italian fiscal code for individuals must be exactly 16 characters." )) if codicefiscale and (not codicefiscale.isvalid( self.fiscalcode)): raise ValidationError( _("Advanced fiscal code verification failed.")) elif self.is_company: if len(self.fiscalcode) != 11: raise ValidationError( _("Italian fiscal code for juridic entities must be exactly 11 characters." ))
def is_valid_cf(string, validate=True): """ Verify the validity of an (italian) fiscal code courtesy of: http://www.icosaedro.it/cf-pi/index.html more info: http://www.agenziaentrate.gov.it/wps/content/Nsilib/Nsi/Home/CosaDeviFare/Richiedere/Codice+fiscale+e+tessera+sanitaria/Richiesta+TS_CF/SchedaI/Informazioni+codificazione+pf/ """ string = str(string) #if len(string) <> 16: return False if not cf.isvalid(string): return False alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' odd_conv = { '0': 1, '1': 0, '2': 5, '3': 7, '4': 9, '5': 13, '6': 15, '7': 17, '8': 19, '9': 21, 'A': 1, 'B': 0, 'C': 5, 'D': 7, 'E': 9, 'F': 13, 'G': 15, 'H': 17, 'I': 19, 'J': 21, 'K': 2, 'L': 4, 'M': 18, 'N': 20, 'O': 11, 'P': 3, 'Q': 6, 'R': 8, 'S': 12, 'T': 14, 'U': 16, 'V': 10, 'W': 22, 'X': 25, 'Y': 24, 'Z': 23 } even_conv = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24, 'Z': 25 } s = 0 for char in string[:-1][1::2]: s += even_conv[char.upper()] for char in string[:-1][::2]: s += odd_conv[char.upper()] r = s%26 r1 = alpha[r] if validate: return string[-1].upper()==r1 else: return r1
def clean(self): """Validate model fields""" # Check tax code field tax_code = self.tax_code.upper().strip().ljust(16) if not codicefiscale.isvalid(tax_code): # Invalid tax code raise ValidationError( {'tax_code': pgettext_lazy('Employee', 'Invalid Tax Code')}) elif codicefiscale.control_code(tax_code[:15]) != tax_code[15]: # Unmatching check digit raise ValidationError( {'tax_code': pgettext_lazy('Employee', 'Incorrect Tax Code')}) elif Employee.objects.filter(tax_code=tax_code).exclude(pk=self.id): # Existing tax code raise ValidationError( {'tax_code': pgettext_lazy('Employee', 'Existing Tax Code')}) else: # No errors self.tax_code = tax_code
def is_valid_cf(string): ''' Verify the validity of an (italian) fiscal code courtesy of: http://www.icosaedro.it/cf-pi/index.html ''' string = str(string) #if len(string) <> 16: return False if not cf.isvalid(string): return False alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' odd_conv = { '0': 1, '1': 0, '2': 5, '3': 7, '4': 9, '5': 13, '6': 15, '7': 17, '8': 19, '9': 21, 'A': 1, 'B': 0, 'C': 5, 'D': 7, 'E': 9, 'F': 13, 'G': 15, 'H': 17, 'I': 19, 'J': 21, 'K': 2, 'L': 4, 'M': 18, 'N': 20, 'O': 11, 'P': 3, 'Q': 6, 'R': 8, 'S': 12, 'T': 14, 'U': 16, 'V': 10, 'W': 22, 'X': 25, 'Y': 24, 'Z': 23 } even_conv = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24, 'Z': 25 } s = 0 for char in string[:-1][1::2]: s += even_conv[char.upper()] for char in string[:-1][::2]: s += odd_conv[char.upper()] r = s%26 r1 = alpha[r] return string[-1].upper()==r1
def __init__(self, nome='', cognome='', cf=None, sesso=None, data_nascita=None, municipalita=None): """Metodo magico che assolve alla funzione di costruttore è un metodo che viene eseguito automaticamente in fase di creazione dell'oggetto """ self.nome = nome self.cognome = cognome self.cf = cf self.municipalita = municipalita self.sesso = sesso self.data_nascita = data_nascita # controlli a seguire if self.data_nascita: # conversione su formati concessi for formato in ('%d/%m/%Y', '%Y-%m-%d'): try: self.data_nascita = datetime.datetime.strptime( data_nascita, formato) break except Exception as e: print(e) assert self.data_nascita if self.sesso: if sesso not in ('M', 'F'): raise Exception('Sesso: M o F. Non {}'.format(sesso)) if self.cf: assert codicefiscale.isvalid(self.cf) assert nome assert cognome
def search(self, cr, uid, args, offset=0, limit=0, order=None, context=None, count=False): partner_model = self.pool['res.partner'] new_args = [] for arg in args: if arg[0] == 'year': new_args.append( ('date_invoice', '>=', '{year}-01-01'.format(year=arg[2]))) new_args.append( ('date_invoice', '<=', '{year}-12-31'.format(year=arg[2]))) elif arg[0] == 'private': private_partner_ids = partner_model.search( cr, uid, [('vat', '=', False), ('fiscalcode', '!=', False)]) private_partner_ids = [ partner.id for partner in partner_model.browse( cr, uid, private_partner_ids, context) if codicefiscale.isvalid(partner.fiscalcode) ] new_args.append(('partner_id.id', 'in', private_partner_ids)) else: new_args.append(arg) return super(account_invoice, self).search(cr, uid, new_args, offset=offset, limit=limit, order=order, context=context, count=count)
def test_02_no_first_name_bug(self): self.assertTrue(isvalid("XXXXXX77A01Z2P6B"))
def calcoloCodiceFiscale( ): # Controlla che che il codice fiscale inserito sia corretto: test_codice_fiscale = -1 while not codicefiscale.isvalid(test_codice_fiscale): test_codice_fiscale = leggiCodiceFiscale() return test_codice_fiscale
def import_valida_volontario_riga(riga): for i in range(0, len(riga)): riga[i] = riga[i] log = [] nome = normalizza_nome(riga[0]) if not nome: log += [(VALIDAZIONE_ERRORE, "Nome vuoto")] cognome = normalizza_nome(riga[1]) if not cognome: log += [(VALIDAZIONE_ERRORE, "Cognome vuoto")] data_nascita = None try: data_nascita = datetime.datetime.strptime(riga[2], "%d/%m/%Y").date() except ValueError: log += [(VALIDAZIONE_ERRORE, "Data di nascita non valida (gg/mm/YYYY)") ] if data_nascita and data_nascita < datetime.date(1800, 1, 1): log += [(VALIDAZIONE_ERRORE, "Data di nascita errata (prima del 1800)") ] luogo_nascita = normalizza_nome(riga[3]) luogo_nascita = re.search("(.*) \((.*)\)", luogo_nascita) if not luogo_nascita: log += [(VALIDAZIONE_ERRORE, "Luogo di nascita non valido (Comune (PV))")] comune_nascita = luogo_nascita.group(1) if luogo_nascita else None provincia_nascita = luogo_nascita.group(2) if luogo_nascita else None if provincia_nascita and len(provincia_nascita) > 2: log += [(VALIDAZIONE_ERRORE, "Provincia di nascita non valida (>2 caratteri)")] codice_fiscale = riga[4].upper() if not codicefiscale.isvalid(codice_fiscale): log += [(VALIDAZIONE_ERRORE, "Codice fiscale non valido")] sede = riga[15] try: sede = Sede.objects.get(nome__iexact=sede) except Sede.DoesNotExist: log += [(VALIDAZIONE_ERRORE, "Sede non trovata: %s" % (sede, ))] sede = None email = riga[10] email_2 = riga[11] email = email or email_2 if email: try: validate_email(email) except ValidationError: log += [(VALIDAZIONE_ERRORE, "E-mail non valida")] precedente = Persona.objects.filter(codice_fiscale=codice_fiscale).first() if sede: if precedente: presso_mia_sede = precedente.appartenenze_attuali().filter( sede__in=sede.comitato.espandi(includi_me=True)).first() presso_qualche_sede = precedente.appartenenze_attuali().exists() aspirante = Aspirante.objects.filter(persona=precedente).exists() if presso_mia_sede: log += [ (VALIDAZIONE_ERRORE, "Già appartenente come %s presso %s" % (presso_mia_sede.get_membro_display(), presso_mia_sede.sede.nome_completo)) ] elif presso_qualche_sede: log += [(VALIDAZIONE_ERRORE, "Già appartenente presso Sede fuori da %s" % (sede.comitato.nome, ))] elif aspirante: log += [( VALIDAZIONE_AVVISO, "Persona pre-esistente in Gaia, iscritta come aspirante. Verrà aggiornata la " "sua appartenenza e disattivata la possibilita di partecipare a nuovi corsi base. " )] else: log += [(VALIDAZIONE_AVVISO, "Esiste in Gaia ma senza alcuna appartenenza")] else: # log += [(VALIDAZIONE_AVVISO, "Non pre-esistente in Gaia")] if email and Utenza.objects.filter(email__iexact=email).exists(): log += [( VALIDAZIONE_AVVISO, "Impossibile attivare credenziali automaticamente, email gia esistente (%s), " "sarà necessario attivare delle credenziali manualmente dal pannello credenziali" " della sua scheda." % (email, ))] elif not email: log += [( VALIDAZIONE_AVVISO, "Impossibile attivare credenziali automaticamente, email non specificata, " "sarà necessario attivare delle credenziali manualmente dal pannello credenziali" " della sua scheda.")] indirizzo_residenza = "%s, %s" % (riga[5], riga[6]) if indirizzo_residenza == ", ": indirizzo_residenza = "" comune_residenza = riga[7] if not comune_residenza: log += [(VALIDAZIONE_ERRORE, "Comune di residenza obbligatorio")] provincia_residenza = riga[8] if not provincia_residenza: log += [(VALIDAZIONE_ERRORE, "Provincia di residenza obbligatorio")] cap = riga[9] if not cap: log += [(VALIDAZIONE_ERRORE, "CAP di residenza obbligatorio")] telefono = riga[12] telefono_servizio = riga[13] data_ingresso = None try: data_ingresso = datetime.datetime.strptime(riga[14], "%d/%m/%Y").date() except ValueError: log += [(VALIDAZIONE_ERRORE, "Data di ingresso non valida (gg/mm/YYYY)")] if data_ingresso and data_ingresso < datetime.date(1800, 1, 1): log += [(VALIDAZIONE_ERRORE, "Data di ingresso errata (prima del 1800)")] if not _ha_errore(log): log += [(VALIDAZIONE_OK, { "nome": nome, "cognome": cognome, "data_nascita": data_nascita, "comune_nascita": comune_nascita, "provincia_nascita": provincia_nascita, "codice_fiscale": codice_fiscale, "indirizzo_residenza": indirizzo_residenza, "comune_residenza": comune_residenza, "provincia_residenza": provincia_residenza, "stato_nascita": "IT", "stato_residenza": "IT", "cap_residenza": cap, "email_contatto": email, "email": email, "telefono": telefono, "telefono_servizio": telefono_servizio, "data_ingresso": data_ingresso, "sede": sede, })] return log
def verifica_cf(self, cf=None): return codicefiscale.isvalid(cf or self.cf)
def collect_values(self, cr, uid, record): self.first_row = False for field in self.REQUIRED: if not getattr(record, field): error = u"Riga {0}: Manca il valore della {1}. La riga viene ignorata.".format(self.processed_lines, field) _logger.debug(error) self.error.append(error) return False if self.FORMAT == 'FormatOmnitron': if record.client_supplier == u'1': self.partner_type = 'supplier' else: self.partner_type = 'customer' # manage partners vals_partner = { 'name': record.name, 'fiscalcode': record.fiscalcode, self.partner_type: True } if self.is_fiscalcode(record.fiscalcode): vals_partner['fiscalcode'] = record.fiscalcode else: error = u"Riga {0}: Fiscalcode {1} is not valid".format(self.processed_lines, record.fiscalcode) _logger.debug(error) self.error.append(error) vals_partner['fiscalcode'] = '' if self.PARTNER_UNIQUE_OFFICE_CODE: if hasattr(record, 'fiscalcode') and record.fiscalcode: if len(vals_partner['fiscalcode']) == 6: vals_partner['unique_office_code'] = vals_partner['fiscalcode'] if hasattr(record, 'additiona_id') and record.additional_id: vals_partner['fiscalcode'] = vals_partner['additional_id'] else: vals_partner['fiscalcode'] = False else: vals_partner['fiscalcode'] = False if self.FORMAT == 'FormatOmnitron': if 'customer' in vals_partner: del vals_partner['customer'] if record.client_supplier == u'1': vals_partner.update({ 'supplier': True, }) else: vals_partner.update({ 'customer': True }) else: # TODO: Check this code!!! if 'supplier' in vals_partner: vals_partner.update({ 'customer': False, 'supplier': True }) if hasattr(record, 'person_name') and record.person_name: vals_partner['name'] += ' {0}'.format(record.person_name) if hasattr(record, 'country_code'): country_id = self._country_by_code(cr, uid, record.country_code) elif getattr(record, 'country_name'): country_id = self._country_by_code(cr, uid, record.country_name) if not country_id: _logger.error("Can't find country {}".format(record.country_name)) else: country_id = False if country_id: country = self.pool['res.country'].browse(cr, uid, country_id, self.context) country_code = country.code else: if hasattr(record, 'vat') and record.vat and record.vat[:2] in VAT_CODES: country_code = record.vat[:2] country_id = self._country_by_code(cr, uid, country_code) country = self.pool['res.country'].browse(cr, uid, country_id, self.context) else: country_code = '' if country_id: fiscal_position_ids = self.account_fiscal_position_obj.search( cr, uid, [('name', '=ilike', country.name)], context=self.context ) if fiscal_position_ids and len(fiscal_position_ids) == 1: vals_partner['property_account_position'] = fiscal_position_ids[0] else: warning = u"Riga {0}: Fiscal position can't be determined for partner {1}".format( self.processed_lines, vals_partner['name']) _logger.debug(warning) self.warning.append(warning) else: error = u"Riga {0}: {1} Country non è riconosciuto".format( self.processed_lines, vals_partner['name']) _logger.debug(error) self.error.append(error) if hasattr(record, 'fiscal_position') and record.fiscal_position: fiscal_position = self.partner_template.map_account_fiscal_position( cr, uid, self.partner_template_id, record.fiscal_position) if fiscal_position: vals_partner['property_account_position'] = fiscal_position if hasattr(record, 'payment_term') and record.payment_term: vals_payment = self.partner_template.map_payment_term( cr, uid, self.partner_template_id, record.payment_term) if vals_payment.get('property_payment_term', False): vals_partner['property_payment_term'] = vals_payment['property_payment_term'] if vals_payment.get('company_bank_id', False): vals_partner['company_bank_id'] = vals_payment['company_bank_id'] if hasattr(record, 'credit_limit') and record.credit_limit: vals_partner['credit_limit'] = record.credit_limit if record.vat and len(record.vat) > 3: vals_partner['vat_subjected'] = True vals_partner['individual'] = False vat = record.vat if vat and len(vat) == 10 and country_code[:2] == 'IT': vat = '0' + vat if vat and len(vat) == 9 and country_code[:2] == 'IT': vat = '00' + vat if not country_code == record.vat[:2]: vals_partner['vat'] = country_code + vat else: vals_partner['vat'] = vat vals_partner['vat'] = vals_partner['vat'].replace(' ', '') # if not self.partner_obj.simple_vat_check(cr, uid, country_code.lower(), vals_partner['vat'][2:], None): if vatnumber.check_vat(vals_partner['vat']) or vatnumber.check_vat('IT' + vals_partner['vat']): if vatnumber.check_vat('IT' + vals_partner['vat']): vals_partner['vat'] = 'IT' + vals_partner['vat'] if record.vat == record.fiscalcode: if codicefiscale.isvalid(record.vat): vals_partner['fiscalcode'] = vals_partner['vat'] else: vals_partner['fiscalcode'] = False else: error = u"Riga {line}: Partner '{record.code} {record.name}'; Partita IVA errata: <strong>'{vat}'</strong>".format( line=self.processed_lines, record=record, vat=vals_partner['vat'] ) _logger.debug(error) self.error.append(error) if DONT_STOP_ON_WRONG_VAT: del vals_partner['vat'] if vals_partner.get('fiscalcode'): del vals_partner['fiscalcode'] else: return False # if record.fiscalcode and not record.fiscalcode == record.vat and not len(record.fiscalcode) == 16: # error = u"Riga {0}: Codice Fiscale {1} errato".format(self.processed_lines, record.fiscalcode) # _logger.debug(error) # self.error.append(error) # return False # elif record.fiscalcode and not record.vat: # vals_partner['individual'] = True if vals_partner.get('fiscalcode') and not vals_partner.get('vat'): vals_partner['individual'] = True # if country_code == 'IT': # vals_partner['property_account_position'] = self.italy_fiscal_position_id # if record.vat: # pdb.set_trace() # old_vat = vals_input['Partita IVA'] # if len(vals_input['Partita IVA']) < 11: # zero_add = 11 - len(vals_input['Partita IVA']) # for zero in range(0, zero_add): # vals_input['Partita IVA'] = '0' + vals_input['Partita IVA'] if hasattr(record, 'comment') and record.comment: vals_partner['comment'] = record.comment record_code = self.simple_string(record.code, as_integer=True) if self.UPDATE_ON_CODE and PROPERTY_REF_MAP[self.partner_type]: code_partner_ids = self.partner_obj.search(cr, uid, [(PROPERTY_REF_MAP[self.partner_type], '=', record_code)], context=self.context) else: code_partner_ids = False if code_partner_ids and not self.UPDATE_ON_CODE: code_partner_data = self.partner_obj.browse(cr, uid, code_partner_ids[0], self.context) if vals_partner.get('vat', False) and not code_partner_data.vat == vals_partner['vat']: error = u"Riga {0}: Partner '{1} {2}'; codice gia utilizzato per partner {3}. La riga viene ignorata.".format(self.processed_lines, record_code, vals_partner['name'], code_partner_data['name']) _logger.debug(error) self.error.append(error) return False elif vals_partner.get('fiscalcode', False) and not code_partner_data.fiscalcode == vals_partner['fiscalcode']: error = u"Riga {0}: Partner '{1} {2}'; codice gia utilizzato per partner {3}. La riga viene ignorata.".format(self.processed_lines, record_code, vals_partner['name'], code_partner_data['name']) _logger.debug(error) self.error.append(error) return False elif code_partner_ids and self.UPDATE_ON_CODE: vals_partner[PROPERTY_REF_MAP[self.partner_type]] = record_code if PROPERTY_REF_MAP[self.partner_type] not in self.PARTNER_SEARCH: self.PARTNER_SEARCH.insert(0, PROPERTY_REF_MAP[self.partner_type]) else: if record_code: vals_partner[PROPERTY_REF_MAP[self.partner_type]] = record_code if hasattr(record, 'category') and record.category: category_ids = self.category_obj.search(cr, uid, [('name', '=', record.category)], context=self.context) if len(category_ids): vals_partner['category_id'] = [(6, 0, category_ids)] else: category_id = self.category_obj.create(cr, uid, { 'name': record.category, 'active': True }, self.context) vals_partner['category_id'] = [(6, 0, [category_id])] return vals_partner, country_id
def validate_fiscal_code (fiscal_code) : if codicefiscale.isvalid (fiscal_code) : return None else : raise ValidationError ("Please enter a valid fiscal code.")
def test_03_unicode_handling_isvalid(self): self.assertTrue(isvalid('MRTNTN23M02D969P')) self.assertTrue(isvalid(u'MRTNTN23M02D969P'))
def validate_fiscal_code(fiscal_code): if codicefiscale.isvalid(fiscal_code): return None else: raise ValidationError("Please enter a valid fiscal code.")
def import_row(self, cr, uid, row_list, book_datemode): if not len(row_list) == len(self.HEADER): row_str_list = [self.toStr(value) for value in row_list] if DEBUG: if len(row_list) > len(self.HEADER): pprint(zip(self.HEADER, row_str_list[:len(self.HEADER)])) else: pprint(zip(self.HEADER[:len(row_list)], row_str_list)) error = u"""Row {row}: Row_list is {row_len} long. We expect it to be {expected} long, with this columns: {keys} Instead of this we got this: {header} """.format(row=self.processed_lines, row_len=len(row_list), expected=len(self.HEADER), keys=self.HEADER, header=', '.join(map(lambda s: s or '', row_str_list))) _logger.error(str(row_list)) _logger.error(error) # error = u'Riga {0} non importata. Colonne non corrsipondono al Header definito'.format(self.processed_lines) # _logger.debug(error) # self.error.append(error) return False if DEBUG: # pprint(row_list) row_str_list = [self.simple_string(value) for value in row_list] pprint(zip(self.HEADER, row_str_list)) record = self.Record._make([self.toStr(value) for value in row_list]) if self.first_row: if not record.name: warning = u'Riga {0}: Trovato Header'.format(self.processed_lines) _logger.debug(warning) self.warning.append(warning) return True else: for column in record: # column_ascii = unicodedata.normalize('NFKD', column).encode('ascii', 'ignore').lower() if column in self.HEADER: warning = u'Riga {0}: Trovato Header'.format(self.processed_lines) _logger.debug(warning) self.warning.append(warning) return True self.first_row = False for field in self.REQUIRED: if not getattr(record, field): error = u"Riga {0}: Manca il valore della {1}. La riga viene ignorata.".format(self.processed_lines, field) _logger.debug(error) self.error.append(error) return False # manage partners vals_partner = { 'name': record.name, 'fiscalcode': record.fiscalcode, self.partner_type: True } if self.is_fiscalcode(record.fiscalcode): vals_partner['fiscalcode'] = record.fiscalcode else: error = u"Riga {0}: Fiscalcode {1} is not valid".format(self.processed_lines, record.fiscalcode) _logger.debug(error) self.error.append(error) vals_partner['fiscalcode'] = '' if self.PARTNER_UNIQUE_OFFICE_CODE: if hasattr(record, 'fiscalcode') and record.fiscalcode: if len(vals_partner['fiscalcode']) == 6: vals_partner['unique_office_code'] = vals_partner['fiscalcode'] if hasattr(record, 'additiona_id') and record.additional_id: vals_partner['fiscalcode'] = vals_partner['additional_id'] else: vals_partner['fiscalcode'] = False else: vals_partner['fiscalcode'] = False if 'supplier' in vals_partner: vals_partner.update({ 'customer': False, 'supplier': True }) if self.FORMAT == 'FormatOmnitron': if 'customer' in vals_partner: del vals_partner['customer'] if record.client_supplier == u'1': vals_partner.update({ 'supplier': True }) else: vals_partner.update({ 'customer': True }) if hasattr(record, 'person_name') and record.person_name: vals_partner['name'] += ' {0}'.format(record.person_name) if hasattr(record, 'country_code'): country_code = COUNTRY_CODES.get(record.country_code, record.country_code) else: if hasattr(record, 'vat') and record.vat and record.vat[:2] in VAT_CODES: country_code = record.vat[:2] else: country_code = '' if country_code: country_id = self._country_by_code(cr, uid, country_code) if country_id: country = self.pool['res.country'].browse(cr, uid, country_id, self.context) fiscal_position_ids = self.account_fiscal_position_obj.search(cr, uid, [('name', '=ilike', country.name)], context=self.context) if fiscal_position_ids and len(fiscal_position_ids) == 1: vals_partner['property_account_position'] = fiscal_position_ids[0] else: warning = u"Riga {0}: Fiscal position can't be determined for partner {1}".format(self.processed_lines, vals_partner['name']) _logger.debug(warning) self.warning.append(warning) else: error = u"Riga {0}: Country code '{1}' non è riconosciuto. La riga viene ignorata.".format(self.processed_lines, country_code) _logger.debug(error) self.error.append(error) return False if hasattr(record, 'fiscal_position') and record.fiscal_position: fiscal_position = self.partner_template.map_account_fiscal_position(cr, uid, self.partner_template_id, record.fiscal_position) if fiscal_position: vals_partner['property_account_position'] = fiscal_position if hasattr(record, 'payment_term') and record.payment_term: vals_payment = self.partner_template.map_payment_term(cr, uid, self.partner_template_id, record.payment_term) if vals_payment.get('property_payment_term', False): vals_partner['property_payment_term'] = vals_payment['property_payment_term'] if vals_payment.get('company_bank_id', False): vals_partner['company_bank_id'] = vals_payment['company_bank_id'] if hasattr(record, 'credit_limit') and record.credit_limit: vals_partner['credit_limit'] = record.credit_limit if record.vat and len(record.vat) > 3: vals_partner['vat_subjected'] = True vals_partner['individual'] = False if country_code: country_code = country_code[:2] else: country_code = '' vat = record.vat if vat and len(vat) == 10 and country_code[:2] == 'IT': vat = '0' + vat if vat and len(vat) == 9 and country_code[:2] == 'IT': vat = '00' + vat if not country_code == record.vat[:2]: vals_partner['vat'] = country_code + vat else: vals_partner['vat'] = vat vals_partner['vat'] = vals_partner['vat'].replace(' ', '') # if not self.partner_obj.simple_vat_check(cr, uid, country_code.lower(), vals_partner['vat'][2:], None): if vatnumber.check_vat(vals_partner['vat']): if record.vat == record.fiscalcode: if codicefiscale.isvalid(record.vat): vals_partner['fiscalcode'] = vals_partner['vat'] else: vals_partner['fiscalcode'] = False else: error = u"Riga {line}: Partner '{record.code} {record.name}'; Partita IVA errata: <strong>'{vat}'</strong>".format( line=self.processed_lines, record=record, vat=vals_partner['vat'] ) _logger.debug(error) self.error.append(error) if DONT_STOP_ON_WRONG_VAT: del vals_partner['vat'] if vals_partner.get('fiscalcode'): del vals_partner['fiscalcode'] else: return False # if record.fiscalcode and not record.fiscalcode == record.vat and not len(record.fiscalcode) == 16: # error = u"Riga {0}: Codice Fiscale {1} errato".format(self.processed_lines, record.fiscalcode) # _logger.debug(error) # self.error.append(error) # return False # elif record.fiscalcode and not record.vat: # vals_partner['individual'] = True if vals_partner.get('fiscalcode') and not vals_partner.get('vat'): vals_partner['individual'] = True # if country_code == 'IT': # vals_partner['property_account_position'] = self.italy_fiscal_position_id # if record.vat: # pdb.set_trace() # old_vat = vals_input['Partita IVA'] # if len(vals_input['Partita IVA']) < 11: # zero_add = 11 - len(vals_input['Partita IVA']) # for zero in range(0, zero_add): # vals_input['Partita IVA'] = '0' + vals_input['Partita IVA'] if hasattr(record, 'comment') and record.comment: vals_partner['comment'] = record.comment record_code = self.simple_string(record.code, as_integer=True) if self.UPDATE_ON_CODE and PROPERTY_REF_MAP[self.partner_type]: code_partner_ids = self.partner_obj.search(cr, uid, [(PROPERTY_REF_MAP[self.partner_type], '=', record_code)], context=self.context) else: code_partner_ids = False if code_partner_ids and not self.UPDATE_ON_CODE: code_partner_data = self.partner_obj.browse(cr, uid, code_partner_ids[0], self.context) if vals_partner.get('vat', False) and not code_partner_data.vat == vals_partner['vat']: error = u"Riga {0}: Partner '{1} {2}'; codice gia utilizzato per partner {3}. La riga viene ignorata.".format(self.processed_lines, record_code, vals_partner['name'], code_partner_data['name']) _logger.debug(error) self.error.append(error) return False elif vals_partner.get('fiscalcode', False) and not code_partner_data.fiscalcode == vals_partner['fiscalcode']: error = u"Riga {0}: Partner '{1} {2}'; codice gia utilizzato per partner {3}. La riga viene ignorata.".format(self.processed_lines, record_code, vals_partner['name'], code_partner_data['name']) _logger.debug(error) self.error.append(error) return False elif code_partner_ids and self.UPDATE_ON_CODE: vals_partner[PROPERTY_REF_MAP[self.partner_type]] = record_code if PROPERTY_REF_MAP[self.partner_type] not in self.PARTNER_SEARCH: self.PARTNER_SEARCH.insert(0, PROPERTY_REF_MAP[self.partner_type]) else: if record_code: vals_partner[PROPERTY_REF_MAP[self.partner_type]] = record_code if hasattr(record, 'category') and record.category: category_ids = self.category_obj.search(cr, uid, [('name', 'ilike', record.category)], context=self.context) if len(category_ids) == 1: vals_partner['category_id'] = [(6, 0, category_ids)] else: vals_partner['category_id'] = [(6, 0, [self.category_obj.create(cr, uid, { 'name': record.category, 'active': True }), self.context])] # partner_id = self._find_partner(cr, uid, record) partner_id = self._find_partner(cr, uid, vals_partner) if partner_id and partner_id > 0: self.partner_obj.write(cr, uid, partner_id, vals_partner, self.context) self.updated += 1 elif partner_id and partner_id < 0: return False else: self.context['import'] = True try: partner_id = self.partner_obj.create(cr, uid, vals_partner, self.context) self.uo_new += 1 # except ValidateError as e: except Exception as e: # e = sys.exc_info()[0] e = e[1].split(':')[1] error = u"Riga {0}: Partner '{1} {2}'. I dati non corretti. (Error: {3}) La riga viene ignorata.".format(self.processed_lines, record_code, vals_partner['name'], e) _logger.debug(error) self.error.append(error) return False address_type_1 = self.ADDRESS_TYPE[0] address_type_2 = self.ADDRESS_TYPE[1] if getattr(record, 'street_' + address_type_1) or getattr(record, 'zip_' + address_type_1) or getattr(record, 'city_' + address_type_1) or getattr(record, 'province_' + address_type_1): first_address = True else: first_address = False if getattr(record, 'street_' + address_type_2) or getattr(record, 'zip_' + address_type_2) or getattr(record, 'city_' + address_type_2) or getattr(record, 'province_' + address_type_2): second_address = True else: second_address = False if first_address and second_address: self.write_address(cr, uid, address_type_1, partner_id, record, vals_partner, country_code) self.write_address(cr, uid, address_type_2, partner_id, record, vals_partner, country_code) elif first_address: self.write_address(cr, uid, address_type_1, partner_id, record, vals_partner, country_code, force_default=True) elif second_address: self.write_address(cr, uid, address_type_2, partner_id, record, vals_partner, country_code, force_default=True) if self.FORMAT == 'FormatOmnitron': if hasattr(record, 'email_invoice') and record.email_invoice: self.write_address(cr, uid, 'invoice', partner_id, record, vals_partner, country_code) # if hasattr(record, 'iban') and record.iban: # self.get_or_create_bank(cr, uid, record.iban, partner_id, self.context) return partner_id
def is_fiscalcode(self, code): if not code: return True if code.isdigit() or code[2:].isdigit(): return True return codicefiscale.isvalid(code.upper())
def _check_subscriber_fiscalcode(self): for mandate in self: if mandate.subscriber_fiscalcode and not isvalid(mandate.subscriber_fiscalcode): raise ValidationError( _("This fiscal code is not formally correct: '%s'") % mandate.subscriber_fiscalcode)
def test_04_unicode_handling_isvalid(self): self.assertTrue(isvalid('MRTNTN23M02D969P')) self.assertTrue(isvalid(u'MRTNTN23M02D969P'))
def import_valida_volontario_riga(riga): for i in range(0, len(riga)): riga[i] = riga[i] log = [] nome = normalizza_nome(riga[0]) if not nome: log += [(VALIDAZIONE_ERRORE, "Nome vuoto")] cognome = normalizza_nome(riga[1]) if not cognome: log += [(VALIDAZIONE_ERRORE, "Cognome vuoto")] data_nascita = None try: data_nascita = datetime.datetime.strptime(riga[2], "%d/%m/%Y").date() except ValueError: log += [(VALIDAZIONE_ERRORE, "Data di nascita non valida (gg/mm/YYYY)")] if data_nascita and data_nascita < datetime.date(1800, 1, 1): log += [(VALIDAZIONE_ERRORE, "Data di nascita errata (prima del 1800)")] luogo_nascita = normalizza_nome(riga[3]) luogo_nascita = re.search("(.*) \((.*)\)", luogo_nascita) if not luogo_nascita: log += [(VALIDAZIONE_ERRORE, "Luogo di nascita non valido (Comune (PV))")] comune_nascita = luogo_nascita.group(1) if luogo_nascita else None provincia_nascita = luogo_nascita.group(2) if luogo_nascita else None if provincia_nascita and len(provincia_nascita) > 2: log += [(VALIDAZIONE_ERRORE, "Provincia di nascita non valida (>2 caratteri)")] codice_fiscale = riga[4].upper() if not codicefiscale.isvalid(codice_fiscale): log += [(VALIDAZIONE_ERRORE, "Codice fiscale non valido")] sede = riga[15] try: sede = Sede.objects.get(nome__iexact=sede) except Sede.DoesNotExist: log += [(VALIDAZIONE_ERRORE, "Sede non trovata: %s" % (sede,))] sede = None email = riga[10] email_2 = riga[11] email = email or email_2 if email: try: validate_email(email) except ValidationError: log += [(VALIDAZIONE_ERRORE, "E-mail non valida")] precedente = Persona.objects.filter(codice_fiscale=codice_fiscale).first() if sede: if precedente: presso_mia_sede = precedente.appartenenze_attuali().filter(sede__in=sede.comitato.espandi(includi_me=True)).first() presso_qualche_sede = precedente.appartenenze_attuali().exists() aspirante = Aspirante.objects.filter(persona=precedente).exists() if presso_mia_sede: log += [(VALIDAZIONE_ERRORE, "Già appartenente come %s presso %s" % (presso_mia_sede.get_membro_display(), presso_mia_sede.sede.nome_completo))] elif presso_qualche_sede: log += [(VALIDAZIONE_ERRORE, "Già appartenente presso Sede fuori da %s" % (sede.comitato.nome,))] elif aspirante: log += [(VALIDAZIONE_AVVISO, "Persona pre-esistente in Gaia, iscritta come aspirante. Verrà aggiornata la " "sua appartenenza e disattivata la possibilita di partecipare a nuovi corsi base. ")] else: log += [(VALIDAZIONE_AVVISO, "Esiste in Gaia ma senza alcuna appartenenza")] else: # log += [(VALIDAZIONE_AVVISO, "Non pre-esistente in Gaia")] if email and Utenza.objects.filter(email__iexact=email).exists(): log += [(VALIDAZIONE_AVVISO, "Impossibile attivare credenziali automaticamente, email gia esistente (%s), " "sarà necessario attivare delle credenziali manualmente dal pannello credenziali" " della sua scheda." % (email,))] elif not email: log += [(VALIDAZIONE_AVVISO, "Impossibile attivare credenziali automaticamente, email non specificata, " "sarà necessario attivare delle credenziali manualmente dal pannello credenziali" " della sua scheda.")] indirizzo_residenza = "%s, %s" % (riga[5], riga[6]) if indirizzo_residenza == ", ": indirizzo_residenza = "" comune_residenza = riga[7] if not comune_residenza: log += [(VALIDAZIONE_ERRORE, "Comune di residenza obbligatorio")] provincia_residenza = riga[8] if not provincia_residenza: log += [(VALIDAZIONE_ERRORE, "Provincia di residenza obbligatorio")] cap = riga[9] if not cap: log += [(VALIDAZIONE_ERRORE, "CAP di residenza obbligatorio")] telefono = riga[12] telefono_servizio = riga[13] data_ingresso = None try: data_ingresso = datetime.datetime.strptime(riga[14], "%d/%m/%Y").date() except ValueError: log += [(VALIDAZIONE_ERRORE, "Data di ingresso non valida (gg/mm/YYYY)")] if data_ingresso and data_ingresso < datetime.date(1800, 1, 1): log += [(VALIDAZIONE_ERRORE, "Data di ingresso errata (prima del 1800)")] if not _ha_errore(log): log += [ (VALIDAZIONE_OK, { "nome": nome, "cognome": cognome, "data_nascita": data_nascita, "comune_nascita": comune_nascita, "provincia_nascita": provincia_nascita, "codice_fiscale": codice_fiscale, "indirizzo_residenza": indirizzo_residenza, "comune_residenza": comune_residenza, "provincia_residenza": provincia_residenza, "stato_nascita": "IT", "stato_residenza": "IT", "cap_residenza": cap, "email_contatto": email, "email": email, "telefono": telefono, "telefono_servizio": telefono_servizio, "data_ingresso": data_ingresso, "sede": sede, } ) ] return log
def collect_values(self, cr, uid, record): self.first_row = False for field in self.REQUIRED: if not getattr(record, field): error = u"Riga {0}: Manca il valore della {1}. La riga viene ignorata.".format( self.processed_lines, field) _logger.debug(error) self.error.append(error) return False if self.FORMAT == 'FormatOmnitron': if record.client_supplier == u'1': self.partner_type = 'supplier' else: self.partner_type = 'customer' # manage partners vals_partner = { 'name': record.name, 'fiscalcode': record.fiscalcode, self.partner_type: True } if self.is_fiscalcode(record.fiscalcode): vals_partner['fiscalcode'] = record.fiscalcode else: error = u"Riga {0}: Fiscalcode {1} is not valid".format( self.processed_lines, record.fiscalcode) _logger.debug(error) self.error.append(error) vals_partner['fiscalcode'] = '' if self.PARTNER_UNIQUE_OFFICE_CODE: if hasattr(record, 'fiscalcode') and record.fiscalcode: if len(vals_partner['fiscalcode']) == 6: vals_partner['unique_office_code'] = vals_partner[ 'fiscalcode'] if hasattr(record, 'additiona_id') and record.additional_id: vals_partner['fiscalcode'] = vals_partner[ 'additional_id'] else: vals_partner['fiscalcode'] = False else: vals_partner['fiscalcode'] = False if self.FORMAT == 'FormatOmnitron': if 'customer' in vals_partner: del vals_partner['customer'] if record.client_supplier == u'1': vals_partner.update({ 'supplier': True, }) else: vals_partner.update({'customer': True}) else: # TODO: Check this code!!! if 'supplier' in vals_partner: vals_partner.update({'customer': False, 'supplier': True}) if hasattr(record, 'person_name') and record.person_name: vals_partner['name'] += ' {0}'.format(record.person_name) if hasattr(record, 'country_code'): country_id = self._country_by_code(cr, uid, record.country_code) elif getattr(record, 'country_name'): country_id = self._country_by_code(cr, uid, record.country_name) if not country_id: _logger.error("Can't find country {}".format( record.country_name)) else: country_id = False if country_id: country = self.pool['res.country'].browse(cr, uid, country_id, self.context) country_code = country.code else: if hasattr(record, 'vat') and record.vat and record.vat[:2] in VAT_CODES: country_code = record.vat[:2] country_id = self._country_by_code(cr, uid, country_code) country = self.pool['res.country'].browse( cr, uid, country_id, self.context) else: country_code = '' if country_id: fiscal_position_ids = self.account_fiscal_position_obj.search( cr, uid, [('name', '=ilike', country.name)], context=self.context) if fiscal_position_ids and len(fiscal_position_ids) == 1: vals_partner[ 'property_account_position'] = fiscal_position_ids[0] else: warning = u"Riga {0}: Fiscal position can't be determined for partner {1}".format( self.processed_lines, vals_partner['name']) _logger.debug(warning) self.warning.append(warning) else: error = u"Riga {0}: {1} Country non è riconosciuto".format( self.processed_lines, vals_partner['name']) _logger.debug(error) self.error.append(error) if hasattr(record, 'fiscal_position') and record.fiscal_position: fiscal_position = self.partner_template.map_account_fiscal_position( cr, uid, self.partner_template_id, record.fiscal_position) if fiscal_position: vals_partner['property_account_position'] = fiscal_position if hasattr(record, 'payment_term') and record.payment_term: vals_payment = self.partner_template.map_payment_term( cr, uid, self.partner_template_id, record.payment_term) if vals_payment.get('property_payment_term', False): vals_partner['property_payment_term'] = vals_payment[ 'property_payment_term'] if vals_payment.get('company_bank_id', False): vals_partner['company_bank_id'] = vals_payment[ 'company_bank_id'] if hasattr(record, 'credit_limit') and record.credit_limit: vals_partner['credit_limit'] = record.credit_limit if record.vat and len(record.vat) > 3: vals_partner['vat_subjected'] = True vals_partner['individual'] = False vat = record.vat if vat and len(vat) == 10 and country_code[:2] == 'IT': vat = '0' + vat if vat and len(vat) == 9 and country_code[:2] == 'IT': vat = '00' + vat if not country_code == record.vat[:2]: vals_partner['vat'] = country_code + vat else: vals_partner['vat'] = vat vals_partner['vat'] = vals_partner['vat'].replace(' ', '') # if not self.partner_obj.simple_vat_check(cr, uid, country_code.lower(), vals_partner['vat'][2:], None): if vatnumber.check_vat(vals_partner['vat']) or vatnumber.check_vat( 'IT' + vals_partner['vat']): if vatnumber.check_vat('IT' + vals_partner['vat']): vals_partner['vat'] = 'IT' + vals_partner['vat'] if record.vat == record.fiscalcode: if codicefiscale.isvalid(record.vat): vals_partner['fiscalcode'] = vals_partner['vat'] else: vals_partner['fiscalcode'] = False else: error = u"Riga {line}: Partner '{record.code} {record.name}'; Partita IVA errata: <strong>'{vat}'</strong>".format( line=self.processed_lines, record=record, vat=vals_partner['vat']) _logger.debug(error) self.error.append(error) if DONT_STOP_ON_WRONG_VAT: del vals_partner['vat'] if vals_partner.get('fiscalcode'): del vals_partner['fiscalcode'] else: return False # if record.fiscalcode and not record.fiscalcode == record.vat and not len(record.fiscalcode) == 16: # error = u"Riga {0}: Codice Fiscale {1} errato".format(self.processed_lines, record.fiscalcode) # _logger.debug(error) # self.error.append(error) # return False # elif record.fiscalcode and not record.vat: # vals_partner['individual'] = True if vals_partner.get('fiscalcode') and not vals_partner.get('vat'): vals_partner['individual'] = True # if country_code == 'IT': # vals_partner['property_account_position'] = self.italy_fiscal_position_id # if record.vat: # pdb.set_trace() # old_vat = vals_input['Partita IVA'] # if len(vals_input['Partita IVA']) < 11: # zero_add = 11 - len(vals_input['Partita IVA']) # for zero in range(0, zero_add): # vals_input['Partita IVA'] = '0' + vals_input['Partita IVA'] if hasattr(record, 'comment') and record.comment: vals_partner['comment'] = record.comment record_code = self.simple_string(record.code, as_integer=True) if self.UPDATE_ON_CODE and PROPERTY_REF_MAP[self.partner_type]: code_partner_ids = self.partner_obj.search( cr, uid, [(PROPERTY_REF_MAP[self.partner_type], '=', record_code)], context=self.context) else: code_partner_ids = False if code_partner_ids and not self.UPDATE_ON_CODE: code_partner_data = self.partner_obj.browse( cr, uid, code_partner_ids[0], self.context) if vals_partner.get( 'vat', False ) and not code_partner_data.vat == vals_partner['vat']: error = u"Riga {0}: Partner '{1} {2}'; codice gia utilizzato per partner {3}. La riga viene ignorata.".format( self.processed_lines, record_code, vals_partner['name'], code_partner_data['name']) _logger.debug(error) self.error.append(error) return False elif vals_partner.get( 'fiscalcode', False ) and not code_partner_data.fiscalcode == vals_partner[ 'fiscalcode']: error = u"Riga {0}: Partner '{1} {2}'; codice gia utilizzato per partner {3}. La riga viene ignorata.".format( self.processed_lines, record_code, vals_partner['name'], code_partner_data['name']) _logger.debug(error) self.error.append(error) return False elif code_partner_ids and self.UPDATE_ON_CODE: vals_partner[PROPERTY_REF_MAP[self.partner_type]] = record_code if PROPERTY_REF_MAP[self.partner_type] not in self.PARTNER_SEARCH: self.PARTNER_SEARCH.insert(0, PROPERTY_REF_MAP[self.partner_type]) else: if record_code: vals_partner[PROPERTY_REF_MAP[self.partner_type]] = record_code if hasattr(record, 'category') and record.category: category_ids = self.category_obj.search( cr, uid, [('name', '=', record.category)], context=self.context) if len(category_ids): vals_partner['category_id'] = [(6, 0, category_ids)] else: category_id = self.category_obj.create(cr, uid, { 'name': record.category, 'active': True }, self.context) vals_partner['category_id'] = [(6, 0, [category_id])] return vals_partner, country_id