[IMP] barcodes: use builtin python sets when it makes sense
[odoo/odoo.git] / addons / l10n_be / wizard / l10n_be_account_vat_declaration.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 #     - enforce correct vat number
9 #     - support negative balance
10 #     - assign amount of tax code 71-72 correclty to grid 71 or 72
11 #     - support Noviat tax code scheme
12 #
13 #    This program is free software: you can redistribute it and/or modify
14 #    it under the terms of the GNU Affero General Public License as
15 #    published by the Free Software Foundation, either version 3 of the
16 #    License, or (at your option) any later version.
17 #
18 #    This program is distributed in the hope that it will be useful,
19 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
20 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 #    GNU Affero General Public License for more details.
22 #
23 #    You should have received a copy of the GNU Affero General Public License
24 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
25 #
26 ##############################################################################
27 import base64
28
29 from openerp.osv import fields, osv
30 from openerp.tools.translate import _
31
32 class l10n_be_vat_declaration(osv.osv_memory):
33     """ Vat Declaration """
34     _name = "l1on_be.vat.declaration"
35     _description = "Vat Declaration"
36
37     def _get_xml_data(self, cr, uid, context=None):
38         if context.get('file_save', False):
39             return base64.encodestring(context['file_save'].encode('utf8'))
40         return ''
41
42     _columns = {
43         'name': fields.char('File Name'),
44         'period_id': fields.many2one('account.period','Period', required=True),
45         'tax_code_id': fields.many2one('account.tax.code', 'Tax Code', domain=[('parent_id', '=', False)], required=True),
46         'msg': fields.text('File created', readonly=True),
47         'file_save': fields.binary('Save File'),
48         'ask_restitution': fields.boolean('Ask Restitution',help='It indicates whether a restitution is to make or not?'),
49         'ask_payment': fields.boolean('Ask Payment',help='It indicates whether a payment is to make or not?'),
50         'client_nihil': fields.boolean('Last Declaration, no clients in client listing', help='Tick this case only if it concerns only the last statement on the civil or cessation of activity: ' \
51             'no clients to be included in the client listing.'),
52         'comments': fields.text('Comments'),
53     }
54
55     def _get_tax_code(self, cr, uid, context=None):
56         obj_tax_code = self.pool.get('account.tax.code')
57         obj_user = self.pool.get('res.users')
58         company_id = obj_user.browse(cr, uid, uid, context=context).company_id.id
59         tax_code_ids = obj_tax_code.search(cr, uid, [('company_id', '=', company_id), ('parent_id', '=', False)], context=context)
60         return tax_code_ids and tax_code_ids[0] or False
61
62     _defaults = {
63         'msg': 'Save the File with '".xml"' extension.',
64         'file_save': _get_xml_data,
65         'name': 'vat_declaration.xml',
66         'tax_code_id': _get_tax_code,
67     }
68
69     def create_xml(self, cr, uid, ids, context=None):
70         obj_tax_code = self.pool.get('account.tax.code')
71         obj_acc_period = self.pool.get('account.period')
72         obj_user = self.pool.get('res.users')
73         obj_partner = self.pool.get('res.partner')
74         mod_obj = self.pool.get('ir.model.data')
75
76         if context is None:
77             context = {}
78
79         list_of_tags = ['00','01','02','03','44','45','46','47','48','49','54','55','56','57','59','61','62','63','64','71','72','81','82','83','84','85','86','87','88','91']
80         data_tax = self.browse(cr, uid, ids[0])
81         if data_tax.tax_code_id:
82             obj_company = data_tax.tax_code_id.company_id
83         else:
84             obj_company = obj_user.browse(cr, uid, uid, context=context).company_id
85         vat_no = obj_company.partner_id.vat
86         if not vat_no:
87             raise osv.except_osv(_('Insufficient Data!'), _('No VAT number associated with your company.'))
88         vat_no = vat_no.replace(' ','').upper()
89         vat = vat_no[2:]
90
91         tax_code_ids = obj_tax_code.search(cr, uid, [('parent_id','child_of',data_tax.tax_code_id.id), ('company_id','=',obj_company.id)], context=context)
92         ctx = context.copy()
93         data  = self.read(cr, uid, ids)[0]
94         ctx['period_id'] = data['period_id'][0]
95         tax_info = obj_tax_code.read(cr, uid, tax_code_ids, ['code','sum_period'], context=ctx)
96
97         default_address = obj_partner.address_get(cr, uid, [obj_company.partner_id.id])
98         default_address_id = default_address.get("default", obj_company.partner_id.id)
99         address_id= obj_partner.browse(cr, uid, default_address_id, context)
100
101         account_period = obj_acc_period.browse(cr, uid, data['period_id'][0], context=context)
102         issued_by = vat_no[:2]
103         comments = data['comments'] or ''
104
105         send_ref = str(obj_company.partner_id.id) + str(account_period.date_start[5:7]) + str(account_period.date_stop[:4])
106
107         starting_month = account_period.date_start[5:7]
108         ending_month = account_period.date_stop[5:7]
109         quarter = str(((int(starting_month) - 1) / 3) + 1)
110
111         if not address_id.email:
112             raise osv.except_osv(_('Insufficient Data!'),_('No email address associated with the company.'))
113         if not address_id.phone:
114             raise osv.except_osv(_('Insufficient Data!'),_('No phone associated with the company.'))
115         file_data = {
116                         'issued_by': issued_by,
117                         'vat_no': vat_no,
118                         'only_vat': vat_no[2:],
119                         'cmpny_name': obj_company.name,
120                         'address': "%s %s"%(address_id.street or "",address_id.street2 or ""),
121                         'post_code': address_id.zip or "",
122                         'city': address_id.city or "",
123                         'country_code': address_id.country_id and address_id.country_id.code or "",
124                         'email': address_id.email or "",
125                         'phone': address_id.phone.replace('.','').replace('/','').replace('(','').replace(')','').replace(' ',''),
126                         'send_ref': send_ref,
127                         'quarter': quarter,
128                         'month': starting_month,
129                         'year': str(account_period.date_stop[:4]),
130                         'client_nihil': (data['client_nihil'] and 'YES' or 'NO'),
131                         'ask_restitution': (data['ask_restitution'] and 'YES' or 'NO'),
132                         'ask_payment': (data['ask_payment'] and 'YES' or 'NO'),
133                         'comments': comments,
134                      }
135
136         data_of_file = """<?xml version="1.0"?>
137 <ns2:VATConsignment xmlns="http://www.minfin.fgov.be/InputCommon" xmlns:ns2="http://www.minfin.fgov.be/VATConsignment" VATDeclarationsNbr="1">
138     <ns2:Representative>
139         <RepresentativeID identificationType="NVAT" issuedBy="%(issued_by)s">%(only_vat)s</RepresentativeID>
140         <Name>%(cmpny_name)s</Name>
141         <Street>%(address)s</Street>
142         <PostCode>%(post_code)s</PostCode>
143         <City>%(city)s</City>
144         <CountryCode>%(country_code)s</CountryCode>
145         <EmailAddress>%(email)s</EmailAddress>
146         <Phone>%(phone)s</Phone>
147     </ns2:Representative>
148     <ns2:VATDeclaration SequenceNumber="1" DeclarantReference="%(send_ref)s">
149         <ns2:Declarant>
150             <VATNumber xmlns="http://www.minfin.fgov.be/InputCommon">%(only_vat)s</VATNumber>
151             <Name>%(cmpny_name)s</Name>
152             <Street>%(address)s</Street>
153             <PostCode>%(post_code)s</PostCode>
154             <City>%(city)s</City>
155             <CountryCode>%(country_code)s</CountryCode>
156             <EmailAddress>%(email)s</EmailAddress>
157             <Phone>%(phone)s</Phone>
158         </ns2:Declarant>
159         <ns2:Period>
160     """ % (file_data)
161
162         if starting_month != ending_month:
163             #starting month and ending month of selected period are not the same
164             #it means that the accounting isn't based on periods of 1 month but on quarters
165             data_of_file += '\t\t<ns2:Quarter>%(quarter)s</ns2:Quarter>\n\t\t' % (file_data)
166         else:
167             data_of_file += '\t\t<ns2:Month>%(month)s</ns2:Month>\n\t\t' % (file_data)
168         data_of_file += '\t<ns2:Year>%(year)s</ns2:Year>' % (file_data)
169         data_of_file += '\n\t\t</ns2:Period>\n'
170         data_of_file += '\t\t<ns2:Data>\t'
171         cases_list = []
172         for item in tax_info:
173             if item['code'] == '91' and ending_month != 12:
174                 #the tax code 91 can only be send for the declaration of December
175                 continue
176             if item['code'] and item['sum_period']:
177                 if item['code'] == 'VI':
178                     if item['sum_period'] >= 0:
179                         item['code'] = '71'
180                     else:
181                         item['code'] = '72'
182                 if item['code'] in list_of_tags:
183                     cases_list.append(item)
184         cases_list.sort()
185         for item in cases_list:
186             grid_amount_data = {
187                     'code': str(int(item['code'])),
188                     'amount': '%.2f' % abs(item['sum_period']),
189                     }
190             data_of_file += '\n\t\t\t<ns2:Amount GridNumber="%(code)s">%(amount)s</ns2:Amount''>' % (grid_amount_data)
191
192         data_of_file += '\n\t\t</ns2:Data>'
193         data_of_file += '\n\t\t<ns2:ClientListingNihil>%(client_nihil)s</ns2:ClientListingNihil>' % (file_data)
194         data_of_file += '\n\t\t<ns2:Ask Restitution="%(ask_restitution)s" Payment="%(ask_payment)s"/>' % (file_data)
195         data_of_file += '\n\t\t<ns2:Comment>%(comments)s</ns2:Comment>' % (file_data)
196         data_of_file += '\n\t</ns2:VATDeclaration> \n</ns2:VATConsignment>'
197         model_data_ids = mod_obj.search(cr, uid,[('model','=','ir.ui.view'),('name','=','view_vat_save')], context=context)
198         resource_id = mod_obj.read(cr, uid, model_data_ids, fields=['res_id'], context=context)[0]['res_id']
199         context = dict(context or {})
200         context['file_save'] = data_of_file
201         return {
202             'name': _('Save XML For Vat declaration'),
203             'context': context,
204             'view_type': 'form',
205             'view_mode': 'form',
206             'res_model': 'l1on_be.vat.declaration',
207             'views': [(resource_id,'form')],
208             'view_id': 'view_vat_save',
209             'type': 'ir.actions.act_window',
210             'target': 'new',
211         }
212
213
214 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: