|
| 1 | +# tin.py - functions for handling Tanzania TIN numbers |
| 2 | +# coding: utf-8 |
| 3 | +# |
| 4 | +# Copyright (C) 2023 Leandro Regueiro |
| 5 | +# |
| 6 | +# This library is free software; you can redistribute it and/or |
| 7 | +# modify it under the terms of the GNU Lesser General Public |
| 8 | +# License as published by the Free Software Foundation; either |
| 9 | +# version 2.1 of the License, or (at your option) any later version. |
| 10 | +# |
| 11 | +# This library is distributed in the hope that it will be useful, |
| 12 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 14 | +# Lesser General Public License for more details. |
| 15 | +# |
| 16 | +# You should have received a copy of the GNU Lesser General Public |
| 17 | +# License along with this library; if not, write to the Free Software |
| 18 | +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
| 19 | +# 02110-1301 USA |
| 20 | + |
| 21 | +"""TIN (Taxpayer Identification Number, or TIN namba, Tanzania tax number). |
| 22 | +
|
| 23 | +This number consists of 9 digits, usually separated into three groups |
| 24 | +using hyphens to make it easier to read, like XXX-XXX-XXX. |
| 25 | +
|
| 26 | +>>> validate('121-207-079') |
| 27 | +'121207079' |
| 28 | +>>> validate('12345') |
| 29 | +Traceback (most recent call last): |
| 30 | + ... |
| 31 | +InvalidLength: ... |
| 32 | +>>> format('121207079') |
| 33 | +'121-207-079' |
| 34 | +""" |
| 35 | + |
| 36 | +from stdnum.exceptions import * |
| 37 | +from stdnum.util import clean, isdigits |
| 38 | + |
| 39 | + |
| 40 | +def compact(number): |
| 41 | + """Convert the number to the minimal representation. |
| 42 | +
|
| 43 | + This strips the number of any valid separators and removes surrounding |
| 44 | + whitespace. |
| 45 | + """ |
| 46 | + return str(clean(number, u' -–').strip()) |
| 47 | + |
| 48 | + |
| 49 | +def validate(number): |
| 50 | + """Check if the number is a valid Tanzania TIN number. |
| 51 | +
|
| 52 | + This checks the length and formatting. |
| 53 | + """ |
| 54 | + number = compact(number) |
| 55 | + if len(number) != 9: |
| 56 | + raise InvalidLength() |
| 57 | + if not isdigits(number): |
| 58 | + raise InvalidFormat() |
| 59 | + return number |
| 60 | + |
| 61 | + |
| 62 | +def is_valid(number): |
| 63 | + """Check if the number is a valid Tanzania TIN number.""" |
| 64 | + try: |
| 65 | + return bool(validate(number)) |
| 66 | + except ValidationError: |
| 67 | + return False |
| 68 | + |
| 69 | + |
| 70 | +def format(number): |
| 71 | + """Reformat the number to the standard presentation format.""" |
| 72 | + number = compact(number) |
| 73 | + return '-'.join([number[:3], number[3:-3], number[-3:]]) |
0 commit comments