Arthur de Jong

Open Source / Free Software developer

summaryrefslogtreecommitdiffstats
path: root/stdnum/es/cups.py
blob: 5aa847a4b08d31646bbba9c7b30eefebdf09896a (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
# cups.py - functions for handling Spanish CUPS code
# coding: utf-8
#
# Copyright (C) 2016 David García Garzón
# Copyright (C) 2016 Arthur de Jong
#
# 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

"""CUPS (Código Unificado de Punto de Suministro, Supply Point Unified Code)

CUPS codes are used in Spain as unique identifier for energy supply points.
They are used both for electricity and pipelined gas.

The format is set by the Energy Ministry, and individual codes are issued by
each local distribution company. The number consist or 20 or 22 digits and is
built up as follows:

* LL: (letters) country (always 'ES' since it is a national code)
* DDDD: (numbers) distribution company code (numeric)
* CCCC CCCC CCCC: identifier within the distribution company (numeric)
* EE: (letters) check digits
* N: (number) border point sequence
* T: (letter) kind of border point

More information:

* https://es.wikipedia.org/wiki/Código_Unificado_de_Punto_de_Suministro

>>> validate('ES 1234-123456789012-JY')
'ES1234123456789012JY'
>>> validate('ES 1234-123456789012-JY 1T')
Traceback (most recent call last):
    ...
InvalidFormat: ...
>>> validate('ES 1234-123456789012-XY 1F')
Traceback (most recent call last):
    ...
InvalidChecksum: ...
>>> format('ES1234123456789012JY1F')
'ES 1234 1234 5678 9012 JY 1F'
"""

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


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


def format(number):
    """Reformat the passed number to the standard format."""
    number = compact(number)
    return ' '.join((
        number[:2],
        number[2:6],
        number[6:10],
        number[10:14],
        number[14:18],
        number[18:20],
        number[20:],
        )).strip()


def calc_check_digits(number):
    """Calculate the check digits for the number."""
    alphabet = 'TRWAGMYFPDXBNJZSQVHLCKE'
    check0, check1 = divmod(int(number[2:18]) % 529, 23)
    return alphabet[check0] + alphabet[check1]


def validate(number):
    """Check to see if the number provided is a valid CUPS. This checks
    length, formatting and check digits."""
    number = compact(number)
    if len(number) not in (20, 22):
        raise InvalidLength()
    if number[:2] != 'ES':
        raise InvalidComponent()
    if not number[2:18].isdigit():
        raise InvalidFormat()
    if number[20:]:
        pnumber, ptype = number[20:]
        if not pnumber.isdigit():
            raise InvalidFormat()
        if ptype not in 'FPRCXYZ':
            raise InvalidFormat()
    if calc_check_digits(number) != number[18:20]:
        raise InvalidChecksum()
    return number


def is_valid(number):
    """Check to see if the number provided is a valid CUPS."""
    try:
        return bool(validate(number))
    except ValidationError:
        return False