def __init__(self, clientId, data, verifykey, apiEndPoint):
     self.message = data
     self.sessionkey = verifykey
     self.apiEndPoint = apiEndPoint
     self.splitUrl = apiEndPoint.split('/')
     self.auth = Authentication()
     self.master = Master()
     self.admin = Admin()
     self.role = roleManage()
     self.attendance = attendanceManage()
     self.project = projectManage()
     self.labourer = labbourerManage()
     self.labclass = labourerClass()
     self.shift = shiftManage()
     self.log = Logger()
     self.paymentDesk = paymentDesk()
     self.clientId = clientId
class Attendance:
    def __init__(self):
        self.log = Logger()
        self.dbobj = DatabaseAgent("kunnel", "kunnel", "127.0.0.1",
                                   "kunnel123", "5432")
        self.dbobj.initConnection()

    def getAttendace(self):  #to be filled from the call site (module launcher)
        dataFields = [
            "labourerid", "labourername", "labouercategory", "labourertype",
            "intime", "outtime", "numberofhours", "overtimeallocated",
            "overtimeworked", "siteid", "projectid"
        ]
        tableName = "attendance"
        condition = {"siteid": "siteamerica"}
        dbattendance = self.dbobj.fetchData(tableName, dataFields, condition)
        print("dictonary", dbattendance)
        self.log.logEvent("Admin", 2, "attendance listed sucess fully")
        return dbattendance


# atten = Attendance()
# print("attandence",atten.getAttendace())
示例#3
0
 def __init__(self):
     self.log = Logger()
示例#4
0
class paymentDesk:

    def __init__(self):
        self.log = Logger()

    def requstList(self,clientId,sessionkey):
        try:
            masterdb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
            masterdb.initConnection()
            dbpass = masterdb.fetchData("regusers",["password"],{"clientid":clientId})
            password = dbpass[0][0]
            admindb = DatabaseAgent(clientId,clientId,conf.host,password,conf.port)
            admindb.initConnection()
            listAdvance = admindb.fetchData("accountinfo",["labourerid","phonenumber","reson","recoveryPeriod","approvestatus","approveid"])
            listpayment = admindb.fetchData("payment",["timestamp","projectid","siteid","amount","debitaccountid","resontype","creditaccountid"])
            totalLs =[]
            finalLS = []
            print("payment......",listpayment)
            print("advnavce list...........",listAdvance)
            for cnt in range(len(listAdvance)):
                totalLs = list(listAdvance[cnt]) + list(listpayment[cnt])
                finalLS.append(totalLs)

            response = {"Header":{"status":"success","module":"labfinace"},"Body":{"message":"labourer requstedAdvance list","data":finalLS},"Signature":{"signature":"","Key":""}}
            return response
        except Exception as expc:
            # self.syslog.eventHandle("labourerclassManage","exception","exception on labourerclassManage module",str(expc))  
            self.log.logEvent("labourerclassManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"]) 
            print("exception is occured at",str(expc))


    def advancePayList(self,clientId,sessionkey):
        try:
            masterdb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
            masterdb.initConnection()
            dbpass = masterdb.fetchData("regusers",["password"],{"clientid":clientId})
            password = dbpass[0][0]
            admindb = DatabaseAgent(clientId,clientId,conf.host,password,conf.port)
            admindb.initConnection()
            listAdvance = admindb.fetchData("accountinfo",["labourerid","reson","recoveryPeriod","approvestatus","approveid","paystatus"])
            listpayment = admindb.fetchData("payment",["timestamp","projectid","siteid","amount"])
            totalLs =[]
            finalLS = []
            print("payment......",listpayment)
            print("advnavce list...........",listAdvance)
            for cnt in range(len(listAdvance)):
                totalLs = list(listAdvance[cnt]) + list(listpayment[cnt])
                finalLS.append(totalLs)

            response = {"Header":{"status":"success","module":"labfinace"},"Body":{"message":"labourer Advancepay list","data":finalLS},"Signature":{"signature":"","Key":""}}
            return response
        except Exception as expc:
            # self.syslog.eventHandle("labourerclassManage","exception","exception on labourerclassManage module",str(expc))  
            self.log.logEvent("labourerclassManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"]) 
            print("exception is occured at",str(expc))


    def approvecodeList(self,clientId,msgDict,sessionkey):
        try:
            masterdb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
            masterdb.initConnection()
            dbpass = masterdb.fetchData("regusers",["password"],{"clientid":clientId})
            password = dbpass[0][0]
            admindb = DatabaseAgent(clientId,clientId,conf.host,password,conf.port)
            admindb.initConnection()
            listAdvance = admindb.fetchData("accountinfo",["labourerid","reson","recoveryPeriod","approvestatus","approveid","paystatus"],{"approveid":msgDict["approveId"]})
            timeStamp = admindb.fetchData("accountinfo",["timestamp"],{"approveid":msgDict["approveId"]})[0][0]
            print("time stamp............................",timeStamp)
            listpayment = admindb.fetchData("payment",["timestamp","projectid","siteid","amount"],{"timestamp":timeStamp})
            print("payment......",listpayment)
            print("advnavce list...........",listAdvance)
            totalLs =[]
            finalLS = []            
            for cnt in range(len(listAdvance)):
                totalLs = list(listAdvance[cnt]) + list(listpayment[cnt])
                finalLS.append(totalLs)

            response = {"Header":{"status":"success","module":"labfinace"},"Body":{"message":"labourer Advancepay list","data":finalLS},"Signature":{"signature":"","Key":""}}
            return response
        except Exception as expc:
            # self.syslog.eventHandle("labourerclassManage","exception","exception on labourerclassManage module",str(expc))  
            self.log.logEvent("labourerclassManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"]) 
            print("exception is occured at",str(expc))            



    def payProcess(self,clientId,msgDict,sessionkey):
        try:
            masterdb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
            masterdb.initConnection()
            dbpass = masterdb.fetchData("regusers",["password"],{"clientid":clientId})
            password = dbpass[0][0]
            admindb = DatabaseAgent(clientId,clientId,conf.host,password,conf.port)
            admindb.initConnection()
            accountDb = admindb.fetchData("accountinfo",["labourerid","timestamp"],{"approveid":msgDict["approveId"]})
            print("accoutndb........................",accountDb)
            timeStamp = accountDb[0][1]
            labourerId = accountDb[0][0]
            print("time stamp............................",timeStamp)            
            admindb.connection
            hash = hashlib.md5(str(datetime.datetime.now()) .encode()).hexdigest()
            transationId = hash[:10]
            accinfoCont = " set paystatus =' paid ' "+" where  "
            accountcont = " set transationid = '"+str(transationId) +" ' where "
            payflag = " set payflag = 'True'"+", issuer = '"+sessionMange.session[sessionkey]["userid"]+"',reciverid = '"+labourerId +"',transationid = '"+str(transationId)+"' where  "
            if admindb.updateTable(accinfoCont,"accountinfo",{"approveid":msgDict["approveId"]}):
                if admindb.updateTable(payflag,"payment",{"timestamp":timeStamp}):
                    if admindb.updateTable(accountcont,"account",{"timestamp":timeStamp}):
                        response = {"Header":{"status":"success","module":"labfinace"},"Body":{"message":"amount payed sucessfully","data":""},"Signature":{"signature":"","Key":""}}
                        return response                           
            else:
                response = {"Header":{"status":"fail","module":"labfinace"},"Body":{"message":"amout can't paid","data":""},"Signature":{"signature":"","Key":""}}
                return response   
        except Exception as expc:
            # self.syslog.eventHandle("labourerclassManage","exception","exception on labourerclassManage module",str(expc))  
            self.log.logEvent("labourerclassManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"]) 
            print("exception is occured at",str(expc))            
        
            
            
    
    def requstApprove(self,clientId,msgDist,sessionkey):
        masterdb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
        masterdb.initConnection()
        dbpass = masterdb.fetchData("regusers",["password"],{"clientid":clientId})
        password = dbpass[0][0]
        admindb = DatabaseAgent(clientId,clientId,conf.host,password,conf.port)
        admindb.initConnection()
        randomid = str(random.randint(10000000000,1000000000000))[:8]
        approveCont = " set approvestatus = 'approved', approveid = "+randomid+" where "
        try:
            if admindb.updateTable(approveCont,"accountinfo",{"labourerid":msgDist["labourerId"]}):
                response = {"Header":{"status":"success","module":"labfinace"},"Body":{"message":"labourer requst is approved","data":""},"Signature":{"signature":"","Key":""}}
                return response                
            else:
                response = {"Header":{"status":"fail","module":"labfinace"},"Body":{"message":"labourer requst is can't approved","data":""},"Signature":{"signature":"","Key":""}}
                return response   
        except Exception as expc:
            # self.syslog.eventHandle("labourerclassManage","exception","exception on labourerclassManage module",str(expc))  
            self.log.logEvent("labourerclassManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"])   


    def requstReject(self,clientId,msgDist,sessionkey):
        masterdb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
        masterdb.initConnection()
        dbpass = masterdb.fetchData("regusers",["password"],{"clientid":clientId})
        password = dbpass[0][0]
        admindb = DatabaseAgent(clientId,clientId,conf.host,password,conf.port)
        admindb.initConnection()
        approveCont = " set approvestatus = 'rejected' where "
        try:
            if admindb.updateTable(approveCont,"accountinfo",{"labourerid":msgDist["labourerId"]}):
                self.log.logEvent("advanceapply",2,"rejustreject",clientId,sessionMange.session[sessionkey]["userid"])
                response = {"Header":{"status":"success","module":"labfinace"},"Body":{"message":"labourer requst is rejected","data":""},"Signature":{"signature":"","Key":""}}
                return response                
            else:
                self.log.logEvent("advanceapply",2,"can't reject",clientId,sessionMange.session[sessionkey]["userid"])
                response = {"Header":{"status":"fail","module":"labfinace"},"Body":{"message":"labourer requst is can't rejected","data":""},"Signature":{"signature":"","Key":""}}
                return response   
        except Exception as expc:
            # self.syslog.eventHandle("labourerclassManage","exception","exception on labourerclassManage module",str(expc))  
            self.log.logEvent("labourerclassManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"])  

##################################################################labourer phase#########################################################



    def advanceApply(self,clientId,msgDict,sessionkey):
        masterDb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
        masterDb.initConnection()
        cond = {"clientid":clientId}
        dbData = masterDb.fetchData("regusers",["password"],cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host,password, 5432)
        adminDb.initConnection()
        # try:
        if adminDb.fetchData("labourer",["labourerid"],{"siteid":msgDict["siteId"],"labourerid":msgDict["labourerId"]}):
            timestamp = datetime.datetime.now()
            if adminDb.pushData("accountinfo",["labourerid","timestamp","phonenumber","siteid","recoveryperiod","reson"],[msgDict["labourerId"],timestamp,msgDict["phoneNumber"],msgDict["siteId"],msgDict["recoveryPeriod"],msgDict["reasonForRequest"]]):
                sitedbData = adminDb.fetchData("sites",[ "projectid","siteid ","creditaccountid","debitaccountid"],{"siteid":msgDict["siteId"]})
                print("............ls",sitedbData)
                adminDb.pushData("account",["timestamp","projectid","siteid ","creditaccountid","debitaccountid"],[timestamp,sitedbData[0][0],sitedbData[0][1],sitedbData[0][2],sitedbData[0][3]])
                adminDb.pushData("payment",["timestamp","projectid","siteid ","creditaccountid","debitaccountid","amount","resontype"],[timestamp,sitedbData[0][0],sitedbData[0][1],sitedbData[0][2],sitedbData[0][3],msgDict["fundAuthorized"],msgDict["reasonType"]])
                response = {"Header":{"status":"success","module":"labourerManage"},"Body":{"message":"labbouerAdavnce request placed sucessfully","data":""},"Signature":{"signature":"","Key":""}}
                return response             
            else:
                self.log.logEvent("laboureradvance",2,"advanceapply canot apply",clientId,sessionMange.session[sessionkey]["userid"])
                response = {"Header":{"status":"fail","module":"labourerManage"},"Body":{"message":"labbouerAdavnce request can't be placed","data":""},"Signature":{"signature":"","Key":""}}
                return response  
        else:
            response = {"Header":{"status":"fail","module":"labourerManage"},"Body":{"message":"labbouer can't exist this site","data":""},"Signature":{"signature":"","Key":""}}
            return response  
        # except Exception as expc:
        #     # self.syslog.eventHandle("labourerManage","exception","exception on labourerManage module",str(expc))  
        #     self.log.logEvent("labourerclassManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"]) 
        #     print("exception is occured at",str(expc))                  

    def advanceRespo(self,clientId,msgDict,sessionkey):
        try:
            masterdb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
            masterdb.initConnection()
            dbpass = masterdb.fetchData("regusers",["password"],{"clientid":clientId})
            password = dbpass[0][0]
            admindb = DatabaseAgent(clientId,clientId,conf.host,password,conf.port)
            admindb.initConnection()
            listAdvance = admindb.fetchData("laboureradvance",["status","advanceid"],{"labourerid":msgDict["labourerId"]})
            self.log.logEvent("paymentDesk",2,"advancerespo",clientId,sessionMange.session[sessionkey]["userid"])
            response = {"Header":{"status":"success","module":"labourerManage"},"Body":{"message":"labourer requstedAdvance satus check","data":listAdvance},"Signature":{"signature":"","Key":""}}
            return response
        except Exception as expc:
            # self.syslog.eventHandle("labourerManage","exception","exception on labourerManage module",str(expc))
            self.log.logEvent("labourerclassManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"]) 
            print("exception is occured at",str(expc))

# labad = paymentDesk()
# # print("total advance list",labad.requstList("kec166"))
# print("approvelist",labad.requstApprove("kec166",{"labourerId":"lab1001"}))
# # print("approvelist",labad.requstReject("kec166",{"labourerId":"lab1001"}))
示例#5
0
class shiftManage:

    def __init__(self):
        self.log = Logger()
        self .authen = Authentication()

############################################################################shift management#############################################################
    def shiftCreation(self,clientId,msgDict,sessionkey):
        masterDb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
        masterDb.initConnection()
        cond = {"clientid":clientId}
        dbData = masterDb.fetchData("regusers",["password"],cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host,password, 5432)
        adminDb.initConnection()
        nameLs = []
        valueLs = []
        for key in msgDict:
            nameLs.append(key)
            valueLs.append(msgDict[key])
        curTime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        nameLs.append("shiftcreatedon")
        valueLs.append(curTime)
        reval = False
        try:
            reval = adminDb.pushData("shift",nameLs,valueLs)
            if reval:
                self.log.logEvent("shiftManage",2,"labourer shift created successfully",clientId,sessionMange.session[sessionkey]["userid"])
                response = {"Header":{"status":"success","module":"ShiftManage"},"Body":{"message":"shift Added successfully","data":""},"Signature":{"signature":"","Key":""}}
                return response                  
            else:
                self.log.logEvent("shiftManage",2,"labourer shift creation error",clientId,sessionMange.session[sessionkey]["userid"])
                response = {"Header":{"status":"fail","module":"ShiftManage"},"Body":{"message":"shift can't created","data":""},"Signature":{"signature":"","Key":""}}
                return response      
        except Exception as expc:
            print("oocured exception is",expc)
            self.log.logEvent("shiftmanage",2,str(expc),clientId,sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("shiftmanage","exception","exception on shiftManage module",str(expc))          

    def shiftList(self,clientId,sessionkey):
        masterDb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
        masterDb.initConnection()
        cond = {"clientid":clientId}
        dbData = masterDb.fetchData("regusers",["password"],cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host,password, 5432)
        adminDb.initConnection()
        try:
            responseData =  adminDb.fetchData("shift","*")
            self.log.logEvent("shiftmanage",2,"labourer shift list",clientId,sessionMange.session[sessionkey]["userid"])
            response = {"Header":{"status":"success","module":"ShiftManage"},"Body":{"message":"shift can't created","data":responseData},"Signature":{"signature":"","Key":""}}
            return response            
            
        except Exception as expc:
            # self.syslog.eventHandle("shiftmanage","exception","exception on shiftManage module",str(expc))          
            print("oocured exception is",expc)
        
        self.log.logEvent("shiftmanage",2,"labourer shift listed successfully",clientId,sessionMange.session[sessionkey]["userid"])

    # def shiftEdit(self,msgDict):
    #     adminDb = DatabaseAgent("admin", "admin", conf.host, "admin123", 5432)
    #     adminDb.initConnection()
    #     admin = Admin()
    #     condition = {"shiftid":msgDict["shiftId"]}
    #     changDict = {}
    #     for key in msgDict:
    #         if key == "shiftId":
    #             continue
    #         else:
    #             changDict[key.lower()] = (msgDict[key])
    #             print("conditon",condition)
    #             print("datas",changDict)
    #     if adminDb.editData("shift",changDict,condition):
    #         self.log.logEvent("Admin",2,"labourer shift edited successfully")
    #         return admin.shiftList()

    #     else:
    #         self.log.logEvent("Admin",2,"labourer shift cant edited")
    #         return "shift creation error"
            
    def shiftDeleted(self,clientId,msgDict,sessionkey):
        masterDb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
        masterDb.initConnection()
        cond = {"clientid":clientId}
        dbData = masterDb.fetchData("regusers",["password"],cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host,password, 5432)
        adminDb.initConnection()
        delete = " set delete = 'True' where "
        condition = {"shiftid":msgDict["shiftId"]}
        reval = False
        try:
            if adminDb.updateTable(delete,"shift",condition):
                self.log.logEvent("shiftManage",2,msgDict["shiftId"]+"labourer shift deleted successfully",clientId,sessionMange.session[sessionkey]["userid"])
                response = {"Header":{"status":"success","module":"ShiftManage"},"Body":{"message":"shift deleted succes","data":""},"Signature":{"signature":"","Key":""}}
                return response            
            else:
                self.log.logEvent("shiftManage",2,msgDict["shiftId"]+"labourer shift cant deleted",clientId,sessionMange.session[sessionkey]["userid"])
                response = {"Header":{"status":"fail","module":"ShiftManage"},"Body":{"message":"shift canot deleted","data":""},"Signature":{"signature":"","Key":""}}
                return response     
        except Exception as expc: 
            print("oocured exception is",expc) 
            self.log.logEvent("shiftmanage",2,"labourer shift delete successfully",clientId,sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("shiftmanage","exception","exception on shiftManage module",str(expc))    

    def shiftAssingn(self,clientId,msgDict,sessionkey):
        masterDb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
        masterDb.initConnection()
        cond = {"clientid":clientId}
        dbData = masterDb.fetchData("regusers",["password"],cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host,password, 5432)
        adminDb.initConnection()
        changDict = {"shiftid":msgDict["shiftId"]}
        condition = {}
        for key in msgDict:
            condition[key.lower()] = (msgDict[key])
            self.log.logEvent("shiftManage",2,"shift assigned successfully",clientId,sessionMange.session[sessionkey]["userid"])
        reval = False
        try:
            reval = adminDb.editData("labourer",changDict,condition)
            
        except Exception as expc:
            # self.syslog.eventHandle("shiftmanage","exception","exception on shiftManage module",str(expc))    
            print("oocured exception is",expc)

        if reval:
            self.log.logEvent("shiftManage",2,"shift can't assigned ",clientId,sessionMange.session[sessionkey]["userid"]) 
            return "shift assingend successfully"                  #admin.labouerList()
示例#6
0
 def __init__(self):
     self.log = Logger()
     self .authen = Authentication()
class projectManage:
    def __init__(self):
        self.log = Logger()
        self.authen = Authentication()

    def projectsAdding(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        # nameLs = []
        # valueLs = []
        # sites = ""
        # labourercnt = ""
        # for key in msgDict:
        #     if key == "locations":
        #         continue
        #     else:
        #         nameLs.append(key.lower())
        #         valueLs.append(msgDict[key])
        # print("namels............",nameLs)
        # print("valuels...............",valueLs)
        try:
            if adminDb.pushData("projects", ["projectname"],
                                [msgDict["projectName"]]):
                projectid = adminDb.fetchData(
                    "projects", ["projectid"],
                    {"projectname": msgDict["projectName"]})
                # for key in msgDict:
                #     if key == "locations":
                # for cnt in range(len(msgDict["locations"])):
                adminDb.pushData("sites", [
                    "sitenames", "numoflabourer", "projectid",
                    "compensationamount", "compensationdays", "concreteamount",
                    "debitaccountid", "creditaccountid"
                ], [
                    msgDict["siteNames"], msgDict["numOfLabourer"],
                    projectid[0], msgDict["compensationAmount"],
                    msgDict["compensationDays"], msgDict["concreteAmount"],
                    msgDict["debitAccountId"], msgDict["creditAccountId"]
                ])
                self.log.logEvent(
                    "projectManage", 2,
                    msgDict["projectName"] + " project added successfully",
                    clientId, sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "success",
                        "module": "projectManage"
                    },
                    "Body": {
                        "message": "project added successfully",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
            else:
                self.log.logEvent(
                    "Admin", 2,
                    msgDict["projectName"] + " project canot added", clientId,
                    sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "fail",
                        "module": "projectManage"
                    },
                    "Body": {
                        "message": "project can't added",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
        except Exception as expc:
            # self.syslog.eventHandle("projectmanagement","exception","exception on projectManage module",str(expc))
            self.log.logEvent(
                "projectManage", 3,
                " all role permission listed occured " + str(expc), clientId,
                sessionMange.session[sessionkey]["userid"])

    def listProjects(self, clientId, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        totalLs = []
        datalis = ["projectname,projectid"]
        siteinfo = [
            "sitenames", "siteid", "numoflabourer", "compensationamount",
            "compensationdays", "concreteamount", "debitaccountid",
            "creditaccountid"
        ]
        self.log.logEvent("projectManage", 0, "project listed successfully",
                          clientId, sessionMange.session[sessionkey]["userid"])
        try:
            projectData = adminDb.fetchData("projects", datalis)
            print("Project Names and ID : ", projectData)
            print("Length od Project Data : ", len(projectData))
            for cnt in range(len(projectData)):
                print("Count: ", cnt)
                ls = adminDb.fetchData("sites", siteinfo,
                                       {"projectid": projectData[cnt][1]})
                print("List: ", ls)

                totalLs.append([projectData[cnt][0], projectData[cnt][1]])

                totalLs[-1].append(list(ls))
                print("TotalLs: ", totalLs)

            response = {
                "Header": {
                    "status": "success",
                    "module": "projectManage"
                },
                "Body": {
                    "message": "project list",
                    "data": totalLs
                },
                "Signature": {
                    "signature": "",
                    "Key": ""
                }
            }
            return response
        except Exception as expc:
            # self.syslog.eventHandle("projectmanagement","exception","exception on projectManage module",str(expc))
            self.log.logEvent(
                "projectManage", 3,
                " all role permission listed occured " + str(expc), clientId,
                sessionMange.session[sessionkey]["userid"])

    def editList(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        totalLs = []
        datalis = ["projectname,projectid"]
        siteinfo = [
            "sitenames", "siteid", "numoflabourer", "compensationamount",
            "compensationdays", "concreteamount"
        ]
        self.log.logEvent("projectManage", 0, "project listed successfully",
                          clientId, sessionMange.session[sessionkey]["userid"])
        try:
            projectData = adminDb.fetchData(
                "projects", datalis, {"projectid": msgDict["projectId"]})
            print("Project Names and ID : ", projectData)
            print("Length od Project Data : ", len(projectData))
            for cnt in range(len(projectData)):
                print("Count: ", cnt)
                ls = adminDb.fetchData("sites", siteinfo,
                                       {"projectid": projectData[cnt][1]})
                print("List: ", ls)

                totalLs.append([projectData[cnt][0], projectData[cnt][1]])

                totalLs[-1].append(list(ls))
                print("TotalLs: ", totalLs)

            response = {
                "Header": {
                    "status": "success",
                    "module": "projectManage"
                },
                "Body": {
                    "message": "project list",
                    "data": totalLs
                },
                "Signature": {
                    "signature": "",
                    "Key": ""
                }
            }
            return response
        except Exception as expc:
            # self.syslog.eventHandle("projectmanagement","exception","exception on projectManage module",str(expc))
            self.log.logEvent(
                "projectManage", 3,
                " all role permission listed occured " + str(expc), clientId,
                sessionMange.session[sessionkey]["userid"])

    def editProjects(self, clientId, msgDict):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        condition = {"projectid": msgDict["projectId"]}
        changDist = {}
        for key in msgDict:
            if "projectId" == key:
                continue
            else:
                changDist[key.lowe()] = (msgDict[key])
        try:
            if adminDb.editData("projects", changDist, condition):
                self.log.logEvent("projectManage", 0,
                                  "project edited successfully", clientId,
                                  sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "success",
                        "module": "projectManage"
                    },
                    "Body": {
                        "message": "project edited successfully",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
            else:
                self.log.logEvent("projectManage", 0,
                                  "project database error ", clientId,
                                  sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "fail",
                        "module": "projectManage"
                    },
                    "Body": {
                        "message": "project can't edited",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
        except Exception as expc:
            # self.syslog.eventHandle("projectmanagement","exception","exception on projectManage module",str(expc))
            self.log.logEvent(
                "projectManage", 3,
                " all role permission listed occured " + str(expc), clientId,
                sessionMange.session[sessionkey]["userid"])

    def deleteProjects(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        delete = " set delete = 'True' where "
        condition = {"projectid": msgDict["projectId"]}
        try:
            if adminDb.updateTable(delete, "projects",
                                   condition) and adminDb.updateTable(
                                       delete, "sites", condition):
                self.log.logEvent("projectManage", 3,
                                  "project deleted successfully", clientId,
                                  sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "success",
                        "module": "projectManage"
                    },
                    "Body": {
                        "message": "project deleted successfully",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
            else:
                self.log.logEvent("projectManage", 3,
                                  "project deleted db error occured", clientId,
                                  sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "fail",
                        "module": "projectManage"
                    },
                    "Body": {
                        "message": "project can't deleted",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
        except Exception as expc:
            # self.syslog.eventHandle("projectmanagement","exception","exception on projectManage module",str(expc))
            self.log.logEvent(
                "projectManage", 3,
                " all role permission listed occured " + str(expc), clientId,
                sessionMange.session[sessionkey]["userid"])

    def filterProjects(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        # condiotion ={"delete ":"False"}
        condition = {}
        try:
            for key in msgDict:
                condition[key.lower()] = msgDict(key)
            datalis = [
                "projectname,projectlocations,projectlabourers,projectid,siteid"
            ]
            self.log.logEvent("projectManage", 0,
                              "project listed successfully", clientId,
                              sessionMange.session[sessionkey]["userid"])
            responseData = adminDb.fetchData("projects", datalis, condition)
            response = {
                "Header": {
                    "status": "success",
                    "module": "projectManage"
                },
                "Body": {
                    "message": "project filterd",
                    "data": responseData
                },
                "Signature": {
                    "signature": "",
                    "Key": ""
                }
            }
            return response
        except Exception as expc:
            # self.syslog.eventHandle("projectmanagement","exception","exception on projectManage module",str(expc))
            self.log.logEvent(
                "projectManage", 3,
                " all role permission listed occured " + str(expc), clientId,
                sessionMange.session[sessionkey]["userid"])

    def addSites(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        nameLs = []
        valuels = []
        try:
            for key in msgDict:
                nameLs.append(key.lower())
                valuels.append(msgDict[key])
            if adminDb.pushData("sites", nameLs, valuels):
                self.log.logEvent("projectManage", 2,
                                  "project added successfully", clientId,
                                  sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "success",
                        "module": "projectManage"
                    },
                    "Body": {
                        "message": "site added sucessfully",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
            else:
                self.log.logEvent("projectManage", 2, "project can't added",
                                  clientId,
                                  sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "success",
                        "module": "projectManage"
                    },
                    "Body": {
                        "message": "site can't added",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response

        except Exception as expc:
            # self.syslog.eventHandle("projectmanagement","exception","exception on projectManage module",str(expc))
            self.log.logEvent(
                "projectManage", 3,
                " all role permission listed occured " + str(expc), clientId,
                sessionMange.session[sessionkey]["userid"])

    def deletSites(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        delete = " set delete = 'True' where "
        try:
            if adminDb.updateTable(delete, "sites",
                                   {"siteid": msgDict["siteId"]}):
                self.log.logEvent("projectManage", 3,
                                  "project deleted successfully", clientId,
                                  sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "success",
                        "module": "projectManage"
                    },
                    "Body": {
                        "message": "site deleted sucessfully",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
            else:
                self.log.logEvent("projectManage", 0, "project can't delete",
                                  clientId,
                                  sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "fail",
                        "module": "projectManage"
                    },
                    "Body": {
                        "message": "site can't deleted",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
        except Exception as expc:
            # self.syslog.eventHandle("projectmanagement","exception","exception on projectManage module",str(expc))
            self.log.logEvent("projectManage", 3, str(expc), clientId,
                              sessionMange.session[sessionkey]["userid"])

    def projectIdList(self, clientId, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        try:
            responseData = adminDb.fetchData("projects", ["projectid"])
            self.log.logEvent("projectManage", 0,
                              "projectId  listed successfully", clientId,
                              sessionMange.session[sessionkey]["userid"])
            response = {
                "Header": {
                    "status": "success",
                    "module": "projectManage"
                },
                "Body": {
                    "message": "project idlist",
                    "data": responseData
                },
                "Signature": {
                    "signature": "",
                    "Key": ""
                }
            }
            return response
        except Exception as expc:
            # self.syslog.eventHandle("projectmanagement","exception","exception on projectManage module",str(expc))
            self.log.logEvent("projectManage", 3, str(expc), clientId,
                              sessionMange.session[sessionkey]["userid"])


# pro = projectManage()
# pro.listProjects("kec119","karthi007")
示例#8
0
class roleManage:
    def __init__(self):
        self.log = Logger()
        self.authen = Authentication()

    def createRoles(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        valuelist = []
        templist = []
        valuelist.append(msgDict["roleName"])
        for key in msgDict:
            if key == "roleName":
                continue
            else:
                templist.append(msgDict[key])
        bigstr = ""
        for val in templist:
            bigstr += val + "&&"
        valuelist.append(bigstr)
        try:
            if adminDb.pushData("permission", ["rolename", "permissions"],
                                valuelist):
                self.log.logEvent("roleManage", 2,
                                  "Client role created successfully", clientId,
                                  sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "success",
                        "module": "roleMange"
                    },
                    "Body": {
                        "message": "role created successfully",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
            else:
                self.log.logEvent("roleManage", 2,
                                  "Client role creation db error occured",
                                  clientId,
                                  sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "success",
                        "module": "roleManage"
                    },
                    "Body": {
                        "message": "role can't created",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
        except Exception as expc:
            # self.syslog.eventHandle("rolemanagement","exception","exception on rolemanage module",str(expc))
            self.log.logEvent("labourerManage", 2,
                              "occured expection is" + str(expc), clientId,
                              sessionMange.session[sessionkey]["userid"])

    def editRoles(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        changDict = {}
        templist = []
        valueList = []
        for key in msgDict:
            if key == "roleName":
                continue
            elif key == "roleId":
                continue
            else:
                templist.append(msgDict[key])
        bigstr = ""
        for val in templist:
            bigstr += val + "&&"
        # valuelist.append(bigstr)
        changDict["rolename"] = (msgDict["roleName"])
        changDict["roleid"] = (msgDict["roleId"])
        changDict["permissions"] = (bigstr)
        condition = {"roleid": msgDict["roleId"]}
        print("total.......................................", changDict)
        reval = False
        try:
            if adminDb.editData("permission", changDict, condition):
                self.log.logEvent(
                    "roleManage", 3,
                    msgDict["roleId"] + "role permission edited successfully",
                    clientId, sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "success",
                        "module": "roleManage"
                    },
                    "Body": {
                        "message": "user role edited successfully",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
            else:
                self.log.logEvent(
                    "roleManage", 3,
                    msgDict["roleId"] + "role permission canot edited ",
                    clientId, sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "success",
                        "module": "roleManage"
                    },
                    "Body": {
                        "message": "uerer role canot edit",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
        except Exception as expc:
            # self.syslog.eventHandle("rolemanagement","exception","exception on rolemanage module",str(expc))
            self.log.logEvent("labourerManage", 2,
                              "occured expection is" + str(expc), clientId,
                              sessionMange.session[sessionkey]["userid"])

    def listRoles(self, clientId, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        permiSdata = []
        try:
            permiSdata = adminDb.fetchData(
                "permission", ["rolename", "roleid", "permissions"])

            # out = [item for t in permiSdata for item in t]
            print("database value is", permiSdata)
            out = []
            for t in permiSdata:
                out.append(list(t))

            # for cnt in range(2,len(out),+3):
            print("out", out)
            for cnt in range(len(out)):
                data = bytes(out[cnt][2])
                data1 = data.decode("utf-8")
                data2 = str(data1).split('&&')
                out[cnt][2] = data2
            self.log.logEvent("roleManage", 3,
                              " all role permission listed successfully",
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            response = {
                "Header": {
                    "status": "success",
                    "module": "roleManage"
                },
                "Body": {
                    "message": "uerer role list",
                    "data": out
                },
                "Signature": {
                    "signature": "",
                    "Key": ""
                }
            }
            return response
        except Exception as expc:
            # self.syslog.eventHandle("rolemanagement","exception","exception on rolemanage module",str(expc))
            self.log.logEvent(
                "roleManage", 3,
                " all role permission listed occured exception is = " +
                str(expc), clientId,
                sessionMange.session[sessionkey]["userid"])

    def deleteRole(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        delete = " set delete = 'True' where "
        condition = {"roleid": msgDict["roleId"]}
        try:
            if self.adminDb.updateTable(delete, "permission", condition):
                self.log.logEvent(
                    "roleManage", 3,
                    msgDict["roleId"] + "role deleted  successfully", clientId,
                    sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "success",
                        "module": "roleManage"
                    },
                    "Body": {
                        "message": "uerer role deleted successfully",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
            else:
                self.log.logEvent(
                    "roleManage", 3,
                    msgDict["roleId"] + "user prmiisson database error",
                    clientId, sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "success",
                        "module": "roleManage"
                    },
                    "Body": {
                        "message": "uerer role canot deleted",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
        except Exception as expc:
            # self.syslog.eventHandle("rolemanagement","exception","exception on rolemanage module",str(expc))
            self.log.logEvent(
                "roleManage", 3,
                " all role permission listed occured " + str(expc), clientId,
                sessionMange.session[sessionkey]["userid"])
class labourerClass:

    def __init__(self):
        self.log = Logger()
        self .authen = Authentication()

    def classList(self,clientId,sessionkey):
        masterDb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
        masterDb.initConnection()
        cond = {"clientid":clientId}
        dbData = masterDb.fetchData("regusers",["password"],cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host,password, 5432)
        adminDb.initConnection()
        labclas = ["labourerclass","wageclass","labourerclassid","compensation","retention","advance","concretecharges"]                           #,"compensation","Retention","Advance","Concrete_charges"]
        self.log.logEvent("Admin",2,"class list listed successfully",clientId,sessionMange.session[sessionkey]["userid"]) 
        try:
            responseData = adminDb.fetchData("labourerclass",labclas)
            response = {"Header":{"status":"success","module":"labourerClass"},"Body":{"message":"class list","data":responseData},"Signature":{"signature":"","Key":""}}
            return response            
            
        except Exception as expc:
            # self.syslog.eventHandle("labourerclassManage","exception","exception on labourerclassManage module",str(expc))  
            self.log.logEvent("labourerclassManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"])     

    def classAdding(self,clientId,msgDict,sessionkey):
        masterDb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
        masterDb.initConnection()
        cond = {"clientid":clientId}
        dbData = masterDb.fetchData("regusers",["password"],cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host,password, 5432)
        adminDb.initConnection()
        keyList =[]
        valList = []
        for key in msgDict:
            keyList.append(key.lower())
            valList.append(msgDict[key])
        try:
            if adminDb.pushData("labourerclass",keyList,valList):
                self.log.logEvent("Admin",2,msgDict["labourerClass"]+" class added successfully",clientId,sessionMange.session[sessionkey]["userid"])
                response = {"Header":{"status":"success","module":"labourerClass"},"Body":{"message":"class added successfully","data":""},"Signature":{"signature":"","Key":""}}
                return response              
            else:
                response = {"Header":{"status":"fail","module":"labourerClass"},"Body":{"message":"class can't added","data":""},"Signature":{"signature":"","Key":""}}
                return response  
        except Exception as expc:
            # self.syslog.eventHandle("labourerclassManage","exception","exception on labourerclassManage module",str(expc))  
            self.log.logEvent("labourerclassManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"])                  
                   

    def classDelete(self,clientId,msgDict,sessionkey):
        masterDb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
        masterDb.initConnection()
        cond = {"clientid":clientId}
        dbData = masterDb.fetchData("regusers",["password"],cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host,password, 5432)
        adminDb.initConnection()
        delete = " set delete = 'True' where "
        condition = {"labourerclassid":msgDict["classId"]}
        reval =  False
        try:
            if adminDb.updateTable(delete,"labourerclass",condition):
                self.log.logEvent("Admin",2,msgDict["classId"]+"labourer class deleted successfully",clientId,sessionMange.session[sessionkey]["userid"])
                response = {"Header":{"status":"success","module":"labourerClass"},"Body":{"message":"class deleted succes","data":""},"Signature":{"signature":"","Key":""}}
                return response              
            else:
                self.log.logEvent("Admin",2,msgDict["classId"]+"labourer class cant deleted "+ expc + "exception is occured",clientId,sessionMange.session[sessionkey]["userid"])
                response = {"Header":{"status":"fail","module":"labourerClass"},"Body":{"message":"class canot deleted","data":""},"Signature":{"signature":"","Key":""}}
                return response     
        except Exception as expc:
            # self.syslog.eventHandle("labourerclassManage","exception","exception on labourerclassManage module",str(expc))  
            self.log.logEvent("labourerclassManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"])                 
示例#10
0
class Authentication:
    def __init__(self):
        self.log = Logger()

    def signatureVerify(self, rVerifyKey, signature, plainMsg):
        print("Signature Verification-------")
        print(rVerifyKey)
        print("verfykey", type(rVerifyKey))
        print("sign", type(signature), "----*")
        print(signature)
        print("plaintext........", plainMsg[:7])
        print("plain", type(plainMsg))
        print("Plain Message: ", plainMsg)

        verifyKey = nacl.signing.VerifyKey(rVerifyKey,
                                           encoder=nacl.encoding.HexEncoder)
        sign = bytes.fromhex(signature)
        print(type(verifyKey))
        print(type(sign))

        # print("sign",sign.decode("utf-8"))
        data = plainMsg.encode("utf-8")

        print("type of data     ", type(data))
        print(",.......", data)

        try:
            verifiedMsg = verifyKey.verify(sign)
            if plainMsg.encode('utf-8') == verifiedMsg:
                return True
            else:
                print("Plain and Verified Message Mismatch")
                return False
        except Exception as ex:
            print("Error Occurred in signature verification: ", ex)
            return False

        return True

    def generateKeys(self):
        Priva_key = PrivateKey.generate()
        authDictkey = ["UserId", "privateKey", "publicKey"]
        authDictvalue = []
        tablename = "userkeys"
        userid = 1557
        print("actual key=", Priva_key)
        encoPrivateKey = Priva_key.encode(Base64Encoder).decode('utf8')
        print("publickey", Priva_key.public_key)
        encopubk_key = Priva_key.public_key.encode(Base64Encoder).decode(
            'utf8')
        authDictvalue.append(userid)
        authDictvalue.append(encoPrivateKey)
        authDictvalue.append(encopubk_key)
        dbagent = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                conf.mdbPassword, conf.port)
        dbagent.pushData(tablename, authDictkey, authDictvalue)

    def publicVerification(self):
        dbagent = DatabaseAgent("kunnel", "kunnel", "127.0.0.1", "kunnel123",
                                "5432")
        key = []
        cond = {"userid": "1557"}
        key.append("PrivateKey")
        dbprivatekey = dbagent.fetchData(key, "userkeys", cond)
        prvk = base64.b64decode(str(data).encode('utf8'))
        print("actual key2", prvk)

    def encrypt(self, msg, pubkey, cond):
        dbagent = DatabaseAgent("kunnel", "kunnel", "127.0.0.1", "kunnel123",
                                "5432")
        key = [
            "PrivateKey",
        ]
        dbPrivatekey = dbagent.fetchData(key, "userkeys", cond)
        utf8PriKey = base64.b64decode(str(dbPrivatekey).encode('utf8'))
        print(type(utf8PriKey))
        key_box = libnacl.public.Box(utf8PriKey, pubkey)
        messageEncoded = bytes(msg, 'utf-8')
        cipher = key_box.encrypt(messageEncoded)
        return cipher

    def decrypt(self, encmsg, pubkey, cond):
        dbagent = DatabaseAgent("kunnel", "kunnel", "127.0.0.1", "kunnel123",
                                "5432")
        key = [
            "PrivateKey",
        ]
        dbPrivateKey = dbagent.fetchData(key, "userkeys", cond)
        utf8PriKey = base64.b64decode(str(dbprivatekey).encode('utf8'))
        key_box = libnacl.public.Box(utf8PriKey, pubkey)
        dec_mess = key_box.decrypt(encmsg)
        plainTxt = str(dec_mess, 'utf-8')
        return plainTxt

    def login(self, msg, tableName, fileds, dbConfig, sessionkey):
        val = False
        try:
            username = msg["userName"]
            password = msg["password"]
            #username.replace(" ","")
            condition = {"username": username}
            dbagent = DatabaseAgent(dbConfig[0], dbConfig[1], "127.0.0.1",
                                    dbConfig[2], dbConfig[3])
            dbagent.initConnection()
            value = dbagent.fetchData(tableName, fileds, condition)
            print("totals...", value)
            salt = bytes(value[0][1])
            print("sal.....................", salt)
            hashPassword = hashlib.sha512(password.encode() + salt).hexdigest()
            print("databse hash value", bytes(value[0][0]))
            print("hashedpassword", hashPassword.encode())
            sign = []
            if hashPassword.encode() == bytes(value[0][0]):
                val = True
                sessionMange.session[sessionkey] = {}
                sessionMange.session[sessionkey]["userid"] = (value[0][2])
                sessionMange.session[sessionkey]["userrole"] = (value[0][3])
                sign_key = nacl.signing.SigningKey.generate()
                verifyKey = sign_key.verify_key
                sessionMange.session[sessionkey]["signkey"] = (sign_key)
                sessionMange.session[sessionkey]["verifykey"] = (verifyKey)
            else:
                val = False
            return val
        except Exception as excp:
            print("occured exceptio is ", excp)

    def logout(self, msgDict, key):
        print("session is begign", sessionMange.session)
        # sessionkey = msgDict["sessionKey"]
        del sessionMange.session[key]
        print("session is next", sessionMange.session)
        if not key in sessionMange.session:
            response = {
                "Header": {
                    "status": "success",
                    "module": "Authendication"
                },
                "Body": {
                    "message": "user logout successfully",
                    "data": ""
                },
                "Signature": {
                    "signature": "",
                    "Key": ""
                }
            }
            return response
        else:
            response = {
                "Header": {
                    "status": "fail",
                    "module": "Authendication"
                },
                "Body": {
                    "message": "user lout error",
                    "data": ""
                },
                "Signature": {
                    "signature": "",
                    "Key": ""
                }
            }
            return response

    def signUp(self, password):
        salt = base64.urlsafe_b64encode(uuid.uuid4().bytes)
        hashPassword = hashlib.sha512(password.encode() + salt).hexdigest()
        signobj = {}
        signobj["hashPassword"] = hashPassword
        print("salt type...................", type(salt))
        signobj["salt"] = salt
        print("hashedpassword", hashPassword)
        print("salt---", salt)
        dbagent = DatabaseAgent("kunnel", "kunnel", "127.0.0.1", "kunnel123",
                                "5432")
        dbagent.initConnection()
        fileds = ["username", "password", "salt"]
        datas = ["karthiban", hashPassword, salt]
        dbagent.pushData("users", fileds, datas)

        return signobj

    def uRolePermissionCheck(self, clientid, apiEndPoint, sessionkey):
        if sessionMange.session[sessionkey]["userrole"] == "Admin":

            return True

        else:

            masterDb = DatabaseAgent("kunnel", "kunnel", "127.0.0.1",
                                     "kunnel123", 5432)
            masterDb.initConnection()
            dblist = []
            cond = {"clientid": clientid}
            dbData = masterDb.fetchData("regusers", ["password"], cond)
            password = dbData[0][0]
            adminDb = DatabaseAgent(clientid, clientid, "127.0.0.1", password,
                                    5432)
            adminDb.initConnection()
            # condition = {"roleid":"role1001"}
            condition = {
                "rolename": sessionMange.session[sessionkey]["userrole"]
            }
            dbroleList = adminDb.fetchData("permission", ["permissions"],
                                           condition)
            print("dbrolelist", dbroleList)
            permissions = (bytes(dbroleList[0][0])).decode("utf-8").split("&&")
            print("datas ..", permissions)

            if apiEndPoint in permissions:
                self.log.logEvent("Communication", 2,
                                  "client permission granted")
                return True

            else:
                self.log.logEvent("Communication", 2, "wrong user access")
                return False

    # return True


################################################################################testing################################################
# def testing(self):
#     dbagent = DatabaseAgent("kunnel", "kunnel", "127.0.0.1", "kunnel123", "5432")
#     dbagent.initConnection()
#     value = dbagent.fetchData("users",["password","salt"])
#     salt = value[0][1]
#     print("sal type........",salt)
#     # hashPassword = hashlib.sha512(password.encode() + salt.encode()).hexdigest()
#     #print("producing hash value",hashPassword)
#     print("databse hash value",bytes(value[0][0]))

# auth = Authentication()
# print("reval is....",auth.uRolePermissionCheck("kec136","/user/archieve"))
 def __init__(self):
     self.auth = Authentication()
     self.log = Logger()
     self.rejx = dataVerify()
class Communication:  
    def __init__(self):
        self.auth = Authentication()
        self.log = Logger()
        self.rejx = dataVerify()
        # self.modulauncher = ModuleLauncher()
        # self.launcher = ModuleLauncher()
    # def seralize(self,dicto):
    #     #self.deseralize(data_json)
    #     obj = json.dumps(dicto,default=getDict)
    #     return obj
        

    def deserialize(self, jsonData):
        try:
            deserialized = json.loads(jsonData)
            print(deserialized)
            return deserialized
        except Exception as expc:
            self.log.logEvent("communication deserialize",2,"exception ocureed"+str(expc))            

    def verifyStructure(self, msgDict):
        try:
            containsHeader = False
            containsBody = False
            containsExtraField = False
            containsSignature = False
            for key in msgDict:
                if key == "Header":
                    containsHeader = True
                elif key == "Body":
                    containsBody = True
                elif key == "Signature":
                    containsSignature = True
                else:
                    containsExtraField = True
                    break

            return containsHeader and containsSignature and containsBody and not containsExtraField
        except Exception as expc:
            self.log.logEvent("communication verify structure function",2,"exception ocureed"+str(expc))
            

    def createMessage(self, dictData, message):
        try:
            message.header = dictData["Header"]
            message.body = dictData["Body"]
            message.Signature = dictData["Signature"]
        except Exception as expc:
            self.log.logEvent("communication at create message function",2,"exception ocureed"+str(expc))            

    def sanitizeBody(self,msgBody):
        try:
            success = False
            for key in msgBody:
                if self.sanitizeString(key):
                    if type(msgBody[key]) is dict:
                        if not self.sanitizeBody(msgBody[key]):
                            return False
                        else:
                            success = True
                        self.sanitizeBody(msgBody[key])
                    else:
                        if self.sanitizeString(msgBody[key]):
                            success = True
                            continue

                        else:
                            success = False     
                else:
                    return False

            return success
        except Exception as expc:
            self.log.logEvent("communication at sanatizeBody function",2,"exception ocureed"+str(expc))

    def sanitizeHeader(self,msgheader):
        try:        
            success = True
            for msg in msgheader:
                if self.sanitizeString(msg):
                    if self.sanitizeString(msgheader[msg]):
                        continue
                    else:
                        success = False
                else:
                    success = False

            return success
        except Exception as expc:
            self.log.logEvent("communication at sanitizeHeader function",2,"exception ocureed"+str(expc))            

        

    def sanitizeString(self, stringData):
        try:
            text = str(stringData)
            print("data is" + text)
            ignore_words = [';','"','$','&&','../','*','<','>','%3C','%3E','\'','--','1,2','\x00','`','(',')','file://','input://'] 
            for ch in ignore_words: 
                if ch in text:
                    print("1false")
                    return False
            return True
        except Exception as expc:
            self.log.logEvent("communication at sanitizeString function",2,"exception ocureed"+str(expc))             
            

#######################################################################master handle#######################################################################33
    def receiveRequest(self,data,clientid,apiEndPoint):
        # try:
        print("JSON : ",data)
        msg = Message()
        signString = str(data).split("Body")[1]
        plainMsg = ((signString.split("Signature")[0])[:-2])[2:]
        dictData = self.deserialize(data)
        if self.verifyStructure(dictData):
            self.createMessage(dictData, msg)
            print("MESSAGE HEADER: ")
            for key in msg.Signature:
                print("keys ", key)
                if key == "signature":
                    print(" encrypetedkey will be there")
                elif key == "Key":
                    print("verfykey will  be there")
                else:
                    self.log.logEvent("Communication",3,"signatrue part is missing")
                    print("signature missing  there")
                    return "signature missing  there"
            verifyKey = msg.Signature["Key"]
            signature = msg.Signature["signature"]
            contStr = ""            
            # print("signString..........................",plainMsg)
            # sigtest = self.auth.signatureVerify(verifyKey, signature,plainMsg)
            # print("Signature Verified::::::::::::::::::::::::::::::::::::::", sigtest)
            if self.auth.signatureVerify(verifyKey, signature,plainMsg):
                if self.rejx.verifyData(msg.body):
                    if clientid == "signup" :
                        modLauncher = ModuleLauncher(clientid, msg.body,verifyKey,'/register')
                        return modLauncher.handleRequest()
                    elif clientid == "masterregister":
                        modLauncher = ModuleLauncher(clientid,msg.body,verifyKey, apiEndPoint)
                        return modLauncher.handleRequest()                        
                    elif clientid == "master":
                        modLauncher = ModuleLauncher(clientid,msg.body,verifyKey, apiEndPoint)
                        # return modLauncher.handleRequest()
                        resDict =  modLauncher.handleRequest()
                        body = resDict["Body"]
                        print("body part is....",body)
                        jsnfyBody = json.dumps(body)
                        print("jsnfyBody) = ",jsnfyBody)
                        if resDict["Header"]["status"] == "success":
                            signkey1 = sessionMange.session[verifyKey]["signkey"]
                            verifykey1 = sessionMange.session[verifyKey]["verifykey"]
                            print("verifykey type",type(verifykey1))
                            verify_key_hex =verifykey1.encode(encoder=nacl.encoding.HexEncoder)
                            print("signature private key type",type(signkey1))
                            print("type(jsnfyBody) = ", type(jsnfyBody))
                            sessionSign = signkey1.sign(jsnfyBody.encode("utf-8"))
                            print("sessionkey type",type(sessionSign))
                            print("sessionkey ............on backend",sessionSign)
                            sHexSignature = binascii.hexlify(bytes(sessionSign))
                            resDict["Signature"]["signature"] = (sHexSignature)
                            resDict["Signature"]["Key"] = (verify_key_hex)
                            print("siggened signature message................................",resDict)
                            return resDict                        
                    elif apiEndPoint == "/login":
                        # modLauncher = ModuleLauncher(clientid,msg.body,verifyKey, apiEndPoint)
                        # return modLauncher.handleRequest()
                        try:
                            modLauncher = ModuleLauncher(clientid,msg.body,verifyKey, apiEndPoint)
                            resDict =  modLauncher.handleRequest()
                            body = resDict["Body"]
                            print("body part is....",body)
                            jsnfyBody = json.dumps(body)
                            print("jsnfyBody) = ",jsnfyBody)
                            if resDict["Header"]["status"] == "success":
                                signkey1 = sessionMange.session[verifyKey]["signkey"]
                                verifykey1 = sessionMange.session[verifyKey]["verifykey"]
                                print("verifykey type",type(verifykey1))
                                verify_key_hex =verifykey1.encode(encoder=nacl.encoding.HexEncoder)
                                print("signature private key type",type(signkey1))
                                print("type(jsnfyBody) = ", type(jsnfyBody))
                                sessionSign = signkey1.sign(jsnfyBody.encode("utf-8"))
                                print("sessionkey type",type(sessionSign))
                                print("sessionkey ............",sessionSign)
                                sHexSignature = binascii.hexlify(bytes(sessionSign))
                                resDict["Signature"]["signature"] = (sHexSignature)
                                resDict["Signature"]["Key"] = (verify_key_hex)

                            return resDict 
                        except Exception as expc:
                            print("expection",expc)                      
                            response = {"Header":{"status":"fail","module":"communication"},"Body":{"message":"wrong username or password","data":""},"Signature":{"signature":"","Key":""}}
                            return response                          
                    elif apiEndPoint == "/logout":
                        modLauncher = ModuleLauncher(clientid,msg.body,verifyKey, apiEndPoint)
                        return modLauncher.handleRequest()                    
                        # resDict =  modLauncher.handleRequest()
                        # body = resDict["Body"]
                        # print("body part is....",body)
                        # jsnfyBody = str(jsonify(body))
                        # signkey1 = sessionMange.session[verifyKey]["signkey"]
                        # verifykey1 = sessionMange.session[verifyKey]["verifykey"]
                        # verify_key_hex =verifykey1.encode(encoder=nacl.encoding.HexEncoder)
                        # print("signature private key type",type(signkey1))
                        # print("type(jsnfyBody) = ", type(jsnfyBody))
                        # sessionSign = signkey1.sign(jsnfyBody.encode("utf-8"))
                        # print("sessionkey type",type(sessionSign))
                        # sHexSignature = binascii.hexlify(bytes(sessionSign))
                        # resDict["Signature"]["signature"] = (sHexSignature)
                        # resDict["Signature"]["Key"] = (verify_key_hex)
                        # return resDict                    
                    elif self.auth.uRolePermissionCheck(clientid,apiEndPoint,verifyKey) :
                        # try:
                        modLauncher = ModuleLauncher(clientid,msg.body,verifyKey, apiEndPoint)
                        resDict =  modLauncher.handleRequest()
                        body = resDict["Body"]
                        print("body part is....",body)
                        jsnfyBody = json.dumps(body)
                        print("jsnfyBody) = ",jsnfyBody)
                        if resDict["Header"]["status"] == "success":
                            signkey1 = sessionMange.session[verifyKey]["signkey"]
                            verifykey1 = sessionMange.session[verifyKey]["verifykey"]
                            print("verifykey type",type(verifykey1))
                            verify_key_hex =verifykey1.encode(encoder=nacl.encoding.HexEncoder)
                            print("signature private key type",type(signkey1))
                            print("type(jsnfyBody) = ", type(jsnfyBody))
                            sessionSign = signkey1.sign(jsnfyBody.encode("utf-8"))
                            print("sessionkey type",type(sessionSign))
                            print("sessionkey ............",sessionSign)
                            sHexSignature = binascii.hexlify(bytes(sessionSign))
                            resDict["Signature"]["signature"] = (sHexSignature)
                            resDict["Signature"]["Key"] = (verify_key_hex)
                        return resDict     
                        # except Exception as expc:
                        #     print("expection",expc) 
                        #     self.log.logEvent("communication",2,"role checking function ")        
                else:
                    print(">>............................wrong datastructure")
                    return " wrong datastructure at communication"                           
                    
            else:
                self.log.logEvent("Communication",3,"signature is wrong")
                return "error occured"            
        elif self.sanitizeBody(msg.body) and self.sanitizeHeader(msg.header):
            print("Message body verified")
        else:
            self.log.logEvent("Communication",3,"invalied requst formate")
            print("Invalid body structure format ")
            return "Invalid body structure format "
class attendanceManage:
    def __init__(self):
        self.log = Logger()
        self.authen = Authentication()

    def getAttendace(
            self, clientId,
            sessionkey):  #to be filled from the call site (module launcher)
        masterDb = DatabaseAgent("kunnel", "kunnel", "127.0.0.1", "kunnel123",
                                 "5432")
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, "127.0.0.1", password,
                                5432)
        adminDb.initConnection()
        dataFields = [
            "date", "labourerid", "labourername", "labourerclass", "shiftid",
            "intime", "outtime", "numberofhours", "overtimeallocated",
            "overtimeworked", "siteid", "projectid"
        ]
        tableName = "attendance"
        responseData = adminDb.fetchData(tableName, dataFields)
        print("dictonary", responseData)
        try:
            self.log.logEvent("Admin", 2, "attendance listed success fully")
            response = {
                "Header": {
                    "status": "success",
                    "module": "attendance"
                },
                "Body": {
                    "message": "filtered attendance",
                    "data": responseData
                },
                "Signature": {
                    "signature": "",
                    "Key": ""
                }
            }
            return response
        except Exception as expc:
            # self.syslog.eventHandle("attendanceManage","exception","exception on attendanceManage module",str(expc))
            self.log.logEvent(
                "attendanceManage", 3,
                " all role permission listed occured " + str(expc))

    def getAttendacePers(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent("kunnel", "kunnel", "127.0.0.1", "kunnel123",
                                 "5432")
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, "127.0.0.1", password,
                                5432)
        adminDb.initConnection()
        dataFields = [
            "day", "date", "labourerid", "labourername", "labouercategory",
            "intime", "outtime", "numberofhours", "overtimeallocated",
            "overtimeworked", "shiftid"
        ]
        tableName = "attendance"
        condition = {}
        try:
            for key in msgDict:
                condition[key.lower()] = (msgDict[key])
            responseData = adminDb.fetchData(tableName, dataFields, condition)
            print("dictonary", responseData)
            self.log.logEvent("Admin", 2, "attendance listed success fully")
            response = {
                "Header": {
                    "status": "success",
                    "module": "attendance"
                },
                "Body": {
                    "message": "filtered attendance",
                    "data": responseData
                },
                "Signature": {
                    "signature": "",
                    "Key": ""
                }
            }
            return response
        except Exception as expc:
            # self.syslog.eventHandle("attendanceManage","exception","exception on attendanceManage module",str(expc))
            self.log.logEvent(
                "attendanceManage", 3,
                " all role permission listed occured " + str(expc))

    def filterAttendance(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent("kunnel", "kunnel", "127.0.0.1", "kunnel123",
                                 "5432")
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, "127.0.0.1", password,
                                5432)
        adminDb.initConnection()
        condition = {}
        for key in msgDict:
            condition[key.lower()] = msgDict(key)
        dataFields = [
            "day", "date", "labourerid", "labourername", "labouercategory",
            "labourertype", "intime", "outtime", "numberofhours",
            "overtimeallocated", "overtimeworked", "siteid", "projectid"
        ]
        self.log.logEvent("Admin", 2, "attendance filtering geting")
        try:
            responseData = adminDb.fetchData("attendance", dataFields,
                                             condition)
            response = {
                "Header": {
                    "status": "success",
                    "module": "attendance"
                },
                "Body": {
                    "message": "filtered attendance",
                    "data": responseData
                },
                "Signature": {
                    "signature": "",
                    "Key": ""
                }
            }
            return response
        except Exception as expc:
            # self.syslog.eventHandle("attendanceManage","exception","exception on attendanceManage module",str(expc))
            self.log.logEvent(
                "attendanceManage", 3,
                " all role permission listed occured " + str(expc))
class labbourerManage:

    def __init__(self):
        self.log = Logger()
        self .authen = Authentication()


    def labourerReg(self,clientId,msgDict,sessionkey):
        masterDb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
        masterDb.initConnection()
        cond = {"clientid":clientId}
        dbData = masterDb.fetchData("regusers",["password"],cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host,password, 5432)
        adminDb.initConnection()
        nameLs = []
        valueLs = []
        for key,val in msgDict.items():
            nameLs.append(key.lower())
            valueLs.append(val)
        try:
            siteid = adminDb.fetchData("sites",["siteid"],{"sitenames":msgDict["siteOfJoining"]})
            nameLs.append("siteid")
            valueLs.append(siteid[0])
            if adminDb.pushData("labourer",nameLs,valueLs):
                self.log.logEvent("labourerManage",2,"labourer added successfully",clientId,sessionMange.session[sessionkey]["userid"])
                response = {"Header":{"status":"success","module":"labourerManage"},"Body":{"message":"labourer added successfully","data":""},"Signature":{"signature":"","Key":""}}
                return response            

            else:
                self.log.logEvent("labourerManage",2,"labourer can't added",clientId,sessionMange.session[sessionkey]["userid"])
                response = {"Header":{"status":"fail","module":"labourerManage"},"Body":{"message":"labourer can't added","data":""},"Signature":{"signature":"","Key":""}}
                return response   
        except Exception as expc:
            # self.syslog.eventHandle("labourerManage","exception","exception on labourerManage module",str(expc))
            self.log.logEvent("labourerManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"])

        
    def labouerList(self,clientId,sessionkey):
        masterDb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
        masterDb.initConnection()
        cond = {"clientid":clientId}
        dbData = masterDb.fetchData("regusers",["password"],cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host,password, 5432)
        adminDb.initConnection()
        try:
            labourerData = ["labourername","labourerid","projectname","siteid","labourerclass","shiftid"]
            self.log.logEvent("labourerManage",2,"labourer info showed successfully",clientId,sessionMange.session[sessionkey]["userid"])
            responseData =  adminDb.fetchData("labourer",labourerData )
            response = {"Header":{"status":"success","module":"labourerManage"},"Body":{"message":"labourer list","data":responseData},"Signature":{"signature":"","Key":""}}
            return response              
        except Exception as expc:
            # self.syslog.eventHandle("labourerManage","exception","exception on labourerManage module",str(expc))
            self.log.logEvent("labourerManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"])        



    def labourerInfo(self,clientId,msgDict,sessionkey):
        masterDb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
        masterDb.initConnection()
        cond = {"clientid":clientId}
        dbData = masterDb.fetchData("regusers",["password"],cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host,password, 5432)
        adminDb.initConnection()
        conditiond = {"labourerid":msgDict["labourerId"]}
        try:
            labourdata = ["labourername","callbyname","gender","dateofbirth","fathername","bloodgroup","nextofkin","contactnumberofnextofkin","mothertounge","addressline1","addressline2","addressline3","village","state","country","pincode" ,"mobilenumber","residancephonenumber","emergencyphonenumber","dateofjoining" ,"migrantworker","designation","projectname" ,"siteid" ,"siteofjoining","labourerclass","shiftid","documenttype","documentnumber","nameasperdoc","bankname","ifsccode","branchname","bankaccountnumber","nameinbank","labourerid"]
            self.log.logEvent("labourerManage",2,"labourer info showed successfully",clientId,sessionMange.session[sessionkey]["userid"])
            responseData = adminDb.fetchData("labourer",labourdata,conditiond)
            response = {"Header":{"status":"success","module":"labourerManage"},"Body":{"message":"labourer info","data":responseData},"Signature":{"signature":"","Key":""}}
            return response       
        except Exception as expc:
            # self.syslog.eventHandle("labourerManage","exception","exception on labourerManage module",str(expc))
            self.log.logEvent("labourerManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"])                 


    # def editList(self,clientId,msgDict,sessionkey):
    #     masterDb = DatabaseAgent("kunnel", "kunnel", conf.host, "kunnel123", conf.port)
    #     masterDb.initConnection()
    #     cond = {"clientid":clientId}
    #     dbData = masterDb.fetchData("regusers",["password"],cond)
    #     password = dbData[0][0]
    #     adminDb = DatabaseAgent(clientId, clientId, conf.host,password, 5432)
    #     adminDb.initConnection()
    #     conditiond = {"labourerid":msgDict["labourerId"]}
    #     try:
    #         labourdata = ["labourername","callbyname","gender","dateofbirth","fathername","bloodgroup","nextofkin","contactnumberofnextofkin","mothertounge","addressline1","addressline2","addressline3","village","state","country","pincode" ,"mobilenumber","residancephonenumber","emergencyphonenumber","dateofjoining" ,"migrantworker","designation","projectname" ,"siteid" ,"siteofjoining","labourerclass","shiftid","documenttype","documentnumber","nameasperdoc","bankname","ifsccode","branchname","bankaccountnumber","nameinbank","labourerid"]
    #         self.log.logEvent("labourerManage",2,"labourer info showed successfully",clientId,sessionMange.session[sessionkey]["userid"])
    #         responseData = adminDb.fetchData("labourer",labourdata,conditiond)
    #         response = {"Header":{"status":"success","module":"labourerManage"},"Body":{"message":"labourer info","data":responseData},"Signature":{"signature":"","Key":""}}
    #         return response       
    #     except Exception as expc:
    #         # self.syslog.eventHandle("labourerManage","exception","exception on labourerManage module",str(expc))
    #         self.log.logEvent("labourerManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"])  


    def personalInfo(self,clientId,msgDict,sessionkey):
        masterDb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
        masterDb.initConnection()
        cond = {"clientid":clientId}
        dbData = masterDb.fetchData("regusers",["password"],cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host,password, 5432)
        adminDb.initConnection()
        conditiond = {"labourerid":msgDict["labourerId"]}
        try:
            personaldata = ["labourername","callbyname","gender","dateofbirth","fathername","bloodgroup","nextofkin","contactnumberofnextofkin","mothertounge","addressline1","addressline2","addressline3","village","state","country","pincode" ,"mobilenumber","residancephonenumber","emergencyphonenumber"]
            self.log.logEvent("labourerManage",2,"labourer info showed successfully",clientId,sessionMange.session[sessionkey]["userid"])
            responseData = adminDb.fetchData("labourer",personaldata,conditiond)
            response = {"Header":{"status":"success","module":"labourerManage"},"Body":{"message":"labourer info","data":responseData},"Signature":{"signature":"","Key":""}}
            return response       
        except Exception as expc:
            # self.syslog.eventHandle("labourerManage","exception","exception on labourerManage module",str(expc))
            self.log.logEvent("labourerManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"])  


    def employeeInfo(self,clientId,msgDict,sessionkey):
        masterDb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
        masterDb.initConnection()
        cond = {"clientid":clientId}
        dbData = masterDb.fetchData("regusers",["password"],cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host,password, 5432)
        adminDb.initConnection()
        conditiond = {"labourerid":msgDict["labourerId"]}
        try:
            employeedata = ["dateofjoining" ,"migrantworker","designation","projectname" ,"siteid" ,"siteofjoining","labourerclass","shiftid"]
            self.log.logEvent("labourerManage",2,"labourer info showed successfully",clientId,sessionMange.session[sessionkey]["userid"])
            responseData = adminDb.fetchData("labourer",employeedata,conditiond)
            response = {"Header":{"status":"success","module":"labourerManage"},"Body":{"message":"labourer info","data":responseData},"Signature":{"signature":"","Key":""}}
            return response       
        except Exception as expc:
            # self.syslog.eventHandle("labourerManage","exception","exception on labourerManage module",str(expc))
            self.log.logEvent("labourerManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"])  


    def identityInfo(self,clientId,msgDict,sessionkey):
        masterDb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
        masterDb.initConnection()
        cond = {"clientid":clientId}
        dbData = masterDb.fetchData("regusers",["password"],cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host,password, 5432)
        adminDb.initConnection()
        conditiond = {"labourerid":msgDict["labourerId"]}
        print("what is the exception/.............")
        try:
            identitydata = ["documenttype","documentnumber","nameasperdoc"]
            self.log.logEvent("labourerManage",2,"labourer info showed successfully",clientId,sessionMange.session[sessionkey]["userid"])
            responseData = adminDb.fetchData("labourer",identitydata,conditiond)
            response = {"Header":{"status":"success","module":"labourerManage"},"Body":{"message":"labourer info","data":responseData},"Signature":{"signature":"","Key":""}}
            return response       
        except Exception as expc:
            # self.syslog.eventHandle("labourerManage","exception","exception on labourerManage module",str(expc))
            self.log.logEvent("labourerManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"])  


    def bankInfo(self,clientId,msgDict,sessionkey):
        masterDb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
        masterDb.initConnection()
        cond = {"clientid":clientId}
        dbData = masterDb.fetchData("regusers",["password"],cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host,password, 5432)
        adminDb.initConnection()
        conditiond = {"labourerid":msgDict["labourerId"]}
        try:
            bankdata = ["bankname","ifsccode","branchname","bankaccountnumber","nameinbank"]
            self.log.logEvent("labourerManage",2,"labourer info showed successfully",clientId,sessionMange.session[sessionkey]["userid"])
            responseData = adminDb.fetchData("labourer",bankdata,conditiond)
            response = {"Header":{"status":"success","module":"labourerManage"},"Body":{"message":"labourer info","data":responseData},"Signature":{"signature":"","Key":""}}
            return response       
        except Exception as expc:
            # self.syslog.eventHandle("labourerManage","exception","exception on labourerManage module",str(expc))
            self.log.logEvent("labourerManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"])                                               


    def editLabourer(self,clientId,msgDict,sessionkey):
        masterDb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
        masterDb.initConnection()
        cond = {"clientid":clientId}
        dbData = masterDb.fetchData("regusers",["password"],cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host,password, 5432)
        adminDb.initConnection()
        condition = {"labourerid": msgDict["labourerId"]}
        changDist = {}
        for key in msgDict:
            if key == "labourerId":
                continue
            else:
                changDist[key.lower()] = (msgDict[key])

        try:
            if adminDb.editData("labourer",changDist,condition):
                self.log.logEvent("labourerManage",2,"labourer Edited success",clientId,sessionMange.session[sessionkey]["userid"])
                response = {"Header":{"status":"success","module":"labourerManage"},"Body":{"message":"labourer edited successfully","data":""},"Signature":{"signature":"","Key":""}}
                return response              

            else:
                self.log.logEvent("labourerManage",2,"labourer labourer can't ediot",clientId,sessionMange.session[sessionkey]["userid"])
                response = {"Header":{"status":"fail","module":"labourerManage"},"Body":{"message":"labourer canot edited","data":""},"Signature":{"signature":"","Key":""}}
                return response   
        except Exception as expc:
            # self.syslog.eventHandle("labourerManage","exception","exception on labourerManage module",str(expc))
            self.log.logEvent("labourerManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"])                  

    def deleteLabourer(self,clientId,msgDict,sessionkey):
        masterDb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
        masterDb.initConnection()
        cond = {"clientid":clientId}
        dbData = masterDb.fetchData("regusers",["password"],cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host,password, 5432)
        adminDb.initConnection()
        delete = " set delete = 'True' where "
        condition = {"labourerid": msgDict["labourerId"]}
        try:
            if adminDb.updateTable(delete,"labourer",condition):
                self.log.logEvent("labourerManage",2,"labourer deleted successfully",clientId,sessionMange.session[sessionkey]["userid"])
                response = {"Header":{"status":"success","module":"labourerManage"},"Body":{"message":"labourer deleted successfully","data":""},"Signature":{"signature":"","Key":""}}
                return response              
            else:
                self.log.logEvent("labourerManage",2,"labourer deletd successfully",clientId,sessionMange.session[sessionkey]["userid"])
                response = {"Header":{"status":"fail","module":"labourerManage"},"Body":{"message":"labouer cant deleted","data":""},"Signature":{"signature":"","Key":""}}
                return response           
        except Exception as expc:
            # self.syslog.eventHandle("labourerManage","exception","exception on labourerManage module",str(expc))
            self.log.logEvent("labourerManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"])               
            

    def labourerChange(self,clientId,msgDict,sessionkey):
        masterDb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
        masterDb.initConnection()
        cond = {"clientid":clientId}
        dbData = masterDb.fetchData("regusers",["password"],cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host,password, 5432)
        adminDb.initConnection()
        condition = {"labourerid":msgDict["labouerId"]}
        dataDict = {}
        try:        
            for key,val in msgDict:
                dataDict[key.lower()] = (msgDict[key])
            if adminDb.editData("labourer",dataDict,condition):
                self.log.logEvent("labourerManage",2,"labourer changed successfully",clientId,sessionMange.session[sessionkey]["userid"])
                response = {"Header":{"status":"success","module":"labourerManage"},"Body":{"message":"labourer changed successfully","data":""},"Signature":{"signature":"","Key":""}}
                return response             
            else:
                self.log.logEvent("labourerManage",2,"labourer can't changed",clientId,sessionMange.session[sessionkey]["userid"])
                response = {"Header":{"status":"fail","module":"labourerManage"},"Body":{"message":"labbourer can't changed","data":""},"Signature":{"signature":"","Key":""}}
                return response  
        except Exception as expc:
            # self.syslog.eventHandle("labourerManage","exception","exception on labourerManage module",str(expc))
            self.log.logEvent("labourerManage",2,"occured expection is"+str(expc),clientId,sessionMange.session[sessionkey]["userid"])                       
            
            
    def labbourerAddlist(self,clientId,sessionkey):
        masterDb = DatabaseAgent(conf.mdbName,conf.muserName,conf.host,conf.mdbPassword,conf.port)
        masterDb.initConnection()
        cond = {"clientid":clientId}
        dbData = masterDb.fetchData("regusers",["password"],cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host,password, 5432)
        adminDb.initConnection()
        total = []
        final = []
        projectData = adminDb.fetchData("projects",["projectname","projectid"]) 
        shiftList =[]
        proLs = []
        try:
            for cnt in range(len(projectData)):
                sitedb = adminDb.fetchData("sites",["sitenames"],{"projectid":projectData[cnt][1]}) 
                total.append([projectData[cnt][0],sitedb])
                # total.append(sitedb)
            final.append(list(total))
            print("projects",total)
            classdb = adminDb.fetchData("labourerclass",["labourerclass "])     #"compensation","Retention","Advance","Concrete_charges"
            final.append(classdb)
            print("\n\n\nclass",final)
            shiftdb = adminDb.fetchData("shift",["shiftid"])
            final.append(shiftdb)
            print("\n\n\n.......total",final)
            self.log.logEvent("labourerManage",0,"labourer addlist listed sucessfully",clientId,sessionMange.session[sessionkey]["userid"])                
            response = {"Header":{"status":"success","module":"labourerManage"},"Body":{"message":"labbouerAddlist","data":final},"Signature":{"signature":"","Key":""}}
            return response 
        except Exception as expc:
            # self.syslog.eventHandle("labourerManage","exception","exception on labourerManage module",str(expc))
            self.log.logEvent("labourerMange",2,str(expc),clientId,sessionMange.session[sessionkey]["userid"])
class ModuleLauncher:
    def __init__(self, clientId, data, verifykey, apiEndPoint):
        self.message = data
        self.sessionkey = verifykey
        self.apiEndPoint = apiEndPoint
        self.splitUrl = apiEndPoint.split('/')
        self.auth = Authentication()
        self.master = Master()
        self.admin = Admin()
        self.role = roleManage()
        self.attendance = attendanceManage()
        self.project = projectManage()
        self.labourer = labbourerManage()
        self.labclass = labourerClass()
        self.shift = shiftManage()
        self.log = Logger()
        self.paymentDesk = paymentDesk()
        self.clientId = clientId

    def handleRequest(self):
        if self.splitUrl[0] == "master":
            return self.handleMaster()
        elif self.apiEndPoint == "/register":
            return self.master.adminRegister(self.message, self.sessionkey)

        elif self.apiEndPoint == "/companyprofile":
            return self.admin.companyProfile(self.clientId, self.sessionkey)

        elif self.apiEndPoint == "/userprofile":

            return self.admin.userProfile(self.clientId, self.message,
                                          self.sessionkey)

        else:
            return self.handleClient(self.splitUrl[0])

    def handleClient(self, clientId):
        if self.splitUrl[1] == "login":
            return self.admin.login(self.clientId, self.message,
                                    self.sessionkey)
        elif self.splitUrl[1] == "user":
            return self.handleClientUser()

        elif self.splitUrl[1] == "projects":
            return self.handleProjects()

        elif self.splitUrl[1] == "paymentDesk":
            return self.handlePaymentDesk()

        elif self.splitUrl[1] == "userrole":
            return self.roleManage()

        elif self.splitUrl[1] == "labourer":
            return self.handleLabourer()

        elif self.splitUrl[1] == "attendance":
            if self.splitUrl[2] == "list":
                return self.attendance.getAttendace(self.clientId,
                                                    self.sessionkey)
        elif self.splitUrl[1] == "logout":
            return self.auth.logout(self.message, self.sessionkey)

        elif self.splitUrl[1] == "payments":
            pass

        else:
            self.log.logEvent("ModuleLauncher", 3, "wrong url acess")
        return "url does not defined"

    def handleMaster(self):
        if self.splitUrl[1] == "login":
            return self.master.login(self.message, self.sessionkey)

        elif self.splitUrl[1] == "register":
            # digest = self.auth.signUp(self.message["password"])
            # self.message["password"] = digest["hashPassword"]
            # self.message["salt"] = digest["salt"]
            # print("message",self.message)
            # return self.master.createMaster(self.message)
            # self.log.logEvent("ModuleLauncher",3,"Master registerd")
            return self.master.createMaster(self.message, self.sessionkey)
            #return "sucess"

        elif self.splitUrl[1] == "user":
            return self.handleMasterUser()

        elif self.splitUrl[1] == "app":

            if self.splitUrl[2] == "logs":
                return self.master.fetchAppLogs(self.message, self.sessionkey)

        elif self.splitUrl[1] == "clients":
            return self.handleMasterclients()
        elif self.splitUrl[1] == "logout":
            return self.auth.logout(self.message, self.sessionkey)

        else:
            print("master can't have  this endpoint")
            self.log.logEvent("ModuleLauncher", 3,
                              "master can't have  this endpoint")
            return "master can't have  this endpoint"

    def handleMasterUser(self):
        if self.splitUrl[2] == "add":
            return self.master.addUser(self.message, self.sessionkey)

        elif self.splitUrl[2] == "delete":
            return self.master.deleteUser(self.message, self.sessionkey)

        elif self.splitUrl[2] == "list":
            return self.master.listUser(self.sessionkey)

        elif self.splitUrl[2] == "editlist":
            return self.master.mastereditList(self.message, self.sessionkey)

        elif self.splitUrl[2] == "save":
            return self.master.editUser(self.message, self.sessionkey)

        elif self.splitUrl[2] == "archive":
            return self.master.archiveUser(self.message, self.sessionkey)

        elif self.splitUrl[2] == "unarchive":
            return self.master.unArchiveUser(self.message, self.sessionkey)

        else:
            self.log.logEvent("ModuleLauncher", 3,
                              "master_user can't have  this endpoint")
            return "wrong url access1"

    def handleMasterclients(self):
        if self.splitUrl[2] == "list":
            return self.master.getRegUserDetails(self.sessionkey)

        elif self.splitUrl[2] == "editlist":
            return self.master.clienteditList(self.message)

        elif self.splitUrl[2] == 'delete':
            return self.master.deleteClient(self.message, self.sessionkey)

        elif self.splitUrl[2] == "archive":
            return self.master.archiveClient(self.message, self.sessionkey)

        elif self.splitUrl[2] == "save":
            return self.master.editClient(self.message, self.sessionkey)

        elif self.splitUrl[2] == "approve":
            return self.master.clientApprove(self.message, self.sessionkey)

        elif self.splitUrl[2] == "reject":
            self.master.rejectClients(self.message, self.sessionkey)

        else:
            self.log.logEvent("ModuleLauncher", 3,
                              "master_client can't have  this endpoint")
            return "url access error"

    def handleClientUser(self):
        if self.splitUrl[2] == "add":
            return self.admin.addUser(self.clientId, self.message,
                                      self.sessionkey)

        elif self.splitUrl[2] == "delete":
            return self.admin.deleteUser(self.clientId, self.message,
                                         self.sessionkey)

        elif self.splitUrl[2] == "save":
            return self.admin.editUser(self.clientId, self.message,
                                       self.sessionkey)

        elif self.splitUrl[2] == "archive":
            return self.admin.archiveUser(self.clientId, self.message,
                                          self.sessionkey)
        elif self.splitUrl[2] == "unarchive":
            return self.admin.unArchiveUser(self.clientId, self.message,
                                            self.sessionkey)

        elif self.splitUrl[2] == "list":
            return self.admin.listClientUser(self.clientId, self.sessionkey)
        elif self.splitUrl[2] == "roles":
            return self.admin.roleList(self.clientId, self.sessionkey)
        elif self.splitUrl[2] == "editlist":
            return self.admin.editList(self.clientId, self.message,
                                       self.sessionkey)

        else:
            self.log.logEvent("ModuleLauncher", 3,
                              "client_user can't have  this endpoint")
            return "wrong url access2"

    def handleProjects(self):
        if self.splitUrl[2] == "list":
            return self.project.listProjects(self.clientId, self.sessionkey)

        elif self.splitUrl[2] == "add":
            return self.project.projectsAdding(self.clientId, self.message,
                                               self.sessionkey)
        elif self.splitUrl[2] == "siteadd":
            return self.project.addSites(self.clientId, self.message,
                                         self.sessionkey)
        elif self.splitUrl[2] == "editList":
            return self.project.editList(self.clientId, self.message,
                                         self.sessionkey)
        elif self.splitUrl[2] == "sitedelete":
            return self.project.deletSites(self.clientId, self.message,
                                           self.sessionkey)
        elif self.splitUrl[2] == "idList":
            return self.project.projectIdList(self.clientId, self.sessionkey)
        else:
            self.log.logEvent("ModuleLauncher", 3,
                              "client_user can't have  this endpoint")
            return "wrong url access2"

    def handleLabourer(self):
        if self.splitUrl[2] == "info":
            return self.labourer.labourerInfo(self.clientId, self.message,
                                              self.sessionkey)
        elif self.splitUrl[2] == "list":
            return self.labourer.labouerList(self.clientId, self.sessionkey)

        elif self.splitUrl[2] == "personalInfo":
            return self.labourer.personalInfo(self.clientId, self.message,
                                              self.sessionkey)

        elif self.splitUrl[2] == "employeeInfo":
            return self.labourer.employeeInfo(self.clientId, self.message,
                                              self.sessionkey)

        elif self.splitUrl[2] == "identityInfo":
            return self.labourer.identityInfo(self.clientId, self.message,
                                              self.sessionkey)

        elif self.splitUrl[2] == "bankInfo":
            return self.labourer.bankInfo(self.clientId, self.message,
                                          self.sessionkey)

        elif self.splitUrl[2] == "save":
            return self.labourer.labourerReg(self.clientId, self.message,
                                             self.sessionkey)

        elif self.splitUrl[2] == "update":
            return self.labourer.editLabourer(self.clientId, self.message,
                                              self.sessionkey)

        elif self.splitUrl[2] == "delete":
            return self.labourer.deleteLabourer(self.clientId, self.message,
                                                self.sessionkey)

        elif self.splitUrl[2] == "attendance":
            return self.labourer.getAttendacePers(self.clientId, self.message,
                                                  self.sessionkey)
        elif self.splitUrl[2] == "class":
            return self.classManage()
        elif self.splitUrl[2] == "addlist":
            return self.labourer.labbourerAddlist(self.clientId,
                                                  self.sessionkey)

        elif self.splitUrl[2] == "shift":
            return self.shiftManage()

        else:
            return "wrong url access"

    def shiftManage(self):
        if self.splitUrl[3] == "add":
            return self.shift.shiftCreation(self.clientId, self.message,
                                            self.sessionkey)

        elif self.splitUrl[3] == "list":
            return self.shift.shiftList(self.clientId, self.sessionkey)

        elif self.splitUrl[3] == "delete":
            return self.shift.shiftDeleted(self.clientId, self.message,
                                           self.sessionkey)
        else:
            return "wrong url acess"

    def classManage(self):
        if self.splitUrl[3] == "list":
            return self.labclass.classList(self.clientId, self.sessionkey)

        elif self.splitUrl[3] == "add":
            return self.labclass.classAdding(self.clientId, self.message,
                                             self.sessionkey)

        elif self.splitUrl[3] == "delete":
            return self.labclass.classDelete(self.clientId, self.message,
                                             self.sessionkey)

        else:
            return "wrong url acess"

    def roleManage(self):
        if self.splitUrl[2] == "add":
            return self.role.createRoles(self.clientId, self.message,
                                         self.sessionkey)
        elif self.splitUrl[2] == "list":
            return self.role.listRoles(self.clientId, self.sessionkey)
        elif self.splitUrl[2] == "update":
            return self.role.editRoles(self.clientId, self.message,
                                       self.sessionkey)
        else:
            return "wrong url acess"

    def handlePaymentDesk(self):
        if self.splitUrl[2] == "apply":
            return self.paymentDesk.advanceApply(self.clientId, self.message,
                                                 self.sessionkey)
        elif self.splitUrl[2] == "applyList":

            return self.paymentDesk.requstList(self.clientId, self.sessionkey)
        elif self.splitUrl[2] == "payList":

            return self.paymentDesk.advancePayList(self.clientId,
                                                   self.sessionkey)

        elif self.splitUrl[2] == "approveCodeList":
            return self.paymentDesk.approvecodeList(self.clientId,
                                                    self.message,
                                                    self.sessionkey)

        elif self.splitUrl[2] == "payment":
            return self.paymentDesk.payProcess(self.clientId, self.message,
                                               self.sessionkey)

        elif self.splitUrl[2] == "status":
            return self.paymentDesk.advanceRespo(self.clientId, self.message,
                                                 self.sessionkey)

        elif self.splitUrl[2] == "approve":
            return self.paymentDesk.requstApprove(self.clientId, self.message,
                                                  self.sessionkey)

        elif self.splitUrl[2] == "reject":
            return self.paymentDesk.requstReject(self.clientId, self.message,
                                                 self.sessionkey)

        else:
            return "wrong url acess"
 def __init__(self):
     self.log = Logger()
     self.dbobj = DatabaseAgent("kunnel", "kunnel", "127.0.0.1",
                                "kunnel123", "5432")
     self.dbobj.initConnection()
示例#17
0
class Admin:
    def __init__(self):
        self.log = Logger()
        self.authen = Authentication()

    def addUser(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        digest = self.authen.signUp(msgDict["password"])
        msgDict["password"] = digest["hashPassword"]
        msgDict["salt"] = digest["salt"]
        print("message", msgDict)
        # admin = Admin()
        nameLs = []
        valueLs = []
        for key, val in msgDict.items():
            nameLs.append(key.lower())
            valueLs.append(val)
        print(nameLs)
        print(valueLs)
        reval = False
        try:
            if not adminDb.fetchData("clientusers", ["username"],
                                     {"username": msgDict["userName"]}):
                if adminDb.pushData("clientusers", nameLs, valueLs):
                    self.log.logEvent(
                        "Admin", 1, msgDict["userName"] +
                        " Client user registerd successfully", clientId,
                        msgDict["userName"])
                    response = {
                        "Header": {
                            "status": "success",
                            "module": "admin"
                        },
                        "Body": {
                            "message": "user added successfully",
                            "data": ""
                        },
                        "Signature": {
                            "signature": "",
                            "Key": ""
                        }
                    }
                    return response
                else:
                    self.log.logEvent(
                        "Admin", 1, msgDict["userName"] +
                        "Client user registerd failed and eception is occured")
                    response = {
                        "Header": {
                            "status": "success",
                            "module": "admin"
                        },
                        "Body": {
                            "message": "user can't added ",
                            "data": ""
                        },
                        "Signature": {
                            "signature": "",
                            "Key": ""
                        }
                    }
                    return response
            else:
                self.log.logEvent(
                    "Admin", 1,
                    msgDict["userName"] + "Client user name alraedy exist",
                    clientId, msgDict["userName"])
                response = {
                    "Header": {
                        "status": "success",
                        "module": "admin"
                    },
                    "Body": {
                        "message": "user name already exixt ",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response

        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc))
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))

    def login(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        fileds = ["username", "password"]
        con = {"clientid": clientId}
        data = masterDb.fetchData("regusers", fileds, con)
        print("........................", data)
        datalis = [clientId, clientId, data[0][1], 5432]
        print("...datalis...........", datalis)
        adminDb = DatabaseAgent(clientId, clientId, conf.host, data[0][1],
                                5432)
        adminDb.initConnection()
        try:
            statusFlag = masterDb.fetchData("regusers", ["status"],
                                            {"clientid": clientId})
            if statusFlag[0][0] == "approved":
                #####################################################################
                filedLs = ["password", "salt", "employeeid", "userrole"]
                if self.authen.login(msgDict, "clientusers", filedLs, datalis,
                                     sessionkey):
                    adminDb = DatabaseAgent(clientId, clientId, conf.host,
                                            data[0][1], 5432)
                    adminDb.initConnection()
                    userid = adminDb.fetchData(
                        "clientusers", ["employeeid"],
                        {"username": msgDict["userName"]})
                    archiveflag = adminDb.fetchData(
                        "clientusers", ["archive"],
                        {"username": msgDict["userName"]})
                    print("boolean value", archiveflag)
                    if archiveflag:
                        self.log.logEvent("Admin", 3,
                                          "user logined suceessfully",
                                          clientId, msgDict["userName"])
                        response = {
                            "Header": {
                                "status": "success",
                                "module": "admin"
                            },
                            "Body": {
                                "message": "user login successfully",
                                "data": userid
                            },
                            "Signature": {
                                "signature": "",
                                "Key": ""
                            }
                        }
                        return response
                    else:
                        self.log.logEvent(
                            "Admin", 3,
                            "your archived please connact to the admin",
                            clientId, msgDict["userName"])
                        response = {
                            "Header": {
                                "status": "fail",
                                "module": "admin"
                            },
                            "Body": {
                                "message":
                                "your archived please connact to the admin",
                                "data": ""
                            },
                            "Signature": {
                                "signature": "",
                                "Key": ""
                            }
                        }
                        return response
                else:
                    self.log.logEvent("Admin", 3, "user logined error",
                                      clientId, msgDict["userName"])
                    response = {
                        "Header": {
                            "status": "fail",
                            "module": "admin"
                        },
                        "Body": {
                            "message": "wrong username or password",
                            "data": ""
                        },
                        "Signature": {
                            "signature": "",
                            "Key": ""
                        }
                    }
                    return response

            elif statusFlag[0][0] == "rejected":
                self.log.logEvent("Admin", 3, "comapny is rejected", clientId,
                                  msgDict["userName"])
                response = {
                    "Header": {
                        "status": "fail",
                        "module": "admin"
                    },
                    "Body": {
                        "message": "your comapny is rejected",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response

            else:
                self.log.logEvent("Admin", 3, "comapny has not been approved",
                                  clientId, msgDict["userName"])
                response = {
                    "Header": {
                        "status": "fail",
                        "module": "admin"
                    },
                    "Body": {
                        "message": "your comapny has not been approved",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response

        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId, msgDict["userName"])
            # self.syslog.eventHandle("admin","exception","exception on admin module"+str(expc))

    def editUser(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        condition = {"employeeid": msgDict["employeeId"]}
        changDist = {}

        for key in msgDict:
            if key == "emplyeeId":
                continue
            else:
                changDist[key.lower()] = (msgDict[key])
        try:

            if adminDb.editData("clientusers", changDist, condition):
                self.log.logEvent(
                    "Admin", 2,
                    msgDict["employeeId"] + "user edited successfully",
                    clientId, sessionMange.session[sessionkey]["userid"])
                # datalis = ["fullname","employeeid","designation","emailid","userrole",'archive']
                # adminDb.fetchData("clients",datalis)
                response = {
                    "Header": {
                        "status": "success",
                        "module": "admin"
                    },
                    "Body": {
                        "message": "user deatils edited successfully",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response

            else:
                self.log.logEvent("Admin", 2, "user cant edited", clientId,
                                  sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "success",
                        "module": "admin"
                    },
                    "Body": {
                        "message": "user deatils can't edited ",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))

    def deleteUser(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        delete = " set delete = 'True' where "
        datdict = {"employeeid": msgDict["employeeId"]}
        try:
            if msgDict["employeeId"] == "kcemp1001":
                response = {
                    "Header": {
                        "status": "success",
                        "module": "admin"
                    },
                    "Body": {
                        "message": "admin can't be delete",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
            else:
                if adminDb.updateTable(delete, "clientusers", datdict):
                    self.log.logEvent(
                        "Admin", 2, msgDict["employeeId"] +
                        "Client user deletd successfully", clientId,
                        sessionMange.session[sessionkey]["userid"])
                    response = {
                        "Header": {
                            "status": "success",
                            "module": "admin"
                        },
                        "Body": {
                            "message": "user delete successfully",
                            "data": ""
                        },
                        "Signature": {
                            "signature": "",
                            "Key": ""
                        }
                    }
                    return response  #self.listClientUser()
                else:
                    self.log.logEvent(
                        "Admin", 2,
                        msgDict["employeeId"] + "Client can't user deleted ",
                        clientId, sessionMange.session[sessionkey]["userid"])
                    response = {
                        "Header": {
                            "status": "success",
                            "module": "admin"
                        },
                        "Body": {
                            "message": "user can't delete",
                            "data": ""
                        },
                        "Signature": {
                            "signature": "",
                            "Key": ""
                        }
                    }
                    return response
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))

    def archiveUser(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        archive = " set archive = 'True' where "
        admin = Admin()
        datdict = {"employeeid": msgDict["employeeId"]}
        try:
            if msgDict["employeeId"] == "kcemp1001":
                response = {
                    "Header": {
                        "status": "success",
                        "module": "admin"
                    },
                    "Body": {
                        "message": "admin can't be archived",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
            else:
                if adminDb.updateTable(archive, "clientusers", datdict):
                    self.log.logEvent(
                        "Admin", 2,
                        msgDict["employeeId"] + "Client archived successfully",
                        clientId, sessionMange.session[sessionkey]["userid"])
                    response = {
                        "Header": {
                            "status": "success",
                            "module": "admin"
                        },
                        "Body": {
                            "message": "user archived successfully",
                            "data": ""
                        },
                        "Signature": {
                            "signature": "",
                            "Key": ""
                        }
                    }
                    return response

                else:
                    self.log.logEvent(
                        "Admin", 2,
                        msgDict["employeeId"] + "Client canot archived",
                        clientId, sessionMange.session[sessionkey]["userid"])
                    response = {
                        "Header": {
                            "status": "fail",
                            "module": "admin"
                        },
                        "Body": {
                            "message": "user can't archived ",
                            "data": ""
                        },
                        "Signature": {
                            "signature": "",
                            "Key": ""
                        }
                    }
                    return response
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId, msgDict["employeeId"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc)

    def unArchiveUser(
        self,
        clientId,
        msgDict,
    ):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        archive = " set archive = 'False' where "
        admin = Admin()
        datdict = {"employeeid": msgDict["employeeId"]}
        try:
            if adminDb.updateTable(archive, "clientusers", datdict):
                self.log.logEvent(
                    "Admin", 2,
                    msgDict["employeeId"] + "Client archived successfully",
                    clientId, sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "success",
                        "module": "admin"
                    },
                    "Body": {
                        "message": "user unarchived successfully",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
            else:
                self.log.logEvent(
                    "Admin", 2,
                    msgDict["employeeId"] + "Client canot archived", clientId,
                    sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "fail",
                        "module": "admin"
                    },
                    "Body": {
                        "message": "user can't unarchived ",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))

    def editList(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        condition = {"employeeid": msgDict["employeeId"]}
        datalis = [
            "fullname", "employeeid", "designation", "emailid", "userrole",
            'archive'
        ]
        cliList = adminDb.fetchData("clientusers", datalis, condition)
        infolist = []
        try:
            for info in cliList:
                for tup in info:
                    infolist.append(tup)
            role = adminDb.fetchData("permission", ["rolename", "roleid"])
            infolist.append(role)
            self.log.logEvent("Admin", 2,
                              "edit button wanted listed successfully",
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            response = {
                "Header": {
                    "status": "success",
                    "module": "admin"
                },
                "Body": {
                    "message": "user edit list",
                    "data": infolist
                },
                "Signature": {
                    "signature": "",
                    "Key": ""
                }
            }
            return response
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))

    def roleList(self, clientId, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        self.log.logEvent("Admin", 2,
                          "total permission list listed successfully",
                          clientId, sessionMange.session[sessionkey]["userid"])
        try:
            responseData = adminDb.fetchData("permission",
                                             ["rolename", "roleid"])
            response = {
                "Header": {
                    "status": "success",
                    "module": "admin"
                },
                "Body": {
                    "message": "user role list",
                    "data": responseData
                },
                "Signature": {
                    "signature": "",
                    "Key": ""
                }
            }
            return response
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))

    def listClientUser(self, clientId, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        print(".................", dbData)
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        datalis = [
            "fullname", "employeeid", "designation", "userrole", 'archive'
        ]
        self.log.logEvent("Admin", 0, "Client user listed successfully",
                          clientId, sessionMange.session[sessionkey]["userid"])
        try:
            responseData = adminDb.fetchData("clientusers", datalis)
            print("dbdata is................................", responseData)
            response = {
                "Header": {
                    "status": "success",
                    "module": "admin"
                },
                "Body": {
                    "message": "user list",
                    "data": responseData
                },
                "Signature": {
                    "signature": "",
                    "Key": ""
                }
            }
            return response
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))

    def userProfile(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        dbCompanyname = masterDb.fetchData("regusers", ["companyname"], cond)
        print(".................", dbData)
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        conditions = {"employeeid": msgDict["employeeId"]}
        detail = ["fullname", "employeeid", "userrole", "designation"]
        self.log.logEvent("Admin", 0, "user profile showed", clientId,
                          msgDict["employeeId"])
        try:
            responseData = adminDb.fetchData("clientusers", detail, conditions)
            print("response data", responseData)
            responseData.append(dbCompanyname[0][0])
            response = {
                "Header": {
                    "status": "success",
                    "module": "admin"
                },
                "Body": {
                    "message": "user profile",
                    "data": responseData
                },
                "Signature": {
                    "signature": "",
                    "Key": ""
                }
            }
            return response
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))

######################################################companyprofile#######################################################

    def companyProfile(self, clientId, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        try:
            compnydata = self.fetchCompanySummary(adminDb)

            projectsColl = self.fetchProjectsSummary(adminDb)

            finalList = []
            finalList.append(list(compnydata))
            finalList.append(list(projectsColl))
            self.log.logEvent("Admin", 2, "Company pofile sended successfully",
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            print("final list is...", finalList)
            response = {
                "Header": {
                    "status": "success",
                    "module": "admin"
                },
                "Body": {
                    "message": "companyprile",
                    "data": finalList
                },
                "Signature": {
                    "signature": "",
                    "Key": ""
                }
            }
            return response
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))

    def fetchCompanySummary(self, dbAgent):
        condition = {"userrole": "Admin"}
        dataList = ["fullname", "employeeid", "designation", "companyname"]
        try:
            return dbAgent.fetchData("clientusers", dataList, condition)
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))

    def fetchProjectsSummary(self, dbAgent):
        projCollection = []
        projectData = dbAgent.fetchData("projects",
                                        ["Projectname", "projectid"])
        # print("\n\n\n")
        try:
            for i in range(len(projectData)):
                cond = {"projectid": projectData[i][1]}
                curSite = dbAgent.fetchData("sites", ["sitenames"], cond)
                lCount = dbAgent.fetchData("sites", ["numOfLabourer"], cond)
                # print("\n\n\nSites:::::::::::: ", curSite)
                # print("\nSites:::::::::::::: ", curSite[0])
                # print("\nSites:::::::::::::: ", curSite[0][0])
                projectSummary = [[], []]

                for j in range(len(curSite)):
                    # print ("\n\n\n\nJ:::::::    ", j)
                    sitesList = curSite[j][0]
                    labourerList = lCount[j][0]
                    projectSummary[-1].append(sitesList)
                    projectSummary[-2].append(labourerList)

                projectSummary.insert(0, projectData[i][0])
                projCollection.append(projectSummary)
                #del labourerList[:]
                #del sitesList[:]
                # print("Project Summary:::::::::::::::::::::::::::::::: ", projectSummary)
                # print("sites..........  ",sitesList)
                # print("lab........................  ",labourerList)
                # print("\n\n\n")

            print("PROJECTS CONTAINER:::::::::::::::::::::::::: ",
                  projCollection)

            return projCollection
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))


#################################################################permissions#########################################

##################################################################attendance############################################################################

######################################################################company management################################################

# try:
#     reval

# except Exception as expc:
#     print("oocured exception is",expc)

# admin = Admin()
# print("companyprofile.....",admin.companyProfile("kec119","karthiban"))

# # print(admin.classList("sessionkey"))
# # # print("....................",admin.labbourerAddlist("karthiban"))
# # admin.roleList("sessionkey")
# # print("list is..........",admin.listRoles("sessionkey"))
# # print("datasss.....................................",admin.listRoles())

# # sessions["xyzabcd"] = ["karthiban","karthi007"]

# # # admin.adminRegister({"userName":"******","fullName":"karthibanvediraj","emailId":"*****@*****.**","companyName":"admin","employId":"k1551","designation":"softwaredeveloper","password":"******"})
# # admin.createRoles()
# # ###################labourer reg###################################
# # data = {"labourername":"spartan","callbyname":"spartan","gender":"male","dateofbirth":"07/07/1997","fathername":"spartan","bloodgroup":"a1+","nextofkin":"ben","contactnumberofnextofkin":"155525145522","mothertounge":"tamil","addressline1":"address","addressline2":"somthing2","addressline3":"somthing","village":"newyear","state":"newyark","country":"usa","pincode":"600000" ,"mobilenumber":"666575454654656","residancephonenumber":"456518555472320","emergencyphonenumber":"45545554360","dateofjoining":"09/04/1993" ,"migrantworker":"yes" ,"siteid":"usa" ,"siteofjoining":"05/03/2019","designation":"admin","labourerclass":"best","wageclass":"good","documenttype":"adhar","documentnumber":"2585685758120","nameasperdoc":"spartan","bankname":"national","ifsccode":"55365845435520","backaccountnumber":"546546544420","brancname":"usa","nameinbank":"indian"}
# # print("datais",admin.labourerReg(data))
# ###############################################labourerlist########################################
# #print("list labourer",admin.labourerInfo())
# ######################labourer change##############################################################
# # data = {"labourerId":""}
# shift = {"shiftstart":"12:00","shiftend":"07:00","break1start":"00:00","break1end":"04:00","lunchbreakstart":"03:00","lunchbreakend":"00:00","break2start":"00:00","break2end":"04:00"}
# # admin.labourerChange()
# admin.shiftCreation(shift,"sessionkey")
# #print("list of shift",admin.shiftList())
# # shiftedit = {"shiftId":"shift1001","lunchstart":"07:00"}
# # print("list of shift",admin.shiftEdit(shiftedit))
# # shiftdelete = {"shiftId":"shift1003"}
# # print("list of shift",admin.shiftDeleted(shiftdelete))
# # print("company profile page",admin.shiftAssingn(shiftdelete))
# # print("njnkjnbkjbkjbkj",admin.companyProfile())
# #