Skip to content

Commit

Permalink
Fix of issue 0203. If the person is more that 100 years old the year …
Browse files Browse the repository at this point in the history
…number in not computed correctly and an exception is raised. The fix attempt several time (3) to use the correct number until the exception is not raised
  • Loading branch information
Michele Faedi committed Nov 22, 2024
1 parent de8018d commit d56d0c4
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 14 deletions.
39 changes: 25 additions & 14 deletions codicefiscale/codicefiscale.py
Original file line number Diff line number Diff line change
Expand Up @@ -463,21 +463,32 @@ def decode(code: str) -> dict[str, Any]:
birthdate_year = int(f"{current_year_century_prefix}{birthdate_year_suffix}")
if birthdate_year > current_year:
birthdate_year -= 100
birthdate_str = f"{birthdate_year}/{birthdate_month}/{birthdate_day}"
birthdate = _get_date(birthdate_str, separator="/")
if not birthdate:
raise ValueError(f"[codicefiscale] invalid date: {birthdate_str}")

birthplace_code = raw["birthplace"][0] + raw["birthplace"][1:].translate(
_OMOCODIA_DECODE_TRANS
)
birthplace = _get_birthplace(birthplace_code, birthdate)
# print(birthplace)
if not birthplace:
raise ValueError(
"[codicefiscale] wrong birthplace code: "
f"{birthplace_code!r} / birthdate: {birthdate.isoformat()!r}."
)
attempt = 1
while True:
birthdate_str = f"{birthdate_year}/{birthdate_month}/{birthdate_day}"

try:
birthdate = _get_date(birthdate_str, separator="/")
if not birthdate:
raise ValueError(f"[codicefiscale] invalid date: {birthdate_str}")

birthplace_code = raw["birthplace"][0] + raw["birthplace"][1:].translate(
_OMOCODIA_DECODE_TRANS
)
birthplace = _get_birthplace(birthplace_code, birthdate)
# print(birthplace)
if not birthplace:
raise ValueError(
"[codicefiscale] wrong birthplace code: "
f"{birthplace_code!r} / birthdate: {birthdate.isoformat()!r}."
)
break
except ValueError as e:
attempt += 1
birthdate_year -= 100
if attempt > 3:
raise e

cin = raw["cin"]
cin_check = encode_cin(code)
Expand Down
16 changes: 16 additions & 0 deletions tests/test_issue_0203.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import unittest
from datetime import datetime, timedelta

from codicefiscale import codicefiscale


class Issue0203TestCase(unittest.TestCase):
def test_issue_0203(self):
"""
Encode a person in an old municipality (active = false)
And the person is more than 100 years old
"""
try:
codicefiscale.encode('Mario', 'Rossi', 'm', datetime.now() - timedelta(days=150 * 365), 'Gallico')
except ValueError as e:
self.fail(f"codicefiscale.encode raised an exception: {e}")

0 comments on commit d56d0c4

Please sign in to comment.