Arthur de Jong

Open Source / Free Software developer

summaryrefslogtreecommitdiffstats
path: root/stdnum/be/nn.py
blob: fd6c6273d38b36d04483e53dc9677e0d30e12e56 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# coding=utf-8
# nn.py - function for handling Belgian national numbers
#
# Copyright (C) 2021-2022 Cédric Krier
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA

"""NN, NISS, RRN (Belgian national number).

The national registration number (Rijksregisternummer, Numéro de registre
national, Nationalregisternummer) is a unique identification number of
natural persons who are registered in Belgium.

The number consists of 11 digits and includes the person's date of birth and
gender. It encodes the date of birth in the first 6 digits in the format
YYMMDD. The following 3 digits represent a counter of people born on the same
date, seperated by sex (odd for male and even for females respectively). The
final 2 digits form a check number based on the 9 preceding digits.

More information:

* https://nl.wikipedia.org/wiki/Rijksregisternummer
* https://fr.wikipedia.org/wiki/Numéro_de_registre_national

>>> compact('85.07.30-033 28')
'85073003328'
>>> validate('85 07 30 033 28')
'85073003328'
>>> validate('17 07 30 033 84')
'17073003384'
>>> validate('12345678901')
Traceback (most recent call last):
    ...
InvalidChecksum: ...
>>> format('85073003328')
'85.07.30-033.28'
>>> get_birth_date('85.07.30-033 28')
datetime.date(1985, 7, 30)
>>> get_gender('85.07.30-033 28')
'M'
"""

import datetime

from stdnum.exceptions import *
from stdnum.util import clean, isdigits


def compact(number):
    """Convert the number to the minimal representation. This strips the number
    of any valid separators and removes surrounding whitespace."""
    number = clean(number, ' -.').strip()
    return number


def _checksum(number):
    """Calculate the checksum and return the detected century."""
    numbers = [number]
    if int(number[:2]) + 2000 <= datetime.date.today().year:
        numbers.append('2' + number)
    for century, n in zip((19, 20), numbers):
        if 97 - (int(n[:-2]) % 97) == int(n[-2:]):
            return century
    return False


def validate(number):
    """Check if the number is a valid National Number."""
    number = compact(number)
    if not isdigits(number) or int(number) <= 0:
        raise InvalidFormat()
    if len(number) != 11:
        raise InvalidLength()
    if not _checksum(number):
        raise InvalidChecksum()
    return number


def is_valid(number):
    """Check if the number is a valid National Number."""
    try:
        return bool(validate(number))
    except ValidationError:
        return False


def format(number):
    """Reformat the number to the standard presentation format."""
    number = compact(number)
    return (
        '.'.join(number[i:i + 2] for i in range(0, 6, 2)) +
        '-' + '.'.join([number[6:9], number[9:11]]))


def get_birth_date(number):
    """Return the date of birth."""
    number = compact(number)
    century = _checksum(number)
    if not century:
        raise InvalidChecksum()
    try:
        return datetime.datetime.strptime(
            str(century) + number[:6], '%Y%m%d').date()
    except ValueError:
        raise InvalidComponent()


def get_gender(number):
    """Get the person's gender ('M' or 'F')."""
    number = compact(number)
    if int(number[6:9]) % 2:
        return 'M'
    return 'F'