*complted Analytic Balance reports.
[odoo/odoo.git] / addons / account / report / account_balance.py
1 ##############################################################################
2 #
3 # Copyright (c) 2004-2008 TINY SPRL. (http://tiny.be) All Rights Reserved.
4 #
5 # $Id$
6 #
7 # WARNING: This program as such is intended to be used by professional
8 # programmers who take the whole responsability 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 # garantees and support are strongly adviced 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 xml
31 import copy
32 from operator import itemgetter
33 import time
34 import datetime
35 from report import report_sxw
36
37 class account_balance(report_sxw.rml_parse):
38     
39         _name = 'report.account.account.balance'
40         def __init__(self, cr, uid, name, context):
41             super(account_balance, self).__init__(cr, uid, name, context)
42             self.sum_debit = 0.00
43             self.sum_credit = 0.00
44             self.date_lst = []
45             self.date_lst_string = ''
46             self.localcontext.update({
47                 'time': time,
48                 'lines': self.lines,
49                 'moveline':self.moveline,
50                 'sum_debit': self._sum_debit,
51                 'sum_credit': self._sum_credit,
52                 'get_fiscalyear':self.get_fiscalyear,
53                 'get_periods':self.get_periods,
54             })
55             self.context = context
56     
57         def get_fiscalyear(self, form):
58             res=[]
59             if form.has_key('fiscalyear'): 
60                 fisc_id = form['fiscalyear']
61                 if not (fisc_id):
62                     return ''
63                 self.cr.execute("select name from account_fiscalyear where id = %d" %(int(fisc_id)))
64                 res=self.cr.fetchone()
65             return res and res[0] or ''
66     
67         def get_periods(self, form):
68             result=''
69             if form.has_key('periods'): 
70                 period_ids = ",".join([str(x) for x in form['periods'][0][2] if x])
71                 self.cr.execute("select name from account_period where id in (%s)" % (period_ids))
72                 res=self.cr.fetchall()
73                 for r in res:
74                     if (r == res[res.__len__()-1]):
75                         result+=r[0]+". "
76                     else:
77                         result+=r[0]+", "
78             return str(result and result[:-1]) or ''
79     
80         def lines(self, form, ids={}, done=None, level=1):
81             if not ids:
82                 ids = self.ids
83             if not ids:
84                 return []
85             if not done:
86                 done={}
87             res={}
88             result_acc=[]
89             ctx = self.context.copy()
90             if form.has_key('fiscalyear'): 
91                 self.transform_period_into_date_array(form)
92                 ctx['fiscalyear'] = form['fiscalyear']
93                 ctx['periods'] = form['periods'][0][2]
94             else:
95                 self.transform_date_into_date_array(form)
96                 ctx['date_from'] = form['date_from']
97                 ctx['date_to'] = form['date_to']
98                 
99             accounts = self.pool.get('account.account').browse(self.cr, self.uid, ids, ctx)
100             def cmp_code(x, y):
101                 return cmp(x.code, y.code)
102             accounts.sort(cmp_code)
103             for account in accounts:
104                 if account.id in done:
105                     continue
106                 done[account.id] = 1     
107                 res = {
108                         'lid' :'',
109                         'date':'',
110                         'jname':'',
111                         'ref':'',
112                         'lname':'',
113                         'debit1':'',
114                         'credit1':'',
115                         'balance1' :'',
116                         'id' : account.id,
117                         'code': account.code,
118                         'name': account.name,
119                         'level': level,
120                         'debit': account.debit,
121                         'credit': account.credit,
122                         'balance': account.balance,
123                         'leef': not bool(account.child_id),
124                         'bal_type':'',
125                     }
126                 self.sum_debit += account.debit
127                 self.sum_credit += account.credit
128                 if not (res['credit'] or res['debit']) and not account.child_id:
129                     continue
130                 if account.child_id:
131                     def _check_rec(account):
132                         if not account.child_id:
133                             return bool(account.credit or account.debit)
134                         for c in account.child_id:
135                             if _check_rec(c):
136                                 return True
137                         return False
138                     if not _check_rec(account):
139                         continue
140                 if form['display_account'] == 'bal_mouvement':
141                     if res['credit'] <> 0 or res['debit'] <> 0 or res['balance'] <> 0:
142                         result_acc.append(res)
143                 elif form['display_account'] == 'bal_solde':        
144                     if  res['balance'] <> 0:
145                         result_acc.append(res)
146                 else:
147                     result_acc.append(res)
148                 res1 = self.moveline(form, account.id,res['level'])
149                 if res1:
150                     for r in res1:
151                         result_acc.append(r)
152                 if account.code=='0':
153                     result_acc.pop(-1)
154                 if account.child_id:
155                     ids2 = [(x.code,x.id) for x in account.child_id]
156                     ids2.sort()
157                     result_acc += self.lines(form, [x[1] for x in ids2], done, level+1)
158             return result_acc
159         
160         def moveline(self,form,ids,level):
161             res={}
162             self.date_lst_string = '\'' + '\',\''.join(map(str,self.date_lst)) + '\''
163             self.cr.execute(
164                     "SELECT l.id as lid,l.date,j.code as jname, l.ref, l.name as lname, l.debit as debit1, l.credit as credit1 " \
165                     "FROM account_move_line l " \
166                     "LEFT JOIN account_journal j " \
167                         "ON (l.journal_id = j.id) " \
168                     "WHERE l.account_id = '"+str(ids)+"' " \
169                     "AND l.date IN (" + self.date_lst_string + ") " \
170                         "ORDER BY l.id")
171             res = self.cr.dictfetchall() 
172             sum = 0.0
173             for r in res:
174                 sum = r['debit1'] - r['credit1']
175                 r['balance1'] = sum
176                 r['id'] =''
177                 r['code']= ''
178                 r['name']=''
179                 r['level']=level
180                 r['debit']=''
181                 r['credit']=''
182                 r['balance']=''
183                 r['leef']=''
184                 if sum > 0.0:
185                     r['bal_type']=" Dr."
186                 else:
187                     r['bal_type']=" Cr."
188             return res or ''
189         
190         def date_range(self,start,end):
191             start = datetime.date.fromtimestamp(time.mktime(time.strptime(start,"%Y-%m-%d")))
192             end = datetime.date.fromtimestamp(time.mktime(time.strptime(end,"%Y-%m-%d")))
193             full_str_date = []
194         #
195             r = (end+datetime.timedelta(days=1)-start).days
196         #
197             date_array = [start+datetime.timedelta(days=i) for i in range(r)]
198             for date in date_array:
199                 full_str_date.append(str(date))
200             return full_str_date
201             
202         #
203         def transform_period_into_date_array(self,form):
204             ## Get All Period Date
205             if not form['periods'][0][2] :
206                 periods_id =  self.pool.get('account.period').search(self.cr, self.uid, [('fiscalyear_id','=',form['fiscalyear'])])
207             else:
208                 periods_id = form['periods'][0][2]
209             date_array = [] 
210             for period_id in periods_id:
211                 period_obj = self.pool.get('account.period').browse(self.cr, self.uid, period_id)
212                 date_array = date_array + self.date_range(period_obj.date_start,period_obj.date_stop)
213                 
214             self.date_lst = date_array
215             self.date_lst.sort()
216                 
217         def transform_date_into_date_array(self,form):
218             return_array = self.date_range(form['date_from'],form['date_to'])
219             self.date_lst = return_array
220             self.date_lst.sort()
221             
222         def _sum_credit(self):
223             return self.sum_credit 
224     
225         def _sum_debit(self):
226             return self.sum_debit 
227 report_sxw.report_sxw('report.account.account.balance', 'account.account', 'addons/account/report/account_balance.rml', parser=account_balance, header=2)
228