api_organisation.py 19.1 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
from gkcore.models.gkdb import metadata
44
from gkcore.models.meta import inventoryMigration
45

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

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

68
69
	@view_config(route_name='orgyears', request_method='GET', renderer ='json')
	def getYears(self):
70
		try:
71
			self.con = eng.connect()
72
			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)))
73
74
75
			years = []
			for row in result:
				years.append({"yearstart":str(row["yearstart"]), "yearend":str(row["yearend"]),"orgcode":row["orgcode"]})
76
			self.con.close()
77
78
			return {"gkstatus":enumdict["Success"],"gkdata":years}
		except:
79
			self.con.close()
80
			return {"gkstatus":enumdict["ConnectionFailed"]}
81

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

85
		try:
86
			self.con = eng.connect()
87
			dataset = self.request.json_body
88
89
			orgdata = dataset["orgdetails"]
			userdata = dataset["userdetails"]
90
91
92
			result = self.con.execute(select([gkdb.signature]))
			sign = result.fetchone()
			if sign == None:
93
94
95
96
97
				key = RSA.generate(2560)
				privatekey = key.exportKey('PEM')
				sig = {"secretcode":privatekey}
				gkcore.secret = privatekey
				result = self.con.execute(gkdb.signature.insert(),[sig])
98
99
100
101
102
103
104
105
			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])
106
107
108
109
			try:
				self.con.execute(select([gkdb.organisation.c.invflag]))
			except:
				inventoryMigration(self.con,eng)
110
			result = self.con.execute(gkdb.organisation.insert(),[orgdata])
111
			if result.rowcount==1:
112
				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"])))
113
				orgcode = code.fetchone()
114
				try:
115
					currentassets= {"groupname":"Current Assets","orgcode":orgcode["orgcode"]}
116
117
					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"])))
118
					grpcode = result.fetchone()
119
					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"]} ])
120

121
					currentliability= {"groupname":"Current Liabilities","orgcode":orgcode["orgcode"]}
122
123
					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"])))
124
					grpcode = result.fetchone()
125
					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"]}])
126

127
					directexpense= {"groupname":"Direct Expense","orgcode":orgcode["orgcode"]}
128
					result = self.con.execute(gkdb.groupsubgroups.insert(),directexpense)
129

130
					directincome= {"groupname":"Direct Income","orgcode":orgcode["orgcode"]}
131
					result = self.con.execute(gkdb.groupsubgroups.insert(),directincome)
132

133
					fixedassets= {"groupname":"Fixed Assets","orgcode":orgcode["orgcode"]}
134
135
					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"])))
136
					grpcode = result.fetchone()
137
					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"]} ])
138

139
					indirectexpense= {"groupname":"Indirect Expense","orgcode":orgcode["orgcode"]}
140
					result = self.con.execute(gkdb.groupsubgroups.insert(),indirectexpense)
141

142
					indirectincome= {"groupname":"Indirect Income","orgcode":orgcode["orgcode"]}
143
					result = self.con.execute(gkdb.groupsubgroups.insert(),indirectincome)
144

145
					investment= {"groupname":"Investments","orgcode":orgcode["orgcode"]}
146
147
					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"])))
148
					grpcode = result.fetchone()
149
					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"]}, ])
150

151
					loansasset= {"groupname":"Loans(Asset)","orgcode":orgcode["orgcode"]}
152
					result = self.con.execute(gkdb.groupsubgroups.insert(),loansasset)
153

154
					loansliab= {"groupname":"Loans(Liability)","orgcode":orgcode["orgcode"]}
155
156
					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"])))
157
					grpcode = result.fetchone()
158
					result = self.con.execute(gkdb.groupsubgroups.insert(),[{"groupname":"Secured","orgcode":orgcode["orgcode"],"subgroupof":grpcode["groupcode"]},{"groupname":"Unsecured","orgcode":orgcode["orgcode"],"subgroupof":grpcode["groupcode"]} ])
159

160
					reserves= {"groupname":"Reserves","orgcode":orgcode["orgcode"]}
161
					result = self.con.execute(gkdb.groupsubgroups.insert(),reserves)
162

163
					result = self.con.execute(select([gkdb.groupsubgroups.c.groupcode]).where(and_(gkdb.groupsubgroups.c.groupname=="Direct Income",gkdb.groupsubgroups.c.orgcode==orgcode["orgcode"])))
164
165
					grpcode = result.fetchone()
					if orgdata["orgtype"] == "Profit Making":
166
						result = self.con.execute(gkdb.groupsubgroups.insert(),[{"groupname":"Capital","orgcode":orgcode["orgcode"]},{"groupname":"Miscellaneous Expenses(Asset)","orgcode":orgcode["orgcode"]}])
167

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

170
					else:
171
						result = self.con.execute(gkdb.groupsubgroups.insert(),{"groupname":"Corpus","orgcode":orgcode["orgcode"]})
172

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

175
					result = self.con.execute(select([gkdb.groupsubgroups.c.groupcode]).where(and_(gkdb.groupsubgroups.c.groupname=="Inventory",gkdb.groupsubgroups.c.orgcode==orgcode["orgcode"])))
176
					grpcode = result.fetchone()
177
					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"]}])
178

179
					result = self.con.execute(select([gkdb.groupsubgroups.c.groupcode]).where(and_(gkdb.groupsubgroups.c.groupname=="Direct Expense",gkdb.groupsubgroups.c.orgcode==orgcode["orgcode"])))
180
					grpcode = result.fetchone()
181
					result = self.con.execute(gkdb.accounts.insert(),{"accountname":"Opening Stock","groupcode":grpcode["groupcode"],"orgcode":orgcode["orgcode"]})
182
183
184



185
186
					userdata["orgcode"] = orgcode["orgcode"]
					userdata["userrole"] = -1
187
					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"]))
188
					if result.rowcount==1:
189
						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"])) )
190
191
						if result.rowcount == 1:
							record = result.fetchone()
192

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

ishan masdekar's avatar
ishan masdekar committed
213
	@view_config(route_name='organisation', request_method='GET',renderer='json')
214
	def getOrg(self):
215
		try:
216
			token = self.request.headers["gktoken"]
217
		except:
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
302
303
304
305
306
307
			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"]


308
				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"]}
309
				self.con.close()
abhi1tb's avatar
abhi1tb committed
310
#				print orgDetails
311
312
313
314
315
316
317
318
				return {"gkstatus":enumdict["Success"],"gkdata":orgDetails}
			except:
				self.con.close()
				return {"gkstatus":enumdict["ConnectionFailed"]}




319

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

342
343
	@view_config(request_method='DELETE', renderer='json')
	def deleteOrg(self):
344
345
346
347
348
		token = self.request.headers['gktoken']
		authDetails = authCheck(token)
		if authDetails["auth"]==False:
			return {"gkstatus":enumdict["UnauthorisedAccess"]}
		else:
349
			try:
350
				self.con = eng.connect()
351
				user=self.con.execute(select([gkdb.users.c.userrole]).where(gkdb.users.c.userid == authDetails["userid"] ))
352
353
				userRole = user.fetchone()
				if userRole[0]==-1:
354
					result = self.con.execute(gkdb.organisation.delete().where(gkdb.organisation.c.orgcode==authDetails["orgcode"]))
355
356
357
358
359
					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())
360
					self.con.close()
361
362
363
					return {"gkstatus":enumdict["Success"]}
				else:
					{"gkstatus":  enumdict["BadPrivilege"]}
364
			except:
365
				self.con.close()
366
				return {"gkstatus":  enumdict["ConnectionFailed"]}
367

368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
	@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"]}


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


	@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:
408
				self.con =eng.connect()
409
410
411
412
413
414
415
				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"]}
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437

	@view_config(request_method='PUT', request_param="type=getinventory", renderer='json')
	def getinventory(self):
		token = self.request.headers['gktoken']
		authDetails = authCheck(token)
		if authDetails["auth"]==False:
			return {"gkstatus":enumdict["UnauthorisedAccess"]}
		else:
			try:
				self.con = eng.connect()
				user=self.con.execute(select([gkdb.users.c.userrole]).where(gkdb.users.c.userid == authDetails["userid"] ))
				userRole = user.fetchone()
				dataset = self.request.json_body
				if userRole[0]==-1:
					result = self.con.execute(gkdb.organisation.update().where(gkdb.organisation.c.orgcode==authDetails["orgcode"]).values(dataset))
					self.con.close()
					return {"gkstatus":enumdict["Success"]}
				else:
					{"gkstatus":  enumdict["BadPrivilege"]}
			except:
				self.con.close()
				return {"gkstatus":enumdict["ConnectionFailed"]}