ff86a6ba21e92f19a6b2353e411cca0e1e11d6d1
[odoo/odoo.git] / addons / l10n_be / wizard / l10n_be_vat_intra.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
7 #    Adapted by Noviat to
8 #     - make the 'mand_id' field optional
9 #     - support Noviat tax code scheme
10 #
11 #    This program is free software: you can redistribute it and/or modify
12 #    it under the terms of the GNU Affero General Public License as
13 #    published by the Free Software Foundation, either version 3 of the
14 #    License, or (at your option) any later version.
15 #
16 #    This program is distributed in the hope that it will be useful,
17 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
18 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 #    GNU Affero General Public License for more details.
20 #
21 #    You should have received a copy of the GNU Affero General Public License
22 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 #
24 ##############################################################################
25 import time
26 import base64
27
28 from openerp.osv import fields, osv
29 from openerp.tools.translate import _
30 from openerp.report import report_sxw
31
32 class partner_vat_intra(osv.osv_memory):
33     """
34     Partner Vat Intra
35     """
36     _name = "partner.vat.intra"
37     _description = 'Partner VAT Intra'
38
39     def _get_xml_data(self, cr, uid, context=None):
40         if context.get('file_save', False):
41             return base64.encodestring(context['file_save'].encode('utf8'))
42         return ''
43
44     def _get_europe_country(self, cursor, user, context=None):
45         return self.pool.get('res.country').search(cursor, user, [('code', 'in', ['AT', 'BG', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'GB'])])
46
47     _columns = {
48         'name': fields.char('File Name', size=32),
49         'period_code': fields.char('Period Code',size = 6,required = True, help = '''This is where you have to set the period code for the intracom declaration using the format: ppyyyy
50       PP can stand for a month: from '01' to '12'.
51       PP can stand for a trimester: '31','32','33','34'
52           The first figure means that it is a trimester,
53           The second figure identify the trimester.
54       PP can stand for a complete fiscal year: '00'.
55       YYYY stands for the year (4 positions).
56     '''
57     ),
58         'period_ids': fields.many2many('account.period', 'account_period_rel', 'acc_id', 'period_id', 'Period (s)', help = 'Select here the period(s) you want to include in your intracom declaration'),
59         'tax_code_id': fields.many2one('account.tax.code', 'Company', domain=[('parent_id', '=', False)], help="Keep empty to use the user's company", required=True),
60         'test_xml': fields.boolean('Test XML file', help="Sets the XML output as test file"),
61         'mand_id' : fields.char('Reference', size=14, help="Reference given by the Representative of the sending company."),
62         'msg': fields.text('File created', size=14, readonly=True),
63         'no_vat': fields.text('Partner With No VAT', size=14, readonly=True, help="The Partner whose VAT number is not defined  and they are not included in XML File."),
64         'file_save' : fields.binary('Save File', readonly=True),
65         'country_ids': fields.many2many('res.country', 'vat_country_rel', 'vat_id', 'country_id', 'European Countries'),
66         'comments': fields.text('Comments'),
67         }
68
69     def _get_tax_code(self, cr, uid, context=None):
70         obj_tax_code = self.pool.get('account.tax.code')
71         obj_user = self.pool.get('res.users')
72         company_id = obj_user.browse(cr, uid, uid, context=context).company_id.id
73         tax_code_ids = obj_tax_code.search(cr, uid, [('company_id', '=', company_id), ('parent_id', '=', False)], context=context)
74         return tax_code_ids and tax_code_ids[0] or False
75
76     _defaults = {
77         'country_ids': _get_europe_country,
78         'file_save': _get_xml_data,
79         'name': 'vat_intra.xml',
80         'tax_code_id': _get_tax_code,
81     }
82
83     def _get_datas(self, cr, uid, ids, context=None):
84         """Collects require data for vat intra xml
85         :param ids: id of wizard.
86         :return: dict of all data to be used to generate xml for Partner VAT Intra.
87         :rtype: dict
88         """
89         if context is None:
90             context = {}
91
92         obj_user = self.pool.get('res.users')
93         obj_sequence = self.pool.get('ir.sequence')
94         obj_partner = self.pool.get('res.partner')
95
96         xmldict = {}
97         post_code = street = city = country = data_clientinfo = ''
98         seq = amount_sum = 0
99
100         wiz_data = self.browse(cr, uid, ids[0], context=context)
101         comments = wiz_data.comments
102
103         if wiz_data.tax_code_id:
104             data_company = wiz_data.tax_code_id.company_id
105         else:
106             data_company = obj_user.browse(cr, uid, uid, context=context).company_id
107
108         # Get Company vat
109         company_vat = data_company.partner_id.vat
110         if not company_vat:
111             raise osv.except_osv(_('Insufficient Data!'),_('No VAT number associated with your company.'))
112         company_vat = company_vat.replace(' ','').upper()
113         issued_by = company_vat[:2]
114
115         if len(wiz_data.period_code) != 6:
116             raise osv.except_osv(_('Error!'), _('Period code is not valid.'))
117
118         if not wiz_data.period_ids:
119             raise osv.except_osv(_('Insufficient Data!'),_('Please select at least one Period.'))
120
121         p_id_list = obj_partner.search(cr, uid, [('vat','!=',False)], context=context)
122         if not p_id_list:
123             raise osv.except_osv(_('Insufficient Data!'),_('No partner has a VAT number associated with him.'))
124
125         seq_declarantnum = obj_sequence.get(cr, uid, 'declarantnum')
126         dnum = company_vat[2:] + seq_declarantnum[-4:]
127
128         addr = obj_partner.address_get(cr, uid, [data_company.partner_id.id], ['invoice'])
129         email = data_company.partner_id.email or ''
130         phone = data_company.partner_id.phone or ''
131
132         if addr.get('invoice',False):
133             ads = obj_partner.browse(cr, uid, [addr['invoice']])[0]
134             city = (ads.city or '')
135             post_code = (ads.zip or '')
136             if ads.street:
137                 street = ads.street
138             if ads.street2:
139                 street += ' '
140                 street += ads.street2
141             if ads.country_id:
142                 country = ads.country_id.code
143
144         if not country:
145             country = company_vat[:2]
146         if not email:
147             raise osv.except_osv(_('Insufficient Data!'),_('No email address associated with the company.'))
148         if not phone:
149             raise osv.except_osv(_('Insufficient Data!'),_('No phone associated with the company.'))
150         xmldict.update({
151                         'company_name': data_company.name,
152                         'company_vat': company_vat,
153                         'vatnum':  company_vat[2:],
154                         'mand_id': wiz_data.mand_id,
155                         'sender_date': str(time.strftime('%Y-%m-%d')),
156                         'street': street,
157                         'city': city,
158                         'post_code': post_code,
159                         'country': country,
160                         'email': email,
161                         'phone': phone.replace('/','').replace('.','').replace('(','').replace(')','').replace(' ',''),
162                         'period': wiz_data.period_code,
163                         'clientlist': [],
164                         'comments': comments,
165                         'issued_by': issued_by,
166                         })
167         #tax code 44: services
168         #tax code 46L: normal good deliveries
169         #tax code 46T: ABC good deliveries
170         #tax code 48xxx: credite note on tax code xxx
171         codes = ('44', '46L', '46T', '48s44', '48s46L', '48s46T')
172         cr.execute('''SELECT p.name As partner_name, l.partner_id AS partner_id, p.vat AS vat,
173                       (CASE WHEN t.code = '48s44' THEN '44'
174                             WHEN t.code = '48s46L' THEN '46L'
175                             WHEN t.code = '48s46T' THEN '46T'
176                        ELSE t.code END) AS intra_code,
177                       SUM(CASE WHEN t.code in ('48s44','48s46L','48s46T') THEN -l.tax_amount ELSE l.tax_amount END) AS amount
178                       FROM account_move_line l
179                       LEFT JOIN account_tax_code t ON (l.tax_code_id = t.id)
180                       LEFT JOIN res_partner p ON (l.partner_id = p.id)
181                       WHERE t.code IN %s
182                        AND l.period_id IN %s
183                        AND t.company_id = %s
184                       GROUP BY p.name, l.partner_id, p.vat, intra_code''', (codes, tuple([p.id for p in wiz_data.period_ids]), data_company.id))
185
186         p_count = 0
187
188         for row in cr.dictfetchall():
189             if not row['vat']:
190                 row['vat'] = ''
191                 p_count += 1
192
193             seq += 1
194             amt = row['amount'] or 0.0
195             amount_sum += amt
196
197             intra_code = row['intra_code'] == '44' and 'S' or (row['intra_code'] == '46L' and 'L' or (row['intra_code'] == '46T' and 'T' or ''))
198
199             xmldict['clientlist'].append({
200                                         'partner_name': row['partner_name'],
201                                         'seq': seq,
202                                         'vatnum': row['vat'][2:].replace(' ','').upper(),
203                                         'vat': row['vat'],
204                                         'country': row['vat'][:2],
205                                         'amount': round(amt,2),
206                                         'intra_code': row['intra_code'],
207                                         'code': intra_code})
208
209         xmldict.update({'dnum': dnum, 'clientnbr': str(seq), 'amountsum': round(amount_sum,2), 'partner_wo_vat': p_count})
210         return xmldict
211
212     def create_xml(self, cursor, user, ids, context=None):
213         """Creates xml that is to be exported and sent to estate for partner vat intra.
214         :return: Value for next action.
215         :rtype: dict
216         """
217         mod_obj = self.pool.get('ir.model.data')
218         xml_data = self._get_datas(cursor, user, ids, context=context)
219         month_quarter = xml_data['period'][:2]
220         year = xml_data['period'][2:]
221         data_file = ''
222
223         # Can't we do this by etree?
224         data_head = """<?xml version="1.0" encoding="ISO-8859-1"?>
225 <ns2:IntraConsignment xmlns="http://www.minfin.fgov.be/InputCommon" xmlns:ns2="http://www.minfin.fgov.be/IntraConsignment" IntraListingsNbr="1">
226     <ns2:Representative>
227         <RepresentativeID identificationType="NVAT" issuedBy="%(issued_by)s">%(company_vat)s</RepresentativeID>
228         <Name>%(company_name)s</Name>
229         <Street>%(street)s</Street>
230         <PostCode>%(post_code)s</PostCode>
231         <City>%(city)s</City>
232         <CountryCode>%(country)s</CountryCode>
233         <EmailAddress>%(email)s</EmailAddress>
234         <Phone>%(phone)s</Phone>
235     </ns2:Representative>""" % (xml_data)
236         if xml_data['mand_id']:
237             data_head += '\n\t\t<ns2:RepresentativeReference>%(mand_id)s</ns2:RepresentativeReference>' % (xml_data)
238         data_comp_period = '\n\t\t<ns2:Declarant>\n\t\t\t<VATNumber>%(vatnum)s</VATNumber>\n\t\t\t<Name>%(company_name)s</Name>\n\t\t\t<Street>%(street)s</Street>\n\t\t\t<PostCode>%(post_code)s</PostCode>\n\t\t\t<City>%(city)s</City>\n\t\t\t<CountryCode>%(country)s</CountryCode>\n\t\t\t<EmailAddress>%(email)s</EmailAddress>\n\t\t\t<Phone>%(phone)s</Phone>\n\t\t</ns2:Declarant>' % (xml_data)
239         if month_quarter.startswith('3'):
240             data_comp_period += '\n\t\t<ns2:Period>\n\t\t\t<ns2:Quarter>'+month_quarter[1]+'</ns2:Quarter> \n\t\t\t<ns2:Year>'+year+'</ns2:Year>\n\t\t</ns2:Period>'
241         elif month_quarter.startswith('0') and month_quarter.endswith('0'):
242             data_comp_period+= '\n\t\t<ns2:Period>\n\t\t\t<ns2:Year>'+year+'</ns2:Year>\n\t\t</ns2:Period>'
243         else:
244             data_comp_period += '\n\t\t<ns2:Period>\n\t\t\t<ns2:Month>'+month_quarter+'</ns2:Month> \n\t\t\t<ns2:Year>'+year+'</ns2:Year>\n\t\t</ns2:Period>'
245
246         data_clientinfo = ''
247         for client in xml_data['clientlist']:
248             if not client['vatnum']:
249                 raise osv.except_osv(_('Insufficient Data!'),_('No vat number defined for %s.') % client['partner_name'])
250             data_clientinfo +='\n\t\t<ns2:IntraClient SequenceNumber="%(seq)s">\n\t\t\t<ns2:CompanyVATNumber issuedBy="%(country)s">%(vatnum)s</ns2:CompanyVATNumber>\n\t\t\t<ns2:Code>%(code)s</ns2:Code>\n\t\t\t<ns2:Amount>%(amount).2f</ns2:Amount>\n\t\t</ns2:IntraClient>' % (client)
251
252         data_decl = '\n\t<ns2:IntraListing SequenceNumber="1" ClientsNbr="%(clientnbr)s" DeclarantReference="%(dnum)s" AmountSum="%(amountsum).2f">' % (xml_data)
253
254         data_file += data_head + data_decl + data_comp_period + data_clientinfo + '\n\t\t<ns2:Comment>%(comments)s</ns2:Comment>\n\t</ns2:IntraListing>\n</ns2:IntraConsignment>' % (xml_data)
255         context['file_save'] = data_file
256
257         model_data_ids = mod_obj.search(cursor, user,[('model','=','ir.ui.view'),('name','=','view_vat_intra_save')], context=context)
258         resource_id = mod_obj.read(cursor, user, model_data_ids, fields=['res_id'], context=context)[0]['res_id']
259
260         return {
261             'name': _('Save'),
262             'context': context,
263             'view_type': 'form',
264             'view_mode': 'form',
265             'res_model': 'partner.vat.intra',
266             'views': [(resource_id,'form')],
267             'view_id': 'view_vat_intra_save',
268             'type': 'ir.actions.act_window',
269             'target': 'new',
270         }
271
272     def preview(self, cr, uid, ids, context=None):
273         xml_data = self._get_datas(cr, uid, ids, context=context)
274         datas = {
275              'ids': [],
276              'model': 'partner.vat.intra',
277              'form': xml_data
278         }
279         return {
280             'type': 'ir.actions.report.xml',
281             'report_name': 'partner.vat.intra.print',
282             'datas': datas,
283         }
284
285 partner_vat_intra()
286
287 class vat_intra_print(report_sxw.rml_parse):
288     def __init__(self, cr, uid, name, context):
289         super(vat_intra_print, self).__init__(cr, uid, name, context=context)
290         self.localcontext.update({
291             'time': time,
292         })
293
294 report_sxw.report_sxw('report.partner.vat.intra.print', 'partner.vat.intra', 'addons/l10n_be/wizard/l10n_be_vat_intra_print.rml', parser=vat_intra_print, header="internal")
295
296 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: