[MERGE] merge with main branch
[odoo/odoo.git] / addons / account / report / account_tax_report.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
22 import time
23
24 from common_report_header import common_report_header
25 from report import report_sxw
26
27 class tax_report(report_sxw.rml_parse, common_report_header):
28     _name = 'report.account.vat.declaration'
29
30     def set_context(self, objects, data, ids, report_type=None):
31         new_ids = ids
32         res = {}
33         self.period_ids = []
34         period_obj = self.pool.get('account.period')
35         self.display_detail = data['form']['display_detail']
36         res['periods'] = ''
37         res['fiscalyear'] = data['form'].get('fiscalyear_id', False)
38
39         if data['form'].get('period_from', False) and data['form'].get('period_to', False):
40             self.period_ids = period_obj.build_ctx_periods(self.cr, self.uid, data['form']['period_from'], data['form']['period_to'])
41             periods_l = period_obj.read(self.cr, self.uid, self.period_ids, ['name'])
42             for period in periods_l:
43                 if res['periods'] == '':
44                     res['periods'] = period['name']
45                 else:
46                     res['periods'] += ", "+ period['name']
47         return super(tax_report, self).set_context(objects, data, new_ids, report_type=report_type)
48
49     def __init__(self, cr, uid, name, context=None):
50         super(tax_report, self).__init__(cr, uid, name, context=context)
51         self.localcontext.update({
52             'time': time,
53             'get_codes': self._get_codes,
54             'get_general': self._get_general,
55             'get_currency': self._get_currency,
56             'get_lines': self._get_lines,
57             'get_fiscalyear': self._get_fiscalyear,
58             'get_account': self._get_account,
59             'get_start_period': self.get_start_period,
60             'get_end_period': self.get_end_period,
61             'get_basedon': self._get_basedon,
62         })
63
64     def _get_basedon(self, form):
65         return form['form']['based_on']
66
67     def _get_lines(self, based_on, company_id=False, parent=False, level=0, context=None):
68         period_list = self.period_ids
69         res = self._get_codes(based_on, company_id, parent, level, period_list, context=context)
70         if period_list:
71             res = self._add_codes(based_on, res, period_list, context=context)
72         else:
73             self.cr.execute ("select id from account_fiscalyear")
74             fy = self.cr.fetchall()
75             self.cr.execute ("select id from account_period where fiscalyear_id = %s",(fy[0][0],))
76             periods = self.cr.fetchall()
77             for p in periods:
78                 period_list.append(p[0])
79             res = self._add_codes(based_on, res, period_list, context=context)
80
81         i = 0
82         top_result = []
83         while i < len(res):
84
85             res_dict = { 'code': res[i][1].code,
86                 'name': res[i][1].name,
87                 'debit': 0,
88                 'credit': 0,
89                 'tax_amount': res[i][1].sum_period,
90                 'type': 1,
91                 'level': res[i][0],
92                 'pos': 0
93             }
94
95             top_result.append(res_dict)
96             res_general = self._get_general(res[i][1].id, period_list, company_id, based_on, context=context)
97             ind_general = 0
98             while ind_general < len(res_general):
99                 res_general[ind_general]['type'] = 2
100                 res_general[ind_general]['pos'] = 0
101                 res_general[ind_general]['level'] = res_dict['level']
102                 top_result.append(res_general[ind_general])
103                 ind_general+=1
104             i+=1
105         return top_result
106
107     def _get_general(self, tax_code_id, period_list, company_id, based_on, context=None):
108         if not self.display_detail:
109             return []
110         res = []
111         obj_account = self.pool.get('account.account')
112         periods_ids = tuple(period_list)
113         if based_on == 'payments':
114             self.cr.execute('SELECT SUM(line.tax_amount) AS tax_amount, \
115                         SUM(line.debit) AS debit, \
116                         SUM(line.credit) AS credit, \
117                         COUNT(*) AS count, \
118                         account.id AS account_id, \
119                         account.name AS name,  \
120                         account.code AS code \
121                     FROM account_move_line AS line, \
122                         account_account AS account, \
123                         account_move AS move \
124                         LEFT JOIN account_invoice invoice ON \
125                             (invoice.move_id = move.id) \
126                     WHERE line.state<>%s \
127                         AND line.tax_code_id = %s  \
128                         AND line.account_id = account.id \
129                         AND account.company_id = %s \
130                         AND move.id = line.move_id \
131                         AND line.period_id IN %s \
132                         AND ((invoice.state = %s) \
133                             OR (invoice.id IS NULL))  \
134                     GROUP BY account.id,account.name,account.code', ('draft', tax_code_id,
135                         company_id, periods_ids, 'paid',))
136
137         else:
138             self.cr.execute('SELECT SUM(line.tax_amount) AS tax_amount, \
139                         SUM(line.debit) AS debit, \
140                         SUM(line.credit) AS credit, \
141                         COUNT(*) AS count, \
142                         account.id AS account_id, \
143                         account.name AS name,  \
144                         account.code AS code \
145                     FROM account_move_line AS line, \
146                         account_account AS account \
147                     WHERE line.state <> %s \
148                         AND line.tax_code_id = %s  \
149                         AND line.account_id = account.id \
150                         AND account.company_id = %s \
151                         AND line.period_id IN %s\
152                         AND account.active \
153                     GROUP BY account.id,account.name,account.code', ('draft', tax_code_id,
154                         company_id, periods_ids,))
155         res = self.cr.dictfetchall()
156
157         i = 0
158         while i<len(res):
159             res[i]['account'] = obj_account.browse(self.cr, self.uid, res[i]['account_id'], context=context)
160             i+=1
161         return res
162
163     def _get_codes(self, based_on, company_id, parent=False, level=0, period_list=[], context=None):
164         obj_tc = self.pool.get('account.tax.code')
165         ids = obj_tc.search(self.cr, self.uid, [('parent_id','=',parent),('company_id','=',company_id)], order='sequence', context=context)
166
167         res = []
168         for code in obj_tc.browse(self.cr, self.uid, ids, {'based_on': based_on}):
169             res.append(('.'*2*level, code))
170
171             res += self._get_codes(based_on, company_id, code.id, level+1, context=context)
172         return res
173
174     def _add_codes(self, based_on, account_list=[], period_list=[], context=None):
175         res = []
176         obj_tc = self.pool.get('account.tax.code')
177         for account in account_list:
178             ids = obj_tc.search(self.cr, self.uid, [('id','=', account[1].id)], context=context)
179             sum_tax_add = 0
180             for period_ind in period_list:
181                 for code in obj_tc.browse(self.cr, self.uid, ids, {'period_id':period_ind,'based_on': based_on}):
182                     sum_tax_add = sum_tax_add + code.sum_period
183
184             code.sum_period = sum_tax_add
185
186             res.append((account[0], code))
187         return res
188
189     def _get_currency(self, form, context=None):
190         return self.pool.get('res.company').browse(self.cr, self.uid, form['company_id'], context=context).currency_id.name
191
192     def sort_result(self, accounts, context=None):
193         # On boucle sur notre rapport
194         result_accounts = []
195         ind=0
196         old_level=0
197         while ind<len(accounts):
198             #
199             account_elem = accounts[ind]
200             #
201
202             #
203             # we will now check if the level is lower than the previous level, in this case we will make a subtotal
204             if (account_elem['level'] < old_level):
205                 bcl_current_level = old_level
206                 bcl_rup_ind = ind - 1
207
208                 while (bcl_current_level >= int(accounts[bcl_rup_ind]['level']) and bcl_rup_ind >= 0 ):
209                     res_tot = { 'code': accounts[bcl_rup_ind]['code'],
210                         'name': '',
211                         'debit': 0,
212                         'credit': 0,
213                         'tax_amount': accounts[bcl_rup_ind]['tax_amount'],
214                         'type': accounts[bcl_rup_ind]['type'],
215                         'level': 0,
216                         'pos': 0
217                     }
218
219                     if res_tot['type'] == 1:
220                         # on change le type pour afficher le total
221                         res_tot['type'] = 2
222                         result_accounts.append(res_tot)
223                     bcl_current_level =  accounts[bcl_rup_ind]['level']
224                     bcl_rup_ind -= 1
225
226             old_level = account_elem['level']
227             result_accounts.append(account_elem)
228             ind+=1
229
230         return result_accounts
231
232 report_sxw.report_sxw('report.account.vat.declaration', 'account.tax.code',
233     'addons/account/report/account_tax_report.rml', parser=tax_report, header="internal")
234
235 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: