def register():
    if session.get('name'):
        return redirect(url_for('index'))
    form = CreateCustomer()
    if form.validate_on_submit():

        ssnid = form.ssnid.data
        name = form.name.data
        age = form.age.data
        dateofadmit = form.dateofadmit.data
        typeofbed = form.typeofbed.data
        address = form.address.data
        city = form.city.data
        state = form.state.data

        patient = Patient(ssnid=ssnid,
                          name=name,
                          age=age,
                          dateofadmit=dateofadmit,
                          typeofbed=typeofbed,
                          address=address,
                          city=city,
                          state=state)
        patient.save()
        flash("You are successfully registered!", "success")
        return redirect(url_for('admin'))
    return render_template("register.html",
                           title="Register",
                           form=form,
                           register=True)
Beispiel #2
0
def add_patient():
    logged_in=True  #you are logged in (logged_in=True)
    title = "Add Patient"

    form = AddingPatientForm()

    if form.validate_on_submit():
        #get the new patient's credentials
        newPatientName             = form.name.data
        newPatientSurname          = form.surname.data
        NewPatientPhoneNumber      = form.phone_number.data
        NewPatientAddress          = form.address.data
        NewPatientClinic           = form.clinic.data
        NewPatientRegistrationDate = form.registrationDate.data
        newPatientEmail            = form.email.data   #WILL USE LATER
        
        #create a new patient object and save it to the database
        newPatient = Patient(name = newPatientName, surname = newPatientSurname, 
        phone_number = NewPatientPhoneNumber, address = NewPatientAddress,
        clinic = NewPatientClinic, registrationDate = NewPatientRegistrationDate)

        #save the new patient object to the database
        newPatient.save()

        flash(f"{newPatientName} has been successfully registered." , "success")

        return redirect("/patients")

    return render_template("add_patient.html", form=form, add_patient=True, title=title, logged_in=logged_in)
def fetch_To_delete():
    if session.get('username'):
        if session.get('usertype') == "rde":
            patientData = {}
            patientid = request.args.get("patientid")
            if patientid:
                cursor.execute(
                    """SELECT (`*`) FROM `patient` WHERE `ws_ssn` LIKE '{}' """
                    .format(patientid))
                patientData = cursor.fetchone()
                #Splitting the address in to Street State and City
                getCompleteAddress = patientData[4].__str__()
                splittedAddress = getCompleteAddress.split(" , ", 2)
                street = splittedAddress[0]
                State = splittedAddress[1]
                city = splittedAddress[2]
                patient = Patient(patientData[0], patientData[2],
                                  patientData[3], patientData[6], street,
                                  State, city)
            else:
                flash("No patient found")
                return redirect("/update_patient")
            form = ShowPatient(obj=patient)
            form.populate_obj(patient)
            if form.validate_on_submit():
                cursor.execute(
                    "DELETE FROM `patient` WHERE `ws_ssn` LIKE '{}' "
                    "".format(patientid))
                conn.commit()
                flash("Patient Deleted Successfully")
                return redirect("/create_patient")
            return render_template("delete_patient.html", form=form)

    return redirect("/login")
Beispiel #4
0
def create():
    form = CreateForm()

    if request.method == 'POST' and form.validate_on_submit():
        result = Patient.query.filter_by(pid=form.pid.data).first()
        if result:
            flash('Patient already exists!', 'danger')
            return redirect(url_for('create'))
        else:
            autopid = ''.join(secrets.choice(string.digits) for i in range(N))
            x = datetime.datetime.strptime(request.form.get('doa'), '%Y-%m-%d')
            newp = Patient(autopid=autopid,
                           pid=request.form.get('pid'),
                           name=request.form.get('name'),
                           age=request.form.get('age'),
                           doa=x.date(),
                           tob=request.form.get('tob'),
                           address=request.form.get('address'),
                           state=request.form.get('state'),
                           city=request.form.get('city'),
                           status='Active')
            db.session.add(newp)
            db.session.commit()
            flash('Patient creation initiated successfully', 'success')
            return redirect(url_for('create'))
    return render_template('create.html', title='CREATE PATIENT', form=form)
def register():
    if (session.get("email")):
        if (session.get("accesslevel") == 1):
            form = Register()
            if request.method == "POST":
                Patient_SSN_ID = request.form['patient_ssn_id']
                Patient_Name = request.form['name']
                Patient_Age = request.form['age']
                Date_of_Admission = datetime.strptime(request.form.get("date"),
                                                      '%Y-%m-%dT%H:%M')
                Date_of_Admission.strftime("%Y-%m-%d %H:%M:%S")

                Type_of_Bed = request.form['type']
                Address = request.form['address']
                State = request.form['state']
                City = request.form['city']
                count = len(Patient.query.all())
                print(Patient.query.column_descriptions)
                initial = 100000000  #The inital value of the patient ID is set to this to maintain the 9 digit requiment.
                Patient_ID = initial + count
                patient_status = "Active"
                if (int(Patient_Age) >= 1000):
                    flash(
                        "The age is too large, please cross check", "danger"
                    )  #Flash is used to print messages to the user on the screen.
                    return render_template("register.html",
                                           patient=True,
                                           form=form,
                                           loggedin=session.get('email'))
                #The below lines contains the Patient Class which is associated to the patient_details table. Each table has an associated class in the models.py folder.
                reg = Patient(patient_id=Patient_ID,
                              patient_ssn=Patient_SSN_ID,
                              patient_name=Patient_Name,
                              patient_age=Patient_Age,
                              patient_doj=Date_of_Admission,
                              patient_rtype=Type_of_Bed,
                              patient_address=Address,
                              patient_state=State,
                              patient_city=City,
                              patient_status=patient_status)

                db.session.add(reg)
                db.session.commit()
                #return render_template("success.html")
                flash("Registeration Success", "success")
            return render_template("register.html",
                                   patient=True,
                                   form=form,
                                   loggedin=session.get('email'))
        else:
            #The accesslevel is not enough to view the page,returned back to home page.
            flash(
                "Sorry! You don't have the required permission to view this page,contact administrator",
                'danger')
            return redirect("/")
    else:
        flash("Looks like you are not logged in! Please log in", "danger")
        return redirect("/login")
Beispiel #6
0
def create_patient():
    if 'user_id' in session and session['user_type'] == 'E':
        form = RegisterationForm()
        if form.validate_on_submit():
            # Assumption that same person with same id is not registered
            ssn = form.patient_ssn.data
            name = form.patient_name.data
            age = form.age.data
            doa = form.doa.data
            bed = form.bed_type.data
            address = form.address.data
            state = form.state.data
            city = form.city.data
            sql = text(
                "SELECT patient_ssn, status FROM patients WHERE patient_ssn = :x "
            )
            rslt = db.engine.execute(sql, x=ssn)
            items = [row[1] for row in rslt]
            if not len(items) or items[0] == 'INACTIVE':
                flash('Patient creation initiated successfully', 'success')
                if items[
                        0] == 'INACTIVE':  # This ensures that only one entry exists per patient
                    Patient.query.filter_by(patient_ssn=ssn).update(
                        dict(patient_name=name,
                             age=age,
                             admission_date=doa,
                             bed_type=bed,
                             address=address,
                             city=city,
                             state=state,
                             status="ACTIVE"))
                else:
                    db.session.add(
                        Patient(patient_ssn=ssn,
                                patient_name=name,
                                age=age,
                                admission_date=doa,
                                bed_type=bed,
                                address=address,
                                city=city,
                                state=state,
                                status="ACTIVE"))
                db.session.commit()
                return redirect(url_for('create_patient'))
            else:
                flash("SSN ID already exists", 'danger')
        return render_template('create_patient.html',
                               form=form,
                               title='Patient Registeration')
    else:
        flash('You are not logged in ', 'danger')
        return redirect(url_for('login'))
Beispiel #7
0
def search_patient():
    logged_in     = True
    patientName   = request.args.get('patientName')
    patientsFound = Patient.objects(name=patientName).all() #get list of patients with given name

    if patientsFound:
        atLeastOnePatientFound = True
        numberOfPatientsFound  = patientsFound.count() #get number of patients found
        flash(f"{numberOfPatientsFound} patient(s) found.", "success")
    else:
        atLeastOnePatientFound = False
        flash("Patient could not be found.", "warning")
        return redirect("/patients")

    return render_template("patients.html", patients=True,
    numberOfPatientsFound=numberOfPatientsFound, patientsFound=patientsFound,
    atLeastOnePatientFound=atLeastOnePatientFound)
def fetch_to_update():
    if session.get('username'):
        if session.get('usertype') == "rde":
            patientData = {}
            patientid = request.args.get("patientid")
            if patientid:
                cursor.execute(
                    """SELECT (`*`) FROM `patient` WHERE `ws_ssn` LIKE '{}' """
                    .format(patientid))
                patientData = cursor.fetchone()
                #Splitting the address in to Street State and City
                getCompleteAddress = patientData[4].__str__()
                splittedAddress = getCompleteAddress.split(" , ", 2)
                street = splittedAddress[0]
                State = splittedAddress[1]
                city = splittedAddress[2]
                #completeAddress = street +" , "+State+" , "+city
                patient = Patient(patientData[0], patientData[2],
                                  patientData[3], patientData[6], street,
                                  State, city)
            else:
                flash("No patient found")
                return redirect("/update_patient")
            form = UpdatePatient(obj=patient)
            form.populate_obj(patient)
            if form.validate_on_submit():
                ssn = form.patientid.data
                name = form.patient_name.data
                age = form.patient_age.data
                bed = form.bed_type.data
                addrs = form.address.data
                state = form.state.data
                city = form.city.data
                adrs = addrs + " , " + city + " , " + state
                cursor.execute(
                    "UPDATE patient SET ws_pat_name = %s, ws_adrs = %s, ws_age = %s, ws_rtype = %s where ws_ssn = %s",
                    (name, adrs, age, bed, ssn))
                conn.commit()
                flash("Patient Detail Updated")
                return redirect("/create_patient")
            return render_template("update_patient.html", form=form)
    return redirect("/login")
Beispiel #9
0
def pat_create():
    if not (current_user.is_authenticated
            and current_user.user_login_id == 'reception'):
        return redirect(url_for('home'))
    form = PatCreateForm()

    # selecting all states in D.B
    form.state.choices = [(state.stateid, state.statename)
                          for state in State.query.all()]

    # valiating and checking if Request is POST
    if form.validate_on_submit():

        # Querying through the table to find match with 'ws_ssn'
        pat = Patient.query.filter_by(ws_ssn=form.ws_ssn.data).first()
        if pat:
            flash('Sorry that SSN ID already exists', 'danger')
        else:
            # 'ws_pat_id' is not added since its auto generated by the table
            statedata = State.query.filter_by(stateid=form.state.data).first()
            # print(form.city.data) None
            entry = Patient(ws_ssn=form.ws_ssn.data,
                            ws_pat_name=form.ws_pat_name.data,
                            ws_age=form.ws_age.data,
                            ws_doj=form.ws_doj.data,
                            ws_rtype=form.ws_rtype.data,
                            ws_adrs=form.ws_adrs.data,
                            patient_state=statedata.statename,
                            patient_city=form.city.data,
                            patient_status='Active')
            db.session.add(entry)
            db.session.commit()
            flash('Patient creation initiated successfully', 'success')
            return redirect(url_for('home'))

    return render_template("pat_create.html",
                           reception=True,
                           pat_create=True,
                           title="Create Patient",
                           form=form)
def generate_bille():
    if session.get('username'):
        if session.get('usertype') == "rde":
            patientData = {}
            med_detail = {}
            diag_detail = {}
            todaysDate = datetime.now().strftime("%m/%d/%Y")
            totalRoomCost = 0
            doj = 0
            patientid = request.args.get("patientid")
            if patientid:
                cursor.execute(
                    """SELECT (`*`) FROM `patient` WHERE `ws_pat_id` LIKE '{}' """
                    .format(patientid))
                patientData = cursor.fetchone()
                cursor.execute(
                    """SELECT track_medicine.ws_qty, master_med_file.ws_med_name,master_med_file.ws_rate FROM `master_med_file` INNER JOIN `track_medicine` ON master_med_file.ws_med_id=track_medicine.ws_med_id WHERE track_medicine.ws_pat_id LIKE '{}'"""
                    .format(patientid))
                med_detail = cursor.fetchall()

                cursor.execute(
                    """SELECT diag_master_file.ws_test_rate,diag_master_file.ws_test_name FROM `diag_master_file` INNER JOIN `track_diag` ON diag_master_file.ws_test_id=track_diag.ws_test_id WHERE track_diag.ws_pat_id LIKE '{}'"""
                    .format(patientid))

                diag_detail = cursor.fetchall()

                totalMed = 0
                totalDiag = 0

                for med in med_detail:
                    totalMed += (int(med[2]) * int(med[0]))

                for diag in diag_detail:
                    totalDiag += (int(diag[0]))

                #Splitting the address in to Street State and City
                getCompleteAddress = patientData[4].__str__()
                splittedAddress = getCompleteAddress.split(" , ", 2)
                street = splittedAddress[0]
                State = splittedAddress[1]
                city = splittedAddress[2]
                patient = Patient(patientData[0], patientData[2],
                                  patientData[3], patientData[6], street,
                                  State, city)
            else:
                flash("No patient found")
                return redirect("/generate_bill")
            form = ConfirmBill()
            if form.validate_on_submit():
                cursor.execute(
                    "UPDATE `patient` SET `ws_status`='{}' WHERE `ws_pat_id` LIKE '{}'"
                    "".format("Discharged", patientid))
                conn.commit()
                flash("Patient Discharged")
                return redirect("/view_patient")
        #calculate how many days patient stayed
            doj = patientData[5].__str__()
            doj = doj[0:10]
            doj = doj.split("-", 2)
            dojy = int(doj[0])
            dojm = int(doj[1])
            dojd = int(doj[2])
            totalDays = datetime.today() - datetime(dojy, dojm, dojd)
            totalDays = totalDays.__str__()
            totalDays = totalDays[:2]
            totalDays = int(totalDays)

            totalRoomCost = getRoomPrice(patientData[6]) * int(totalDays)

            grandTotal = totalMed + totalDiag + totalRoomCost
            return render_template("patient_bill.html",
                                   patientData=patientData,
                                   totalDays=totalDays,
                                   todaysDate=todaysDate,
                                   totalRoomCost=totalRoomCost,
                                   roomPrice=getRoomPrice(patientData[6]),
                                   med_detail=med_detail,
                                   diag_detail=diag_detail,
                                   totalMed=totalMed,
                                   totalDiag=totalDiag,
                                   grandTotal=grandTotal,
                                   form=form)
    return redirect("/login")
Beispiel #11
0
def calendarEvents(arg):
    try:
        user = ''
        if current_user.is_authenticated:
            user = current_user.practice_uuid
        id = request.args.get('id')
        patient_id = request.args.get('patient_id')
        title = request.args.get('title')
        description = request.args.get('description')
        color = request.args.get('color')
        start = request.args.get('start')
        end = request.args.get('end')
        if arg == 'retrieve':
            _CalendarEntries = db.session.query(Calendar).\
                    filter(Calendar.practice_uuid == user,
                            Calendar.start >= start,
                            Calendar.end <= end).\
                                    all()
            return jsonify(_CalendarEntries)
        if arg=='add':
            if(patient_id == 'new'):
                _NewPatient = Patient(practice_uuid=user,
                        patient_name=title,
                        medical_aid=request.args.get('medical_aid'),
                        main_member=request.args.get('main_member') or None,
                        patient_birth_date=request.args.get('patient_dob') or None,
                        medical_number=request.args.get('medical_number') or None,
                        case_number=request.args.get('case_number') or None)
                patient_id = _NewPatient.patient_id
                db.session.add(_NewPatient)
            _AddNewAppointment = Calendar(practice_uuid=user,
                    title=title,
                    description=description,
                    patient_id = patient_id,
                    start=datetime.fromisoformat(start),
                    end=datetime.fromisoformat(end),
                    color=color)
            db.session.add(_AddNewAppointment)
            db.session.commit()
            return jsonify(_AddNewAppointment.id)
        if arg == 'detail':
            _CalendarEntries = db.session.query(Calendar).\
                    filter(Calendar.practice_uuid == user,
                            Calendar.id == id).\
                                    all()
            return jsonify(_CalendarEntries)
        if arg == 'update':
            db.session.query(Calendar).\
                    filter(Calendar.id == id).\
                    update({Calendar.start:datetime.fromisoformat(start),
                        Calendar.end:datetime.fromisoformat(end)})
            db.session.commit()
            return jsonify("success")
        if arg == 'delete':
            db.session.query(Calendar).\
                    filter(Calendar.id == id).\
                    delete()
            db.session.commit()
            return jsonify("success")
    except Exception as ex:
        template = "An exception of type {0} occurred. Arguments:\n{1!r}"
        errorMessage = template.format(type(ex).__name__, ex.args)
        return jsonify(errorMessage), 500