Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Panama TIN #348

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions stdnum/pa/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# __init__.py - collection of Panamanian numbers
# coding: utf-8
#
# Copyright (C) 2023 Leandro Regueiro
#
# 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

"""Collection of Panamanian numbers."""

# provide aliases
from stdnum.pa import ruc as vat # noqa: F401
165 changes: 165 additions & 0 deletions stdnum/pa/ruc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
# ruc.py - functions for handling Panama RUC numbers
# coding: utf-8
#
# Copyright (C) 2023 Leandro Regueiro
#
# 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

"""RUC (Registro Único del Contribuyente, Panama tax number).

The Registro Único del Contribuyente (RUC) is an identifier of legal entities
for tax purposes.

This number has different variants both for natural and legal persons, each
with its own structure, but basically it consists on a number of digits and
letters (only for natural persons) usually separated by hyphens (the number and
position of these varies according to the variant), then followed by a check
number (dígito verificador) consisting in up to two digits.

More information:

* https://www.oecd.org/tax/automatic-exchange/crs-implementation-and-assistance/tax-identification-numbers/Panama-TIN.pdf
* https://studylib.es/doc/545131/algoritmo-para-el-calculo-del-digito-verificador-de-la-ru

>>> validate('253-92-57027 DV 76')
'00000002530092057027DV76'
>>> validate('155587169-2-2014 D.V. 9')
'01555871690002002014DV09'
>>> validate('253-92-57027 DV 23')
Traceback (most recent call last):
...
InvalidChecksum: ...
>>> validate('12345678')
Traceback (most recent call last):
...
InvalidLength: ...
>>> format('253-92-57027 DV 76')
'0000000253-0092-057027 DV76'
""" # noqa: E501

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


ARRVAL = {
'00': '00',
'10': '01',
'11': '02',
'12': '03',
'13': '04',
'14': '05',
'15': '06',
'16': '07',
'17': '08',
'18': '09',
'19': '01',
'20': '02',
'21': '03',
'22': '04',
'23': '07',
'24': '08',
'25': '09',
'26': '02',
'27': '03',
'28': '04',
'29': '05',
'30': '06',
'31': '07',
'32': '08',
'33': '09',
'34': '01',
'35': '02',
'36': '03',
'37': '04',
'38': '05',
'39': '06',
'40': '07',
'41': '08',
'42': '09',
'43': '01',
'44': '02',
'45': '03',
'46': '04',
'47': '05',
'48': '06',
'49': '07',
}


def compact(number):
"""Convert the number to the minimal representation.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The output of this function seems to be something that does not resemble any of the formats that are used. From an initial glance it seems that the - separators are not optional but rather part of the number. The idea of the compact() and validate() return values is that they are still considered valid numbers. It appears they are considered valid identifiers in this code but it is unclear if this a normal way to represent a RUC in Panama.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought that that was the purpose of the format function, and that compact was meant to reduce the number to the minimal representation so it could be used by the rest of the functions.

The - are usually present because people omits the leading zeroes on each of the parts of the number. By ensuring those zeroes are present (using zfill) we are able to return the whole number, still being valid, without the - separators. Or at least that is my understanding of the situation.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • If you go to the online website to verify the DV (https://etax2.mef.gob.pa/etax2web/Login.aspx then go to Registro, and then to Dígito Verificador, then select Juridica in the form)
  • Then enter the values to verify 253-92-57027 it indeed returns a DV 76 and it identifies a company.
  • If then you try again adding leading zeroes it still returns the same DV, but it gives some error.

IMHO this error might happen because in their database probably the RUC are stored without the zeroes, and then the website doesn't find a match.

I have quickly checked and I didn't find any example with those leading zeroes, but we also have to keep in mind that in order for the algorithm to work it requires all those zeroes.

In other words, I don't know whether the version with the zeroes and no separators is invalid or not. What do you think?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is important that the output of the compact() (and validate()) functions result in a number in a format that is generally accepted to be valid. In this case it seems that the - separators are actually a significant part of the number and not just cosmetic like they are in most formats.

Perhaps this behaviour is nicer:

>>> ruc.compact('253-92-57027 DV 76')
'253-92-57027DV76'
>>> ruc.compact('155587169-2-2014    D.V. 9')
'155587169-2-2014DV9'
>>> ruc.compact('32812-2-249262      D.V. 63')
'32812-2-249262DV63'
>>> ruc.compact('155625946-2-2016 DV00')
'155625946-2-2016DV0''
>>> ruc.compact('00253-0092-0057027 DV 76')
'253-92-57027DV76'


This strips the number of any valid separators and removes surrounding
whitespace.
"""
parts = clean(number, ' .').strip().upper().split('-')

# We can currently only compact legal person's RUC numbers with check digit.
if len(parts) != 3 or len(parts[0]) in (1, 2) or 'DV' not in parts[2]:
return ''

parts[2], dv = parts[2].split('DV')

return ''.join([parts[0].zfill(10), parts[1].zfill(4),
parts[2].strip().zfill(6), 'DV', dv.strip().zfill(2)])


def calc_check_digit(number, is_old_legal_ruc):
"""Calculate the check digit."""
if is_old_legal_ruc:
weights = list(range(2, 12)) + list(range(11, len(number) + 1))
else:
weights = list(range(2, len(number) + 2))
total = sum(int(n) * w for w, n in zip(weights, reversed(number)))
r = total % 11
return str(11 - r) if r > 1 else '0'


def validate(number):
"""Check if the number is a valid Panama RUC number.

This checks the length, formatting and check digits.
"""
number = compact(number)
if len(number) != 24:
raise InvalidLength()
if not isdigits(number[:-4]) or not isdigits(number[-2:]):
raise InvalidComponent()
is_old_legal_ruc = number[3:6] in ('000', '001', '002', '003', '004')
if is_old_legal_ruc and number[5:7] in ARRVAL:
number = number[:5] + ARRVAL[number[5:7]] + number[7:]
dv1 = calc_check_digit(number[:-4], is_old_legal_ruc)
if number[-2] != dv1:
raise InvalidChecksum()
dv2 = calc_check_digit(number[:-4] + dv1, is_old_legal_ruc)
if number[-1] != dv2:
raise InvalidChecksum()
return number


def is_valid(number):
"""Check if the number is a valid Panama RUC 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[:10], '-', number[10:14], '-', number[14:-4], ' ',
number[-4:]])
Loading