Launchpad automatic translations update.
[odoo/odoo.git] / addons / base_vat / base_vat.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2011 OpenERP SA (<http://openerp.com>)
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU General Public License as published by
9 #    the Free Software Foundation, either version 3 of the License, or
10 #    (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU General Public License for more details.
16 #
17 #    You should have received a copy of the GNU General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 import logging
23 import string
24 import datetime
25 import re
26 _logger = logging.getLogger(__name__)
27
28 try:
29     import vatnumber
30 except ImportError:
31     _logger.warning("VAT validation partially unavailable because the `vatnumber` Python library cannot be found. "
32                                           "Install it to support more countries, for example with `easy_install vatnumber`.")
33     vatnumber = None
34
35 from osv import osv, fields
36 from tools.misc import ustr
37 from tools.translate import _
38
39 _ref_vat = {
40     'at': 'ATU12345675',
41     'be': 'BE0477472701',
42     'bg': 'BG1234567892',
43     'ch': 'CHE-123.456.788 TVA or CH TVA 123456', #Swiss by Yannick Vaucher @ Camptocamp
44     'cy': 'CY12345678F',
45     'cz': 'CZ12345679',
46     'de': 'DE123456788',
47     'dk': 'DK12345674',
48     'ee': 'EE123456780',
49     'el': 'EL12345670',
50     'es': 'ESA12345674',
51     'fi': 'FI12345671',
52     'fr': 'FR32123456789',
53     'gb': 'GB123456782',
54     'gr': 'GR12345670',
55     'hu': 'HU12345676',
56     'hr': 'HR01234567896', # Croatia, contributed by Milan Tribuson 
57     'ie': 'IE1234567T',
58     'it': 'IT12345670017',
59     'lt': 'LT123456715',
60     'lu': 'LU12345613',
61     'lv': 'LV41234567891',
62     'mt': 'MT12345634',
63     'mx': 'MXABC123456T1B',
64     'nl': 'NL123456782B90',
65     'no': 'NO123456785',
66     'pl': 'PL1234567883',
67     'pt': 'PT123456789',
68     'ro': 'RO1234567897',
69     'se': 'SE123456789701',
70     'si': 'SI12345679',
71     'sk': 'SK0012345675',
72 }
73
74 class res_partner(osv.osv):
75     _inherit = 'res.partner'
76
77     def _split_vat(self, vat):
78         vat_country, vat_number = vat[:2].lower(), vat[2:].replace(' ', '')
79         return vat_country, vat_number
80
81     def simple_vat_check(self, cr, uid, country_code, vat_number, context=None):
82         '''
83         Check the VAT number depending of the country.
84         http://sima-pc.com/nif.php
85         '''
86         check_func_name = 'check_vat_' + country_code
87         check_func = getattr(self, check_func_name, None) or \
88                         getattr(vatnumber, check_func_name, None)
89         if not check_func:
90             # No VAT validation available, default to check that the country code exists
91             res_country = self.pool.get('res.country')
92             return bool(res_country.search(cr, uid, [('code', '=ilike', country_code)], context=context))
93         return check_func(vat_number)
94
95     def vies_vat_check(self, cr, uid, country_code, vat_number, context=None):
96         try:
97             # Validate against  VAT Information Exchange System (VIES)
98             # see also http://ec.europa.eu/taxation_customs/vies/
99             return vatnumber.check_vies(country_code.upper()+vat_number)
100         except Exception:
101             # see http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl
102             # Fault code may contain INVALID_INPUT, SERVICE_UNAVAILABLE, MS_UNAVAILABLE,
103             # TIMEOUT or SERVER_BUSY. There is no way we can validate the input
104             # with VIES if any of these arise, including the first one (it means invalid
105             # country code or empty VAT number), so we fall back to the simple check.
106             return self.simple_vat_check(cr, uid, country_code, vat_number, context=context)
107
108     def button_check_vat(self, cr, uid, ids, context=None):
109         if not self.check_vat(cr, uid, ids, context=context):
110             msg = self._construct_constraint_msg(cr, uid, ids, context=context)
111             raise osv.except_osv(_('Error!'), msg)
112         return True
113
114     def check_vat(self, cr, uid, ids, context=None):
115         user_company = self.pool.get('res.users').browse(cr, uid, uid).company_id
116         if user_company.vat_check_vies:
117             # force full VIES online check
118             check_func = self.vies_vat_check
119         else:
120             # quick and partial off-line checksum validation
121             check_func = self.simple_vat_check
122         for partner in self.browse(cr, uid, ids, context=context):
123             if not partner.vat:
124                 continue
125             vat_country, vat_number = self._split_vat(partner.vat)
126             if not check_func(cr, uid, vat_country, vat_number, context=context):
127                 return False
128         return True
129
130     def vat_change(self, cr, uid, ids, value, context=None):
131         return {'value': {'vat_subjected': bool(value)}}
132
133     _columns = {
134         'vat_subjected': fields.boolean('VAT Legal Statement', help="Check this box if the partner is subjected to the VAT. It will be used for the VAT legal statement.")
135     }
136
137     def _construct_constraint_msg(self, cr, uid, ids, context=None):
138         def default_vat_check(cn, vn):
139             # by default, a VAT number is valid if:
140             #  it starts with 2 letters
141             #  has more than 3 characters
142             return cn[0] in string.ascii_lowercase and cn[1] in string.ascii_lowercase
143         vat_country, vat_number = self._split_vat(self.browse(cr, uid, ids)[0].vat)
144         vat_no = "'CC##' (CC=Country Code, ##=VAT Number)"
145         if default_vat_check(vat_country, vat_number):
146             vat_no = _ref_vat[vat_country] if vat_country in _ref_vat else vat_no
147         return '\n' + _('This VAT number does not seem to be valid.\nNote: the expected format is %s') % vat_no
148
149     _constraints = [(check_vat, _construct_constraint_msg, ["vat"])]
150
151
152     __check_vat_ch_re1 = re.compile(r'(MWST|TVA|IVA)[0-9]{6}$')
153     __check_vat_ch_re2 = re.compile(r'E([0-9]{9}|-[0-9]{3}\.[0-9]{3}\.[0-9]{3})(MWST|TVA|IVA)$')
154
155     def check_vat_ch(self, vat):
156         '''
157         Check Switzerland VAT number.
158         '''
159         # VAT number in Switzerland will change between 2011 and 2013 
160         # http://www.estv.admin.ch/mwst/themen/00154/00589/01107/index.html?lang=fr
161         # Old format is "TVA 123456" we will admit the user has to enter ch before the number
162         # Format will becomes such as "CHE-999.999.99C TVA"
163         # Both old and new format will be accepted till end of 2013
164         # Accepted format are: (spaces are ignored)
165         #     CH TVA ######
166         #     CH IVA ######
167         #     CH MWST #######
168         #
169         #     CHE#########MWST
170         #     CHE#########TVA
171         #     CHE#########IVA
172         #     CHE-###.###.### MWST
173         #     CHE-###.###.### TVA
174         #     CHE-###.###.### IVA
175         #     
176         if self.__check_vat_ch_re1.match(vat):
177             return True
178         match = self.__check_vat_ch_re2.match(vat) 
179         if match:
180             # For new TVA numbers, do a mod11 check
181             num = filter(lambda s: s.isdigit(), match.group(1))        # get the digits only
182             factor = (5,4,3,2,7,6,5,4)
183             csum = sum([int(num[i]) * factor[i] for i in range(8)])
184             check = 11 - (csum % 11)
185             return check == int(num[8])
186         return False
187
188
189     # Mexican VAT verification, contributed by <moylop260@hotmail.com>
190     # and Panos Christeas <p_christ@hol.gr>
191     __check_vat_mx_re = re.compile(r"(?P<primeras>[A-Za-z\xd1\xf1&]{3,4})" \
192                                     r"[ \-_]?" \
193                                     r"(?P<ano>[0-9]{2})(?P<mes>[01][0-9])(?P<dia>[0-3][0-9])" \
194                                     r"[ \-_]?" \
195                                     r"(?P<code>[A-Za-z0-9&\xd1\xf1]{3})$")
196     def check_vat_mx(self, vat):
197         ''' Mexican VAT verification
198
199         Verificar RFC México
200         '''
201         # we convert to 8-bit encoding, to help the regex parse only bytes
202         vat = ustr(vat).encode('iso8859-1')
203         m = self.__check_vat_mx_re.match(vat)
204         if not m:
205             #No valid format
206             return False
207         try:
208             ano = int(m.group('ano'))
209             if ano > 30:
210                 ano = 1900 + ano
211             else:
212                 ano = 2000 + ano
213             datetime.date(ano, int(m.group('mes')), int(m.group('dia')))
214         except ValueError:
215             return False
216
217         #Valid format and valid date
218         return True
219
220
221     # Norway VAT validation, contributed by Rolv Råen (adEgo) <rora@adego.no>
222     def check_vat_no(self, vat):
223         '''
224         Check Norway VAT number.See http://www.brreg.no/english/coordination/number.html
225         '''
226         if len(vat) != 9:
227             return False
228         try:
229             int(vat)
230         except ValueError:
231             return False
232
233         sum = (3 * int(vat[0])) + (2 * int(vat[1])) + \
234             (7 * int(vat[2])) + (6 * int(vat[3])) + \
235             (5 * int(vat[4])) + (4 * int(vat[5])) + \
236             (3 * int(vat[6])) + (2 * int(vat[7]))
237
238         check = 11 -(sum % 11)
239         if check == 11:
240             check = 0
241         if check == 10:
242             # 10 is not a valid check digit for an organization number
243             return False
244         return check == int(vat[8])
245
246 res_partner()
247
248 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: