api_organisation.py 37.5 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
  published by the Free Software Foundation; either version 3 of
9
  the License, or (at your option) any later version.
10
11
12
13

  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
"Krishnakant Mane" <kkmane@riseup.net>
24
25
"Ishan Masdekar " <imasdekar@dff.org.in>
"Navin Karkera" <navin@dff.org.in>
26
'Prajkta Patkar'<prajakta@dff.org.in>
27
'Reshma Bhatwadekar'<reshma_b@riseup.net>
28
29
"""

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

48
@view_defaults(route_name='organisations')
49
class api_organisation(object):
50
51
52
53
54
55
56
57
58
59
60
61
62
    def __init__(self,request):
        self.request = Request
        self.request = request
        self.con = Connection
        print "Organisation initialized"
    def gkUpgrade(self):
        """
        This function will be called only once while upgrading gnukhata.
        We check if the field stockdate is present.
        If it is not present it means that this is an upgrade.
        """
        self.con = eng.connect()
        try:
63
            self.con.execute(select([func.count(gkdb.invoice.c.orgstategstin)]))
64
            self.con.execute(select([func.count(gkdb.invoice.c.cess)]))
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
            self.con.execute(select([func.count(gkdb.state.c.statecode)]))
            self.con.execute(select([func.count(gkdb.invoice.c.reversecharge)]))
            self.con.execute(select(gkdb.organisation.c.gstin))
            self.con.execute(select([func.count(gkdb.invoice.c.consignee)]))
            self.con.execute(select([func.count(gkdb.customerandsupplier.c.gstin)]))
            self.con.execute(select([func.count(gkdb.product.c.gscode)]))
            self.con.execute(select([func.count(gkdb.rejectionnote.c.rnid)]))
            self.con.execute(select([func.count(gkdb.stock.c.stockdate)]))
            self.con.execute(select([func.count(gkdb.transfernote.c.fromgodown)]))
            self.con.execute(select([func.count(gkdb.customerandsupplier.c.advamt)]))
            self.con.execute(select([func.count(gkdb.transfernote.c.duedate)]))
            self.con.execute(select(gkdb.dcinv.c.invprods))
            self.con.execute(select(gkdb.organisation.c.logo))
            self.con.execute(select(gkdb.vouchers.c.instrumentno))
            self.con.execute(select(gkdb.organisation.c.invsflag))
            self.con.execute(select(gkdb.organisation.c.billflag))
            self.con.execute(select([func.count(gkdb.billwise.c.billid)]))
        except:
Krishnakant Mane's avatar
Krishnakant Mane committed
83
            self.con.execute("update invoice set reversecharge = '0'" )
84
            self.con.execute("alter table invoice add orgstategstin text")
85
            self.con.execute("alter table invoice add cess jsonb")
86
            self.con.execute("alter table product add UNIQUE(productdesc,orgcode)")
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
            self.con.execute("create table state( statecode integer,statename text,primary key (statecode))")
            self.con.execute("insert into state( statecode, statename)values(1, 'Jammu and Kashmir')")
            self.con.execute("insert into state( statecode, statename)values(2, 'Himachal Pradesh')")
            self.con.execute("insert into state( statecode, statename)values(3, 'Punjab')")
            self.con.execute("insert into state( statecode, statename)values(4, 'Chandigarh')")
            self.con.execute("insert into state( statecode, statename)values(5, 'Uttranchal')")
            self.con.execute("insert into state( statecode, statename)values(6, 'Haryana')")
            self.con.execute("insert into state( statecode, statename)values(7, 'Delhi')")
            self.con.execute("insert into state( statecode, statename)values(8, 'Rajasthan')")
            self.con.execute("insert into state( statecode, statename)values(9, 'Uttar Pradesh')")
            self.con.execute("insert into state( statecode, statename)values(10, 'Bihar')")
            self.con.execute("insert into state( statecode, statename)values(11, 'Sikkim')")
            self.con.execute("insert into state( statecode, statename)values(12, 'Arunachal Pradesh')")
            self.con.execute("insert into state( statecode, statename)values(13, 'Nagaland')")
            self.con.execute("insert into state( statecode, statename)values(14, 'Manipur')")
            self.con.execute("insert into state( statecode, statename)values(15, 'Mizoram')")
            self.con.execute("insert into state( statecode, statename)values(16, 'Tripura')")
            self.con.execute("insert into state( statecode, statename)values(17, 'Meghalaya')")
            self.con.execute("insert into state( statecode, statename)values(18, 'Assam')")
            self.con.execute("insert into state( statecode, statename)values(19, 'West Bengal')")
            self.con.execute("insert into state( statecode, statename)values(20, 'Jharkhand')")
            self.con.execute("insert into state( statecode, statename)values(21, 'Odisha')")
            self.con.execute("insert into state( statecode, statename)values(22, 'Chhattisgarh')")
            self.con.execute("insert into state( statecode, statename)values(23, 'Madhya Pradesh')")
            self.con.execute("insert into state( statecode, statename)values(24, 'Gujarat')")
            self.con.execute("insert into state( statecode, statename)values(25, 'Daman and Diu')")
            self.con.execute("insert into state( statecode, statename)values(26, 'Dadra and Nagar Haveli')")
            self.con.execute("insert into state( statecode, statename)values(27, 'Maharashtra')")
            self.con.execute("insert into state( statecode, statename)values(28, 'Andhra Pradesh')")
            self.con.execute("insert into state( statecode, statename)values(29, 'Karnataka')")
            self.con.execute("insert into state( statecode, statename)values(30, 'Goa')")
            self.con.execute("insert into state( statecode, statename)values(31, 'Lakshdweep')")
            self.con.execute("insert into state( statecode, statename)values(32, 'Kerala')")
            self.con.execute("insert into state( statecode, statename)values(33, 'Tamil Nadu')")
            self.con.execute("insert into state( statecode, statename)values(34, 'Pondicherry')")
            self.con.execute("insert into state( statecode, statename)values(35, 'Andaman and Nicobar Islands')")
            self.con.execute("insert into state( statecode, statename)values(36, 'Telangana')")
            self.con.execute("insert into state( statecode, statename)values(37, 'Andhra Pradesh (New)')")
            self.con.execute("alter table invoice drop column cancelflag,drop column canceldate")
126
127
            # this is to clean null and empty values during old vat based invoices
            self.con.execute("update invoice set taxstate = null where taxstate = '' or taxstate = 'none'")
128
            self.con.execute("alter table invoice add consignee jsonb, add sourcestate text ,add discount jsonb ,add taxflag integer default 22, add reversecharge text, add bankdetails jsonb,add transportationmode text,add vehicleno text,add dateofsupply timestamp")
129
            self.con.execute("update invoice set taxflag = 22 ")
130
            self.con.execute("alter table delchal drop column issuerid")
131
132
            self.con.execute("ALTER TABLE delchal DROP CONSTRAINT delchal_custid_fkey, ADD CONSTRAINT delchal_custid_fkey FOREIGN KEY (custid) REFERENCES customerandsupplier(custid)")
            self.con.execute("ALTER TABLE invoice DROP CONSTRAINT invoice_custid_fkey, ADD CONSTRAINT invoice_custid_fkey FOREIGN KEY (custid) REFERENCES customerandsupplier(custid)")
133
            self.con.execute("alter table organisation add gstin jsonb")
134
            self.con.execute("alter table product alter specs drop not null,alter uomid drop not null")
135
            self.con.execute("alter table customerandsupplier add gstin jsonb")
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
            self.con.execute("alter table customerandsupplier add UNIQUE(orgcode,custname,gstin)")
            self.con.execute("alter table product add gsflag integer")
            self.con.execute("update product set gsflag = 7")
            self.con.execute("alter table product add gscode text")
            self.con.execute("alter table product alter specs drop not null,alter uomid drop not null")
            self.con.execute("create table billwise(billid serial, vouchercode integer, invid integer, adjdate timestamp, adjamount numeric (12,2), orgcode integer, primary key (billid), foreign key (vouchercode) references vouchers(vouchercode), foreign key(invid) references invoice(invid), foreign key (orgcode) references organisation (orgcode))")
            self.con.execute("create table rejectionnote(rnid serial, rnno integer not null, rndate timestamp not null, inout integer not null, dcid integer, invid integer, issuerid integer, orgcode integer not null, primary key(rnid), foreign key (dcid) references delchal(dcid) ON DELETE CASCADE, foreign key (invid) references invoice(invid) ON DELETE CASCADE, foreign key (issuerid) references users(userid) ON DELETE CASCADE, foreign key (orgcode) references organisation(orgcode) ON DELETE CASCADE, unique(rnno, inout, orgcode))")
            self.con.execute("alter table organisation add invsflag integer default 1")
            self.con.execute("alter table organisation add billflag integer default 1")
            self.con.execute("alter table vouchers add instrumentno text")
            self.con.execute("alter table vouchers add branchname text")
            self.con.execute("alter table vouchers add bankname text")
            self.con.execute("alter table vouchers add instrumentdate timestamp")
            self.con.execute("alter table organisation add logo json")
            self.con.execute("alter table dcinv add invprods jsonb")
            self.con.execute("alter table transfernote add duedate timestamp")
            self.con.execute("alter table transfernote add grace integer")
            self.con.execute("alter table customerandsupplier add advamt numeric default 0.00")
            self.con.execute("alter table customerandsupplier add onaccamt numeric default 0.00")
            self.con.execute("alter table transfernote add fromgodown integer")
            self.con.execute("alter table transfernote add foreign key(fromgodown) references godown(goid)")
            self.con.execute("alter table transfernote drop column canceldate")
            self.con.execute("alter table transfernote drop column cancelflag")
            self.con.execute("alter table invoice add freeqty jsonb")
            self.con.execute("alter table invoice add amountpaid numeric default 0.00")
            self.con.execute("alter table stock add stockdate timestamp")
            self.con.execute("alter table delchal add attachment json")
            self.con.execute("alter table delchal add attachmentcount integer default 0")
            self.con.execute("alter table invoice add attachment json")
            self.con.execute("alter table invoice add attachmentcount integer default 0")
            self.con.execute("alter table purchaseorder add creditperiod text")
            self.con.execute("alter table purchaseorder add taxstate text")
            self.con.execute("alter table purchaseorder add togodown integer")
            self.con.execute("alter table purchaseorder drop column schedule")
            self.con.execute("alter table purchaseorder add schedule jsonb")
            self.con.execute("alter table purchaseorder drop column maxdate")
            self.con.execute("alter table purchaseorder drop column datedelivery")
            self.con.execute("alter table purchaseorder drop column deliveryplaceaddr")
            self.con.execute("alter table purchaseorder drop column tax")
            self.con.execute("alter table purchaseorder drop column productdetails")
            self.con.execute("alter table purchaseorder add foreign key(togodown) references godown(goid)")
            self.con.execute("create table usergodown(ugid serial, goid integer, userid integer, orgcode integer, primary key(ugid), foreign key (goid) references godown(goid),  foreign key (userid) references users(userid), foreign key (orgcode) references organisation(orgcode))")
            self.con.execute("create table log(logid serial, time timestamp, activity text, userid integer, orgcode integer,  primary key (logid), foreign key(userid) references users(userid), foreign key (orgcode) references organisation(orgcode))")
179
            
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
            #return 0
        finally:
            self.con.close()
            return 0

    @view_config(request_method='GET', renderer ='json')
    def getOrgs(self):
        try:
            self.gkUpgrade()
            self.con=eng.connect()
            result = self.con.execute(select([gkdb.organisation.c.orgname, gkdb.organisation.c.orgtype]).order_by(gkdb.organisation.c.orgname).distinct())
            orgs = []
            for row in result:
                orgs.append({"orgname":row["orgname"], "orgtype":row["orgtype"]})
                orgs.sort()
            self.con.close()
            return {"gkstatus":enumdict["Success"], "gkdata":orgs}
        except:
            self.con.close()
            return {"gkstatus":enumdict["ConnectionFailed"]}

    @view_config(request_method='GET', request_param='type=orgcodelist', renderer='json' , route_name="organisations")
    def getsubOrgs(self):
        try:
            self.con=eng.connect()
            result = self.con.execute(select([gkdb.organisation.c.orgname, gkdb.organisation.c.orgtype,gkdb.organisation.c.orgcode,gkdb.organisation.c.yearstart,gkdb.organisation.c.yearend]).order_by(gkdb.organisation.c.orgcode))
            orgs = []
            for row in result:
                orgs.append({"orgname":row["orgname"], "orgtype":row["orgtype"], "orgcode":row["orgcode"], "yearstart":str(row["yearstart"]), "yearend":str(row["yearend"]) })
                orgs.sort()
            self.con.close()
            return {"gkstatus":enumdict["Success"], "gkdata":orgs}
        except:
            self.con.close()
            return {"gkstatus":enumdict["ConnectionFailed"]}

    @view_config(route_name='orgyears', request_method='GET', renderer ='json')
    def getYears(self):
        try:
            self.con = eng.connect()
            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)))
            years = []
            for row in result:
                years.append({"yearstart":str(row["yearstart"]), "yearend":str(row["yearend"]),"orgcode":row["orgcode"]})
            self.con.close()
            return {"gkstatus":enumdict["Success"],"gkdata":years}
        except:
            self.con.close()
            return {"gkstatus":enumdict["ConnectionFailed"]}

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

233
        try:
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
            self.con = eng.connect()
            dataset = self.request.json_body
            orgdata = dataset["orgdetails"]
            userdata = dataset["userdetails"]
            result = self.con.execute(select([gkdb.signature]))
            sign = result.fetchone()
            if sign == None:
                key = RSA.generate(2560)
                privatekey = key.exportKey('PEM')
                sig = {"secretcode":privatekey}
                gkcore.secret = privatekey
                result = self.con.execute(gkdb.signature.insert(),[sig])
            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])
254
255
256
257
            try:
                self.con.execute(select([gkdb.organisation.c.invflag]))
            except:
                inventoryMigration(self.con,eng)
258
259
260
261
262
            try:
                self.con.execute(select([gkdb.delchal.c.modeoftransport,gkdb.delchal.c.noofpackages]))
                self.con.execute(select([gkdb.transfernote.c.recieveddate]))
            except:
                addFields(self.con,eng)
263
264
265
266
267

            result = self.con.execute(gkdb.organisation.insert(),[orgdata])
            if result.rowcount==1:
                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"])))
                orgcode = code.fetchone()
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
                try:
                    currentassets= {"groupname":"Current Assets","orgcode":orgcode["orgcode"]}
                    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"])))
                    grpcode = result.fetchone()
                    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"]} ])

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

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

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

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

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

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

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

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

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

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

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

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

324
325
                    else:
                        result = self.con.execute(gkdb.groupsubgroups.insert(),{"groupname":"Corpus","orgcode":orgcode["orgcode"]})
326

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

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

333
334
335
                    result = self.con.execute(select([gkdb.groupsubgroups.c.groupcode]).where(and_(gkdb.groupsubgroups.c.groupname=="Direct Expense",gkdb.groupsubgroups.c.orgcode==orgcode["orgcode"])))
                    grpcode = result.fetchone()
                    result = self.con.execute(gkdb.accounts.insert(),{"accountname":"Opening Stock","groupcode":grpcode["groupcode"],"orgcode":orgcode["orgcode"]})
336
337
338



339
340
341
342
343
344
345
                    userdata["orgcode"] = orgcode["orgcode"]
                    userdata["userrole"] = -1
                    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"]))
                    if result.rowcount==1:
                        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"])) )
                        if result.rowcount == 1:
                            record = result.fetchone()
346

347
348
349
350
351
352
                            token = jwt.encode({"orgcode":userdata["orgcode"],"userid":record["userid"]},gkcore.secret,algorithm='HS256')
                            self.con.close()
                            return {"gkstatus":enumdict["Success"],"token":token }
                        else:
                            self.con.close()
                            return {"gkstatus":enumdict["ConnectionFailed"]}
353
                    else:
354
355
356
357
358
359
                            self.con.close()
                            return {"gkstatus":enumdict["ConnectionFailed"]}
                except:
                    result = self.con.execute(gkdb.organisation.delete().where(gkdb.organisation.c.orgcode==orgcode["orgcode"]))
                    self.con.close()
                    return {"gkstatus":enumdict["ConnectionFailed"]}
360
361
362
            else:
                self.con.close()
                return {"gkstatus":enumdict["ConnectionFailed"]}
363
364
365
        except:
            self.con.close()
            return {"gkstatus":enumdict["ConnectionFailed"]}
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459

    @view_config(route_name='organisation', request_method='GET',renderer='json')
    def getOrg(self):
        try:
            token = self.request.headers["gktoken"]
        except:
            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"]
460
461
                if(row["gstin"]==None):
                    gstin=""
462

463
                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"],"billflag":row["billflag"],"invsflag":row["invsflag"],"gstin":row["gstin"]}
464
465
466
467
468
                self.con.close()
                return {"gkstatus":enumdict["Success"],"gkdata":orgDetails}
            except:
                self.con.close()
                return {"gkstatus":enumdict["ConnectionFailed"]}
469
470
471
472
473
474
475
    @view_config(request_method="GET",renderer="json",request_param="osg=true")
    def getOrgStateGstin(self):
        token = self.request.headers['gktoken']
        authDetails = authCheck(token)
        if authDetails["auth"]==False:
            return {"gkstatus":enumdict["UnauthorisedAccess"]}
        else:
476
            try:
477
                self.con =eng.connect()
478
                gstinResult = self.con.execute("select gstin ->> '%d' as stgstin from organisation where gstin ? '%d' and orgcode = %d "%(int(self.request.params["statecode"]),int(self.request.params["statecode"]),int(authDetails["orgcode"])))
479
                gstinval = ""
480
                if gstinResult.rowcount > 0 :
481
482
                    gstinrow = gstinResult.fetchone()
                    gstinval = str(gstinrow["stgstin"])
483
484
                return{"gkstatus":enumdict["Success"],"gkresult":gstinval}
            except:
485
486
                return {"gkstatus":  enumdict["ConnectionFailed"]}
                
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
    @view_config(request_method='PUT', renderer='json')
    def putOrg(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"]}

    @view_config(request_method='DELETE', renderer='json')
    def deleteOrg(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()
                if userRole[0]==-1:
                    result = self.con.execute(gkdb.organisation.delete().where(gkdb.organisation.c.orgcode==authDetails["orgcode"]))
                    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())
                    self.con.close()
                    return {"gkstatus":enumdict["Success"]}
                else:
                    {"gkstatus":  enumdict["BadPrivilege"]}
            except:
                self.con.close()
                return {"gkstatus":  enumdict["ConnectionFailed"]}

    @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"]}


    @view_config(request_param='orgcode', request_method='GET',renderer='json')
    def getOrgcode(self):
        try:
            token = self.request.headers["gktoken"]
        except:
            return  {"gkstatus":  enumdict["UnauthorisedAccess"]}
        authDetails = authCheck(token)
        if authDetails["auth"]==False:
            return {"gkstatus":enumdict["UnauthorisedAccess"]}
        else:
            return {"gkstatus":enumdict["Success"],"gkdata":authDetails["orgcode"]}


    @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:
                self.con =eng.connect()
                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"]}

    @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"]}

    @view_config(route_name='organisation', request_method='GET',request_param='attach=image', renderer='json')
    def getattachment(self):
        try:
            token = self.request.headers["gktoken"]
        except:
            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.c.logo]).where(gkdb.organisation.c.orgcode==authDetails["orgcode"]))
                row=result.fetchone()
                return {"logo":row["logo"]}
            except:
                return {"gkstatus":enumdict["ConnectionFailed"]}
            finally:
                self.con.close()