Exemple #1
0
def unsolved(Qid):
    mycursor = mydb.cursor(dictionary=True)
    if request.method == 'GET':
        mycursor.execute(
            "SELECT msgTime, sender, msg FROM Messages WHERE questionID = %s" %
            (Qid))
        messages = mycursor.fetchall()
        mycursor.execute(
            "SELECT id, subject FROM ContactUsForms WHERE id = %s" % (Qid))
        msg = mycursor.fetchone()
        return render_template("question_thread.html",
                               messages=messages,
                               msg=msg,
                               unsolved=1)
    else:
        if 'send' in request.form:
            msg = request.form['msg']
            sql = "INSERT INTO Messages (msgTime, questionID, adminID, sender, msg) VALUES (%s,%s,%s,%s,%s)"
            msgtime = datetime.now()
            a_id = session["u_id"]
            val = (msgtime, Qid, a_id, 'A', msg)
            mycursor.execute(sql, val)
            mydb.commit()
            return redirect(url_for('admin.unsolved', Qid=Qid))

        elif 'solved' in request.form:
            mycursor.execute(
                "UPDATE ContactUsForms SET is_solved = 1 WHERE id = %s" %
                (Qid))
            mydb.commit()
            return redirect(url_for('admin.msg'))
Exemple #2
0
def editDr():
    mycursor = mydb.cursor()
    dr_id = request.form['ID']
    name = request.form['Name']
    gender = request.form['Gender']
    email = request.form['Email']
    phone = request.form['Phone']
    pw = request.form['Password']
    # DATE format YYYY-MM-DD
    bdate = request.form['Birthday']
    ssn = request.form['SSN']
    try:
        sql = "UPDATE Doctors SET Name = %s, Gender = %s, Email = %s, Password = %s, Phone = %s, SSN = %s, Birthday = %s WHERE ID = %s"
        val = (name, gender, email, pw, phone, ssn, bdate, dr_id)
        mycursor.execute(sql, val)
        mydb.commit()
        mycursor.execute("SELECT * FROM Doctors WHERE ID = '%s'" % (dr_id))
        row_headers = [x[0] for x in mycursor.description]
        myresult = mycursor.fetchone()
        return render_template("A_update_doctors.html",
                               type=type,
                               Data=zip(row_headers, myresult),
                               succ="Doctor's profile updated successfully.")
    except:
        mycursor.execute("SELECT * FROM Doctors WHERE ID = '%s'" % (dr_id))
        row_headers = [x[0] for x in mycursor.description]
        myresult = mycursor.fetchone()
        return render_template("A_update_doctors.html",
                               type=type,
                               Data=zip(row_headers, myresult),
                               err="Something went wrong.")
Exemple #3
0
def addDr():
    mycursor = mydb.cursor()

    if request.method == 'GET':
        return render_template("A_add_doctor.html")
    else:
        email = request.form['email']
        mycursor.execute("SELECT * FROM Doctors WHERE Email = '%s'" % (email))
        result = mycursor.fetchone()
        if result:
            return render_template("A_add_doctor.html",
                                   err="This email is already registered!")
        else:
            name = request.form['name']
            gender = request.form['gender']
            phone = request.form['phone']
            pw = request.form['password']
            # DATE format YYYY-MM-DD
            bdate = request.form['birthday']
            ssn = request.form['SSN']
            today = time.strftime('%Y-%m-%d')
            try:
                sql = "INSERT INTO Doctors (Name, Gender, Email, Password, Phone, SSN, Birthday, Join_date) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
                val = (name, gender, email, pw, phone, ssn, bdate, today)
                mycursor.execute(sql, val)
                mydb.commit()
                return render_template("A_add_doctor.html",
                                       succ="Doctor registered successfully.")
            except:
                return render_template(
                    "A_add_doctor.html",
                    err="Something went wrong.")  #"please check your ssn"
Exemple #4
0
def addPatient():
    mycursor = mydb.cursor()
    if request.method == 'GET':
        return render_template("A_addpatient.html")
    else:
        email = request.form['email']
        mycursor.execute("SELECT * FROM Patients WHERE Email = '%s'" % (email))
        result = mycursor.fetchone()
        if result:
            return render_template("A_addpatient.html",
                                   err="This email is already registered!")
        else:
            fname = request.form['fname']
            lname = request.form['lname']
            name = fname + " " + lname
            phone = request.form['phone']
            pw = request.form['password']
            # DATE format YYYY-MM-DD
            bdate = request.form['birthday']
            ssn = request.form['SSN']
            today = time.strftime('%Y-%m-%d')
            if ssn == "":
                ssn = None
            gender = request.form['gender']
            if gender == '0':
                gender = None
            job = request.form['job']
            bloodtype = request.form['bloodtype']
            if bloodtype == '0':
                bloodtype = None
            weight = request.form['weight']
            if weight == "":
                weight = None
            height = request.form['height']
            if height == "":
                height = None
            hypertension = request.form.get('hypertension')
            HyperControl = request.form.get('controlledH')
            diabetic = request.form.get('diabetic')
            diabetesControl = request.form.get('controlledDiabetes')
            heartStroke = request.form.get('heartStroke')
            cholesterol = request.form.get('cholesterol')
            # print(name, email, pw, phone, ssn,gender, bdate, job, bloodtype,
            #     weight, height, hypertension, HyperControl, diabetic, diabetesControl, heartStroke, cholesterol)
            try:
                sql = "INSERT INTO Patients (Name, Email, Password, Phone,Gender, Birthday,SSN,Job,BloodType,Weight,Height,Hypertension,ControlledHypertension,Diabetic,ControlledDiabetes,HeartStroke, Cholesterol, Join_date) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
                val = (name, email, pw, phone, gender, bdate, ssn, job,
                       bloodtype, weight, height, hypertension, HyperControl,
                       diabetic, diabetesControl, heartStroke, cholesterol,
                       today)
                mycursor.execute(sql, val)
                mydb.commit()
                return render_template("A_addpatient.html",
                                       succ="Patient added successfully.")
            except:
                return render_template(
                    "A_addpatient.html",
                    err="Something went wrong.")  #check your ssn
Exemple #5
0
def create_user(name: str = typer.Argument(
    ..., help="Name of user you want to add"),
                phone: int = typer.Argument(
                    None, help="The phone number of the user  [required]")):
    if phone:
        if phone >= 9000000000 and phone <= 9999999999:
            num = "0" + str(phone)
            mycursor.execute("SELECT * FROM users where phone = %s", (num, ))
            check_user = mycursor.fetchone()
            if check_user is None:
                sql = 'INSERT INTO users (Username, phone) VALUES (%s, %s)'
                val = (name, num)
                mycursor.execute(sql, val)
                mydb.commit()
                ending = typer.style("User --((" + name + " " + str(phone) +
                                     "))-- Added",
                                     fg=typer.colors.GREEN,
                                     bold=True)
                typer.echo(ending)
            else:
                raise ValueError(
                    typer.style("Phone number existed",
                                fg=typer.colors.RED,
                                bold=True))
        else:
            raise ValueError(
                typer.style("Invalid phone number",
                            fg=typer.colors.RED,
                            bold=True))
    else:
        num = typer.prompt("Enter your phone number [09xxxxxxxxx]?")
        if int(num):
            if re.search("^09.........", num):
                mycursor.execute("SELECT * FROM users where phone = %s",
                                 (num, ))
                check_user = mycursor.fetchone()
                if check_user is None:
                    sql = 'INSERT INTO users (Username, phone) VALUES (%s, %s)'
                    val = (name, num)
                    mycursor.execute(sql, val)
                    mydb.commit()
                    ending = typer.style("User --((" + name + " " + str(num) +
                                         "))-- Added",
                                         fg=typer.colors.GREEN,
                                         bold=True)
                    typer.echo(ending)
                else:
                    raise ValueError(
                        typer.style("Phone number existed",
                                    fg=typer.colors.RED,
                                    bold=True))
            else:
                raise ValueError(
                    typer.style("Invalid phone number",
                                fg=typer.colors.RED,
                                bold=True))
Exemple #6
0
def del_user(phone: str = Query(..., min_length=11, max_length=11,
                                regex="^09")):
    mycursor.execute("SELECT * FROM users where phone = %s", (phone, ))
    check_user = mycursor.fetchone()
    if check_user is None:
        raise HTTPException(status_code=406, detail="User is not existed")
    else:
        mycursor.execute("DELETE FROM users WHERE phone = %s", (phone, ))
        mydb.commit()
        return {"User is deleted": check_user}
Exemple #7
0
def test_e1_3():
    sql = 'INSERT INTO users (Username, phone) VALUES (%s, %s)'
    val = (name, num)
    mycursor.execute(sql, val)
    mydb.commit()
    response = client.post("/add/?name=" + name + "&phone=" + num)
    assert response.status_code == 406
    assert response.json() == {"detail": "Phone Number is registered"}
    mycursor.execute("DELETE FROM users WHERE phone = %s", (num, ))
    mydb.commit()
Exemple #8
0
def test_e2_1():
    sql = 'INSERT INTO users (Username, phone) VALUES (%s, %s)'
    val = (name, num)
    mycursor.execute(sql, val)
    mydb.commit()
    response = client.get("/read/")
    assert response.status_code == 200
    assert response.json() == {"Users": [[name, num]]}
    mycursor.execute("DELETE FROM users WHERE phone = %s", (num, ))
    mydb.commit()
Exemple #9
0
def test_e3_1():
    sql = 'INSERT INTO users (Username, phone) VALUES (%s, %s)'
    val = (name, num)
    mycursor.execute(sql, val)
    mydb.commit()
    response = client.delete("/del/?phone=" + num)
    assert response.status_code == 200
    assert response.json() == {"User is deleted": [name, num]}
    mycursor.execute("DELETE FROM users WHERE phone = %s", (num, ))
    mydb.commit()
Exemple #10
0
def edit_profile():
    mycursor = mydb.cursor()
    p_id = session['u_id']
    if request.method == 'GET':
      sql = 'SELECT * FROM Patients WHERE ID =%s'
      val = (p_id,)
      #Fetch user's record
      mycursor.execute(sql,val)
      row_headers = [x[0] for x in mycursor.description]
      myresult = mycursor.fetchone()
      return render_template("profile.html", type=type, allData=zip(row_headers, myresult), edit=1)
      
    else: 
      if 'edit' in request.form:
         name = request.form['Name']
         gender = request.form['Gender']
         email = request.form['Email']
         phone = request.form['Phone']
         # DATE format YYYY-MM-DD
         bdate = request.form['Birthday']
         ssn = request.form['SSN']
         job = request.form['Job']
         bloodtype = request.form['BloodType']
         weight = request.form['Weight']
         height = request.form['Height']
         hyper = request.form['Hypertension']
         hypercont = request.form['ControlledHypertension']
         diabetic = request.form['Diabetic']
         diacont = request.form['ControlledDiabetes']
         stroke = request.form['HeartStroke']
         cholesterol = request.form['Cholesterol']
         try:
            # print(name, email, phone, ssn, bday, p_id)
            sql = "UPDATE Patients SET Name = %s, Gender = %s, Email = %s, Phone = %s, SSN = %s, Birthday = %s, Job = %s, BloodType = %s, Weight = %s, Height = %s, Hypertension = %s, ControlledHypertension = %s, Diabetic = %s, ControlledDiabetes = %s, HeartStroke = %s, Cholesterol = %s WHERE ID = %s"
            val = (name, gender, email, phone, ssn, bdate, job, bloodtype, weight, height, hyper, hypercont,diabetic, diacont, stroke, cholesterol, p_id)
            mycursor.execute(sql, val)
            mydb.commit()
            flash("Profile updated successfully!", "info")
         except:
            flash("Something went wrong!", "error")

      elif 'change' in request.form: #for changing password
         old_pw = request.form['password']
         mycursor.execute("SELECT Password FROM Patients where id = '%s'" %(p_id))
         myresult = mycursor.fetchone()
         pw = myresult[0]
         #   print(pw, old_pw)
         if pw == old_pw:
               new_pw = request.form['newpassword']
               mycursor.execute("UPDATE Doctors SET Password = '******' WHERE id = '%s'" % (new_pw, p_id))
               mydb.commit()
               flash("Password changed successfully!", "info")
         else:
               flash("Incorrect password!", "error")
      return redirect(url_for('patient.display_profile'))
Exemple #11
0
def test_e1_1():
    response = client.post("/add/?name=" + name + "&phone=" + num)
    assert response.status_code == 200
    assert response.json() == {
        "User added": {
            "Username": name,
            "PhoneNumber": num
        }
    }
    mycursor.execute("DELETE FROM users WHERE phone = %s", (num, ))
    mydb.commit()
Exemple #12
0
def test_e4_2():
    sql = 'INSERT INTO users (Username, phone) VALUES (%s, %s)'
    val = (name, num)
    mycursor.execute(sql, val)
    mydb.commit()
    response = client.put("/change_username/?name=asghar&phone=" + num)
    assert response.status_code == 200
    assert response.json() == {
        "User": [name, num],
        "Username updated to ": "asghar"
    }
    mycursor.execute("DELETE FROM users WHERE phone = %s", (num, ))
    mydb.commit()
Exemple #13
0
def view_drs():
    mycursor = mydb.cursor()
    if request.method == 'GET':
        mycursor.execute("SELECT * FROM Doctors")
        # this will extract row headers
        row_headers = [x[0] for x in mycursor.description]
        myresult = mycursor.fetchall()
        return render_template("A_view_doctors.html",
                               AllDoctors=myresult,
                               headers=row_headers)
    else:
        if 'edit' in request.form:
            drid = request.form['edit']
            # print(drid)
            mycursor.execute("SELECT * FROM Doctors WHERE ID = '%s'" % (drid))
            row_headers = [x[0] for x in mycursor.description]
            myresult = mycursor.fetchone()
            return render_template("A_update_doctors.html",
                                   type=type,
                                   Data=zip(row_headers, myresult))
        else:  #delete
            drid = request.form['del']
            # print(drid)
            try:
                mycursor.execute("DELETE FROM Doctors WHERE ID = '%s'" %
                                 (drid))
                mydb.commit()
                #delete calendar of the doctor
                mycursor.execute(
                    "SELECT c_id FROM Calendars WHERE drID ='%s'" % (drid))
                c_id = mycursor.fetchone()
                g_api.delete_calendar(c_id['c_id'])
                mycursor.execute("DELETE FROM Calendars WHERE c_id='%s'" %
                                 (c_id['c_id']))
                mydb.commit()
                ##
                mycursor.execute("SELECT * FROM Doctors")
                row_headers = [x[0] for x in mycursor.description]
                myresult = mycursor.fetchall()
                return render_template("A_view_doctors.html",
                                       AllDoctors=myresult,
                                       headers=row_headers,
                                       succ="Doctor deleted successfully.")
            except:
                mycursor.execute("SELECT * FROM Doctors")
                row_headers = [x[0] for x in mycursor.description]
                myresult = mycursor.fetchall()
                return render_template("A_view_doctors.html",
                                       AllDoctors=myresult,
                                       headers=row_headers,
                                       err="Something went wrong.")
Exemple #14
0
def update_username(name: str = Query(..., min_length=1, regex="^[a-z/A-Z]"),
                    phone: str = Query(...,
                                       min_length=11,
                                       max_length=11,
                                       regex="^09")):
    mycursor.execute("SELECT * FROM users where phone = %s", (phone, ))
    check_user = mycursor.fetchone()
    if check_user is None:
        raise HTTPException(status_code=406, detail="User is not existed")
    else:
        mycursor.execute("UPDATE users SET Username = %s WHERE phone = %s",
                         (name, phone))
        mydb.commit()
        return {"User": check_user, "Username updated to ": name}
Exemple #15
0
def add_user(name: str = Query(..., min_length=1, regex="^[a-z/A-Z]"),
             phone: str = Query(..., min_length=11, max_length=11,
                                regex="^09")):
    mycursor.execute("SELECT * FROM users where phone = %s", (phone, ))
    check_phone = mycursor.fetchone()
    if check_phone:
        raise HTTPException(status_code=406,
                            detail="Phone Number is registered")
    else:
        sql = 'INSERT INTO users (Username, phone) VALUES (%s, %s)'
        val = (name, phone)
        mycursor.execute(sql, val)
        mydb.commit()
        return {"User added": {"Username": name, "PhoneNumber": phone}}
Exemple #16
0
def remove_cal():
    if request.method == 'POST':
        doctor_id = request.form['drID']
        mycursor.execute("SELECT c_id FROM Calendars WHERE drID ='%s'" %
                         (doctor_id))
        c_id = mycursor.fetchone()
        if c_id:
            g_api.delete_calendar(c_id['c_id'])
            mycursor.execute("DELETE FROM Calendars WHERE c_id='%s'" %
                             (c_id['c_id']))
            mydb.commit()
            flash("Calendar is Removed Successfully!")
        else:
            flash("Doctor has no Calendar")
    return render_template("calendar.html")
Exemple #17
0
def delApp(id_data):
    sql = "SELECT * FROM Events WHERE a_id = %s"
    val = (id_data, )
    mycursor.execute(sql, val)
    Event = mycursor.fetchone()
    print(Event)
    g_api.delete_event(Event['cal_id'], Event['e_id'])
    sql = "DELETE FROM Events WHERE a_id = %s "
    val = (id_data, )
    mycursor.execute(sql, val)
    mydb.commit()
    sql = 'DELETE FROM Appointments WHERE id=%s'
    val = (id_data, )
    mycursor.execute(sql, val)
    mydb.commit()
    return redirect(url_for("upcoming_app"))
Exemple #18
0
def editpat():
    mycursor = mydb.cursor()
    pat_id = request.form['ID']
    name = request.form['Name']
    gender = request.form['Gender']
    email = request.form['Email']
    pw = request.form['Password']
    phone = request.form['Phone']
    # DATE format YYYY-MM-DD
    bdate = request.form['Birthday']
    ssn = request.form['SSN']
    job = request.form['Job']
    bloodtype = request.form['BloodType']
    weight = request.form['Weight']
    height = request.form['Height']
    hyper = request.form['Hypertension']
    hypercont = request.form['ControlledHypertension']
    diabetic = request.form['Diabetic']
    diacont = request.form['ControlledDiabetes']
    stroke = request.form['HeartStroke']
    cholesterol = request.form['Cholesterol']

    try:
        sql = "UPDATE Patients SET Name = %s, Gender = %s, Email = %s, Password = %s, Phone = %s, SSN = %s, Birthday = %s, Job = %s, BloodType = %s, Weight = %s, Height = %s, Hypertension = %s, ControlledHypertension = %s, Diabetic = %s, ControlledDiabetes = %s, HeartStroke = %s, Cholesterol = %s WHERE ID = %s"
        val = (name, gender, email, pw, phone, ssn, bdate, job, bloodtype,
               weight, height, hyper, hypercont, diabetic, diacont, stroke,
               cholesterol, pat_id)
        mycursor.execute(sql, val)
        mydb.commit()
        mycursor.execute("SELECT * FROM Patients WHERE ID = '%s'" % (pat_id))
        row_headers = [x[0] for x in mycursor.description]
        myresult = mycursor.fetchone()
        return render_template("A_update_patients.html",
                               type=type,
                               Data=zip(row_headers, myresult),
                               succ="Patient's profile updated successfully.")
    except:
        mycursor.execute("SELECT * FROM Patients WHERE ID = '%s'" % (pat_id))
        row_headers = [x[0] for x in mycursor.description]
        myresult = mycursor.fetchone()
        return render_template("A_update_patients.html",
                               type=type,
                               Data=zip(row_headers, myresult),
                               err="Something went wrong.")
Exemple #19
0
def edit_profile():
    mycursor = mydb.cursor()
    d_id = session['u_id']
    if request.method == 'GET':
        sql = 'SELECT * FROM Doctors WHERE ID =%s'
        val = (d_id,)
        #Fetch user's record
        mycursor.execute(sql,val)
        row_headers = [x[0] for x in mycursor.description]
        myresult = mycursor.fetchone()
        return render_template("profile.html", type=type, allData=zip(row_headers, myresult), edit=1)

    else:
        if 'edit' in request.form:
            name = request.form['Name']
            gender = request.form['Gender']
            email = request.form['Email']
            phone = request.form['Phone']
            # DATE format YYYY-MM-DD
            bdate = request.form['Birthday']
            ssn = request.form['SSN']
            # dep = request.form['DepartmentID']
            try:
                # print(name, email, phone, ssn, bday, d_id)
                mycursor.execute("UPDATE Doctors SET Name = '%s', Gender = '%s', Email = '%s', Phone = '%s', SSN = '%s', Birthday = '%s' WHERE id = '%s'" % (name,gender, email, phone, ssn, bdate, d_id))
                mydb.commit()
                flash("Profile updated successfully!", "info")
            except:
                flash("Something went wrong!", "error")

        elif 'change' in request.form: #for changing password
            old_pw = request.form['password']
            mycursor.execute("SELECT Password FROM Doctors where ID = '%s'" %(d_id))
            myresult = mycursor.fetchone()
            pw = myresult[0]
        #   print(pw, old_pw)
            if pw == old_pw:
                new_pw = request.form['newpassword']
                mycursor.execute("UPDATE Doctors SET Password = '******' WHERE ID = '%s'" % (new_pw, d_id))
                mydb.commit()
                flash("Password changed successfully!", "info")
            else:
                flash("Incorrect password!", "error")
        return redirect(url_for('doctor.display_profile'))
Exemple #20
0
def edit_profile():
    mycursor = mydb.cursor()
    a_id = session["u_id"]
    if request.method == 'GET':
        mycursor.execute("SELECT * FROM Admins where ID = '%s'" % (a_id))
        row_headers = [x[0] for x in mycursor.description]
        myresult = mycursor.fetchone()
        return render_template("profile.html",
                               type=type,
                               adminData=zip(row_headers, myresult),
                               edit=1)
    else:
        if 'edit' in request.form:
            name = request.form['Name']
            email = request.form['Email']
            phone = request.form['Phone']
            ssn = request.form['SSN']
            bday = request.form['Birthday']
            try:
                # print(name, email, phone, ssn, bday, a_id)
                mycursor.execute(
                    "UPDATE Admins SET Name = '%s', Email = '%s', Phone = '%s', SSN = '%s', Birthday = '%s' WHERE ID = '%s'"
                    % (name, email, phone, ssn, bday, a_id))
                mydb.commit()
                flash("Profile updated successfully!", "info")
            except:
                flash("Something went wrong!", "error")
        elif 'change' in request.form:  #for changing password
            old_pw = request.form['password']
            mycursor.execute("SELECT Password FROM Admins where ID = '%s'" %
                             (a_id))
            myresult = mycursor.fetchone()
            pw = myresult[0]
            # print(pw, old_pw)
            if pw == old_pw:
                new_pw = request.form['newpassword']
                mycursor.execute(
                    "UPDATE Admins SET Password = '******' WHERE ID = '%s'" %
                    (new_pw, a_id))
                mydb.commit()
                flash("Password changed successfully!", "info")
            else:
                flash("Incorrect password!", "error")
        return redirect(url_for('admin.profile'))
Exemple #21
0
def view_patients():
    mycursor = mydb.cursor()
    if request.method == 'GET':
        mycursor.execute(
            "SELECT ID, Name, Email, Password, Phone, Gender, SSN, Birthday, Job , Join_date FROM Patients"
        )
        # this will extract row headers
        row_headers = [x[0] for x in mycursor.description]
        myresult = mycursor.fetchall()
        return render_template("A_view_patients.html",
                               AllPatients=myresult,
                               headers=row_headers)
    else:
        if 'edit' in request.form:
            patid = request.form['edit']
            mycursor.execute("SELECT * FROM Patients WHERE ID = '%s'" %
                             (patid))
            row_headers = [x[0] for x in mycursor.description]
            myresult = mycursor.fetchone()
            return render_template("A_update_patients.html",
                                   type=type,
                                   Data=zip(row_headers, myresult))
        else:  #delete
            patid = request.form['del']
            try:
                mycursor.execute("DELETE FROM Patients WHERE ID = '%s'" %
                                 (patid))
                mydb.commit()
                mycursor.execute("SELECT * FROM Patients")
                row_headers = [x[0] for x in mycursor.description]
                myresult = mycursor.fetchall()
                return render_template("A_view_patients.html",
                                       AllPatients=myresult,
                                       headers=row_headers,
                                       succ="Patient deleted successfully.")
            except:
                mycursor.execute("SELECT * FROM Patients")
                row_headers = [x[0] for x in mycursor.description]
                myresult = mycursor.fetchall()
                return render_template("A_view_patients.html",
                                       AllPatients=myresult,
                                       headers=row_headers,
                                       err="Something went wrong.")
Exemple #22
0
def contactus():
   if request.method=='POST':
      patid = session["u_id"] 
      subject = request.form['subject']
      msg = request.form['msg']

      sql = "INSERT INTO ContactUsForms (patID, subject) VALUES (%s,%s)"
      val = (patid,subject)
      mycursor.execute(sql, val)

      # get this question id to insert as foreign key in the messages table
      question_id = mycursor.lastrowid

      sql = "INSERT INTO Messages (msgTime, questionID, sender, msg) VALUES (%s,%s,%s,%s)"
      msgtime = datetime.now()
      val = (msgtime, question_id, 'p',msg)
      mycursor.execute(sql, val)
      mydb.commit()
      flash("Thanks for submitting, we well contact you as soon as possible!")            
   return render_template("contactus.html")
Exemple #23
0
def upcoming_app():
    mydb.commit()
    now = datetime.datetime.now()
    if session['msg'] == 'A':
        sql = 'SELECT * FROM Patients AS T1 JOIN ( SELECT a.id , bookedTime, drID,patID, d.ID AS d_id , Name AS dname, Birthday AS dbday , Email AS demail , Phone AS dphone FROM Appointments AS a JOIN Doctors AS d on drID = d.ID WHERE bookedTime >= %s ) AS T2 ON T1.ID = T2.patID'
        val = (now, )
        # mycursor.close()
    elif session['msg'] == 'p':
        sql = 'SELECT a.id , bookedTime, drID ,patID, name AS dname FROM Appointments AS a JOIN Doctors on a.drID = Doctors.ID WHERE bookedTime >= %s AND patID = %s'
        val = (now, session['u_id'])
        # print("HHHHHHHHHHHH")
        # mycursor.close()
    else:
        sql = 'SELECT * FROM Appointments JOIN Patients on Appointments.patID = Patients.ID WHERE bookedTime >= %s AND drID = %s'
        val = (now, session['u_id'])
        # mycursor.close()
    mycursor.execute(sql, val)
    data = mycursor.fetchall()
    # print(data)
    return render_template("upcoming_appointments.html", data=data)
Exemple #24
0
def add_cal():
    if request.method == 'POST':
        doctor_id = request.form['drID']
        mycursor.execute("SELECT * From Calendars")
        c = mycursor.fetchall()
        if c:
            flash("Dr Already has a calendar , Remove the calendar first")
            return render_template("calendar.html")
        mycursor.execute("SELECT Email FROM Doctors WHERE ID ='%s'" %
                         (doctor_id))
        doctor_email = mycursor.fetchone()
        ID = g_api.create_calendar("Cardiology Department", "Africa/Cairo")
        g_api.give_access(ID, doctor_email['Email'])
        sql = "INSERT INTO Calendars (c_id,drID) VALUES (%s,%s)"
        val = (ID, doctor_id)
        print(val)
        mycursor.execute(sql, val)
        mydb.commit()
        flash("Calendar is aded Successfully!")
    return render_template("calendar.html")
Exemple #25
0
def register():

    tipo_usuario = request.form['tipo_usuario']
    username = request.form['username']
    email = request.form['email']
    telefono = request.form['telefono']

    password = request.form['password']
    password2 = request.form['password2']

    nombre = request.form['nombre']
    apellido_paterno = request.form['apellido_paterno']
    apellido_materno = request.form['apellido_materno']
    sexo = request.form['sexo']
    fecha_nacimiento = request.form['fecha_nacimiento']

    #Validar campos vacios
    if tipo_usuario == "1":
        if apellido_materno is None or apellido_materno is None:
            return render_template('register.html',
                                   mensaje="Algun campo está vacío")
        if sexo is None or fecha_nacimiento is None:
            return render_template('register.html',
                                   mensaje="Algun campo está vacío")

    #Validar que las cont coincidan
    if password != password2:
        return render_template('register.html',
                               mensaje="Las contraseñas no coinciden")

    #Validar que no exisa usuario ni correo
    cursor = mydb.cursor()
    cursor.execute('SELECT username FROM Usuario WHERE UserName = "******"' %
                   username)
    result = cursor.fetchone()

    if result is not None:
        return render_template('register.html', mensaje="usuario existente")

    cursor.execute('SELECT Email FROM Usuario WHERE Email = "%s"' % email)
    result = cursor.fetchone()

    if result is not None:
        return render_template('register.html', mensaje="correo existente")

    #REGISTRO DEL USUARIO#
    sentence = 'INSERT INTO Usuario(UserName,TipoUsuario,HashPassword,Email,Telefono,Admin) VALUES (%s,%s,%s,%s,%s,FALSE)'
    variables = (username, tipo_usuario, password, email, telefono)
    cursor.execute(sentence, variables)
    mydb.commit()

    #EXTRACCION DEL NUEVO ID#
    cursor.execute('SELECT idUsuario FROM Usuario WHERE UserName = "******"' %
                   username)
    result = cursor.fetchone()

    if tipo_usuario == "1":
        sentence = 'INSERT INTO Persona(Nombre,ApellidoPaterno,ApellidoMaterno,IdUsuario,Sexo,FechaNacimiento) VALUES (%s,%s,%s,%s,%s,%s)'
        variables = (nombre, apellido_paterno, apellido_materno, result[0],
                     sexo, fecha_nacimiento)
    else:
        sentence = 'INSERT INTO Empresa(Nombre, IdUsuario) VALUES (%s,%s)'
        variables = (nombre, result[0])

    cursor.execute(sentence, variables)
    mydb.commit()
    session['logged_in'] = True
    return home()
Exemple #26
0
def register():

   #check if user submitted form (POST)
   if request.method == 'POST':
         firstName = request.form['fname']
         lastName = request.form['lname']
         ssn = request.form['ssn']
         job = request.form['job']
         bdate = request.form['dob']
         sex = request.form['gender']
         bloodType = request.form['bt']
         weight = request.form['weight']
         phone = request.form['phone']
         hyperTension = convert('hyperTension' in request.form)
         ht_controlled = convert('ht_controlled' in request.form)
         diabetes = convert('diabetes' in request.form)
         diabetes_control = convert('dcontrol' in request.form)
         heartstroke = convert('heartstroke' in request.form)
         cholesterol = convert('ch' in request.form)
         email = request.form['email']
         password = request.form['pw'] 
         today = time.strftime('%Y-%m-%d')
         #check if account exists already
         sql = 'SELECT * FROM Patients WHERE email = %s'
         val = (email,)
         mycursor.execute(sql, val)
         # Fetch user's record
         account = mycursor.fetchone()
         # If account exists show error and validation checks
         if account:
            flash('Account already exists!')
            return render_template('SignIn_p.html')
         elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
            flash('Invalid email address!')
            return render_template('Test_home.html')
         elif not email or not password or not firstName or not ssn or not bloodType:
            flash('Fill out the Registration Form!')
            return render_template('Test_home.html')
         else:
            format_str = '%d/%m/%Y' # The format
            bday_datetime = datetime.strptime(bdate, format_str)
            #registration succed, create patient account
            Name = firstName + " " + lastName
            sql_ ='INSERT INTO Patients (Name,Birthday, Job, Email, Password, Phone, Gender, SSN , BloodType,Weight,Hypertension,ControlledHypertension,Diabetic,ControlledDiabetes,HeartStroke,Cholesterol, Join_date) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'
            val_ = (Name,bday_datetime,job,email,password,phone,sex,ssn,bloodType,weight,hyperTension,ht_controlled,diabetes,diabetes_control,heartstroke,cholesterol,today)
            mycursor.execute(sql_ , val_)
            mydb.commit()
            sql = 'SELECT id FROM Patients WHERE Email = %s AND Password = %s'
            val = (email, password)
            mycursor.execute(sql, val)
            # Fetch user's record
            account = mycursor.fetchone()
            session['loggedin'] = True
            session['user'] = Name
            session['u_id'] = account['id']
            session['email'] = email
            session['msg']='p'
            flash(f"you have been Registered successfully!,{Name}")
            return redirect(url_for('patient.patientDash'))
   else:
      return render_template('SignUp.html')
Exemple #27
0
def book():
    mycursor = mydb.cursor(dictionary=True, buffered=True)
    mycursor.execute("SELECT * FROM Doctors")
    myresult = mycursor.fetchall()
    number_of_doctors = len(myresult)
    id_1_l = math.ceil((number_of_doctors / 2))

    if request.method == 'POST':
        selected_data = request.form['doctor']
        selected_date = request.form['date']  #in mm/dd/yyy
        selected_hour = request.form['hour']
        p_id = request.form['p_id']
        #check if date or time is empty
        if (not request.form['date']) or request.form['hour'] == 'Select Time':
            # print("jjj"))
            flash(
                "please select a date, a time and a doctor/Not Specific Doctor "
            )
            return render_template("p_book_appointment.html",
                                   doctorsData=myresult,
                                   id_1_l=id_1_l)

        #get the values we need
        if selected_data != 'Not Specific Doctor':
            doctor_id, selected_doctor = selected_data.split('-')
        else:
            doctor_id = random.randint(1, number_of_doctors)

        #get the values we need
        format_str = '%m/%d/%Y'  # The format
        date_datetime = datetime.strptime(selected_date, format_str).date()
        time_datetime = datetime.strptime(selected_hour, '%H:%M').time()
        bookedTime = datetime.combine(date_datetime, time_datetime)
        #check if the time is booked already in doctor's schedule
        sql = 'SELECT * FROM Appointments WHERE drID = %s AND bookedTime = %s'
        val = (doctor_id, bookedTime)
        mycursor.execute(sql, val)
        # Fetch user's record
        account = mycursor.fetchall()
        # If account exists show error and validation checks
        if account:
            flash('Doctor is not available in this time, choose another time!')
            return render_template("p_book_appointment.html",
                                   doctorsData=myresult,
                                   id_1_l=id_1_l)
        # Nothing wrong with booking, insertingappointment details
        id = session["u_id"]
        sql = "INSERT INTO Appointments (drID,bookedTime, patID) VALUES (%s, %s, %s)"
        val = (doctor_id, bookedTime, p_id)
        # print(val)
        mycursor.execute(sql, val)
        mydb.commit()
        # mycursor.close()
        flash("Appointment is Booked Successfully!")

        #Synchronize with doctor's calendar
        #getting appointment id to add in events table
        sql = "SELECT id FROM Appointments WHERE drID =%s AND bookedTime =%s"
        val = (doctor_id, bookedTime)
        mycursor.execute(sql, val)
        a_id = mycursor.fetchone()
        #getting dr data
        doctor = next(
            (doctor for doctor in myresult if doctor['ID'] == int(doctor_id)),
            False)
        doctor_email = doctor['Email']
        doctor_id = int(doctor_id)
        sql = "SELECT * FROM Calendars WHERE drID = %s"
        mycursor.execute(sql, (doctor_id, ))
        dr_cal = mycursor.fetchall()
        print(dr_cal)
        if not dr_cal:
            ID = g_api.create_calendar("Cardiology Department", "Africa/Cairo")
            g_api.give_access(ID, doctor_email)
            sql = "INSERT INTO Calendars (c_id,drID) VALUES (%s,%s)"
            val = (ID, doctor_id)
            print(val)
            mycursor.execute(sql, val)
            mydb.commit()
            mycursor.execute("SELECT * FROM Calendars WHERE drID = '%s'" %
                             (doctor_id))
            dr_cal = mycursor.fetchone()
        event_id = g_api.create_event(bookedTime, dr_cal['c_id'])
        #insert event into Events table
        sql = "INSERT INTO Events (e_id,cal_id,a_id) VALUES (%s,%s,%s)"
        val = (event_id, dr_cal['c_id'], a_id['id'])
        mycursor.execute(sql, val)
        mydb.commit()
        print("EVENT CREATED")
        return render_template("p_book_appointment.html",
                               doctorsData=myresult,
                               id_1_l=id_1_l)
    else:
        return render_template("p_book_appointment.html",
                               doctorsData=myresult,
                               id_1_l=id_1_l)