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