d61af532ce9fde389dc2c12f81446d11d6b98d85
[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 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (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 Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21 import time
22 import base64
23
24 from osv import osv, fields
25 from tools.translate import _
26 from report import report_sxw
27
28 class partner_vat_intra(osv.osv_memory):
29     """
30     Partner Vat Intra
31     """
32     _name = "partner.vat.intra"
33     _description = 'Partner VAT Intra'
34
35     def _get_xml_data(self, cr, uid, context=None):
36         if context.get('file_save', False):
37             return base64.encodestring(context['file_save'].encode('utf8'))
38         return ''
39
40     def _get_europe_country(self, cursor, user, context=None):
41         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'])])
42
43     _columns = {
44         'name': fields.char('File Name', size=32),
45         '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
46       PP can stand for a month: from '01' to '12'.
47       PP can stand for a trimester: '31','32','33','34'
48           The first figure means that it is a trimester,
49           The second figure identify the trimester.
50       PP can stand for a complete fiscal year: '00'.
51       YYYY stands for the year (4 positions).
52     '''
53     ),
54         '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'),
55         'tax_code_id': fields.many2one('account.tax.code', 'Tax Code', domain=[('parent_id', '=', False)]),
56         'test_xml': fields.boolean('Test XML file', help="Sets the XML output as test file"),
57         'mand_id' : fields.char('MandataireId', size=14, required=True,  help="This identifies the representative of the sending company. This is a string of 14 characters"),
58         'msg': fields.text('File created', size=14, readonly=True),
59         'no_vat': fields.text('Partner With No VAT', size=14, readonly=True, help="The Partner whose VAT number is not defined they doesn't include in XML File."),
60         'file_save' : fields.binary('Save File', readonly=True),
61         'country_ids': fields.many2many('res.country', 'vat_country_rel', 'vat_id', 'country_id', 'European Countries'),
62         }
63
64     _defaults = {
65         'country_ids': _get_europe_country,
66         'file_save': _get_xml_data,
67         'name': 'vat_Intra.xml',
68     }
69
70     def _get_datas(self, cr, uid, ids, context=None):
71         """Collects require data for vat intra xml
72         :param ids: id of wizard.
73         :return: dict of all data to be used to generate xml for Partner VAT Intra.
74         :rtype: dict
75         """
76         if context is None:
77             context = {}
78
79         obj_user = self.pool.get('res.users')
80         obj_sequence = self.pool.get('ir.sequence')
81         obj_partner = self.pool.get('res.partner')
82         obj_partner_add = self.pool.get('res.partner.address')
83
84         xmldict = {}
85         street = zip_city = country = p_list = data_clientinfo = ''
86         seq = amount_sum = 0
87
88         wiz_data = self.browse(cr, uid, ids[0], context=context)
89
90         if wiz_data.tax_code_id:
91             data_cmpny = wiz_data.tax_code_id.company_id
92         else:
93             data_cmpny = obj_user.browse(cr, uid, uid, context=context).company_id
94
95         # Get Company vat
96         company_vat = data_cmpny.partner_id.vat
97         if not company_vat:
98             raise osv.except_osv(_('Data Insufficient'),_('No VAT Number Associated with Main Company!'))
99         company_vat = company_vat.replace(' ','').upper()
100
101         if len(wiz_data.period_code) != 6:
102             raise osv.except_osv(_('Wrong Period Code'), _('The period code you entered is not valid.'))
103
104         if not wiz_data.period_ids:
105             raise osv.except_osv(_('Data Insufficient!'),_('Please select at least one Period.'))
106
107         p_id_list = obj_partner.search(cr, uid, [('vat','!=',False)], context=context)
108         if not p_id_list:
109             raise osv.except_osv(_('Data Insufficient!'),_('No partner has a VAT Number asociated with him.'))
110
111         seq_controlref = obj_sequence.get(cr, uid, 'controlref')
112         seq_declarantnum = obj_sequence.get(cr, uid, 'declarantnum')
113         cref = company_vat[2:] + seq_controlref[-4:]
114         dnum = cref + seq_declarantnum[-5:]
115
116         addr = obj_partner.address_get(cr, uid, [data_cmpny.partner_id.id], ['invoice'])
117         if addr.get('invoice',False):
118             ads = obj_partner_add.browse(cr, uid, [addr['invoice']])[0]
119             zip_city = (ads.city or '') + ' ' + (ads.zip or '')
120             if zip_city== ' ':
121                 zip_city = ''
122             if ads.street:
123                 street = ads.street
124             if ads.street2:
125                 street += ' '
126                 street += ads.street2
127             if ads.country_id:
128                 country = ads.country_id.code
129
130         xmldict.update({
131                         'company_name': data_cmpny.name,
132                         'company_vat': company_vat, 
133                         'vatnum':  company_vat[2:],
134                         'controlref': seq_controlref,
135                         'cref': cref, 
136                         'mand_id': wiz_data.mand_id, 
137                         'sender_date': str(time.strftime('%Y-%m-%d')),
138                         'street': street,
139                         'zip_city': zip_city,
140                         'country': country,
141                         'period': wiz_data.period_code,
142                         'clientlist': []
143                         })
144         
145         codes = ('44', '46L', '46T')
146         cr.execute('''SELECT p.name As partner_name, l.partner_id AS partner_id, p.vat AS vat, t.code AS intra_code, SUM(l.tax_amount) AS amount
147                       FROM account_move_line l
148                       LEFT JOIN account_tax_code t ON (l.tax_code_id = t.id)
149                       LEFT JOIN res_partner p ON (l.partner_id = p.id)
150                       WHERE t.code IN %s
151                        AND l.period_id IN %s
152                       GROUP BY p.name, l.partner_id, p.vat, t.code''', (codes, tuple([p.id for p in wiz_data.period_ids])))            
153
154         p_count = 0
155         for row in cr.dictfetchall():
156             if not row['vat']:
157                 p_list += str(row['partner_name']) + ', '
158                 p_count += 1
159                 continue
160
161             seq += 1
162             amt = row['amount'] or 0
163             amt = int(round(amt * 100))
164             amount_sum += amt
165
166             intra_code = row['intra_code'] == '44' and 'S' or (row['intra_code'] == '46L' and 'L' or (row['intra_code'] == '46T' and 'T' or ''))
167 #            intra_code = row['intra_code'] == '88' and 'L' or (row['intra_code'] == '44b' and 'T' or (row['intra_code'] == '44a' and 'S' or ''))
168
169             xmldict['clientlist'].append({
170                                         'partner_name': row['partner_name'],
171                                         'seq': seq, 
172                                         'vatnum': row['vat'][2:].replace(' ','').upper(), 
173                                         'vat': row['vat'],
174                                         'country': row['vat'][:2],
175                                         'amount': amt,
176                                         'intra_code': row['intra_code'],
177                                         'code': intra_code})
178
179         xmldict.update({'dnum': dnum, 'clientnbr': str(seq), 'amountsum': amount_sum, 'partner_wo_vat': p_count})
180         return xmldict
181
182     def create_xml(self, cursor, user, ids, context=None):
183         """Creates xml that is to be exported and sent to estate for partner vat intra.
184         :return: Value for next action.
185         :rtype: dict
186         """
187         mod_obj = self.pool.get('ir.model.data')
188         xml_data = self._get_datas(cursor, user, ids, context=context)
189         data_file = ''
190
191         # Can't we do this by etree?
192         data_head = """<?xml version="1.0"?>
193 <VatIntra xmlns="http://www.minfin.fgov.be/VatIntra" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" RecipientId="VAT-ADMIN" SenderId="%(company_vat)s" ControlRef="%(controlref)s" MandataireId="%(mand_id)s" SenderDate="%(sender_date)s" VersionTech="1.3">
194         <AgentRepr DecNumber="1">
195                 <CompanyInfo>
196                         <VATNum>%(company_vat)s</VATNum>
197                         <Name>%(company_name)s</Name>
198                         <Street>%(street)s</Street>
199                         <CityAndZipCode>%(zip_city)s</CityAndZipCode>
200                         <Country>%(country)s</Country>
201                 </CompanyInfo>
202         </AgentRepr>""" % (xml_data)
203
204         data_comp_period = '\n\t\t<CompanyInfo>\n\t\t\t<VATNum>%(vatnum)s</VATNum>\n\t\t\t<Name>%(company_name)s</Name>\n\t\t\t<Street>%(street)s</Street>\n\t\t\t<CityAndZipCode>%(zip_city)s</CityAndZipCode>\n\t\t\t<Country>%(country)s</Country>\n\t\t</CompanyInfo>\n\t\t<Period>%(period)s</Period>' % (xml_data)
205
206         data_clientinfo = ''
207         for client in xml_data['clientlist']:
208             data_clientinfo +='\n\t\t<ClientList SequenceNum="%(seq)s">\n\t\t\t<CompanyInfo>\n\t\t\t\t<VATNum>%(vatnum)s</VATNum>\n\t\t\t\t<Country>%(country)s</Country>\n\t\t\t</CompanyInfo>\n\t\t\t<Amount>%(amount)s</Amount>\n\t\t\t<Code>%(code)s</Code>\n\t\t</ClientList>' % (client)
209
210         data_decl = '\n\t<DeclarantList SequenceNum="1" DeclarantNum="%(dnum)s" ClientNbr="%(clientnbr)s" AmountSum="%(amountsum)s" >' % (xml_data)
211
212         data_file += data_head + data_decl + data_comp_period + data_clientinfo + '\n\t</DeclarantList>\n</VatIntra>'
213         context['file_save'] = data_file
214
215         model_data_ids = mod_obj.search(cursor, user,[('model','=','ir.ui.view'),('name','=','view_vat_intra_save')], context=context)
216         resource_id = mod_obj.read(cursor, user, model_data_ids, fields=['res_id'], context=context)[0]['res_id']
217
218         return {
219             'name': _('Save'),
220             'context': context,
221             'view_type': 'form',
222             'view_mode': 'form',
223             'res_model': 'partner.vat.intra',
224             'views': [(resource_id,'form')],
225             'view_id': 'view_vat_intra_save',
226             'type': 'ir.actions.act_window',
227             'target': 'new',
228         }
229
230     def preview(self, cr, uid, ids, context=None):
231         xml_data = self._get_datas(cr, uid, ids, context=context)
232         datas = {
233              'ids': [],
234              'model': 'partner.vat.intra',
235              'form': xml_data
236         }
237         return {
238             'type': 'ir.actions.report.xml',
239             'report_name': 'partner.vat.intra.print',
240             'datas': datas,
241         }
242
243
244 partner_vat_intra()
245
246
247 class vat_intra_print(report_sxw.rml_parse):
248     def __init__(self, cr, uid, name, context):
249         super(vat_intra_print, self).__init__(cr, uid, name, context=context)
250         self.localcontext.update({
251             'time': time,
252         })
253         
254 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)
255
256
257 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: