Beispiel #1
0
    def updateServiceInformation(self, sid, service, uid):
        """
        Update the information about a service.
        Parameters:

        :param sid: Service ID.
        :type sid: int
        :param service: Dictionary with the service information to update.
        :type service: string
        :param uid: User ID of the caller of this function.
        :type uid: int
        :return Tuple: SQL result of Query as a tuple.
        """
        cursor = self.conn.cursor()
        try:
            fields_list = self.serviceInfoArgs(service)
            audit = AuditDAO()
            tablename = "services"
            pkey = "sid"
            oldValue = audit.getTableValueByIntID(table=tablename,
                                                  pkeyname=pkey,
                                                  pkeyval=sid,
                                                  cursor=cursor)

            query = sql.SQL("update {table1} set {fields}  "
                            "where  {pkey1} = %s AND isdeleted=false  "
                            "returning {pkey1}  ").format(
                                table1=sql.Identifier('services'),
                                fields=sql.SQL(",").join(
                                    map(sql.SQL, fields_list)),
                                pkey1=sql.Identifier('sid'))
            cursor.execute(query, (int(sid), ))
            result = cursor.fetchone()
            newValue = audit.getTableValueByIntID(table=tablename,
                                                  pkeyname=pkey,
                                                  pkeyval=sid,
                                                  cursor=cursor)
            audit.insertAuditEntry(changedTable=tablename,
                                   changeType=audit.UPDATEVALUE,
                                   oldValue=oldValue,
                                   newValue=newValue,
                                   uid=uid,
                                   cursor=cursor)
            self.conn.commit()
            return result

        except errors.UniqueViolation as badkey:
            return jsonify(
                Error=
                "anonther service is using the same name, within the same room"
            ), 403

        except errors.TypeError as badkey:
            return jsonify(Error="Sid problem")
Beispiel #2
0
    def setEventStatus(self, eid, estatus, uid):
        """
        Sets the estatus for a given event.

        Uses :func:`~app.DAOs.AuditDAO.AuditDAO.getTableValueByPkeyPair` &
        :func:`~app.DAOs.AuditDAO.AuditDAO.insertAuditEntry`

        :param eid: Event ID
        :type eid: int
        :param estatus: indicates the event's status.
        :type estatus: str
        :param uid: User ID
        :type uid: int
        :return List[Tuple]: SQL result of Query as a tuple.
        """
        cursor = self.conn.cursor()
        audit = AuditDAO()
        tablename = "events"
        pkey = "eid"
        oldValue = audit.getTableValueByIntID(table=tablename,
                                              pkeyname=pkey,
                                              pkeyval=eid,
                                              cursor=cursor)
        query = sql.SQL("update {table1} "
                        "set {ukey1} = %s,"
                        "estatusdate = CURRENT_TIMESTAMP  "
                        "where {pkey1}= %s "
                        "returning {pkey1}").format(
                            table1=sql.Identifier('events'),
                            ukey1=sql.Identifier('estatus'),
                            pkey1=sql.Identifier('eid'))
        try:
            cursor.execute(query, (str(estatus), int(eid)))
            result = cursor.fetchone()

            newValue = audit.getTableValueByIntID(table=tablename,
                                                  pkeyname=pkey,
                                                  pkeyval=eid,
                                                  cursor=cursor)
            audit.insertAuditEntry(changedTable=tablename,
                                   changeType=audit.UPDATEVALUE,
                                   oldValue=oldValue,
                                   newValue=newValue,
                                   uid=uid,
                                   cursor=cursor)
            self.conn.commit()
            self.conn.close()
        except errors.ForeignKeyViolation as e:
            self.conn.close()
            return ValueError("Invalid values: eid=" + str(eid))
        except ValueError as e:
            self.conn.close()
            return e
        return result
    def removeWebsitesGivenServiceID(self, wid, sid, uid):
        """
        Remove an entry from a website services table
        Uses :func:`~app.DAOs.AuditDAO.AuditDAO.getTableValueByPkeyPair` &
        :func:`~app.DAOs.AuditDAO.AuditDAO.insertAuditEntry`

        :param sid: The Service ID
        :type sid: int
        :param wid: The website ID
        :type wid: int
        :param uid: The user id of the route caller 
        :type uid: int
        :return Tuple: SQL result of Query as a tuple.
        """
        cursor = self.conn.cursor()
        audit = AuditDAO()
        tablename = 'servicewebsites'
        pkeys = ["sid", "wid"]
        oldValue = audit.getTableValueByPkeyPair(table=tablename,
                                                 pkeyname1=pkeys[0],
                                                 pkeyname2=pkeys[1],
                                                 pkeyval1=sid,
                                                 pkeyval2=wid,
                                                 cursor=cursor)
        query = sql.SQL(
            "update {table1} set isdeleted = True  "
            "where ( {pkey1} = %s AND {pkey2} = %s ) "
            "returning {pkey1} ,sid,isdeleted,wdescription ").format(
                table1=sql.Identifier('servicewebsites'),
                pkey1=sql.Identifier('wid'),
                pkey2=sql.Identifier('sid'))
        try:
            cursor.execute(query, (int(wid), int(sid)))
            result = cursor.fetchone()
            newValue = audit.getTableValueByPkeyPair(table=tablename,
                                                     pkeyname1=pkeys[0],
                                                     pkeyname2=pkeys[1],
                                                     pkeyval1=sid,
                                                     pkeyval2=wid,
                                                     cursor=cursor)
            if oldValue and newValue:
                audit.insertAuditEntry(changedTable=tablename,
                                       changeType=audit.UPDATEVALUE,
                                       oldValue=oldValue,
                                       newValue=newValue,
                                       uid=uid,
                                       cursor=cursor)
            self.conn.commit()
        except errors.ForeignKeyViolation as e:
            result = e
        if result is None:
            return None
        return result[0]
    def addWebsitesToEvent(self, eid, wid, wdescription, cursor, uid):
        """
        Create a new entry for a website events table.
        Uses :func:`~app.DAOs.AuditDAO.AuditDAO.getTableValueByPkeyPair` &
        :func:`~app.DAOs.AuditDAO.AuditDAO.insertAuditEntry`

        :param eid: The Event ID
        :type eid: int
        :param wid: The website ID
        :type wid: int
        :param wdescription: Description for  the website 
        :type wdescription: string
        :param uid: The user id of the route caller 
        :type uid: int
        :param cursor: Method call connection cursor to database.
        :type sname: connection cursor
        :return Tuple: SQL result of Query as a tuple.
        """
        cursor = cursor
        audit = AuditDAO()
        tablename = 'eventwebsites'
        pkeys = ["eid", "wid"]
        oldValue = audit.getTableValueByPkeyPair(table=tablename,
                                                 pkeyname1=pkeys[0],
                                                 pkeyname2=pkeys[1],
                                                 pkeyval1=eid,
                                                 pkeyval2=wid,
                                                 cursor=cursor)
        query = sql.SQL("insert into {table1} "
                        "({insert_fields}) "
                        "values (%s, %s, %s);").format(
                            table1=sql.Identifier('eventwebsites'),
                            insert_fields=sql.SQL(',').join([
                                sql.Identifier('eid'),
                                sql.Identifier('wid'),
                                sql.Identifier('wdescription')
                            ]))
        cursor.execute(query, (int(eid), int(wid), wdescription))
        newValue = audit.getTableValueByPkeyPair(table=tablename,
                                                 pkeyname1=pkeys[0],
                                                 pkeyname2=pkeys[1],
                                                 pkeyval1=eid,
                                                 pkeyval2=wid,
                                                 cursor=cursor)
        audit.insertAuditEntry(changedTable=tablename,
                               changeType=audit.INSERTVALUE,
                               oldValue=oldValue,
                               newValue=newValue,
                               uid=uid,
                               cursor=cursor)
        return
    def addWebsite(self, url, cursor, uid):
        """
        Create a new entry for a website
        Uses :func:`~app.DAOs.AuditDAO.AuditDAO.getTableValueByIntID` &
        :func:`~app.DAOs.AuditDAO.AuditDAO.insertAuditEntry`

        :param url: The website link
        :type url: string
        :param uid: The user id of the route caller 
        :type uid: int
        :param cursor: addWebsite method call connection cursor to database.
        :type sname: connection cursor
        :return Tuple: SQL result of Query as a tuple.
        """
        temp = url
        url = Find(url)
        cursor = cursor
        if (url is not None) and (url != "") and len(url) > 0:
            audit = AuditDAO()
            tablename = "websites"
            pkey = "url"
            oldValue = audit.getTableValueByIntID(table=tablename,
                                                  pkeyname=pkey,
                                                  pkeyval=temp,
                                                  cursor=cursor)

            query = sql.SQL("insert into {table1} "
                            "({insert_fields}) "
                            "values (%s) "
                            "on CONFLICT (url) do update "
                            "set url=%s "
                            "returning wid, url").format(
                                table1=sql.Identifier('websites'),
                                insert_fields=sql.SQL(',').join(
                                    [sql.Identifier('url')]))
            cursor.execute(query, (temp, temp))
            result = cursor.fetchone()

            newValue = audit.getTableValueByIntID(table=tablename,
                                                  pkeyname=pkey,
                                                  pkeyval=temp,
                                                  cursor=cursor)
            audit.insertAuditEntry(changedTable=tablename,
                                   changeType=audit.INSERTVALUE,
                                   oldValue=oldValue,
                                   newValue=newValue,
                                   uid=uid,
                                   cursor=cursor)
            return result
        else:
            raise ValueError("URL not valid: " + str(temp))
    def createWebsite(self, url, uid):
        """
        Create a new entry for service websites.
        CURRENTLY DOES NOT COMMIT ANYTHING.

        :param url: The website link
        :type url: string
        :param uid: The user id of the route caller 
        :type uid: int
        :return Tuple: SQL result of Query as a tuple.
        """
        try:
            if url is not None and url != "":
                cursor = self.conn.cursor()

                audit = AuditDAO()
                tablename = "websites"
                pkey = "url"
                oldValue = audit.getTableValueByIntID(table=tablename,
                                                      pkeyname=pkey,
                                                      pkeyval=url,
                                                      cursor=cursor)

                query = sql.SQL("insert into {table1} "
                                "({insert_fields}) "
                                "values (%s) "
                                "on CONFLICT (url) do update "
                                "set url=%s "
                                "returning wid ").format(
                                    table1=sql.Identifier('websites'),
                                    insert_fields=sql.SQL(',').join([
                                        sql.Identifier('url'),
                                    ]))
                cursor.execute(query, (url, url))
                result = cursor.fetchone()
                newValue = audit.getTableValueByIntID(table=tablename,
                                                      pkeyname=pkey,
                                                      pkeyval=url,
                                                      cursor=cursor)
                audit.insertAuditEntry(changedTable=tablename,
                                       changeType=audit.INSERTVALUE,
                                       oldValue=oldValue,
                                       newValue=newValue,
                                       uid=uid,
                                       cursor=cursor)
                return result
            else:
                result = [None, None]
        except:
            result = [None, None]
            return result
Beispiel #7
0
    def changeRoomCoordinates(self, rid, roomKeys, uid):
        """
        Change the Room coordinates given a room ID

        :param rid: The Id of the room to update coordinates for
        :type rid: int
        :param roomKeys: The Json object containing the Coordinates to update
        :type roomKeys: list
        :return Tuple: SQL result of Query as a tuple.
        """
        cursor = self.conn.cursor()
        fields_list = self.roomInfoArgs(roomKeys=roomKeys)

        audit = AuditDAO()
        tablename = "rooms"
        pkey = "rid"
        oldValue = audit.getTableValueByIntID(table=tablename,
                                              pkeyname=pkey,
                                              pkeyval=rid,
                                              cursor=cursor)

        query = sql.SQL(
            "update {table1} set {fields}  "
            "where  {pkey1} = %s  "
            "returning rid,rcode,rfloor,rlongitude,rlatitude,raltitude "
        ).format(table1=sql.Identifier('rooms'),
                 fields=sql.SQL(",").join(map(sql.SQL, fields_list)),
                 pkey1=sql.Identifier('rid'))
        cursor.execute(query, (int(rid), ))
        result = cursor.fetchone()

        newValue = audit.getTableValueByIntID(table=tablename,
                                              pkeyname=pkey,
                                              pkeyval=rid,
                                              cursor=cursor)
        audit.insertAuditEntry(changedTable=tablename,
                               changeType=audit.UPDATEVALUE,
                               oldValue=oldValue,
                               newValue=newValue,
                               uid=uid,
                               cursor=cursor)
        self.conn.commit()

        if result is None:
            return None
        else:
            return result
Beispiel #8
0
    def insertPhoto(self, photourl, uid, cursor):
        """
        Attempt to insert a photo's url into the photos table; Does nothing if
        the photourl is either None or and empty string. DOES NOT COMMIT CHANGES.

        :param photourl: a non-empty string or None
        :type photourl: str
        :param cursor: createEvent method call connection cursor to database.
        :type cursor: psycopg2 cursor object
        :return Tuple: the photoID of the photo in the Photos table, as an SQL result
        """
        if photourl is not None and photourl != "" and not photourl.isspace():
            cursor = cursor
            audit = AuditDAO()
            tablename = "photos"
            pkey = "photourl"
            oldValue = audit.getTableValueByIntID(table=tablename,
                                                  pkeyname=pkey,
                                                  pkeyval=photourl,
                                                  cursor=cursor)

            query = sql.SQL("insert into {table1} "
                            "({insert_field})"
                            "values (%s) on conflict(photourl) "
                            "do update set photourl=%s"
                            "returning {pkey1}").format(
                                table1=sql.Identifier('photos'),
                                insert_field=sql.Identifier('photourl'),
                                pkey1=sql.Identifier('photoid'))
            cursor.execute(query, (str(photourl), str(photourl)))
            result = cursor.fetchone()
            newValue = audit.getTableValueByIntID(table=tablename,
                                                  pkeyname=pkey,
                                                  pkeyval=photourl,
                                                  cursor=cursor)
            audit.insertAuditEntry(changedTable=tablename,
                                   changeType=audit.INSERTVALUE,
                                   oldValue=oldValue,
                                   newValue=newValue,
                                   uid=uid,
                                   cursor=cursor)
        else:
            result = [None, None]
        return result
Beispiel #9
0
    def deleteService(self, sid, uid):
        """
        Remove a service from the database,given a service ID.
        Uses :func:`~app.DAOs.AuditDAO.AuditDAO.getTableValueByIntID` &
        :func:`~app.DAOs.AuditDAO.AuditDAO.insertAuditEntry`

        :param sid: Service ID
        :type sid: int
        :param uid: User ID
        :type uid: int
        :return Tuple: SQL result of Query as a tuple.
        """
        cursor = self.conn.cursor()

        audit = AuditDAO()
        tablename = "services"
        pkey = "sid"
        oldValue = audit.getTableValueByIntID(table=tablename,
                                              pkeyname=pkey,
                                              pkeyval=sid,
                                              cursor=cursor)

        query = sql.SQL(
            "update {table1} set isdeleted = true  "
            "where  {pkey1} = %s "
            "returning sid,rid,sname,sdescription,sschedule  ").format(
                table1=sql.Identifier('services'), pkey1=sql.Identifier('sid'))
        cursor.execute(query, (int(sid), ))
        result = cursor.fetchone()

        newValue = audit.getTableValueByIntID(table=tablename,
                                              pkeyname=pkey,
                                              pkeyval=sid,
                                              cursor=cursor)
        audit.insertAuditEntry(changedTable=tablename,
                               changeType=audit.UPDATEVALUE,
                               oldValue=oldValue,
                               newValue=newValue,
                               uid=uid,
                               cursor=cursor)
        self.conn.commit()
        if result is None:
            return None
        return result
Beispiel #10
0
    def changeRole(self, id, uid, roleid):
        """
        Query database to update roleid value in a row that matches a given uid

        :param id: user id of who is making the change, for log purposes and to check if the user can make the change
        :param uid: The Id of the user to change roles
        :param roleid: The new role to give to the user
        :return Tuple: SQL result of Query as tuple.
        """
        cursor = self.conn.cursor()
        audit = AuditDAO()
        tablename = "users"
        pkey = "uid"
        oldValue = audit.getTableValueByIntID(table=tablename,
                                              pkeyname=pkey,
                                              pkeyval=uid,
                                              cursor=cursor)
        query = sql.SQL(
            "update {table} "
            "SET  {issuer} = %s , {newRole} = %s  "
            "WHERE {user}= %s "
            "returning  uid,email, display_name,roleid,type ").format(
                table=sql.Identifier('users'),
                issuer=sql.Identifier('roleissuer'),
                newRole=sql.Identifier('roleid'),
                user=sql.Identifier('uid'))
        try:
            cursor.execute(query, (id, roleid, uid))
            result = cursor.fetchone()
            newValue = audit.getTableValueByIntID(table=tablename,
                                                  pkeyname=pkey,
                                                  pkeyval=uid,
                                                  cursor=cursor)
            audit.insertAuditEntry(changedTable=tablename,
                                   changeType=audit.UPDATEVALUE,
                                   oldValue=oldValue,
                                   newValue=newValue,
                                   uid=id,
                                   cursor=cursor)
            self.conn.commit()
        except errors.ForeignKeyViolation as e:
            result = e
        return result
Beispiel #11
0
    def addWebsitesToService(self, sid, wid, wdescription, cursor, uid):
        """
        Create a new entry for a website services table.
        Uses :func:`~app.DAOs.AuditDAO.AuditDAO.getTableValueByPkeyPair` &
        :func:`~app.DAOs.AuditDAO.AuditDAO.insertAuditEntry`

        :param sid: The Service ID
        :type sid: int
        :param wid: The website ID
        :type wid: int
        :param wdescription: Description for  the website 
        :type wdescription: string
        :param cursor: Method call connection cursor to database.
        :type cursor: connection cursor
        :param uid: User ID
        :type uid: int
        :return Tuple: SQL result of Query as a tuple.
        """

        cursor = cursor
        audit = AuditDAO()
        tablename = 'servicewebsites'
        pkeys = ["sid", "wid"]
        oldValue = audit.getTableValueByPkeyPair(table=tablename,
                                                 pkeyname1=pkeys[0],
                                                 pkeyname2=pkeys[1],
                                                 pkeyval1=sid,
                                                 pkeyval2=wid,
                                                 cursor=cursor)

        query = sql.SQL("insert into {table1} "
                        "({insert_fields}) "
                        "values (%s, %s,%s,%s) "
                        "on CONFLICT (wid,sid) do update set isdeleted = %s "
                        "returning wid, sid, isdeleted, wdescription").format(
                            table1=sql.Identifier('servicewebsites'),
                            insert_fields=sql.SQL(',').join([
                                sql.Identifier('sid'),
                                sql.Identifier('wid'),
                                sql.Identifier('wdescription'),
                                sql.Identifier('isdeleted')
                            ]))

        try:
            cursor.execute(
                query, (int(sid), str(wid), str(wdescription), False, False))
            result = cursor.fetchone()
            newValue = audit.getTableValueByPkeyPair(table=tablename,
                                                     pkeyname1=pkeys[0],
                                                     pkeyname2=pkeys[1],
                                                     pkeyval1=sid,
                                                     pkeyval2=wid,
                                                     cursor=cursor)
            audit.insertAuditEntry(changedTable=tablename,
                                   changeType=audit.INSERTVALUE,
                                   oldValue=oldValue,
                                   newValue=newValue,
                                   uid=uid,
                                   cursor=cursor)
            return result
        except:
            return None
Beispiel #12
0
    def createService(self, uid, rid, sname, sdescription, sschedule, websites,
                      numbers):
        """
        Creates a new service and adds websites and phones to it.
        Uses :func:`~app.DAOs.AuditDAO.AuditDAO.getTableValueByIntID` &
        :func:`~app.DAOs.AuditDAO.AuditDAO.insertAuditEntry`

        :param uid: The user ID for the creator of the service
        :type uid: int
        :param rid: The ID for the room that would provide the service
        :type rid: int
        :param sname: The name of the service
        :type sname: string
        :param sdescription: A description of the service
        :type sdescription: string 
        :param sschedule: The service's schedule
        :type sschedule: string 
        :param websites: Websites to be asociated with the service
        :type websites: array
        :param numbers: Phone numbers to be added to the service
        :type numbers: array
        :return: results from :func:`~app.DAOs.ServiceDAO.ServiceDAO.getServiceByID` used with
            the new service's sid.
        """
        cursor = self.conn.cursor()

        # Build the query to create an event entry.
        try:
            audit = AuditDAO()
            tablename = "services"
            pkeys = ["rid", "sname"]
            oldValue = audit.getTableValueByPkeyPair(table=tablename,
                                                     pkeyname1=pkeys[0],
                                                     pkeyname2=pkeys[1],
                                                     pkeyval1=rid,
                                                     pkeyval2=sname,
                                                     cursor=cursor)

            query = sql.SQL(
                "insert into {table1} ({insert_fields})"
                "values (%s, %s, %s, %s, %s) "
                "ON CONFLICT (rid,sname) "
                "do update set sdescription=%s, sschedule=%s, isdeleted=false "
                "where services.isdeleted = true "
                "returning {keys} ").format(table1=sql.Identifier('services'),
                                            insert_fields=sql.SQL(',').join([
                                                sql.Identifier('rid'),
                                                sql.Identifier('sname'),
                                                sql.Identifier('sdescription'),
                                                sql.Identifier('sschedule'),
                                                sql.Identifier('isdeleted'),
                                            ]),
                                            keys=sql.SQL(',').join([
                                                sql.Identifier('sid'),
                                                sql.Identifier('rid'),
                                                sql.Identifier('sname'),
                                                sql.Identifier('sdescription'),
                                                sql.Identifier('sschedule'),
                                                sql.Identifier('isdeleted'),
                                            ]))
            cursor.execute(
                query,
                (int(rid), str(sname), str(sdescription), str(sschedule),
                 False, str(sdescription), str(sschedule)))

            result = cursor.fetchone()

            try:
                sid = result[0]
            except:
                return jsonify(Error='Room with service already exists '), 401

            newValue = audit.getTableValueByPkeyPair(table=tablename,
                                                     pkeyname1=pkeys[0],
                                                     pkeyname2=pkeys[1],
                                                     pkeyval1=rid,
                                                     pkeyval2=sname,
                                                     cursor=cursor)
            if not oldValue:
                changeType = audit.INSERTVALUE
            else:
                changeType = audit.UPDATEVALUE

            audit.insertAuditEntry(changedTable=tablename,
                                   changeType=changeType,
                                   oldValue=oldValue,
                                   newValue=newValue,
                                   uid=uid,
                                   cursor=cursor)

            for site in websites:
                website = (WebsiteDAO.addWebsite(self,
                                                 url=site['url'],
                                                 cursor=cursor,
                                                 uid=uid))
                if website is None:

                    return jsonify(Error='Website problem ' + site['url'] +
                                   " Not valid"), 400
                else:
                    WebsiteDAO().addWebsitesToService(
                        sid=sid,
                        wid=website[0],
                        wdescription=site['wdescription'],
                        cursor=cursor,
                        uid=uid)

            for num in numbers:
                phone = PhoneDAO.addPhone(self,
                                          pnumber=num['pnumber'],
                                          ptype=num['ptype'],
                                          cursor=cursor,
                                          uid=uid)

                PhoneDAO().addPhoneToService(sid=sid,
                                             pid=phone[0],
                                             cursor=cursor,
                                             uid=uid)

        # Commit changes if no errors occur.
            self.conn.commit()
            return result
        except errors.UniqueViolation as badkey:
            return jsonify(Error="Room has service with the same name" +
                           str(badkey)), 401
Beispiel #13
0
    def setRecommendation(self, uid, eid, recommendstatus):
        """
         Create an eventuserinteraction entry for the defined user and event
         that sets the recommendstatus to the one provided, and itype as "none". If an entry
         for the user/event key pair exists, update the itype field.

         Uses :func:`~app.DAOs.AuditDAO.AuditDAO.getTableValueByPkeyPair` &
         :func:`~app.DAOs.AuditDAO.AuditDAO.insertAuditEntry`

        :param uid: User ID
        :type uid: int
        :param eid: Event ID
        :type eid: int
        :param recommendstatus: Char that states if the event is recommended or not.
        :type recommendstatus: str
        :return List[Tuple]: SQL result of Query as a tuple.
        """
        cursor = self.conn.cursor()
        audit = AuditDAO()
        tablename = 'eventuserinteractions'
        pkeys = ["eid", "uid"]
        oldValue = audit.getTableValueByPkeyPair(table=tablename,
                                                 pkeyname1=pkeys[0],
                                                 pkeyname2=pkeys[1],
                                                 pkeyval1=eid,
                                                 pkeyval2=uid,
                                                 cursor=cursor)
        query = sql.SQL("insert into {table1} "
                        "({insert_fields}) "
                        "VALUES ('none', %s, %s, %s) "
                        "on CONFLICT({conflict_keys}) do "
                        "update set {ukey1}= %s "
                        "returning {conflict_keys}").format(
                            insert_fields=sql.SQL(',').join([
                                sql.Identifier('itype'),
                                sql.Identifier('recommendstatus'),
                                sql.Identifier('uid'),
                                sql.Identifier('eid')
                            ]),
                            conflict_keys=sql.SQL(',').join(
                                [sql.Identifier('uid'),
                                 sql.Identifier('eid')]),
                            table1=sql.Identifier('eventuserinteractions'),
                            ukey1=sql.Identifier('recommendstatus'))
        try:
            cursor.execute(query, (str(recommendstatus), int(uid), int(eid),
                                   str(recommendstatus)))
            result = cursor.fetchone()
            newValue = audit.getTableValueByPkeyPair(table=tablename,
                                                     pkeyname1=pkeys[0],
                                                     pkeyname2=pkeys[1],
                                                     pkeyval1=eid,
                                                     pkeyval2=uid,
                                                     cursor=cursor)
            audit.insertAuditEntry(changedTable=tablename,
                                   changeType=audit.INSERTVALUE,
                                   oldValue=oldValue,
                                   newValue=newValue,
                                   uid=uid,
                                   cursor=cursor)

            self.conn.commit()
            self.conn.close()
        except errors.ForeignKeyViolation as e:
            self.conn.close()
            return ValueError("Invalid values: eid=" + str(eid) + " uid=" +
                              str(uid))
        except ValueError as e:
            self.conn.close()
            return e
        return result
