api_organisation.py 18 KB
Newer Older
1
2

"""
abhi1tb's avatar
abhi1tb committed
3
Copyright (C) 2013, 2014, 2015, 2016 Digital Freedom Foundation
4
5
6
  This file is part of GNUKhata:A modular,robust and Free Accounting System.

  GNUKhata is Free Software; you can redistribute it and/or modify
abhi1tb's avatar
abhi1tb committed
7
  it under the terms of the GNU Affero General Public License as
8
9
10
11
12
13
  published by the Free Software Foundation; either version 3 of
  the License, or (at your option) any later version.and old.stockflag = 's'

  GNUKhata is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
abhi1tb's avatar
abhi1tb committed
14
  GNU Affero General Public License for more details.
15

abhi1tb's avatar
abhi1tb committed
16
  You should have received a copy of the GNU Affero General Public
17
18
19
20
21
  License along with GNUKhata (COPYING); if not, write to the
  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  Boston, MA  02110-1301  USA59 Temple Place, Suite 330,


abhi1tb's avatar
abhi1tb committed
22
Contributors:
23
24
25
26
27
28
"Krishnakant Mane" <kk@gmail.com>
"Ishan Masdekar " <imasdekar@dff.org.in>
"Navin Karkera" <navin@dff.org.in>
"""


29
from pyramid.view import view_defaults,  view_config
30
from gkcore.views.api_login import authCheck
31
from gkcore import eng, enumdict
32
from pyramid.request import Request
33
from gkcore.models import gkdb
34
from sqlalchemy.sql import select, distinct
35
from sqlalchemy import func, desc
36
import json
37
from sqlalchemy.engine.base import Connection
38
from sqlalchemy import and_
39
40
import jwt
import gkcore
41
from gkcore.models.meta import dbconnect
42
from Crypto.PublicKey import RSA
43

44
@view_defaults(route_name='organisations')
45
46
class api_organisation(object):
	def __init__(self,request):
47
		self.request = Request
48
		self.request = request
49
50
		self.con = Connection
		print "Organisation initialized"
51

52
53
	@view_config(request_method='GET', renderer ='json')
	def getOrgs(self):
54
		try:
55
			self.con=eng.connect()
56
			result = self.con.execute(select([gkdb.organisation.c.orgname, gkdb.organisation.c.orgtype]).order_by(gkdb.organisation.c.orgname).distinct())
57
58
59
			orgs = []
			for row in result:
				orgs.append({"orgname":row["orgname"], "orgtype":row["orgtype"]})
60
			self.con.close()
61
62
			return {"gkstatus":enumdict["Success"], "gkdata":orgs}
		except:
63
			self.con.close()
64
			return {"gkstatus":enumdict["ConnectionFailed"]}
65

66
67
	@view_config(route_name='orgyears', request_method='GET', renderer ='json')
	def getYears(self):
68
		try:
69
			self.con = eng.connect()
70
			result = self.con.execute(select([gkdb.organisation.c.yearstart, gkdb.organisation.c.yearend,gkdb.organisation.c.orgcode]).where(and_(gkdb.organisation.c.orgname==self.request.matchdict["orgname"], gkdb.organisation.c.orgtype == self.request.matchdict["orgtype"])).order_by(desc(gkdb.organisation.c.yearend)))
71
72
73
			years = []
			for row in result:
				years.append({"yearstart":str(row["yearstart"]), "yearend":str(row["yearend"]),"orgcode":row["orgcode"]})
74
			self.con.close()
75
76
			return {"gkstatus":enumdict["Success"],"gkdata":years}
		except:
77
			self.con.close()
78
			return {"gkstatus":enumdict["ConnectionFailed"]}
79

80
81
	@view_config(request_method='POST',renderer='json')
	def postOrg(self):
82

83
		try:
84
			self.con = eng.connect()
85
			dataset = self.request.json_body
86
87
			orgdata = dataset["orgdetails"]
			userdata = dataset["userdetails"]
88
89
90
			result = self.con.execute(select([gkdb.signature]))
			sign = result.fetchone()
			if sign == None:
91
92
93
94
95
				key = RSA.generate(2560)
				privatekey = key.exportKey('PEM')
				sig = {"secretcode":privatekey}
				gkcore.secret = privatekey
				result = self.con.execute(gkdb.signature.insert(),[sig])
96
97
98
99
100
101
102
103
			elif len(sign["secretcode"]) <= 20:
				result = con.execute(gkdb.signature.delete())
				if result.rowcount == 1:
					key = RSA.generate(2560)
					privatekey = key.exportKey('PEM')
					sig = {"secretcode":privatekey}
					gkcore.secret = privatekey
					result = self.con.execute(gkdb.signature.insert(),[sig])
104
			result = self.con.execute(gkdb.organisation.insert(),[orgdata])
105
			if result.rowcount==1:
106
				code = self.con.execute(select([gkdb.organisation.c.orgcode]).where(and_(gkdb.organisation.c.orgname==orgdata["orgname"], gkdb.organisation.c.orgtype==orgdata["orgtype"], gkdb.organisation.c.yearstart==orgdata["yearstart"], gkdb.organisation.c.yearend==orgdata["yearend"])))
107
				orgcode = code.fetchone()
108
				try:
109
					currentassets= {"groupname":"Current Assets","orgcode":orgcode["orgcode"]}
110
111
					result = self.con.execute(gkdb.groupsubgroups.insert(),currentassets)
					result = self.con.execute(select([gkdb.groupsubgroups.c.groupcode]).where(and_(gkdb.groupsubgroups.c.groupname=="Current Assets",gkdb.groupsubgroups.c.orgcode==orgcode["orgcode"])))
112
					grpcode = result.fetchone()
113
					result = self.con.execute(gkdb.groupsubgroups.insert(),[{"groupname":"Bank","orgcode":orgcode["orgcode"],"subgroupof":grpcode["groupcode"]},{"groupname":"Cash","orgcode":orgcode["orgcode"],"subgroupof":grpcode["groupcode"]},{"groupname":"Inventory","orgcode":orgcode["orgcode"],"subgroupof":grpcode["groupcode"]},{"groupname":"Loans & Advance","orgcode":orgcode["orgcode"],"subgroupof":grpcode["groupcode"]},{"groupname":"Sundry Debtors","orgcode":orgcode["orgcode"],"subgroupof":grpcode["groupcode"]} ])
114

115
					currentliability= {"groupname":"Current Liabilities","orgcode":orgcode["orgcode"]}
116
117
					result = self.con.execute(gkdb.groupsubgroups.insert(),currentliability)
					result = self.con.execute(select([gkdb.groupsubgroups.c.groupcode]).where(and_(gkdb.groupsubgroups.c.groupname=="Current Liabilities",gkdb.groupsubgroups.c.orgcode==orgcode["orgcode"])))
118
					grpcode = result.fetchone()
119
					result = self.con.execute(gkdb.groupsubgroups.insert(),[{"groupname":"Provisions","orgcode":orgcode["orgcode"],"subgroupof":grpcode["groupcode"]},{"groupname":"Sundry Creditors for Expense","orgcode":orgcode["orgcode"],"subgroupof":grpcode["groupcode"]},{"groupname":"Sundry Creditors for Purchase","orgcode":orgcode["orgcode"],"subgroupof":grpcode["groupcode"]}])
120

121
					directexpense= {"groupname":"Direct Expense","orgcode":orgcode["orgcode"]}
122
					result = self.con.execute(gkdb.groupsubgroups.insert(),directexpense)
123

124
					directincome= {"groupname":"Direct Income","orgcode":orgcode["orgcode"]}
125
					result = self.con.execute(gkdb.groupsubgroups.insert(),directincome)
126

127
					fixedassets= {"groupname":"Fixed Assets","orgcode":orgcode["orgcode"]}
128
129
					result = self.con.execute(gkdb.groupsubgroups.insert(),fixedassets)
					result = self.con.execute(select([gkdb.groupsubgroups.c.groupcode]).where(and_(gkdb.groupsubgroups.c.groupname=="Fixed Assets",gkdb.groupsubgroups.c.orgcode==orgcode["orgcode"])))
130
					grpcode = result.fetchone()
131
					result = self.con.execute(gkdb.groupsubgroups.insert(),[{"groupname":"Building","orgcode":orgcode["orgcode"],"subgroupof":grpcode["groupcode"]},{"groupname":"Furniture","orgcode":orgcode["orgcode"],"subgroupof":grpcode["groupcode"]},{"groupname":"Land","orgcode":orgcode["orgcode"],"subgroupof":grpcode["groupcode"]},{"groupname":"Plant & Machinery","orgcode":orgcode["orgcode"],"subgroupof":grpcode["groupcode"]} ])
132

133
					indirectexpense= {"groupname":"Indirect Expense","orgcode":orgcode["orgcode"]}
134
					result = self.con.execute(gkdb.groupsubgroups.insert(),indirectexpense)
135

136
					indirectincome= {"groupname":"Indirect Income","orgcode":orgcode["orgcode"]}
137
					result = self.con.execute(gkdb.groupsubgroups.insert(),indirectincome)
138

139
					investment= {"groupname":"Investments","orgcode":orgcode["orgcode"]}
140
141
					result = self.con.execute(gkdb.groupsubgroups.insert(),investment)
					result = self.con.execute(select([gkdb.groupsubgroups.c.groupcode]).where(and_(gkdb.groupsubgroups.c.groupname=="Investments",gkdb.groupsubgroups.c.orgcode==orgcode["orgcode"])))
142
					grpcode = result.fetchone()
143
					result = self.con.execute(gkdb.groupsubgroups.insert(),[{"groupname":"Investment in Bank Deposits","orgcode":orgcode["orgcode"],"subgroupof":grpcode["groupcode"]},{"groupname":"Investment in Shares & Debentures","orgcode":orgcode["orgcode"],"subgroupof":grpcode["groupcode"]}, ])
144

145
					loansasset= {"groupname":"Loans(Asset)","orgcode":orgcode["orgcode"]}
146
					result = self.con.execute(gkdb.groupsubgroups.insert(),loansasset)
147

148
					loansliab= {"groupname":"Loans(Liability)","orgcode":orgcode["orgcode"]}
149
150
					result = self.con.execute(gkdb.groupsubgroups.insert(),loansliab)
					result = self.con.execute(select([gkdb.groupsubgroups.c.groupcode]).where(and_(gkdb.groupsubgroups.c.groupname=="Loans(Liability)",gkdb.groupsubgroups.c.orgcode==orgcode["orgcode"])))
151
					grpcode = result.fetchone()
152
					result = self.con.execute(gkdb.groupsubgroups.insert(),[{"groupname":"Secured","orgcode":orgcode["orgcode"],"subgroupof":grpcode["groupcode"]},{"groupname":"Unsecured","orgcode":orgcode["orgcode"],"subgroupof":grpcode["groupcode"]} ])
153

154
					reserves= {"groupname":"Reserves","orgcode":orgcode["orgcode"]}
155
					result = self.con.execute(gkdb.groupsubgroups.insert(),reserves)
156

157
					result = self.con.execute(select([gkdb.groupsubgroups.c.groupcode]).where(and_(gkdb.groupsubgroups.c.groupname=="Direct Income",gkdb.groupsubgroups.c.orgcode==orgcode["orgcode"])))
158
159
					grpcode = result.fetchone()
					if orgdata["orgtype"] == "Profit Making":
160
						result = self.con.execute(gkdb.groupsubgroups.insert(),[{"groupname":"Capital","orgcode":orgcode["orgcode"]},{"groupname":"Miscellaneous Expenses(Asset)","orgcode":orgcode["orgcode"]}])
161

162
						result = self.con.execute(gkdb.accounts.insert(),{"accountname":"Profit & Loss","groupcode":grpcode["groupcode"],"orgcode":orgcode["orgcode"]})
163

164
					else:
165
						result = self.con.execute(gkdb.groupsubgroups.insert(),{"groupname":"Corpus","orgcode":orgcode["orgcode"]})
166

167
						result = self.con.execute(gkdb.accounts.insert(),{"accountname":"Income & Expenditure","groupcode":grpcode["groupcode"],"orgcode":orgcode["orgcode"]})
168

169
					result = self.con.execute(select([gkdb.groupsubgroups.c.groupcode]).where(and_(gkdb.groupsubgroups.c.groupname=="Inventory",gkdb.groupsubgroups.c.orgcode==orgcode["orgcode"])))
170
					grpcode = result.fetchone()
171
					result = self.con.execute(gkdb.accounts.insert(),[{"accountname":"Closing Stock","groupcode":grpcode["groupcode"],"orgcode":orgcode["orgcode"]},{"accountname":"Stock at the Beginning","groupcode":grpcode["groupcode"],"orgcode":orgcode["orgcode"]}])
172

173
					result = self.con.execute(select([gkdb.groupsubgroups.c.groupcode]).where(and_(gkdb.groupsubgroups.c.groupname=="Direct Expense",gkdb.groupsubgroups.c.orgcode==orgcode["orgcode"])))
174
					grpcode = result.fetchone()
175
					result = self.con.execute(gkdb.accounts.insert(),{"accountname":"Opening Stock","groupcode":grpcode["groupcode"],"orgcode":orgcode["orgcode"]})
176
177
178



179
180
					userdata["orgcode"] = orgcode["orgcode"]
					userdata["userrole"] = -1
181
					result = self.con.execute(gkdb.users.insert().values(username = userdata["username"], userpassword=userdata["userpassword"], userrole = -1, userquestion = userdata["userquestion"], useranswer = userdata["useranswer"], orgcode=userdata["orgcode"]))
182
					if result.rowcount==1:
183
						result = self.con.execute(select([gkdb.users.c.userid]).where(and_(gkdb.users.c.username==userdata["username"], gkdb.users.c.userpassword== userdata["userpassword"], gkdb.users.c.orgcode==userdata["orgcode"])) )
184
185
						if result.rowcount == 1:
							record = result.fetchone()
186

187
							token = jwt.encode({"orgcode":userdata["orgcode"],"userid":record["userid"]},gkcore.secret,algorithm='HS256')
188
							self.con.close()
189
							return {"gkstatus":enumdict["Success"],"token":token }
190
						else:
191
							self.con.close()
192
							return {"gkstatus":enumdict["ConnectionFailed"]}
193
					else:
194
							self.con.close()
195
							return {"gkstatus":enumdict["ConnectionFailed"]}
196
				except:
197
198
					result = self.con.execute(gkdb.organisation.delete().where(gkdb.organisation.c.orgcode==orgcode["orgcode"]))
					self.con.close()
199
					return {"gkstatus":enumdict["ConnectionFailed"]}
200
			else:
201
				self.con.close()
202
				return {"gkstatus":enumdict["ConnectionFailed"]}
203
		except:
204
			self.con.close()
205
			return {"gkstatus":enumdict["ConnectionFailed"]}
206

ishan masdekar's avatar
ishan masdekar committed
207
	@view_config(route_name='organisation', request_method='GET',renderer='json')
208
	def getOrg(self):
209
		try:
210
			token = self.request.headers["gktoken"]
211
		except:
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
			return  {"gkstatus":  enumdict["UnauthorisedAccess"]}
		authDetails = authCheck(token)
		if authDetails["auth"]==False:
			return {"gkstatus":enumdict["UnauthorisedAccess"]}
		else:
			try:
				self.con = eng.connect()
				result = self.con.execute(select([gkdb.organisation]).where(gkdb.organisation.c.orgcode==authDetails["orgcode"]))
				row = result.fetchone()
				if(row["orgcity"]==None):
					orgcity=""
				else:
					orgcity=row["orgcity"]

				if(row["orgaddr"]==None):
					orgaddr=""
				else:
					orgaddr=row["orgaddr"]

				if(row["orgpincode"]==None):
					orgpincode=""
				else:
					orgpincode=row["orgpincode"]

				if(row["orgstate"]==None):
					orgstate=""
				else:
					orgstate=row["orgstate"]

				if(row["orgcountry"]==None):
					orgcountry=""
				else:
					orgcountry=row["orgcountry"]

				if(row["orgtelno"]==None):
					orgtelno=""
				else:
					orgtelno=row["orgtelno"]

				if(row["orgfax"]==None):
					orgfax=""
				else:
					orgfax=row["orgfax"]

				if(row["orgwebsite"]==None):
					orgwebsite=""
				else:
					orgwebsite=row["orgwebsite"]

				if(row["orgemail"]==None):
					orgemail=""
				else:
					orgemail=row["orgemail"]

				if(row["orgpan"]==None):
					orgpan=""
				else:
					orgpan=row["orgpan"]

				if(row["orgmvat"]==None):
					orgmvat=""
				else:
					orgmvat=row["orgmvat"]

				if(row["orgstax"]==None):
					orgstax=""
				else:
					orgstax=row["orgstax"]

				if(row["orgregno"]==None):
					orgregno=""
				else:
					orgregno=row["orgregno"]

				if(row["orgregdate"]==None):
					orgregdate=""
				else:
					orgregdate=row["orgregdate"]

				if(row["orgfcrano"]==None):
					orgfcrano=""
				else:
					orgfcrano=row["orgfcrano"]

				if(row["orgfcradate"]==None):
					orgfcradate=""
				else:
					orgfcradate=row["orgfcradate"]


302
				orgDetails={"orgname":row["orgname"], "orgtype":row["orgtype"], "yearstart":str(row["yearstart"]), "yearend":str(row["yearend"]),"orgcity":orgcity, "orgaddr":orgaddr, "orgpincode":orgpincode, "orgstate":orgstate, "orgcountry":orgcountry, "orgtelno":orgtelno, "orgfax":orgfax, "orgwebsite":orgwebsite, "orgemail":orgemail, "orgpan":orgpan, "orgmvat":orgmvat, "orgstax":orgstax, "orgregno":orgregno, "orgregdate":orgregdate, "orgfcrano":orgfcrano, "orgfcradate":orgfcradate, "roflag":row["roflag"], "booksclosedflag":row["booksclosedflag"],"invflag":row["invflag"]}
303
				self.con.close()
abhi1tb's avatar
abhi1tb committed
304
#				print orgDetails
305
306
307
308
309
310
311
312
				return {"gkstatus":enumdict["Success"],"gkdata":orgDetails}
			except:
				self.con.close()
				return {"gkstatus":enumdict["ConnectionFailed"]}




313

314
315
	@view_config(request_method='PUT', renderer='json')
	def putOrg(self):
316
317
318
319
320
		token = self.request.headers['gktoken']
		authDetails = authCheck(token)
		if authDetails["auth"]==False:
			return {"gkstatus":enumdict["UnauthorisedAccess"]}
		else:
321
			try:
322
				self.con = eng.connect()
323
				user=self.con.execute(select([gkdb.users.c.userrole]).where(gkdb.users.c.userid == authDetails["userid"] ))
324
325
326
				userRole = user.fetchone()
				dataset = self.request.json_body
				if userRole[0]==-1:
327
328
					result = self.con.execute(gkdb.organisation.update().where(gkdb.organisation.c.orgcode==authDetails["orgcode"]).values(dataset))
					self.con.close()
