def post(self):
        # Acquire all of the data in a dict of each argument defined in the parser above.
        data = DinnerRegistrar.parser.parse_args()

        if ProfessorModel.find_by_id(data["professorID"]) is None:
            return {
                "Message":
                "Dinner could not be created as no such professor could be found with id {}."
                .format(data["professorID"])
            }, 404, {
                "Access-Control-Allow-Origin": "*"
            }

        if data["userID"]:
            if data["userID"] == -1:
                # Create a new ProfessorModel object containing the passed properties.
                newDinner = DinnerModel(**(
                    data.pop("userID")
                ))  ## ** automatically separates dict keywords into arguments

                # Iterate the amount of dinners for this professor by one
                associatedProfessor = ProfessorModel.find_by_id(
                    data["professorID"])
                associatedProfessor.dinnerCount += 1
                associatedProfessor.save_to_db()

                # Save the new professor to the database.
                newDinner.save_to_db()

                return newDinner.json(), 201, {
                    "Access-Control-Allow-Origin": "*"
                }

            elif not UserModel.find_by_id(data["userID"]):
                return {
                    "Message":
                    "There is no user in the database with that ID. Could not create dinner"
                }, 404, {
                    "Access-Control-Allow-Origin": "*"
                }
            else:
                user = UserModel.find_by_id(data["userID"])
                user.dinnerCount += 1
                user.semDinnerCount += 1
                user.save_to_db()

        # Create a new ProfessorModel object containing the passed properties.
        newDinner = DinnerModel(
            **data)  ## ** automatically separates dict keywords into arguments

        # Iterate the amount of dinners for this professor by one
        associatedProfessor = ProfessorModel.find_by_id(data["professorID"])
        associatedProfessor.dinnerCount += 1
        associatedProfessor.save_to_db()

        # Save the new professor to the database.
        newDinner.save_to_db()

        return newDinner.json(), 201, {"Access-Control-Allow-Origin": "*"}
    def post(self):

        # Acquire all of the data in a dict of each argument defined in the parser above.
        data = ApplicationRegistrar.parser.parse_args()

        # Checking to see if a student object even exists with that particular net id
        if not (StudentModel.find_by_id(data["studentID"])):
            return {
                "ERROR": "No student could be found with that ID"
            }, 404, {
                "Access-Control-Allow-Origin": "*"
            }

        if StudentModel.find_by_id(data["studentID"]).blackList:
            return {
                "ERROR": "This student has been blacklisted and may not apply"
            }, 400, {
                "Access-Control-Allow-Origin": "*"
            }

        # Checking to see if a dinner object even exists with that particular net id
        if not (DinnerModel.find_by_id(data["dinnerID"])):
            return {
                "ERROR": "No dinner could be found with that ID"
            }, 404, {
                "Access-Control-Allow-Origin": "*"
            }

        # Create a new Application object containing the passed properties.
        newApp = ApplicationModel(
            **data)  ## ** automatically separates dict keywords into arguments

        # Save the new APPLICATION to the database.
        newApp.save_to_db()

        # Send out an email confirming the application

        # Increase the number of applications for the students
        student = StudentModel.find_by_id(data["studentID"])
        student.numberApplications += 1
        student.numberApplicationsSemester += 1

        student.save_to_db()

        # Send a confirmation email to the user
        try:
            msg = Message("Application Successfully Submitted",
                          sender="*****@*****.**",
                          recipients=["{}@duke.edu".format(student.netID)
                                      ])  #entryOfInterest.email
            #TODO
            msg.html = "Your application for {} has been successfully submitted.".format(
                newApp.dinner.topic)
            mail.send(msg)
        except Exception as e:
            return {"Message": str(e)}

        return ApplicationModel.return_last_item().json(), 200, {
            "Access-Control-Allow-Origin": "*"
        }
    def put(self, id):

        data = StudentReviewResource.parser.parse_args()

        if(StudentReviewResource.find_by_id(id)):
            reviewOfInterest = StudentReviewModel.find_by_id(id)
            reviewOfInterest.foodRating = data["foodRating"]
            reviewOfInterest.conversationRating = data["conversationRating"]
            reviewOfInterest.comments = data["comments"]

            if StudentModel.find_by_id(data["studentID"]):
                reviewOfInterest.studentID = data["studentID"]
            else:
                return {"Message":"No student with that ID could be found, please enter a valid student ID"}, 404

            if DinnerModel.find_by_id(data["dinnerID"]):
                reviewOfInterest.dinnerID = data["dinnerID"]
            else:
                return {"Message":"No dinner with that ID could be found, please enter a valid dinner ID"}, 404

        else:
            reviewOfInterest = StudentReviewModel(id=id,**data)

        reviewOfInterest.save_to_db()

        return reviewOfInterest.json(),  200, {"Access-Control-Allow-Origin":"*"}
    def delete(self, id):

        if (DinnerModel.find_by_id(id)):
            dinner = DinnerModel.find_by_id(id)
            dinner.delete_from_db()
            return {
                "Message": "Dinner with id {} deleted.".format(id)
            }, 200, {
                "Access-Control-Allow-Origin": "*"
            }

        return {
            "Message": "No dinner with id {} found.".format(id)
        }, 404, {
            "Access-Control-Allow-Origin": "*"
        }
def hello():
    dinners = DinnerModel.return_all_objects()
    # First, email the user their list of matches
    for dinner in dinners:
        remindStudents(dinner)
        remindProfessor(dinner)
        remindUser(dinner)
    print(time.time())
    def get(self, id):
        found = DinnerModel.find_by_id(id)
        if (found):
            return found.json(), 200, {"Access-Control-Allow-Origin": "*"}

        return {
            "Message": "No Dinner could be found with id {}".format(id)
        }, 404, {
            "Access-Control-Allow-Origin": "*"
        }
    def get(self):
        data = DinnerStatusCodeResource.parser.parse_args()

        if data["status"] is None and data["id"]:
            return DinnerModel.return_by_userID(data["id"]), 200, {
                "Access-Control-Allow-Origin": "*"
            }
        elif data["status"] and data["id"] is None:
            return DinnerModel.return_all_dinners_by_status(
                data["status"]), 200, {
                    "Access-Control-Allow-Origin": "*"
                }
        elif data["status"] and data["id"]:
            return DinnerModel.return_by_status_and_id(
                data["status"], data["id"]), 200, {
                    "Access-Control-Allow-Origin": "*"
                }
        else:
            return DinnerModel.return_all(), 200, {
                "Access-Control-Allow-Origin": "*"
            }
    def get(self, id):
        # Get the dinner, change status, and then email everyone it is complete
        if DinnerModel.find_by_id(id):
            dinnerToConfirm = DinnerModel.find_by_id(id)
        else:
            return {
                "Message": "No dinner could be found with id  {}".format(id)
            }, 404, {
                "Access-Control-Allow-Origin": "*"
            }

        if not UserModel.find_by_id(dinnerToConfirm.userID):
            return {
                "Message": "This dinner is unclaimed and cannot be published"
            }, 400, {
                "Access-Control-Allow-Origin": "*"
            }

        dinnerToConfirm.status = 2
        dinnerToConfirm.save_to_db()

        # Designate all pending applications who are not waitlisted as rejected
        for application in dinnerToConfirm.applications:
            if application.status == 0:
                application.status = 2
                application.save_to_db()

        DinnerConfirmer.notifyRecipients(id)

        dinnerToConfirm.invitationSentTimeStamp = str(time.time())

        return {
            "Message":
            "Dinner with id {} is confirmed. All accepted applicants have been emailed. Confirmation email sent to  {} {}:{}"
            .format(id, dinnerToConfirm.user.firstName,
                    dinnerToConfirm.user.lastName, dinnerToConfirm.user.email)
        }, 200, {
            "Access-Control-Allow-Origin": "*"
        }
def blacklist():
    dinners = DinnerModel.return_all_objects()

    for dinner in dinners:
        # if the dinner has past, i.e. if the current timestamp exceeds the dinner timestamp
        if int(float(dinner.timeStamp)) < time.time():
            # Get all of the applications
            applications = dinner.applications

            # Iterate through all of the applications of the dinner, find the users which confirmed
            # but didn't show up, and then blacklist them.
            for app in applications:
                if app.confirmed and not app.present:
                    student = StudentModel.find_by_id(app.studentID)
                    student.blackList = True
                    student.save_to_db()
Exemple #10
0
    def delete(self, uniqueID):

        if (ProfessorModel.find_by_id(uniqueID)):
            if DinnerModel.return_by_professorID(uniqueID):
                return {
                    "Message":
                    "Professor with id {} is assigned to dinner(s) and cannot be deleted. Sorry bby <3 <3 <3"
                    .format(uniqueID)
                }, 400, {
                    "Access-Control-Allow-Origin": "*"
                }
            ProfessorModel.find_by_id(uniqueID).delete_from_db()
            return {
                "Message": "Professor with id {} deleted.".format(uniqueID)
            }, 200, {
                "Access-Control-Allow-Origin": "*"
            }

        return {
            "Message": "No professor with {} found.".format(uniqueID)
        }, 200, {
            "Access-Control-Allow-Origin": "*"
        }
    def put(self, id):

        data = DinnerResource.parser.parse_args()

        if (DinnerModel.find_by_id(id)):
            dinnerOfInterest = DinnerModel.find_by_id(id)

            if not ProfessorModel.find_by_id(data["professorID"]):
                return {
                    "Message":
                    "There is no professor in the database with that ID"
                }, 404, {
                    "Access-Control-Allow-Origin": "*"
                }

            if data["userID"]:
                if data["userID"] == -1:
                    if UserModel.find_by_id(dinnerOfInterest.userID):
                        user = UserModel.find_by_id(dinnerOfInterest.userID)
                        user.dinnerCount -= 1
                        user.semDinnerCount -= 1
                        user.save_to_db()
                    dinnerOfInterest.userID = None
                elif not UserModel.find_by_id(data["userID"]):
                    return {
                        "Message":
                        "There is no user in the database with that ID"
                    }, 404, {
                        "Access-Control-Allow-Origin": "*"
                    }
                elif UserModel.find_by_id(data["userID"]):
                    dinnerOfInterest.userID = data["userID"]

            dinnerOfInterest.timeStamp = data["timeStamp"]
            dinnerOfInterest.topic = data["topic"]
            dinnerOfInterest.description = data["description"]
            dinnerOfInterest.studentLimit = data["studentLimit"]
            dinnerOfInterest.address = data["address"]
            dinnerOfInterest.dietaryRestrictions = data["dietaryRestrictions"]

            if ProfessorModel.find_by_id(dinnerOfInterest.professorID):
                professor = ProfessorModel.find_by_id(
                    dinnerOfInterest.professorID)
                professor.dinnerCount -= 1
                professor.save_to_db()

            dinnerOfInterest.professorID = data["professorID"]
            dinnerOfInterest.catering = data["catering"]
            dinnerOfInterest.transportation = data["transportation"]
            dinnerOfInterest.invitationSentTimeStamp = data[
                "invitationSentTimeStamp"]

            # Assign new userID

        else:

            if not ProfessorModel.find_by_id(data["professorID"]):
                return {
                    "Message":
                    "There is no professor in the database with that ID"
                }, 404, {
                    "Access-Control-Allow-Origin": "*"
                }

            if not UserModel.find_by_id(
                    data["userID"]) or data["userID"] != -1:
                return {
                    "Message": "There is no user in the database with that ID"
                }, 404, {
                    "Access-Control-Allow-Origin": "*"
                }

            dinnerOfInterest = DinnerModel(id=id, **data)

        # If the dinner gains a userID, but is not completely done "not 2", then update the status to 1, which
        # means it is claimed but does not have a user yet.
        if dinnerOfInterest.userID and dinnerOfInterest.status is not 2:
            dinnerOfInterest.status = 1

        dinnerOfInterest.save_to_db()

        # increase the number of dinners for this new userID
        if data["userID"] and UserModel.find_by_id(data["userID"]):
            user = UserModel.find_by_id(data["userID"])
            user.dinnerCount += 1
            user.semDinnerCount += 1
            user.save_to_db()

        professor = ProfessorModel.find_by_id(data["professorID"])
        professor.dinnerCount += 1
        professor.save_to_db()

        return dinnerOfInterest.json(), 200, {
            "Access-Control-Allow-Origin": "*"
        }
    def notifyRecipients(cls, id):

        from app import mail
        from flask_mail import Message

        dinner = DinnerModel.find_by_id(id)

        # Send a confirmation email to the user
        try:
            dinnerTime = datetime.datetime.fromtimestamp(int(
                dinner.timeStamp)).strftime('%x')
            msg = Message("Dinner Confirmed",
                          sender="*****@*****.**",
                          recipients=["{}@duke.edu".format(dinner.user.email)
                                      ])  #entryOfInterest.email
            msg.html = "You've published the dinner hosted by {} {}. It is on {}. Yay!".format(
                dinner.professor.firstName, dinner.professor.lastName,
                dinnerTime)
            mail.send(msg)
        except Exception as e:
            return {"Message": str(e)}

        # Email all accepted and waitlisted applicants
        for application in dinner.applications:
            print("Applications Status {}".format(application.status))
            if application.status == 1:
                try:
                    dinnerTime = datetime.datetime.fromtimestamp(
                        int(dinner.timeStamp)).strftime('%x')
                    dinnerDay = datetime.datetime.fromtimestamp(
                        int(dinner.timeStamp)).strftime("%A")

                    msg = Message(
                        "Accepted",
                        sender="*****@*****.**",
                        recipients=[
                            "{}@duke.edu".format(application.student.netID)
                        ])  #entryOfInterest.email
                    print("{}@duke.edu".format(application.netID))

                    # Read the html from the email template.
                    soup = BeautifulSoup(
                        open("email-templates/acceptance.html"), "html.parser")

                    msg.html = soup.prettify().format(
                        dinner.professor.firstName + " " +
                        dinner.professor.lastName, dinnerDay, dinnerTime,
                        application.student.firstName + " " +
                        application.student.lastName,
                        dinner.user.firstName + " " + dinner.user.lastName,
                        dinnerDay, dinner.address, dinner.topic,
                        dinner.user.phone,
                        dinner.user.firstName + ' ' + dinner.user.lastName)
                    # msg.html = "<h1> KILL ME </h1>"

                    # print(msg.html)
                    mail.send(msg)
                except Exception as e:
                    return {"Message": str(e)}

            if application.status == 3:
                try:
                    dinnerTime = datetime.datetime.fromtimestamp(
                        int(dinner.timeStamp)).strftime('%x')
                    msg = Message(
                        "Accepted",
                        sender="*****@*****.**",
                        recipients=[
                            "{}@duke.edu".format(application.student.netID)
                        ])  #entryOfInterest.email
                    #TODO
                    msg.html = "You've been waitlisted to the dinner hosted by {} {}. It is on {}. Please contact us if you'd like to be removed from the waitlist.".format(
                        dinner.professor.firstName, dinner.professor.lastName,
                        dinnerTime)
                    mail.send(msg)
                except Exception as e:
                    return {"Message": str(e)}
 def get(self):
     return DinnerModel.return_all(), 200, {
         "Access-Control-Allow-Origin": "*"
     }