|
| 1 | +import re |
| 2 | +from types import SimpleNamespace |
| 3 | +from typing import Optional, TypedDict |
| 4 | +from .util import CHECK_DIGIT |
| 5 | + |
| 6 | + |
| 7 | +class ParseResult(TypedDict): |
| 8 | + yymm: str |
| 9 | + """birthday of this ID""" |
| 10 | + sn: str |
| 11 | + """serial number""" |
| 12 | + checksum: CHECK_DIGIT |
| 13 | + """checksum""" |
| 14 | + |
| 15 | + |
| 16 | +class PersonalNumber: |
| 17 | + """ |
| 18 | + Bahrain Personal Number, Identification Card Number, Arabic: الرقم الشخصي |
| 19 | + https://en.wikipedia.org/wiki/National_identification_number#Bahrain |
| 20 | + * According to the doc, we can know it has checksum algorithm. But we cannot find it. |
| 21 | + """ |
| 22 | + METADATA = SimpleNamespace(**{ |
| 23 | + 'iso3166_alpha2': 'BH', |
| 24 | + 'min_length': 9, |
| 25 | + 'max_length': 9, |
| 26 | + 'parsable': True, |
| 27 | + 'checksum': False, |
| 28 | + 'regexp': re.compile(r'^(?P<yymm>\d{2}(?:0[1-9]|1[012]))' |
| 29 | + r'(?P<sn>\d{4})' |
| 30 | + r'(?P<checksum>\d)$') |
| 31 | + }) |
| 32 | + |
| 33 | + @staticmethod |
| 34 | + def validate(id_number: str) -> bool: |
| 35 | + """ |
| 36 | + Validate the civil number |
| 37 | + """ |
| 38 | + if not id_number: |
| 39 | + return False |
| 40 | + |
| 41 | + if not isinstance(id_number, str): |
| 42 | + id_number = repr(id_number) |
| 43 | + return PersonalNumber.parse(id_number) is not None |
| 44 | + |
| 45 | + @staticmethod |
| 46 | + def parse(id_number: str) -> Optional[ParseResult]: |
| 47 | + """ |
| 48 | + parse the id number |
| 49 | + """ |
| 50 | + match_obj = PersonalNumber.METADATA.regexp.match(id_number) |
| 51 | + if not match_obj: |
| 52 | + return None |
| 53 | + |
| 54 | + # TODO: find and implement checksum |
| 55 | + return { |
| 56 | + 'yymm': match_obj.group('yymm'), |
| 57 | + 'sn': match_obj.group('sn'), |
| 58 | + 'checksum': int(match_obj.group('checksum')) |
| 59 | + } |
| 60 | + |
| 61 | + |
| 62 | +NationalID = PersonalNumber |
| 63 | +"""alias of PersonalNumber""" |
0 commit comments