blob: 71ce8051379c013943cec83f3557fd221668e8dd [file] [log] [blame]
Rushabh Mehta3966f1d2012-02-23 12:35:32 +05301# ERPNext - web based ERP (http://erpnext.com)
2# Copyright (C) 2012 Web Notes Technologies Pvt Ltd
3#
4# This program is free software: you can redistribute it and/or modify
5# it under the terms of the GNU General Public License as published by
6# the Free Software Foundation, either version 3 of the License, or
7# (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License
15# along with this program. If not, see <http://www.gnu.org/licenses/>.
16
Anand Doshi486f9df2012-07-19 13:40:31 +053017from __future__ import unicode_literals
Rushabh Mehta29a75c42011-08-25 19:17:44 +053018dashboards = [
19 {
20 'type': 'account',
21 'account': 'Income',
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +053022 'title': 'Income',
23 'fillColor': '#90EE90'
Rushabh Mehta29a75c42011-08-25 19:17:44 +053024 },
25
26 {
27 'type': 'account',
28 'account': 'Expenses',
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +053029 'title': 'Expenses',
30 'fillColor': '#90EE90'
Rushabh Mehta29a75c42011-08-25 19:17:44 +053031 },
32
33 {
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +053034 'type': 'receivables',
35 'title': 'Receivables',
36 'fillColor': '#FFE4B5'
Rushabh Mehta29a75c42011-08-25 19:17:44 +053037 },
38
39 {
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +053040 'type': 'payables',
41 'title': 'Payables',
42 'fillColor': '#FFE4B5'
Rushabh Mehta29a75c42011-08-25 19:17:44 +053043 },
44
45 {
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +053046 'type': 'collection',
47 'title': 'Collection',
48 'comment':'This info comes from the accounts your have marked as "Bank or Cash"',
49 'fillColor': '#DDA0DD'
Rushabh Mehta29a75c42011-08-25 19:17:44 +053050 },
51
52 {
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +053053 'type': 'payments',
54 'title': 'Payments',
55 'comment':'This info comes from the accounts your have marked as "Bank or Cash"',
56 'fillColor': '#DDA0DD'
Rushabh Mehta29a75c42011-08-25 19:17:44 +053057 },
58
59 {
60 'type': 'creation',
61 'doctype': 'Quotation',
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +053062 'title': 'New Quotations',
63 'fillColor': '#ADD8E6'
Rushabh Mehta29a75c42011-08-25 19:17:44 +053064 },
65
66 {
67 'type': 'creation',
68 'doctype': 'Sales Order',
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +053069 'title': 'New Orders',
70 'fillColor': '#ADD8E6'
Rushabh Mehta29a75c42011-08-25 19:17:44 +053071 }
72]
73
Rushabh Mehtaf17ce7b2012-02-13 16:50:52 +053074import webnotes
75
Rushabh Mehta29a75c42011-08-25 19:17:44 +053076class DashboardWidget:
77 def __init__(self, company, start, end, interval):
Rushabh Mehta29a75c42011-08-25 19:17:44 +053078 from webnotes.utils import getdate
79 from webnotes.model.code import get_obj
80
81 self.company = company
82 self.abbr = webnotes.conn.get_value('Company', company, 'abbr')
83 self.start = getdate(start)
84 self.end = getdate(end)
85
86 self.interval = interval
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +053087
Rushabh Mehta29a75c42011-08-25 19:17:44 +053088 self.glc = get_obj('GL Control')
89 self.cash_accounts = [d[0] for d in webnotes.conn.sql("""
90 select name from tabAccount
91 where account_type='Bank or Cash'
92 and company = %s and docstatus = 0
93 """, company)]
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +053094
95 self.receivables_group = webnotes.conn.get_value('Company', company,'receivables_group')
96 self.payables_group = webnotes.conn.get_value('Company', company,'payables_group')
97
98 # list of bank and cash accounts
99 self.bc_list = [s[0] for s in webnotes.conn.sql("select name from tabAccount where account_type='Bank or Cash'")]
100
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530101
102 def timeline(self):
103 """
104 get the timeline for the dashboard
105 """
106 import webnotes
107 from webnotes.utils import add_days
108 tl = []
109
110 if self.start > self.end:
111 webnotes.msgprint("Start must be before end", raise_exception=1)
112
113 curr = self.start
114 tl.append(curr)
115
116 while curr < self.end:
117 curr = add_days(curr, self.interval, 'date')
118 tl.append(curr)
119
120 tl.append(self.end)
121
122 return tl
123
124 def generate(self, opts):
125 """
126 Generate the dasboard
127 """
Rushabh Mehtac7fbbba2011-08-30 13:45:57 +0530128 from webnotes.utils import flt
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530129 tl = self.timeline()
130 self.out = []
131
132 for i in range(len(tl)-1):
Rushabh Mehtac7fbbba2011-08-30 13:45:57 +0530133 self.out.append([tl[i+1].strftime('%Y-%m-%d'), flt(self.value(opts, tl[i], tl[i+1])) or 0])
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530134
135 return self.out
136
137 def get_account_balance(self, acc, start):
138 """
139 Get as on account balance
140 """
141 import webnotes
142 # add abbreviation to company
143
144 if not acc.endswith(self.abbr):
145 acc += ' - ' + self.abbr
146
147 # get other reqd parameters
148 try:
149 globals().update(webnotes.conn.sql('select debit_or_credit, lft, rgt from tabAccount where name=%s', acc, as_dict=1)[0])
150 except Exception,e:
151 webnotes.msgprint('Wrongly defined account: ' + acc)
152 print acc
153 raise e
Anand Doshi3a23a572011-12-12 19:50:09 +0530154
155 fiscal_year = self.get_fiscal_year(start)
156 if fiscal_year:
157 return self.glc.get_as_on_balance(acc, fiscal_year, start, debit_or_credit, lft, rgt)
158 else:
159 webnotes.msgprint('Please select the START DATE and END DATE such that\
Anand Doshi130ae982011-12-12 20:24:06 +0530160 they fall within <b>fiscal year(s)</b> as defined in\
Anand Doshi3a23a572011-12-12 19:50:09 +0530161 Setup > System > Fiscal Year.', raise_exception=1)
162
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530163
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +0530164 def get_fiscal_year(self, dt):
165 """
166 get fiscal year from date
167 """
168 import webnotes
Anand Doshi3a23a572011-12-12 19:50:09 +0530169 fiscal_year = webnotes.conn.sql("""
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +0530170 select name from `tabFiscal Year`
171 where year_start_date <= %s and
172 DATE_ADD(year_start_date, INTERVAL 1 YEAR) >= %s
Anand Doshi3a23a572011-12-12 19:50:09 +0530173 """, (dt, dt))
174 return fiscal_year and (fiscal_year[0] and fiscal_year[0][0]) or None
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +0530175
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530176 def get_creation_trend(self, doctype, start, end):
177 """
178 Get creation # of creations in period
179 """
180 import webnotes
181 return int(webnotes.conn.sql("""
182 select count(*) from `tab%s` where creation between %s and %s and docstatus=1
183 """ % (doctype, '%s','%s'), (start, end))[0][0])
184
Rushabh Mehta0a187be2011-08-25 19:28:02 +0530185 def get_account_amt(self, acc, start, end, debit_or_credit):
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530186 """
187 Get debit, credit over a period
188 """
189 import webnotes
190 # add abbreviation to company
191
192 if not acc.endswith(self.abbr):
193 acc += ' - ' + self.abbr
194
195 ret = webnotes.conn.sql("""
196 select ifnull(sum(ifnull(t1.debit,0)),0), ifnull(sum(ifnull(t1.credit,0)),0)
197 from `tabGL Entry` t1, tabAccount t2
198 where t1.account = t2.name
199 and t2.is_pl_account = 'Yes'
200 and t2.debit_or_credit=%s
201 and ifnull(t1.is_cancelled, 'No')='No'
202 and t1.posting_date between %s and %s
Rushabh Mehta0a187be2011-08-25 19:28:02 +0530203 """, (debit_or_credit, start, end))[0]
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530204
Rushabh Mehtac91f88c2011-08-25 19:28:56 +0530205 return debit_or_credit=='Credit' and float(ret[1]-ret[0]) or float(ret[0]-ret[1])
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530206
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +0530207 def get_bank_amt(self, debit_or_credit, master_type, start, end):
208 """
209 Get collection (reduction in receivables over a period)
210 """
211 import webnotes
212
213 reg = '('+'|'.join(self.bc_list) + ')'
214
215 return webnotes.conn.sql("""
216 select sum(t1.%s)
217 from `tabGL Entry` t1, tabAccount t2
218 where t1.account = t2.name
219 and t2.master_type='%s'
220 and t1.%s > 0
221 and t1.against REGEXP '%s'
222 and ifnull(t1.is_cancelled, 'No')='No'
223 and t1.posting_date between '%s' and '%s'
224 """ % (debit_or_credit, master_type, debit_or_credit, reg, start, end))[0][0]
225
226
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530227 def value(self, opts, start, end):
228 """
229 Value of the series on a particular date
230 """
231 import webnotes
232 if opts['type']=='account':
Rushabh Mehta0a187be2011-08-25 19:28:02 +0530233 debit_or_credit = 'Debit'
234 if opts['account']=='Income':
235 debit_or_credit = 'Credit'
236
237 return self.get_account_amt(opts['account'], start, end, debit_or_credit)
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530238
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +0530239 elif opts['type']=='receivables':
240 return self.get_account_balance(self.receivables_group, end)[2]
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530241
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +0530242 elif opts['type']=='payables':
243 return self.get_account_balance(self.payables_group, end)[2]
244
245 elif opts['type']=='collection':
246 return self.get_bank_amt('credit', 'Customer', start, end)
247
248 elif opts['type']=='payments':
Rushabh Mehta0b230d12011-08-30 13:55:55 +0530249 return self.get_bank_amt('debit', 'Supplier', start, end)
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530250
251 elif opts['type']=='creation':
252 return self.get_creation_trend(opts['doctype'], start, end)
253
Rushabh Mehtaf17ce7b2012-02-13 16:50:52 +0530254@webnotes.whitelist()
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530255def load_dashboard(args):
256 """
257 Get dashboard based on
258 1. Company (default company)
259 2. Start Date (last 3 months)
260 3. End Date (today)
261 4. Interval (7 days)
262 """
263 dl = []
264 import json
265 args = json.loads(args)
266 dw = DashboardWidget(args['company'], args['start'], args['end'], int(args['interval']))
267
268 # render the dashboards
269 for d in dashboards:
270 dl.append([d, dw.generate(d)])
271
272 return dl
273
274if __name__=='__main__':
275 import sys
276 sys.path.append('/var/www/webnotes/wnframework/cgi-bin')
277 from webnotes.db import Database
278 import webnotes
279 webnotes.conn = Database(use_default=1)
280 webnotes.session = {'user':'Administrator'}
281 print load_dashboard("""{
282 "company": "My Test",
283 "start": "2011-05-01",
284 "end": "2011-08-01",
285 "interval": "7"
Anand Doshi3a23a572011-12-12 19:50:09 +0530286 }""")