api_organisation.py 40.9 KB
Newer Older
1
2

"""
abhi1tb's avatar
abhi1tb committed
3
Copyright (C) 2013, 2014, 2015, 2016 Digital Freedom Foundation
Abhijith Balan's avatar
Abhijith Balan committed
4
Copyright (C) 2017, 2018 Digital Freedom Foundation & Accion Labs Pvt. Ltd.
5
6
7
  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
8
  it under the terms of the GNU Affero General Public License as
9
  published by the Free Software Foundation; either version 3 of
10
  the License, or (at your option) any later version.
11
12
13
14

  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
15
  GNU Affero General Public License for more details.
16

abhi1tb's avatar
abhi1tb committed
17
  You should have received a copy of the GNU Affero General Public
18
19
20
21
22
  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
23
Contributors:
24
"Krishnakant Mane" <kkmane@riseup.net>
25
26
"Ishan Masdekar " <imasdekar@dff.org.in>
"Navin Karkera" <navin@dff.org.in>
27
'Prajkta Patkar'<prajakta@dff.org.in>
28
'Reshma Bhatwadekar'<reshma_b@riseup.net>
29
30
"""

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

50
@view_defaults(route_name='organisations')
51
class api_organisation(object):
52
53
54
55
56
57
58
59
60
61
62
63
64
    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:
65
            self.con.execute(select(gkdb.invoice.c.paymentmode))
66
            self.con.execute(select(gkdb.organisation.c.bankdetails))
67
            self.con.execute(select([func.count(gkdb.delchal.c.consignee)]))
68
            self.con.execute(select([func.count(gkdb.invoice.c.orgstategstin)]))
69
            self.con.execute(select([func.count(gkdb.invoice.c.cess)]))
70
            self.con.execute(select([func.count(gkdb.state.c.statecode)]))
71
72
73
74
            countResult = self.con.execute(select([func.count(gkdb.invoice.c.reversecharge).label('revcount')]))
            countData = countResult.fetchone()
            if int(countData["revcount"]) > 0:
                self.con.execute("update invoice set reversecharge = '0'" )
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
            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:
91
            self.con.execute("alter table invoice add paymentmode integer")
92
            self.con.execute("alter table organisation add bankdetails json")
93
            self.con.execute("alter table delchal add consignee jsonb")
94
            self.con.execute("alter table invoice add orgstategstin text")
95
            self.con.execute("alter table invoice add cess jsonb")
96
            self.con.execute("alter table product add UNIQUE(productdesc,orgcode)")
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
126
127
128
129
130
131
132
133
134
135
            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")
136
137
            # 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'")
138
            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")
139
            self.con.execute("update invoice set taxflag = 22 ")
140
            self.con.execute("alter table delchal drop column issuerid")
141
142
            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)")
143
            self.con.execute("alter table organisation add gstin jsonb")
144
            self.con.execute("alter table product alter specs drop not null,alter uomid drop not null")
145
            self.con.execute("alter table customerandsupplier add gstin jsonb")
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
179
180
181
182
183
184
185
186
187
188
            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))")
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
233
234
235
236
237
238
239
240
241
242
            #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):

243
        try:
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
            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])
264
265
266
267
            try:
                self.con.execute(select([gkdb.organisation.c.invflag]))
            except:
                inventoryMigration(self.con,eng)
268
269
270
271
272
            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)
273
274
275
276
277

            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()
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
323
324
325
326
327
328
329
330
331
332
                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"]})
333

334
335
                    else:
                        result = self.con.execute(gkdb.groupsubgroups.insert(),{"groupname":"Corpus","orgcode":orgcode["orgcode"]})
336

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

339
340
341
                    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"]}])
342

343
344
345
                    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"]})
346
347
348



349
350
351
352
353
354
355
                    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()
356

357
358
359
360
361
362
                            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"]}
363
                    else:
364
365
366
367
368
369
                            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"]}
370
371
372
            else:
                self.con.close()
                return {"gkstatus":enumdict["ConnectionFailed"]}
373
374
375
        except:
            self.con.close()
            return {"gkstatus":enumdict["ConnectionFailed"]}
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
460
461
462
463
464
465
466
467
468
469

    @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"]
470
471
                if(row["gstin"]==None):
                    gstin=""
472

473
                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"]}
474
475
476
477
478
                self.con.close()
                return {"gkstatus":enumdict["Success"],"gkdata":orgDetails}
            except:
                self.con.close()
                return {"gkstatus":enumdict["ConnectionFailed"]}
479

480
481
        """
        This function returns Organisation Details for Invoicing.
482
        'statecode' receiving from frontend view & depending on statecode gstin will get.
483
        """
484
485
486
487
488
489
490
491
492
    @view_config(request_method="GET", renderer="json", request_param="billingdetails")
    def getbillingdetails(self):
        token = self.request.headers['gktoken']
        authDetails = authCheck(token)
        if authDetails["auth"]==False:
            return {"gkstatus":enumdict["UnauthorisedAccess"]}
        else:
            try:
                self.con = eng.connect()
493
                statecode =self.request.params["statecode"]
494
495
                result = self.con.execute(select([gkdb.organisation]).where(gkdb.organisation.c.orgcode==authDetails["orgcode"]))
                row = result.fetchone()
496
497
498
499
                if(row["orgcity"]==None):
                    orgcity=""
                else:
                    orgcity=row["orgcity"]
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
                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["orgwebsite"]==None):
                    orgwebsite=""
                else:
                    orgwebsite=row["orgwebsite"]
                if(row["orgpan"]==None):
                    orgpan=""
                else:
                    orgpan=row["orgpan"]
520
521
522
523
524
525
526
527
                if(row["orgtelno"]==None):
                    orgtelno=""
                else:
                    orgtelno=row["orgtelno"]
                if(row["orgemail"]==None):
                    orgemail=""
                else:
                    orgemail=row["orgemail"]
528
529
                if(row["gstin"]==None):
                    gstin=""
530
531
                elif(row["gstin"].has_key(str(statecode))):
                    gstin = row["gstin"][str(statecode)]
532
                else:
533
                    gstin=""
534
535
536
537
                if(row["bankdetails"]==None):
                    bankdetails = ""
                else:
                    bankdetails = row["bankdetails"]
538

539
                orgDetails={"orgname":row["orgname"], "orgaddr":orgaddr, "orgpincode":orgpincode, "orgstate":orgstate, "orgwebsite":orgwebsite, "orgpan":orgpan, "orgstategstin":gstin, "orgcity":orgcity, "bankdetails":bankdetails, "orgtelno":orgtelno, "orgemail":orgemail}
540
541
542
543
544
                self.con.close()
                return {"gkstatus":enumdict["Success"],"gkdata":orgDetails}
            except:
                return {"gkstatus":  enumdict["ConnectionFailed"]}
        
545
546
547
548
549
550
551
    @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:
552
            try:
553
                self.con =eng.connect()
554
                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"])))
555
                gstinval = ""
556
                if gstinResult.rowcount > 0 :
557
558
                    gstinrow = gstinResult.fetchone()
                    gstinval = str(gstinrow["stgstin"])
559
560
                return{"gkstatus":enumdict["Success"],"gkresult":gstinval}
            except:
561
562
                return {"gkstatus":  enumdict["ConnectionFailed"]}
                
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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
    @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()