Beispiel #14
0
    def setInteraction(self, uid, eid, itype):
        """
         Create an eventuserinteraction entry for the defined user and event
         that sets the interaction type to the one provided, and recommended as "N". If an entry
         for the user/event key pair exists, update the itype field.

        Uses:

         * :func:`~app.DAOs.TagDAO.TagDAO.getCoreUserTagsFromEventID`
         * :func:`~app.DAOs.TagDAO.TagDAO.setUserTag`
         * :func:`~app.DAOs.AuditDAO.AuditDAO.getTableValueByPkeyPair`
         * :func:`~app.DAOs.AuditDAO.AuditDAO.insertAuditEntry`

        :param uid: User ID
        :type uid: int
        :param eid: Event ID
        :type eid: int
        :param itype: interaction Type
        :type itype: str
        :return List[Tuple]: SQL result of Query as a tuple.
        """
        cursor = self.conn.cursor()

        # Get existing user event interaction.
        query = sql.SQL("select itype from eventuserinteractions "
                        "where eid=%s and uid=%s;")
        cursor.execute(query, (int(eid), int(uid)))
        current_itype = cursor.fetchone()

        # Determine what amount to add/subtract from tags.
        if current_itype is None:
            if itype == FOLLOWING_STRING:
                weight_change = STANDARD_CHANGE
            else:
                weight_change = -STANDARD_CHANGE
        else:
            if itype == DISMISSED_STRING:
                if current_itype[0] == FOLLOWING_STRING:
                    weight_change = -2 * STANDARD_CHANGE
                else:
                    weight_change = -STANDARD_CHANGE
            elif itype == UNFOLLOWED_STRING:
                weight_change = -STANDARD_CHANGE
            else:
                weight_change = STANDARD_CHANGE

        # Get a list of the event's tags and whatever weights the user has.
        tag_weights = TagDAO().getCoreUserTagsFromEventID(uid=uid,
                                                          eid=eid,
                                                          cursor=cursor)
        # Determine how to set the usertag weight.
        try:
            updated_usertags = []
            for t_w in tag_weights:
                tid = t_w[0]
                new_weight = -1

                # The user has a weight entry for the given tag:
                if t_w[1] is not None:
                    current_weight = t_w[1]

                    if (weight_change > 0) and (current_weight + weight_change
                                                >= 200):
                        new_weight = 200  # If adding weight goes over limit, set to limit.
                    elif (weight_change <
                          0) and (current_weight + weight_change <= 0):
                        new_weight = 0  # If subtracting weight goes below limit, set to lower limit.
                    else:
                        new_weight = current_weight + weight_change  # Else, add to weight

                # The user does not have a weight entry for the given tag:
                else:
                    if weight_change > 0:
                        new_weight = weight_change  # If the weight is to be added, create an entry with weight.
                    else:
                        pass  # Entry would be negative, so pass.
                if new_weight >= 0:
                    # If the new weight was set above, run the query to set user tag.
                    updated_usertags.append(TagDAO().setUserTag(
                        uid=uid, tid=tid, weight=new_weight, cursor=cursor))
        except errors.ForeignKeyViolation as fke:
            return ValueError("Invalid values: eid=" + str(eid) + " uid=" +
                              str(uid))

        audit = AuditDAO()
        tablename = 'eventuserinteractions'
        pkeys = ["eid", "uid"]
        oldValue = audit.getTableValueByPkeyPair(table=tablename,
                                                 pkeyname1=pkeys[0],
                                                 pkeyname2=pkeys[1],
                                                 pkeyval1=eid,
                                                 pkeyval2=uid,
                                                 cursor=cursor)

        # if you get here with no errors, update the interaction and finish.
        query = sql.SQL("insert into {table1} "
                        "({insert_fields}) "
                        "VALUES (%s, 'N', %s, %s) "
                        "on CONFLICT({conflict_keys}) do "
                        "update set {ukey1}= %s "
                        "returning {conflict_keys}").format(
                            insert_fields=sql.SQL(',').join([
                                sql.Identifier('itype'),
                                sql.Identifier('recommendstatus'),
                                sql.Identifier('uid'),
                                sql.Identifier('eid')
                            ]),
                            conflict_keys=sql.SQL(',').join(
                                [sql.Identifier('uid'),
                                 sql.Identifier('eid')]),
                            table1=sql.Identifier('eventuserinteractions'),
                            ukey1=sql.Identifier('itype'))
        try:
            cursor.execute(query, (str(itype), int(uid), int(eid), str(itype)))
            newValue = audit.getTableValueByPkeyPair(table=tablename,
                                                     pkeyname1=pkeys[0],
                                                     pkeyname2=pkeys[1],
                                                     pkeyval1=eid,
                                                     pkeyval2=uid,
                                                     cursor=cursor)
            audit.insertAuditEntry(changedTable=tablename,
                                   changeType=audit.INSERTVALUE,
                                   oldValue=oldValue,
                                   newValue=newValue,
                                   uid=uid,
                                   cursor=cursor)
            self.conn.commit()
            self.conn.close()
            result = updated_usertags
        except errors.ForeignKeyViolation as fke:
            self.conn.close()
            return ValueError("Invalid values: eid=" + str(eid) + " uid=" +
                              str(uid))
        except ValueError as e:
            self.conn.close()
            return e
        return result