329
330
331
					return {"gkstatus":enumdict["Success"]}
				else:
					{"gkstatus":  enumdict["BadPrivilege"]}
332
			except:
333
				self.con.close()
334
				return {"gkstatus":  enumdict["ConnectionFailed"]}
335

336
337
	@view_config(request_method='DELETE', renderer='json')
	def deleteOrg(self):
338
339
340
341
342
		token = self.request.headers['gktoken']
		authDetails = authCheck(token)
		if authDetails["auth"]==False:
			return {"gkstatus":enumdict["UnauthorisedAccess"]}
		else:
343
			try:
344
				self.con = eng.connect()
345
				user=self.con.execute(select([gkdb.users.c.userrole]).where(gkdb.users.c.userid == authDetails["userid"] ))
346
347
				userRole = user.fetchone()
				if userRole[0]==-1:
348
					result = self.con.execute(gkdb.organisation.delete().where(gkdb.organisation.c.orgcode==authDetails["orgcode"]))
349
350
351
352
353
					if result.rowcount == 1:
						result = self.con.execute(select([func.count(gkdb.organisation.c.orgcode).label('ocount')]))
						orgcount = result.fetchone()
						if orgcount["ocount"]==0:
							result = self.con.execute(gkdb.signature.delete())
354
					self.con.close()
355
356
357
					return {"gkstatus":enumdict["Success"]}
				else:
					{"gkstatus":  enumdict["BadPrivilege"]}
358
			except:
359
				self.con.close()
360
				return {"gkstatus":  enumdict["ConnectionFailed"]}
361

362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
	@view_config(request_method='GET',request_param="type=exists",renderer='json')
	def Orgexists(self):
		try:
			self.con = eng.connect()
			orgtype = self.request.params["orgtype"]
			orgname= self.request.params["orgname"]
			finstart = self.request.params["finstart"]
			finend = self.request.params["finend"]
			orgncount = self.con.execute(select([func.count(gkdb.organisation.c.orgcode).label('orgcode')]).where(and_(gkdb.organisation.c.orgname==orgname,gkdb.organisation.c.orgtype==orgtype, gkdb.organisation.c.yearstart==finstart,gkdb.organisation.c.yearend==finend)))
			org = orgncount.fetchone()
			if org["orgcode"] !=0:
				return {"gkstatus":enumdict["DuplicateEntry"]}
			else:
				return {"gkstatus":enumdict["Success"]}
		except:
			self.con.close()
			return {"gkstatus":  enumdict["ConnectionFailed"]}


381
	@view_config(request_param='orgcode', request_method='GET',renderer='json')
382
	def getOrgcode(self):
383
		try:
ishan masdekar's avatar
ishan masdekar committed
384
			token = self.request.headers["gktoken"]
385
		except:
ishan masdekar's avatar
ishan masdekar committed
386
387
388
389
390
391
			return  {"gkstatus":  enumdict["UnauthorisedAccess"]}
		authDetails = authCheck(token)
		if authDetails["auth"]==False:
			return {"gkstatus":enumdict["UnauthorisedAccess"]}
		else:
			return {"gkstatus":enumdict["Success"],"gkdata":authDetails["orgcode"]}
392
393
394
395
396
397
398
399
400
401


	@view_config(request_method='PUT', request_param="type=editorganisation", renderer='json')
	def editOrg(self):
		token = self.request.headers['gktoken']
		authDetails = authCheck(token)
		if authDetails["auth"]==False:
			return {"gkstatus":enumdict["UnauthorisedAccess"]}
		else:
			try:
402
				self.con =eng.connect()
403
404
405
406
407
408
409
				dataset = self.request.json_body
				result = self.con.execute(gkdb.organisation.update().where(gkdb.organisation.c.orgcode==dataset["orgcode"]).values(dataset))
				self.con.close()
				return {"gkstatus":enumdict["Success"]}
			except:
				self.con.close()
				return {"gkstatus":enumdict["ConnectionFailed"]}