294c7fa99cffba92b97d14fe7b28f9fe00111813
[odoo/odoo.git] / addons / account / report / account_general_ledger.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 # Copyright (c) 2005-2006 CamptoCamp
5 # Copyright (c) 2006-2010 OpenERP S.A
6 #
7 # WARNING: This program as such is intended to be used by professional
8 # programmers who take the whole responsibility of assessing all potential
9 # consequences resulting from its eventual inadequacies and bugs
10 # End users who are looking for a ready-to-use solution with commercial
11 # guarantees and support are strongly advised to contract a Free Software
12 # Service Company
13 #
14 # This program is Free Software; you can redistribute it and/or
15 # modify it under the terms of the GNU General Public License
16 # as published by the Free Software Foundation; either version 2
17 # of the License, or (at your option) any later version.
18 #
19 # This program is distributed in the hope that it will be useful,
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 # GNU General Public License for more details.
23 #
24 # You should have received a copy of the GNU General Public License
25 # along with this program; if not, write to the Free Software
26 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
27 #
28 ##############################################################################
29
30 import time
31 from report import report_sxw
32 from common_report_header import common_report_header
33
34 class general_ledger(report_sxw.rml_parse, common_report_header):
35     _name = 'report.account.general.ledger'
36
37     def set_context(self, objects, data, ids, report_type=None):
38         new_ids = ids
39         obj_move = self.pool.get('account.move.line')
40         self.sortby = data['form'].get('sortby', 'sort_date')
41         self.query = obj_move._query_get(self.cr, self.uid, obj='l', context=data['form'].get('used_context',{}))
42         ctx2 = data['form'].get('used_context',{}).copy()
43         self.init_balance = data['form'].get('initial_balance', True)
44         if self.init_balance:
45             ctx2.update({'initial_bal': True})
46         self.init_query = obj_move._query_get(self.cr, self.uid, obj='l', context=ctx2)
47         self.display_account = data['form']['display_account']
48         self.target_move = data['form'].get('target_move', 'all')
49         ctx = self.context.copy()
50         ctx['fiscalyear'] = data['form']['fiscalyear_id']
51         if data['form']['filter'] == 'filter_period':
52             ctx['periods'] = data['form']['periods']
53         elif data['form']['filter'] == 'filter_date':
54             ctx['date_from'] = data['form']['date_from']
55             ctx['date_to'] =  data['form']['date_to']
56         ctx['state'] = data['form']['target_move']
57         self.context.update(ctx)
58         if (data['model'] == 'ir.ui.menu'):
59             new_ids = [data['form']['chart_account_id']]
60             objects = self.pool.get('account.account').browse(self.cr, self.uid, new_ids)
61         return super(general_ledger, self).set_context(objects, data, new_ids, report_type=report_type)
62
63     def __init__(self, cr, uid, name, context=None):
64         if context is None:
65             context = {}
66         super(general_ledger, self).__init__(cr, uid, name, context=context)
67         self.query = ""
68         self.tot_currency = 0.0
69         self.period_sql = ""
70         self.sold_accounts = {}
71         self.sortby = 'sort_date'
72         self.localcontext.update( {
73             'time': time,
74             'lines': self.lines,
75             'sum_debit_account': self._sum_debit_account,
76             'sum_credit_account': self._sum_credit_account,
77             'sum_balance_account': self._sum_balance_account,
78             'sum_currency_amount_account': self._sum_currency_amount_account,
79             'get_children_accounts': self.get_children_accounts,
80             'get_fiscalyear': self._get_fiscalyear,
81             'get_journal': self._get_journal,
82             'get_account': self._get_account,
83             'get_start_period': self.get_start_period,
84             'get_end_period': self.get_end_period,
85             'get_filter': self._get_filter,
86             'get_sortby': self._get_sortby,
87             'get_start_date':self._get_start_date,
88             'get_end_date':self._get_end_date,
89             'get_target_move': self._get_target_move,
90         })
91         self.context = context
92
93     def _sum_currency_amount_account(self, account):
94         self.cr.execute('SELECT sum(l.amount_currency) AS tot_currency \
95                 FROM account_move_line l \
96                 WHERE l.account_id = %s AND %s' %(account.id, self.query))
97         sum_currency = self.cr.fetchone()[0] or 0.0
98         if self.init_balance:
99             self.cr.execute('SELECT sum(l.amount_currency) AS tot_currency \
100                             FROM account_move_line l \
101                             WHERE l.account_id = %s AND %s '%(account.id, self.init_query))
102             sum_currency += self.cr.fetchone()[0] or 0.0
103         return sum_currency
104
105     def get_children_accounts(self, account):
106         res = []
107         currency_obj = self.pool.get('res.currency')
108         ids_acc = self.pool.get('account.account')._get_children_and_consol(self.cr, self.uid, account.id)
109         currency = account.currency_id and account.currency_id or account.company_id.currency_id
110         for child_account in self.pool.get('account.account').browse(self.cr, self.uid, ids_acc, context=self.context):
111             sql = """
112                 SELECT count(id)
113                 FROM account_move_line AS l
114                 WHERE %s AND l.account_id = %%s
115             """ % (self.query)
116             self.cr.execute(sql, (child_account.id,))
117             num_entry = self.cr.fetchone()[0] or 0
118             sold_account = self._sum_balance_account(child_account)
119             self.sold_accounts[child_account.id] = sold_account
120             if self.display_account == 'movement':
121                 if child_account.type != 'view' and num_entry <> 0:
122                     res.append(child_account)
123             elif self.display_account == 'not_zero':
124                 if child_account.type != 'view' and num_entry <> 0:
125                     if not currency_obj.is_zero(self.cr, self.uid, currency, sold_account):
126                         res.append(child_account)
127             else:
128                 res.append(child_account)
129         if not res:
130             return [account]
131         return res
132
133     def lines(self, account):
134         """ Return all the account_move_line of account with their account code counterparts """
135         move_state = ['draft','posted']
136         if self.target_move == 'posted':
137             move_state = ['posted', '']
138         # First compute all counterpart strings for every move_id where this account appear.
139         # Currently, the counterpart info is used only in landscape mode
140         sql = """
141             SELECT m1.move_id,
142                 array_to_string(ARRAY(SELECT DISTINCT a.code
143                                           FROM account_move_line m2
144                                           LEFT JOIN account_account a ON (m2.account_id=a.id)
145                                           WHERE m2.move_id = m1.move_id
146                                           AND m2.account_id<>%%s), ', ') AS counterpart
147                 FROM (SELECT move_id
148                         FROM account_move_line l
149                         LEFT JOIN account_move am ON (am.id = l.move_id)
150                         WHERE am.state IN %s and %s AND l.account_id = %%s GROUP BY move_id) m1
151         """% (tuple(move_state), self.query)
152         self.cr.execute(sql, (account.id, account.id))
153         counterpart_res = self.cr.dictfetchall()
154         counterpart_accounts = {}
155         for i in counterpart_res:
156             counterpart_accounts[i['move_id']] = i['counterpart']
157         del counterpart_res
158
159         # Then select all account_move_line of this account
160         if self.sortby == 'sort_journal_partner':
161             sql_sort='j.code, p.name, l.move_id'
162         else:
163             sql_sort='l.date, l.move_id'
164         sql = """
165             SELECT l.id AS lid, l.date AS ldate, j.code AS lcode, l.currency_id,l.amount_currency,l.ref AS lref, l.name AS lname, COALESCE(l.debit,0) AS debit, COALESCE(l.credit,0) AS credit, l.period_id AS lperiod_id, l.partner_id AS lpartner_id,
166             m.name AS move_name, m.id AS mmove_id,per.code as period_code,
167             c.symbol AS currency_code,
168             i.id AS invoice_id, i.type AS invoice_type, i.number AS invoice_number,
169             p.name AS partner_name
170             FROM account_move_line l
171             JOIN account_move m on (l.move_id=m.id)
172             LEFT JOIN res_currency c on (l.currency_id=c.id)
173             LEFT JOIN res_partner p on (l.partner_id=p.id)
174             LEFT JOIN account_invoice i on (m.id =i.move_id)
175             LEFT JOIN account_period per on (per.id=l.period_id)
176             JOIN account_journal j on (l.journal_id=j.id)
177             WHERE %s AND m.state IN %s AND l.account_id = %%s ORDER by %s
178         """ %(self.query, tuple(move_state), sql_sort)
179         self.cr.execute(sql, (account.id,))
180         res_lines = self.cr.dictfetchall()
181         res_init = []
182         if res_lines and self.init_balance:
183             #FIXME: replace the label of lname with a string translatable
184             sql = """
185                 SELECT 0 AS lid, '' AS ldate, '' AS lcode, COALESCE(SUM(l.amount_currency),0.0) AS amount_currency, '' AS lref, 'Initial Balance' AS lname, COALESCE(SUM(l.debit),0.0) AS debit, COALESCE(SUM(l.credit),0.0) AS credit, '' AS lperiod_id, '' AS lpartner_id,
186                 '' AS move_name, '' AS mmove_id, '' AS period_code,
187                 '' AS currency_code,
188                 NULL AS currency_id,
189                 '' AS invoice_id, '' AS invoice_type, '' AS invoice_number,
190                 '' AS partner_name
191                 FROM account_move_line l
192                 LEFT JOIN account_move m on (l.move_id=m.id)
193                 LEFT JOIN res_currency c on (l.currency_id=c.id)
194                 LEFT JOIN res_partner p on (l.partner_id=p.id)
195                 LEFT JOIN account_invoice i on (m.id =i.move_id)
196                 JOIN account_journal j on (l.journal_id=j.id)
197                 WHERE %s AND m.state IN %s AND l.account_id = %%s
198             """ %(self.init_query, tuple(move_state))
199             self.cr.execute(sql, (account.id,))
200             res_init = self.cr.dictfetchall()
201         res = res_init + res_lines
202         account_sum = 0.0
203         for l in res:
204             l['move'] = l['move_name'] != '/' and l['move_name'] or ('*'+str(l['mmove_id']))
205             l['partner'] = l['partner_name'] or ''
206             account_sum += l['debit'] - l['credit']
207             l['progress'] = account_sum
208             l['line_corresp'] = l['mmove_id'] == '' and ' ' or counterpart_accounts[l['mmove_id']].replace(', ',',')
209             # Modification of amount Currency
210             if l['credit'] > 0:
211                 if l['amount_currency'] != None:
212                     l['amount_currency'] = abs(l['amount_currency']) * -1
213             if l['amount_currency'] != None:
214                 self.tot_currency = self.tot_currency + l['amount_currency']
215         return res
216
217     def _sum_debit_account(self, account):
218         if account.type == 'view':
219             return account.debit
220         move_state = ['draft','posted']
221         if self.target_move == 'posted':
222             move_state = ['posted','']
223         self.cr.execute('SELECT sum(debit) \
224                 FROM account_move_line l \
225                 JOIN account_move am ON (am.id = l.move_id) \
226                 WHERE (l.account_id = %s) \
227                 AND (am.state IN %s) \
228                 AND '+ self.query +' '
229                 ,(account.id, tuple(move_state)))
230         sum_debit = self.cr.fetchone()[0] or 0.0
231         if self.init_balance:
232             self.cr.execute('SELECT sum(debit) \
233                     FROM account_move_line l \
234                     JOIN account_move am ON (am.id = l.move_id) \
235                     WHERE (l.account_id = %s) \
236                     AND (am.state IN %s) \
237                     AND '+ self.init_query +' '
238                     ,(account.id, tuple(move_state)))
239             # Add initial balance to the result
240             sum_debit += self.cr.fetchone()[0] or 0.0
241         return sum_debit
242
243     def _sum_credit_account(self, account):
244         if account.type == 'view':
245             return account.credit
246         move_state = ['draft','posted']
247         if self.target_move == 'posted':
248             move_state = ['posted','']
249         self.cr.execute('SELECT sum(credit) \
250                 FROM account_move_line l \
251                 JOIN account_move am ON (am.id = l.move_id) \
252                 WHERE (l.account_id = %s) \
253                 AND (am.state IN %s) \
254                 AND '+ self.query +' '
255                 ,(account.id, tuple(move_state)))
256         sum_credit = self.cr.fetchone()[0] or 0.0
257         if self.init_balance:
258             self.cr.execute('SELECT sum(credit) \
259                     FROM account_move_line l \
260                     JOIN account_move am ON (am.id = l.move_id) \
261                     WHERE (l.account_id = %s) \
262                     AND (am.state IN %s) \
263                     AND '+ self.init_query +' '
264                     ,(account.id, tuple(move_state)))
265             # Add initial balance to the result
266             sum_credit += self.cr.fetchone()[0] or 0.0
267         return sum_credit
268
269     def _sum_balance_account(self, account):
270         if account.type == 'view':
271             return account.balance
272         move_state = ['draft','posted']
273         if self.target_move == 'posted':
274             move_state = ['posted','']
275         self.cr.execute('SELECT (sum(debit) - sum(credit)) as tot_balance \
276                 FROM account_move_line l \
277                 JOIN account_move am ON (am.id = l.move_id) \
278                 WHERE (l.account_id = %s) \
279                 AND (am.state IN %s) \
280                 AND '+ self.query +' '
281                 ,(account.id, tuple(move_state)))
282         sum_balance = self.cr.fetchone()[0] or 0.0
283         if self.init_balance:
284             self.cr.execute('SELECT (sum(debit) - sum(credit)) as tot_balance \
285                     FROM account_move_line l \
286                     JOIN account_move am ON (am.id = l.move_id) \
287                     WHERE (l.account_id = %s) \
288                     AND (am.state IN %s) \
289                     AND '+ self.init_query +' '
290                     ,(account.id, tuple(move_state)))
291             # Add initial balance to the result
292             sum_balance += self.cr.fetchone()[0] or 0.0
293         return sum_balance
294
295     def _get_account(self, data):
296         if data['model'] == 'account.account':
297             return self.pool.get('account.account').browse(self.cr, self.uid, data['form']['id']).company_id.name
298         return super(general_ledger ,self)._get_account(data)
299
300     def _get_sortby(self, data):
301         if self.sortby == 'sort_date':
302             return 'Date'
303         elif self.sortby == 'sort_journal_partner':
304             return 'Journal & Partner'
305         return 'Date'
306
307 report_sxw.report_sxw('report.account.general.ledger', 'account.account', 'addons/account/report/account_general_ledger.rml', parser=general_ledger, header='internal')
308 report_sxw.report_sxw('report.account.general.ledger_landscape', 'account.account', 'addons/account/report/account_general_ledger_landscape.rml', parser=general_ledger, header='internal landscape')
309
310 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: