[MERGE] forward port of branch saas-4 up to f68c835
[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
33 class partner_vat_intra(osv.osv_memory):
34     """
35     Partner Vat Intra
36     """
37     _name = "partner.vat.intra"
38     _description = 'Partner VAT Intra'
39
40     def _get_xml_data(self, cr, uid, context=None):
41         if context.get('file_save', False):
42             return base64.encodestring(context['file_save'].encode('utf8'))
43         return ''
44
45     def _get_europe_country(self, cursor, user, context=None):
46         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'])])
47
48     _columns = {
49         'name': fields.char('File Name', size=32),
50         '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
51       PP can stand for a month: from '01' to '12'.
52       PP can stand for a trimester: '31','32','33','34'
53           The first figure means that it is a trimester,
54           The second figure identify the trimester.
55       PP can stand for a complete fiscal year: '00'.
56       YYYY stands for the year (4 positions).
57     '''
58     ),
59         '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'),
60         'tax_code_id': fields.many2one('account.tax.code', 'Company', domain=[('parent_id', '=', False)], help="Keep empty to use the user's company", required=True),
61         'test_xml': fields.boolean('Test XML file', help="Sets the XML output as test file"),
62         'mand_id' : fields.char('Reference', size=14, help="Reference given by the Representative of the sending company."),
63         'msg': fields.text('File created', size=14, readonly=True),
64         '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."),
65         'file_save' : fields.binary('Save File', readonly=True),
66         'country_ids': fields.many2many('res.country', 'vat_country_rel', 'vat_id', 'country_id', 'European Countries'),
67         'comments': fields.text('Comments'),
68         }
69
70     def _get_tax_code(self, cr, uid, context=None):
71         obj_tax_code = self.pool.get('account.tax.code')
72         obj_user = self.pool.get('res.users')
73         company_id = obj_user.browse(cr, uid, uid, context=context).company_id.id
74         tax_code_ids = obj_tax_code.search(cr, uid, [('company_id', '=', company_id), ('parent_id', '=', False)], context=context)
75         return tax_code_ids and tax_code_ids[0] or False
76
77     _defaults = {
78         'country_ids': _get_europe_country,
79         'file_save': _get_xml_data,
80         'name': 'vat_intra.xml',
81         'tax_code_id': _get_tax_code,
82     }
83
84     def _get_datas(self, cr, uid, ids, context=None):
85         """Collects require data for vat intra xml
86         :param ids: id of wizard.
87         :return: dict of all data to be used to generate xml for Partner VAT Intra.
88         :rtype: dict
89         """
90         if context is None:
91             context = {}
92
93         obj_user = self.pool.get('res.users')
94         obj_sequence = self.pool.get('ir.sequence')
95         obj_partner = self.pool.get('res.partner')
96
97         xmldict = {}
98         post_code = street = city = country = data_clientinfo = ''
99         seq = amount_sum = 0
100
101         wiz_data = self.browse(cr, uid, ids[0], context=context)
102         comments = wiz_data.comments
103
104         if wiz_data.tax_code_id:
105             data_company = wiz_data.tax_code_id.company_id
106         else:
107             data_company = obj_user.browse(cr, uid, uid, context=context).company_id
108
109         # Get Company vat
110         company_vat = data_company.partner_id.vat
111         if not company_vat:
112             raise osv.except_osv(_('Insufficient Data!'),_('No VAT number associated with your company.'))
113         company_vat = company_vat.replace(' ','').upper()
114         issued_by = company_vat[:2]
115
116         if len(wiz_data.period_code) != 6:
117             raise osv.except_osv(_('Error!'), _('Period code is not valid.'))
118
119         if not wiz_data.period_ids:
120             raise osv.except_osv(_('Insufficient Data!'),_('Please select at least one Period.'))
121
122         p_id_list = obj_partner.search(cr, uid, [('vat','!=',False)], context=context)
123         if not p_id_list:
124             raise osv.except_osv(_('Insufficient Data!'),_('No partner has a VAT number associated with him.'))
125
126         seq_declarantnum = obj_sequence.get(cr, uid, 'declarantnum')
127         dnum = company_vat[2:] + seq_declarantnum[-4:]
128
129         addr = obj_partner.address_get(cr, uid, [data_company.partner_id.id], ['invoice'])
130         email = data_company.partner_id.email or ''
131         phone = data_company.partner_id.phone or ''
132
133         if addr.get('invoice',False):
134             ads = obj_partner.browse(cr, uid, [addr['invoice']])[0]
135             city = (ads.city or '')
136             post_code = (ads.zip or '')
137             if ads.street:
138                 street = ads.street
139             if ads.street2:
140                 street += ' '
141                 street += ads.street2
142             if ads.country_id:
143                 country = ads.country_id.code
144
145         if not country:
146             country = company_vat[:2]
147         if not email:
148             raise osv.except_osv(_('Insufficient Data!'),_('No email address associated with the company.'))
149         if not phone:
150             raise osv.except_osv(_('Insufficient Data!'),_('No phone associated with the company.'))
151         xmldict.update({
152                         'company_name': data_company.name,
153                         'company_vat': company_vat,
154                         'vatnum':  company_vat[2:],
155                         'mand_id': wiz_data.mand_id,
156                         'sender_date': str(time.strftime('%Y-%m-%d')),
157                         'street': street,
158                         'city': city,
159                         'post_code': post_code,
160                         'country': country,
161                         'email': email,
162                         'phone': phone.replace('/','').replace('.','').replace('(','').replace(')','').replace(' ',''),
163                         'period': wiz_data.period_code,
164                         'clientlist': [],
165                         'comments': comments,
166                         'issued_by': issued_by,
167                         })
168         #tax code 44: services
169         #tax code 46L: normal good deliveries
170         #tax code 46T: ABC good deliveries
171         #tax code 48xxx: credite note on tax code xxx
172         codes = ('44', '46L', '46T', '48s44', '48s46L', '48s46T')
173         cr.execute('''SELECT p.name As partner_name, l.partner_id AS partner_id, p.vat AS vat,
174                       (CASE WHEN t.code = '48s44' THEN '44'
175                             WHEN t.code = '48s46L' THEN '46L'
176                             WHEN t.code = '48s46T' THEN '46T'
177                        ELSE t.code END) AS intra_code,
178                       SUM(CASE WHEN t.code in ('48s44','48s46L','48s46T') THEN -l.tax_amount ELSE l.tax_amount END) AS amount
179                       FROM account_move_line l
180                       LEFT JOIN account_tax_code t ON (l.tax_code_id = t.id)
181                       LEFT JOIN res_partner p ON (l.partner_id = p.id)
182                       WHERE t.code IN %s
183                        AND l.period_id IN %s
184                        AND t.company_id = %s
185                       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))
186
187         p_count = 0
188
189         for row in cr.dictfetchall():
190             if not row['vat']:
191                 row['vat'] = ''
192                 p_count += 1
193
194             seq += 1
195             amt = row['amount'] or 0.0
196             amount_sum += amt
197
198             intra_code = row['intra_code'] == '44' and 'S' or (row['intra_code'] == '46L' and 'L' or (row['intra_code'] == '46T' and 'T' or ''))
199
200             xmldict['clientlist'].append({
201                                         'partner_name': row['partner_name'],
202                                         'seq': seq,
203                                         'vatnum': row['vat'][2:].replace(' ','').upper(),
204                                         'vat': row['vat'],
205                                         'country': row['vat'][:2],
206                                         'amount': round(amt,2),
207                                         'intra_code': row['intra_code'],
208                                         'code': intra_code})
209
210         xmldict.update({'dnum': dnum, 'clientnbr': str(seq), 'amountsum': round(amount_sum,2), 'partner_wo_vat': p_count})
211         return xmldict
212
213     def create_xml(self, cursor, user, ids, context=None):
214         """Creates xml that is to be exported and sent to estate for partner vat intra.
215         :return: Value for next action.
216         :rtype: dict
217         """
218         mod_obj = self.pool.get('ir.model.data')
219         xml_data = self._get_datas(cursor, user, ids, context=context)
220         month_quarter = xml_data['period'][:2]
221         year = xml_data['period'][2:]
222         data_file = ''
223
224         # Can't we do this by etree?
225         data_head = """<?xml version="1.0" encoding="ISO-8859-1"?>
226 <ns2:IntraConsignment xmlns="http://www.minfin.fgov.be/InputCommon" xmlns:ns2="http://www.minfin.fgov.be/IntraConsignment" IntraListingsNbr="1">
227     <ns2:Representative>
228         <RepresentativeID identificationType="NVAT" issuedBy="%(issued_by)s">%(vatnum)s</RepresentativeID>
229         <Name>%(company_name)s</Name>
230         <Street>%(street)s</Street>
231         <PostCode>%(post_code)s</PostCode>
232         <City>%(city)s</City>
233         <CountryCode>%(country)s</CountryCode>
234         <EmailAddress>%(email)s</EmailAddress>
235         <Phone>%(phone)s</Phone>
236     </ns2:Representative>""" % (xml_data)
237         if xml_data['mand_id']:
238             data_head += '\n\t\t<ns2:RepresentativeReference>%(mand_id)s</ns2:RepresentativeReference>' % (xml_data)
239         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)
240         if month_quarter.startswith('3'):
241             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>'
242         elif month_quarter.startswith('0') and month_quarter.endswith('0'):
243             data_comp_period+= '\n\t\t<ns2:Period>\n\t\t\t<ns2:Year>'+year+'</ns2:Year>\n\t\t</ns2:Period>'
244         else:
245             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>'
246
247         data_clientinfo = ''
248         for client in xml_data['clientlist']:
249             if not client['vatnum']:
250                 raise osv.except_osv(_('Insufficient Data!'),_('No vat number defined for %s.') % client['partner_name'])
251             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)
252
253         data_decl = '\n\t<ns2:IntraListing SequenceNumber="1" ClientsNbr="%(clientnbr)s" DeclarantReference="%(dnum)s" AmountSum="%(amountsum).2f">' % (xml_data)
254
255         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)
256         context['file_save'] = data_file
257
258         model_data_ids = mod_obj.search(cursor, user,[('model','=','ir.ui.view'),('name','=','view_vat_intra_save')], context=context)
259         resource_id = mod_obj.read(cursor, user, model_data_ids, fields=['res_id'], context=context)[0]['res_id']
260
261         return {
262             'name': _('Save'),
263             'context': context,
264             'view_type': 'form',
265             'view_mode': 'form',
266             'res_model': 'partner.vat.intra',
267             'views': [(resource_id,'form')],
268             'view_id': 'view_vat_intra_save',
269             'type': 'ir.actions.act_window',
270             'target': 'new',
271         }
272
273     def preview(self, cr, uid, ids, context=None):
274         xml_data = self._get_datas(cr, uid, ids, context=context)
275         datas = {
276              'ids': [],
277              'model': 'partner.vat.intra',
278              'form': xml_data
279         }
280         return self.pool['report'].get_action(
281             cr, uid, [], 'l10n_be.report_l10nvatintraprint', data=datas, context=context
282         )
283
284
285 class vat_intra_print(report_sxw.rml_parse):
286     def __init__(self, cr, uid, name, context):
287         super(vat_intra_print, self).__init__(cr, uid, name, context=context)
288         self.localcontext.update({
289             'time': time,
290         })
291
292
293 class wrapped_vat_intra_print(osv.AbstractModel):
294     _name = 'report.l10n_be.report_l10nvatintraprint'
295     _inherit = 'report.abstract_report'
296     _template = 'l10n_be.report_l10nvatintraprint'
297     _wrapped_report_class = vat_intra_print
298
299 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: