4656987cbeb2bb7e0c0538c67aad1e7aaec6cae7
[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         ctx2.update({'initial_bal': True})
44         self.init_query = obj_move._query_get(self.cr, self.uid, obj='l', context=ctx2)
45         self.init_balance = data['form']['initial_balance']
46         self.display_account = data['form']['display_account']
47         self.target_move = data['form'].get('target_move', 'all')
48         ctx = self.context.copy()
49         ctx['fiscalyear'] = data['form']['fiscalyear_id']
50         if data['form']['filter'] == 'filter_period':
51             ctx['periods'] = data['form']['periods']
52         elif data['form']['filter'] == 'filter_date':
53             ctx['date_from'] = data['form']['date_from']
54             ctx['date_to'] =  data['form']['date_to']
55         ctx['state'] = data['form']['target_move']
56         self.context.update(ctx)
57         if (data['model'] == 'ir.ui.menu'):
58             new_ids = [data['form']['chart_account_id']]
59             objects = self.pool.get('account.account').browse(self.cr, self.uid, new_ids)
60         return super(general_ledger, self).set_context(objects, data, new_ids, report_type=report_type)
61
62     def __init__(self, cr, uid, name, context=None):
63         if context is None:
64             context = {}
65         super(general_ledger, self).__init__(cr, uid, name, context=context)
66         self.query = ""
67         self.tot_currency = 0.0
68         self.period_sql = ""
69         self.sold_accounts = {}
70         self.sortby = 'sort_date'
71         self.localcontext.update( {
72             'time': time,
73             'lines': self.lines,
74             'sum_debit_account': self._sum_debit_account,
75             'sum_credit_account': self._sum_credit_account,
76             'sum_balance_account': self._sum_balance_account,
77             'sum_currency_amount_account': self._sum_currency_amount_account,
78             'get_children_accounts': self.get_children_accounts,
79             'get_fiscalyear': self._get_fiscalyear,
80             'get_journal': self._get_journal,
81             'get_account': self._get_account,
82             'get_start_period': self.get_start_period,
83             'get_end_period': self.get_end_period,
84             'get_filter': self._get_filter,
85             'get_sortby': self._get_sortby,
86             'get_start_date':self._get_start_date,
87             'get_end_date':self._get_end_date,
88             'get_target_move': self._get_target_move,
89             'strip_name': self._strip_name,
90         })
91         self.context = context
92
93     def _ellipsis(self, char, size=100, truncation_str='...'):
94         if len(char) <= size:
95             return char
96         return char[:size-len(truncation_str)] + truncation_str
97
98     def _strip_name(self, name, maxlen=50):
99         return self._ellipsis(name, maxlen)
100
101     def _sum_currency_amount_account(self, account):
102         self.cr.execute('SELECT sum(l.amount_currency) AS tot_currency \
103                 FROM account_move_line l \
104                 WHERE l.account_id = %s AND %s' %(account.id, self.query))
105         sum_currency = self.cr.fetchone()[0] or 0.0
106         if self.init_balance:
107             self.cr.execute('SELECT sum(l.amount_currency) AS tot_currency \
108                             FROM account_move_line l \
109                             WHERE l.account_id = %s AND %s '%(account.id, self.init_query))
110             sum_currency += self.cr.fetchone()[0] or 0.0
111         return sum_currency
112
113     def get_children_accounts(self, account):
114         res = []
115         ids_acc = self.pool.get('account.account')._get_children_and_consol(self.cr, self.uid, account.id)
116         for child_account in self.pool.get('account.account').browse(self.cr, self.uid, ids_acc, context=self.context):
117             sql = """
118                 SELECT count(id)
119                 FROM account_move_line AS l
120                 WHERE %s AND l.account_id = %%s
121             """ % (self.query)
122             self.cr.execute(sql, (child_account.id,))
123             num_entry = self.cr.fetchone()[0] or 0
124             sold_account = self._sum_balance_account(child_account)
125             self.sold_accounts[child_account.id] = sold_account
126             if self.display_account == 'bal_movement':
127                 if child_account.type != 'view' and num_entry <> 0:
128                     res.append(child_account)
129             elif self.display_account == 'bal_solde':
130                 if child_account.type != 'view' and num_entry <> 0:
131                     if ( sold_account <> 0.0):
132                         res.append(child_account)
133             else:
134                 res.append(child_account)
135         if not res:
136             return [account]
137         return res
138
139     def lines(self, account):
140         """ Return all the account_move_line of account with their account code counterparts """
141         move_state = ['draft','posted']
142         if self.target_move == 'posted':
143             move_state = ['posted', '']
144         # First compute all counterpart strings for every move_id where this account appear.
145         # Currently, the counterpart info is used only in landscape mode
146         sql = """
147             SELECT m1.move_id,
148                 array_to_string(ARRAY(SELECT DISTINCT a.code
149                                           FROM account_move_line m2
150                                           LEFT JOIN account_account a ON (m2.account_id=a.id)
151                                           WHERE m2.move_id = m1.move_id
152                                           AND m2.account_id<>%%s), ', ') AS counterpart
153                 FROM (SELECT move_id
154                         FROM account_move_line l
155                         LEFT JOIN account_move am ON (am.id = l.move_id)
156                         WHERE am.state IN %s and %s AND l.account_id = %%s GROUP BY move_id) m1
157         """% (tuple(move_state), self.query)
158         self.cr.execute(sql, (account.id, account.id))
159         counterpart_res = self.cr.dictfetchall()
160         counterpart_accounts = {}
161         for i in counterpart_res:
162             counterpart_accounts[i['move_id']] = i['counterpart']
163         del counterpart_res
164
165         # Then select all account_move_line of this account
166         if self.sortby == 'sort_journal_partner':
167             sql_sort='j.code, p.name'
168         else:
169             sql_sort='l.date'
170         sql = """
171             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,
172             m.name AS move_name, m.id AS mmove_id,
173             c.symbol AS currency_code,
174             i.id AS invoice_id, i.type AS invoice_type, i.number AS invoice_number,
175             p.name AS partner_name
176             FROM account_move_line l
177             JOIN account_move m on (l.move_id=m.id)
178             LEFT JOIN res_currency c on (l.currency_id=c.id)
179             LEFT JOIN res_partner p on (l.partner_id=p.id)
180             LEFT JOIN account_invoice i on (m.id =i.move_id)
181             JOIN account_journal j on (l.journal_id=j.id)
182             WHERE %s AND m.state IN %s AND l.account_id = %%s ORDER by %s
183         """ %(self.query, tuple(move_state), sql_sort)
184         self.cr.execute(sql, (account.id,))
185         res_lines = self.cr.dictfetchall()
186         res_init = []
187         if res_lines and self.init_balance:
188             #FIXME: replace the label of lname with a string translatable
189             sql = """
190                 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,
191                 '' AS move_name, '' AS mmove_id,
192                 '' AS currency_code,
193                 NULL AS currency_id,
194                 '' AS invoice_id, '' AS invoice_type, '' AS invoice_number,
195                 '' AS partner_name
196                 FROM account_move_line l
197                 LEFT JOIN account_move m on (l.move_id=m.id)
198                 LEFT JOIN res_currency c on (l.currency_id=c.id)
199                 LEFT JOIN res_partner p on (l.partner_id=p.id)
200                 LEFT JOIN account_invoice i on (m.id =i.move_id)
201                 JOIN account_journal j on (l.journal_id=j.id)
202                 WHERE %s AND m.state IN %s AND l.account_id = %%s
203             """ %(self.init_query, tuple(move_state))
204             self.cr.execute(sql, (account.id,))
205             res_init = self.cr.dictfetchall()
206         res = res_init + res_lines
207         account_sum = 0.0
208         inv_types = { 'out_invoice': 'CI', 'in_invoice': 'SI', 'out_refund': 'OR', 'in_refund': 'SR', }
209         for l in res:
210             l['move'] = l['move_name']
211             if l['invoice_id']:
212                 l['lref'] = '%s: %s'%(inv_types[l['invoice_type']], l['invoice_number'])
213             l['partner'] = l['partner_name'] or ''
214             account_sum += l['debit'] - l['credit']
215             l['progress'] = account_sum
216             l['line_corresp'] = l['mmove_id'] == '' and ' ' or counterpart_accounts[l['mmove_id']]
217             # Modification of amount Currency
218             if l['credit'] > 0:
219                 if l['amount_currency'] != None:
220                     l['amount_currency'] = abs(l['amount_currency']) * -1
221             if l['amount_currency'] != None:
222                 self.tot_currency = self.tot_currency + l['amount_currency']
223         return res
224
225     def _sum_debit_account(self, account):
226         if account.type == 'view':
227             return account.debit
228         move_state = ['draft','posted']
229         if self.target_move == 'posted':
230             move_state = ['posted','']
231         self.cr.execute('SELECT sum(debit) \
232                 FROM account_move_line l \
233                 JOIN account_move am ON (am.id = l.move_id) \
234                 WHERE (l.account_id = %s) \
235                 AND (am.state IN %s) \
236                 AND '+ self.query +' '
237                 ,(account.id, tuple(move_state)))
238         sum_debit = self.cr.fetchone()[0] or 0.0
239         if self.init_balance:
240             self.cr.execute('SELECT sum(debit) \
241                     FROM account_move_line l \
242                     JOIN account_move am ON (am.id = l.move_id) \
243                     WHERE (l.account_id = %s) \
244                     AND (am.state IN %s) \
245                     AND '+ self.init_query +' '
246                     ,(account.id, tuple(move_state)))
247             # Add initial balance to the result
248             sum_debit += self.cr.fetchone()[0] or 0.0
249         return sum_debit
250
251     def _sum_credit_account(self, account):
252         if account.type == 'view':
253             return account.credit
254         move_state = ['draft','posted']
255         if self.target_move == 'posted':
256             move_state = ['posted','']
257         self.cr.execute('SELECT sum(credit) \
258                 FROM account_move_line l \
259                 JOIN account_move am ON (am.id = l.move_id) \
260                 WHERE (l.account_id = %s) \
261                 AND (am.state IN %s) \
262                 AND '+ self.query +' '
263                 ,(account.id, tuple(move_state)))
264         sum_credit = self.cr.fetchone()[0] or 0.0
265         if self.init_balance:
266             self.cr.execute('SELECT sum(credit) \
267                     FROM account_move_line l \
268                     JOIN account_move am ON (am.id = l.move_id) \
269                     WHERE (l.account_id = %s) \
270                     AND (am.state IN %s) \
271                     AND '+ self.init_query +' '
272                     ,(account.id, tuple(move_state)))
273             # Add initial balance to the result
274             sum_credit += self.cr.fetchone()[0] or 0.0
275         return sum_credit
276
277     def _sum_balance_account(self, account):
278         if account.type == 'view':
279             return account.balance
280         move_state = ['draft','posted']
281         if self.target_move == 'posted':
282             move_state = ['posted','']
283         self.cr.execute('SELECT (sum(debit) - sum(credit)) as tot_balance \
284                 FROM account_move_line l \
285                 JOIN account_move am ON (am.id = l.move_id) \
286                 WHERE (l.account_id = %s) \
287                 AND (am.state IN %s) \
288                 AND '+ self.query +' '
289                 ,(account.id, tuple(move_state)))
290         sum_balance = self.cr.fetchone()[0] or 0.0
291         if self.init_balance:
292             self.cr.execute('SELECT (sum(debit) - sum(credit)) as tot_balance \
293                     FROM account_move_line l \
294                     JOIN account_move am ON (am.id = l.move_id) \
295                     WHERE (l.account_id = %s) \
296                     AND (am.state IN %s) \
297                     AND '+ self.init_query +' '
298                     ,(account.id, tuple(move_state)))
299             # Add initial balance to the result
300             sum_balance += self.cr.fetchone()[0] or 0.0
301         return sum_balance
302
303     def _get_account(self, data):
304         if data['model'] == 'account.account':
305             return self.pool.get('account.account').browse(self.cr, self.uid, data['form']['id']).company_id.name
306         return super(general_ledger ,self)._get_account(data)
307
308     def _get_sortby(self, data):
309         if self.sortby == 'sort_date':
310             return 'Date'
311         elif self.sortby == 'sort_journal_partner':
312             return 'Journal & Partner'
313         return 'Date'
314
315 report_sxw.report_sxw('report.account.general.ledger', 'account.account', 'addons/account/report/account_general_ledger.rml', parser=general_ledger, header='internal')
316 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')
317
318 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: