blob: 29f15022fc265ac7ea5986021c9d0363e764c0ac [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
Rushabh Mehta29a75c42011-08-25 19:17:44 +053017dashboards = [
18 {
19 'type': 'account',
20 'account': 'Income',
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +053021 'title': 'Income',
22 'fillColor': '#90EE90'
Rushabh Mehta29a75c42011-08-25 19:17:44 +053023 },
24
25 {
26 'type': 'account',
27 'account': 'Expenses',
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +053028 'title': 'Expenses',
29 'fillColor': '#90EE90'
Rushabh Mehta29a75c42011-08-25 19:17:44 +053030 },
31
32 {
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +053033 'type': 'receivables',
34 'title': 'Receivables',
35 'fillColor': '#FFE4B5'
Rushabh Mehta29a75c42011-08-25 19:17:44 +053036 },
37
38 {
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +053039 'type': 'payables',
40 'title': 'Payables',
41 'fillColor': '#FFE4B5'
Rushabh Mehta29a75c42011-08-25 19:17:44 +053042 },
43
44 {
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +053045 'type': 'collection',
46 'title': 'Collection',
47 'comment':'This info comes from the accounts your have marked as "Bank or Cash"',
48 'fillColor': '#DDA0DD'
Rushabh Mehta29a75c42011-08-25 19:17:44 +053049 },
50
51 {
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +053052 'type': 'payments',
53 'title': 'Payments',
54 'comment':'This info comes from the accounts your have marked as "Bank or Cash"',
55 'fillColor': '#DDA0DD'
Rushabh Mehta29a75c42011-08-25 19:17:44 +053056 },
57
58 {
59 'type': 'creation',
60 'doctype': 'Quotation',
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +053061 'title': 'New Quotations',
62 'fillColor': '#ADD8E6'
Rushabh Mehta29a75c42011-08-25 19:17:44 +053063 },
64
65 {
66 'type': 'creation',
67 'doctype': 'Sales Order',
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +053068 'title': 'New Orders',
69 'fillColor': '#ADD8E6'
Rushabh Mehta29a75c42011-08-25 19:17:44 +053070 }
71]
72
Rushabh Mehtaf17ce7b2012-02-13 16:50:52 +053073import webnotes
74
Rushabh Mehta29a75c42011-08-25 19:17:44 +053075class DashboardWidget:
76 def __init__(self, company, start, end, interval):
Rushabh Mehta29a75c42011-08-25 19:17:44 +053077 from webnotes.utils import getdate
78 from webnotes.model.code import get_obj
79
80 self.company = company
81 self.abbr = webnotes.conn.get_value('Company', company, 'abbr')
82 self.start = getdate(start)
83 self.end = getdate(end)
84
85 self.interval = interval
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +053086
Rushabh Mehta29a75c42011-08-25 19:17:44 +053087 self.glc = get_obj('GL Control')
88 self.cash_accounts = [d[0] for d in webnotes.conn.sql("""
89 select name from tabAccount
90 where account_type='Bank or Cash'
91 and company = %s and docstatus = 0
92 """, company)]
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +053093
94 self.receivables_group = webnotes.conn.get_value('Company', company,'receivables_group')
95 self.payables_group = webnotes.conn.get_value('Company', company,'payables_group')
96
97 # list of bank and cash accounts
98 self.bc_list = [s[0] for s in webnotes.conn.sql("select name from tabAccount where account_type='Bank or Cash'")]
99
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530100
101 def timeline(self):
102 """
103 get the timeline for the dashboard
104 """
105 import webnotes
106 from webnotes.utils import add_days
107 tl = []
108
109 if self.start > self.end:
110 webnotes.msgprint("Start must be before end", raise_exception=1)
111
112 curr = self.start
113 tl.append(curr)
114
115 while curr < self.end:
116 curr = add_days(curr, self.interval, 'date')
117 tl.append(curr)
118
119 tl.append(self.end)
120
121 return tl
122
123 def generate(self, opts):
124 """
125 Generate the dasboard
126 """
Rushabh Mehtac7fbbba2011-08-30 13:45:57 +0530127 from webnotes.utils import flt
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530128 tl = self.timeline()
129 self.out = []
130
131 for i in range(len(tl)-1):
Rushabh Mehtac7fbbba2011-08-30 13:45:57 +0530132 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 +0530133
134 return self.out
135
136 def get_account_balance(self, acc, start):
137 """
138 Get as on account balance
139 """
140 import webnotes
141 # add abbreviation to company
142
143 if not acc.endswith(self.abbr):
144 acc += ' - ' + self.abbr
145
146 # get other reqd parameters
147 try:
148 globals().update(webnotes.conn.sql('select debit_or_credit, lft, rgt from tabAccount where name=%s', acc, as_dict=1)[0])
149 except Exception,e:
150 webnotes.msgprint('Wrongly defined account: ' + acc)
151 print acc
152 raise e
Anand Doshi3a23a572011-12-12 19:50:09 +0530153
154 fiscal_year = self.get_fiscal_year(start)
155 if fiscal_year:
156 return self.glc.get_as_on_balance(acc, fiscal_year, start, debit_or_credit, lft, rgt)
157 else:
158 webnotes.msgprint('Please select the START DATE and END DATE such that\
Anand Doshi130ae982011-12-12 20:24:06 +0530159 they fall within <b>fiscal year(s)</b> as defined in\
Anand Doshi3a23a572011-12-12 19:50:09 +0530160 Setup > System > Fiscal Year.', raise_exception=1)
161
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530162
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +0530163 def get_fiscal_year(self, dt):
164 """
165 get fiscal year from date
166 """
167 import webnotes
Anand Doshi3a23a572011-12-12 19:50:09 +0530168 fiscal_year = webnotes.conn.sql("""
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +0530169 select name from `tabFiscal Year`
170 where year_start_date <= %s and
171 DATE_ADD(year_start_date, INTERVAL 1 YEAR) >= %s
Anand Doshi3a23a572011-12-12 19:50:09 +0530172 """, (dt, dt))
173 return fiscal_year and (fiscal_year[0] and fiscal_year[0][0]) or None
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +0530174
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530175 def get_creation_trend(self, doctype, start, end):
176 """
177 Get creation # of creations in period
178 """
179 import webnotes
180 return int(webnotes.conn.sql("""
181 select count(*) from `tab%s` where creation between %s and %s and docstatus=1
182 """ % (doctype, '%s','%s'), (start, end))[0][0])
183
Rushabh Mehta0a187be2011-08-25 19:28:02 +0530184 def get_account_amt(self, acc, start, end, debit_or_credit):
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530185 """
186 Get debit, credit over a period
187 """
188 import webnotes
189 # add abbreviation to company
190
191 if not acc.endswith(self.abbr):
192 acc += ' - ' + self.abbr
193
194 ret = webnotes.conn.sql("""
195 select ifnull(sum(ifnull(t1.debit,0)),0), ifnull(sum(ifnull(t1.credit,0)),0)
196 from `tabGL Entry` t1, tabAccount t2
197 where t1.account = t2.name
198 and t2.is_pl_account = 'Yes'
199 and t2.debit_or_credit=%s
200 and ifnull(t1.is_cancelled, 'No')='No'
201 and t1.posting_date between %s and %s
Rushabh Mehta0a187be2011-08-25 19:28:02 +0530202 """, (debit_or_credit, start, end))[0]
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530203
Rushabh Mehtac91f88c2011-08-25 19:28:56 +0530204 return debit_or_credit=='Credit' and float(ret[1]-ret[0]) or float(ret[0]-ret[1])
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530205
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +0530206 def get_bank_amt(self, debit_or_credit, master_type, start, end):
207 """
208 Get collection (reduction in receivables over a period)
209 """
210 import webnotes
211
212 reg = '('+'|'.join(self.bc_list) + ')'
213
214 return webnotes.conn.sql("""
215 select sum(t1.%s)
216 from `tabGL Entry` t1, tabAccount t2
217 where t1.account = t2.name
218 and t2.master_type='%s'
219 and t1.%s > 0
220 and t1.against REGEXP '%s'
221 and ifnull(t1.is_cancelled, 'No')='No'
222 and t1.posting_date between '%s' and '%s'
223 """ % (debit_or_credit, master_type, debit_or_credit, reg, start, end))[0][0]
224
225
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530226 def value(self, opts, start, end):
227 """
228 Value of the series on a particular date
229 """
230 import webnotes
231 if opts['type']=='account':
Rushabh Mehta0a187be2011-08-25 19:28:02 +0530232 debit_or_credit = 'Debit'
233 if opts['account']=='Income':
234 debit_or_credit = 'Credit'
235
236 return self.get_account_amt(opts['account'], start, end, debit_or_credit)
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530237
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +0530238 elif opts['type']=='receivables':
239 return self.get_account_balance(self.receivables_group, end)[2]
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530240
Rushabh Mehtaae5cdeb2011-08-30 13:24:49 +0530241 elif opts['type']=='payables':
242 return self.get_account_balance(self.payables_group, end)[2]
243
244 elif opts['type']=='collection':
245 return self.get_bank_amt('credit', 'Customer', start, end)
246
247 elif opts['type']=='payments':
Rushabh Mehta0b230d12011-08-30 13:55:55 +0530248 return self.get_bank_amt('debit', 'Supplier', start, end)
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530249
250 elif opts['type']=='creation':
251 return self.get_creation_trend(opts['doctype'], start, end)
252
Rushabh Mehtaf17ce7b2012-02-13 16:50:52 +0530253@webnotes.whitelist()
Rushabh Mehta29a75c42011-08-25 19:17:44 +0530254def load_dashboard(args):
255 """
256 Get dashboard based on
257 1. Company (default company)
258 2. Start Date (last 3 months)
259 3. End Date (today)
260 4. Interval (7 days)
261 """
262 dl = []
263 import json
264 args = json.loads(args)
265 dw = DashboardWidget(args['company'], args['start'], args['end'], int(args['interval']))
266
267 # render the dashboards
268 for d in dashboards:
269 dl.append([d, dw.generate(d)])
270
271 return dl
272
273if __name__=='__main__':
274 import sys
275 sys.path.append('/var/www/webnotes/wnframework/cgi-bin')
276 from webnotes.db import Database
277 import webnotes
278 webnotes.conn = Database(use_default=1)
279 webnotes.session = {'user':'Administrator'}
280 print load_dashboard("""{
281 "company": "My Test",
282 "start": "2011-05-01",
283 "end": "2011-08-01",
284 "interval": "7"
Anand Doshi3a23a572011-12-12 19:50:09 +0530285 }""")