blob: 3ce3b0c37d50685fc0f88ff519f70f74edd6df81 [file] [log] [blame]
Rushabh Mehta29a75c42011-08-25 19:17:44 +05301dashboards = [
2 {
3 'type': 'account',
4 'account': 'Income',
5 'title': 'Income'
6 },
7
8 {
9 'type': 'account',
10 'account': 'Expenses',
11 'title': 'Expenses'
12 },
13
14 {
15 'type': 'from_company',
16 'account': 'receivables_group',
17 'title': 'Receivables'
18 },
19
20 {
21 'type': 'from_company',
22 'account': 'payables_group',
23 'title': 'Payables'
24 },
25
26 {
27 'type': 'cash',
28 'debit_or_credit': 'Debit',
29 'title': 'Cash Inflow'
30 },
31
32 {
33 'type': 'cash',
34 'debit_or_credit': 'Credit',
35 'title': 'Cash Outflow'
36 },
37
38 {
39 'type': 'creation',
40 'doctype': 'Quotation',
41 'title': 'New Quotations'
42 },
43
44 {
45 'type': 'creation',
46 'doctype': 'Sales Order',
47 'title': 'New Orders'
48 }
49]
50
51
52class DashboardWidget:
53 def __init__(self, company, start, end, interval):
54 import webnotes
55 from webnotes.utils import getdate
56 from webnotes.model.code import get_obj
57
58 self.company = company
59 self.abbr = webnotes.conn.get_value('Company', company, 'abbr')
60 self.start = getdate(start)
61 self.end = getdate(end)
62
63 self.interval = interval
64 self.fiscal_year = webnotes.conn.sql("""
65 select name from `tabFiscal Year`
66 where year_start_date <= %s and
67 DATE_ADD(year_start_date, INTERVAL 1 YEAR) >= %s
68 """, (start, start))[0][0]
69 self.glc = get_obj('GL Control')
70 self.cash_accounts = [d[0] for d in webnotes.conn.sql("""
71 select name from tabAccount
72 where account_type='Bank or Cash'
73 and company = %s and docstatus = 0
74 """, company)]
75
76 def timeline(self):
77 """
78 get the timeline for the dashboard
79 """
80 import webnotes
81 from webnotes.utils import add_days
82 tl = []
83
84 if self.start > self.end:
85 webnotes.msgprint("Start must be before end", raise_exception=1)
86
87 curr = self.start
88 tl.append(curr)
89
90 while curr < self.end:
91 curr = add_days(curr, self.interval, 'date')
92 tl.append(curr)
93
94 tl.append(self.end)
95
96 return tl
97
98 def generate(self, opts):
99 """
100 Generate the dasboard
101 """
102 tl = self.timeline()
103 self.out = []
104
105 for i in range(len(tl)-1):
106 self.out.append([tl[i+1].strftime('%Y-%m-%d'), self.value(opts, tl[i], tl[i+1]) or 0])
107
108 return self.out
109
110 def get_account_balance(self, acc, start):
111 """
112 Get as on account balance
113 """
114 import webnotes
115 # add abbreviation to company
116
117 if not acc.endswith(self.abbr):
118 acc += ' - ' + self.abbr
119
120 # get other reqd parameters
121 try:
122 globals().update(webnotes.conn.sql('select debit_or_credit, lft, rgt from tabAccount where name=%s', acc, as_dict=1)[0])
123 except Exception,e:
124 webnotes.msgprint('Wrongly defined account: ' + acc)
125 print acc
126 raise e
127
128 return self.glc.get_as_on_balance(acc, self.fiscal_year, start, debit_or_credit, lft, rgt)
129
130 def get_creation_trend(self, doctype, start, end):
131 """
132 Get creation # of creations in period
133 """
134 import webnotes
135 return int(webnotes.conn.sql("""
136 select count(*) from `tab%s` where creation between %s and %s and docstatus=1
137 """ % (doctype, '%s','%s'), (start, end))[0][0])
138
139 def get_account_amt(self, acc, start, end):
140 """
141 Get debit, credit over a period
142 """
143 import webnotes
144 # add abbreviation to company
145
146 if not acc.endswith(self.abbr):
147 acc += ' - ' + self.abbr
148
149 ret = webnotes.conn.sql("""
150 select ifnull(sum(ifnull(t1.debit,0)),0), ifnull(sum(ifnull(t1.credit,0)),0)
151 from `tabGL Entry` t1, tabAccount t2
152 where t1.account = t2.name
153 and t2.is_pl_account = 'Yes'
154 and t2.debit_or_credit=%s
155 and ifnull(t1.is_cancelled, 'No')='No'
156 and t1.posting_date between %s and %s
157 """, (acc=='Income' and 'Credit' or 'Debit', start, end))[0]
158
159 return acc=='Income' and (ret[1]-ret[0]) or (ret[0]-ret[1])
160
161 def value(self, opts, start, end):
162 """
163 Value of the series on a particular date
164 """
165 import webnotes
166 if opts['type']=='account':
167 bal = self.get_account_amt(opts['account'], start, end)
168
169 elif opts['type']=='from_company':
170 acc = webnotes.conn.get_value('Company', self.company, \
171 opts['account'].split('.')[-1])
172
173 return self.get_account_balance(acc, start)[2]
174
175 elif opts['type']=='cash':
176 if type=='Credit':
177 return sum([self.get_account_balance(acc, start)[1] for acc in self.cash_accounts]) or 0
178 if type=='Debit':
179 return sum([self.get_account_balance(acc, start)[0] for acc in self.cash_accounts]) or 0
180
181 elif opts['type']=='creation':
182 return self.get_creation_trend(opts['doctype'], start, end)
183
184
185def load_dashboard(args):
186 """
187 Get dashboard based on
188 1. Company (default company)
189 2. Start Date (last 3 months)
190 3. End Date (today)
191 4. Interval (7 days)
192 """
193 dl = []
194 import json
195 args = json.loads(args)
196 dw = DashboardWidget(args['company'], args['start'], args['end'], int(args['interval']))
197
198 # render the dashboards
199 for d in dashboards:
200 dl.append([d, dw.generate(d)])
201
202 return dl
203
204if __name__=='__main__':
205 import sys
206 sys.path.append('/var/www/webnotes/wnframework/cgi-bin')
207 from webnotes.db import Database
208 import webnotes
209 webnotes.conn = Database(use_default=1)
210 webnotes.session = {'user':'Administrator'}
211 print load_dashboard("""{
212 "company": "My Test",
213 "start": "2011-05-01",
214 "end": "2011-08-01",
215 "interval": "7"
216 }""")