PageRenderTime 507ms CodeModel.GetById 494ms app.highlight 10ms RepoModel.GetById 1ms app.codeStats 0ms

/django/contrib/localflavor/it/util.py

https://code.google.com/p/mango-py/
Python | 44 lines | 40 code | 3 blank | 1 comment | 9 complexity | 31d0f4f92d20f776ef5d8885e16b5dd7 MD5 | raw file
 1from django.utils.encoding import smart_str, smart_unicode
 2
 3def ssn_check_digit(value):
 4    "Calculate Italian social security number check digit."
 5    ssn_even_chars = {
 6        '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8,
 7        '9': 9, 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7,
 8        'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15,
 9        'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23,
10        'Y': 24, 'Z': 25
11    }
12    ssn_odd_chars = {
13        '0': 1, '1': 0, '2': 5, '3': 7, '4': 9, '5': 13, '6': 15, '7': 17, '8':
14        19, '9': 21, 'A': 1, 'B': 0, 'C': 5, 'D': 7, 'E': 9, 'F': 13, 'G': 15,
15        'H': 17, 'I': 19, 'J': 21, 'K': 2, 'L': 4, 'M': 18, 'N': 20, 'O': 11,
16        'P': 3, 'Q': 6, 'R': 8, 'S': 12, 'T': 14, 'U': 16, 'V': 10, 'W': 22,
17        'X': 25, 'Y': 24, 'Z': 23
18    }
19    # Chars from 'A' to 'Z'
20    ssn_check_digits = [chr(x) for x in range(65, 91)]
21
22    ssn = value.upper()
23    total = 0
24    for i in range(0, 15):
25        try:
26            if i % 2 == 0:
27                total += ssn_odd_chars[ssn[i]]
28            else:
29                total += ssn_even_chars[ssn[i]]
30        except KeyError:
31            msg = "Character '%(char)s' is not allowed." % {'char': ssn[i]}
32            raise ValueError(msg)
33    return ssn_check_digits[total % 26]
34
35def vat_number_check_digit(vat_number):
36    "Calculate Italian VAT number check digit."
37    normalized_vat_number = smart_str(vat_number).zfill(10)
38    total = 0
39    for i in range(0, 10, 2):
40        total += int(normalized_vat_number[i])
41    for i in range(1, 11, 2):
42        quotient , remainder = divmod(int(normalized_vat_number[i]) * 2, 10)
43        total += quotient + remainder
44    return smart_unicode((10 - total % 10) % 10)