Пример #1
0
    def dispense_drug_patient (self, message, first, last, gender, age, code, quantity):

        age     = Patient.age_from_str(age)
        gender  = Patient.SEXE_MALE if gender.upper() == 'M' else Patient.SEXE_FEMALE
        receiver= Patient(first_name=first, last_name=last, sexe=gender,age=age)
        receiver.save()
        sender      = StoreProvider.cls().by_mobile(message.peer)
        item        = Item.by_code(code)

        if item == None or sender == None or receiver == None:
            message.respond(_(u"Dispense request failed. Either Item ID or Patient datas are wrong."))
            return True

        try:
            log = transfer_item(sender=sender, receiver=receiver, item=item, quantity=int(quantity))
        except ItemNotInStore:
            message.respond(_(u"Dispense request failed. You do not have %(med)s") % {'med': item})
            return True
        except NotEnoughItemInStock:
            message.respond(_(u"Dispense request failed. You can't dispense %(q)s %(it)s to %(rec)s because you only have %(stk)s.") % {'q': quantity, 'it': item.name, 'rec': receiver.display_full(), 'stk': StockItem.objects.get(peer=sender, item=item).quantity})
            return True

        message.respond("CONFIRMATION #%(d)s-%(sid)s-%(rid)s-%(lid)s You have dispensed %(quantity)s %(item)s to %(receiver)s. If not correct please reply: CANCEL %(lid)s" % {
            'quantity': quantity,
            'item': item.name,
            'receiver': receiver.display_full(),
            'd': log.date.strftime("%d%m%y"),
            'sid': sender.id,
            'rid': receiver.id,
            'lid': log.id
        })
        return True
Пример #2
0
def signup(request):
    """
    Sign Up Page, uses built in Sign-Up
    """
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            name = form.cleaned_data.get('name')
            category = form.cleaned_data.get('category')
            user = authenticate(username=username, password=raw_password)
            if category == "doctor":
                doctor = Doctor(user=user, name=name)
                doctor.save()
            if category == "pharmacist":
                pharmacist = Pharmacist(user=user, name=name)
                pharmacist.save()
            if category == "patient":
                patient = Patient(user=user, name=name)
                patient.save()
            login(request, user)
            return redirect('/pharm/profile')
    else:
        form = SignUpForm()
    return render(request, 'pharmeasyflow/signup.html', {'form': form})
Пример #3
0
def patients():
    query = Patient.query.join(Department.patients).filter(
        Department.department_name == request.cookies.get('department', 'default'))

    if request.method == "GET":
        offset = int(request.args.get('offset', 0))
        limit = int(request.args.get('limit', 100))

        return make_response((json.dumps([
            p.serialize() for p in query
            .order_by(desc(Patient.latest_checkin_time))
            .offset(offset)
            .limit(limit)
            .all()
        ]), 200, {"Content-Type": "application/json"}))

    elif request.method == "POST":
        patient_data = json.loads(request.data)
        patient = Patient(**patient_data)
        patient = db.merge(patient)
        db.commit()

        department = Department.query.filter_by(
            department_name=request.cookies.get('department', 'default')).first()

        if department:
            patient.departments.append(department)

        db.commit()

        if 'checkin' in patient_data:
            add_checkin(patient.nhi, patient_data['checkin'])

        return jsonify(patient.serialize())
Пример #4
0
def add_patient(patient_id):
    from forms import PatientForm
    if patient_id:
        id = int(patient_id.replace('P00', '').replace(
            'P0', '').replace('P', ''))
        patient = Patient.query.get(id)
    else:
        patient = Patient()
    form = PatientForm(obj=patient)
    if form.validate_on_submit():
        if 'photo' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['photo']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = uuid.uuid4().hex+'.' + \
                secure_filename(file.filename).split('.')[-1].lower()
            form.photo.data.save(os.path.join(
                app.config['UPLOAD_FOLDER'], 'patients', filename))
            form.populate_obj(patient)
            patient.photo = filename
            patient.gender = Gender(form.gender.data)
            db.session.add(patient)
            db.session.commit()
            url = url_for('patient_profile', patient_id=repr(patient))
            flash(
                'Patient saved with ID: {}, <a href="{}">view patient profile</a>'.format(repr(patient), url))
        return redirect(url_for('add_patient'))
    return render_template('add-patient.html', form=form)
Пример #5
0
def add_patient(request):
    if request.method == 'POST':
        print request.POST
        firstname = request.POST.get('firstname')
        print firstname
        lastname = request.POST.get('lastname')
        age = request.POST.get('age')
        dob = request.POST.get('dob')
        gender = request.POST.get('gender')
        phone = request.POST.get('phone')
        description = request.POST.get('description')
        response_data = {}

        patient = Patient(firstname=firstname,
                          lastname=lastname,
                          age=age,
                          dob=dob,
                          gender=gender,
                          phone=phone,
                          description=description)
        patient.save()

        response_data['result'] = 'Data stored successfully!'
        return HttpResponse(json.dumps(response_data),
                            content_type="application/json")
    else:
        return HttpResponse(json.dumps(
            {"nothing to see": "this isn't happening"}),
                            content_type="application/json")
Пример #6
0
 def clean(self, request):
     self.cleaned_data = {}
     if 'Add' in request.POST:
         for fieldname in self.fields:
             if self.fields[fieldname].required and fieldname not in request.POST:
                 messages.error(request, u'Для добавления нужно дополнить данные')
                 self.patients = Patient.objects.all()
                 return False
             else:
                 if fieldname in request.POST:
                     self.cleaned_data[fieldname] = request.POST[fieldname]
         try:
             bd = datetime.strptime(self.cleaned_data['birthdate'], '%Y-%m-%d').date()
         except:
             self.patients = Patient.objects.all()
             return False
         user = User.objects.create_user(username=self.cleaned_data['polis_number'])
         user.set_password(self.cleaned_data['password'])
         user.groups = Group.objects.filter(id=3)
         user.save()
         p = Patient(fio=self.cleaned_data['fio'], birthdate=bd,
                     address=self.cleaned_data['address'], phone_number=int(self.cleaned_data['phone_number']),
                     area=Area.objects.get(number=self.cleaned_data['area']),
                     polis_number=self.cleaned_data['polis_number'], user=user, password=self.cleaned_data['password'])
         p.save()
         messages.info(request, u'Пациент добавлен')
         self.patients = Patient.objects.all()
     self.patients = Patient.objects.all()
     return True
Пример #7
0
def create_patient():
    patient_data = json.loads(request.data)

    doctor = Doctor.query.get(patient_data['doctor_id'])
    if not doctor:
        return jsonify({
            "success": False,
            "description": "doctor id not found"
        }), 404

    patient = Patient(
        name=patient_data["name"],
        age=patient_data["age"],
        address=patient_data["address"],
        email=patient_data["email"],
        examine_report=patient_data["examine_report"],
    )
    patient.doctor = doctor
    try:
        patient.insert()
    except IntegrityError as err:
        print(err)
        return jsonify({
            "success": False,
            "description": "there is patient with the same email"
        }), 200
    except Exception as err:
        # print(err)
        return jsonify({"success": False, "error": str(err)}), 500

    return jsonify({
        "success": True,
        "patient": Patient.query.get(patient.id).format()
    }), 200
Пример #8
0
def patient_all():
    if request.method == "GET":
        records = Patient.select()
        return template("index.html", items=records)

    elif request.method == "POST":
        json = request.POST

        # check to see if request has provided all necessary values to create object
        #

        name = json["pname"]
        surname = json["surname"]
        dob = json["dob"]
        gp = GP[app.config["user_id"]]
        status = True
        city = json["city"]
        district = json["district"]

        address = Address(cityName=city,
                          districtName=district,
                          districtCode="fix this")

        patient = Patient(name=name,
                          sex="fix this",
                          dob=dob,
                          address=address,
                          gp=gp,
                          status=status)
        #save progress
        db.commit()

        #redirect to the newly created patient's page
        redirect("/patient/{}".format(patient.id))

    elif request.method == "DELETE":

        patient_id = request.POST.id.strip()
        try:
            patient = Patient[patient_id]
        except:
            return "Patient does not exist"
        patient.delete()

    elif request.method == "PUT":
        json = request.POST
        update = json["update"]
        value = json["value"]
        id = json["id"]
        with db_session():
            try:
                patient = Patient[id]
            except:
                return {"message": 'patient not found'}
            setattr(patient, update, value)
            return {"message": "patient updated"}
    return {"message": "missing token"}
Пример #9
0
    def _parse_patients(self, records):
        if not isinstance(records, list):
            name, patient_id, patronymic, surname, gender, birth_date, mobile_number, place, address = records
            return Patient(name, patient_id, patronymic, surname, gender,
                           birth_date, mobile_number, place, address)

        for i in range(len(records)):
            name, patient_id, patronymic, surname, gender, birth_date, mobile_number, place, address = records[
                i]
            records[i] = Patient(name, patient_id, patronymic, surname, gender,
                                 birth_date, mobile_number, place, address)
        return records
Пример #10
0
def drop_all_data(session):
    from models import Patient, Encounter, Observation, Procedure

    Patient.clear_all_records(session)
    Encounter.clear_all_records(session)
    Observation.clear_all_records(session)
    Procedure.clear_all_records(session)

    session.execute(f"DROP INDEX IF EXISTS {Patient.SRC_INDEX}")
    session.execute(f"DROP INDEX IF EXISTS {Encounter.SRC_INDEX}")

    session.commit()
Пример #11
0
    def test_descriptors(self):
        with self.assertRaises(ValueError):
            patient = Patient(mobile='07894565434581')

        with self.assertRaises(TypeError):
            patient = Patient(id='Nathan')

        with self.assertRaises(TypeError):
            patient = Patient(name=1000)

        with self.assertRaises(ValueError):
            patient = Patient(name='Abiira Nathan of Uganda')
Пример #12
0
 def add_patient(self, ccd_file, pref_email):
     #Because of a chicken-egg problem, we need to write the CCDA to disk then have bluebutton parse it before we can
     #pass it to a model
     with NamedTemporaryFile(delete=False) as xml_file:
         for chunk in ccd_file.chunks():
             xml_file.write(chunk)
     ccda = parse_ccda(xml_file.name)
     new_user = User.objects.create_user(pref_email, pref_email, 'password')
     new_user.first_name = ccda['demographics']['name']['given'][0]
     new_user.last_name = ccda['demographics']['name']['family']
     new_user.save()
     new_patient = Patient(user=new_user, chart=ccd_file)
     new_patient.save()
Пример #13
0
 def add_patient(self, ccd_file, pref_email):
     #Because of a chicken-egg problem, we need to write the CCDA to disk then have bluebutton parse it before we can
     #pass it to a model
     with NamedTemporaryFile(delete=False) as xml_file:
         for chunk in ccd_file.chunks():
             xml_file.write(chunk)
     ccda = parse_ccda(xml_file.name)
     new_user = User.objects.create_user(pref_email, pref_email, 'password')
     new_user.first_name = ccda['demographics']['name']['given'][0]
     new_user.last_name = ccda['demographics']['name']['family']
     new_user.save()
     new_patient = Patient(user=new_user, chart=ccd_file)
     new_patient.save()
Пример #14
0
def create_patient():
    content = request.get_json(silent=True)
    session = DBSession()
    session.expire_on_commit = False
    patient = Patient()
    if content and ("mac_address" in content):
        patient.mac_address = content["mac_address"].upper()
    stmt = session.add(patient)
    print(patient.id)
    session.commit()
    id = patient.id
    print(patient.id)
    session.close()
    return jsonify(patient.id)
Пример #15
0
def test_patients(_db):
    # json, create & update time
    now = datetime.datetime.utcnow()
    pat = Patient.from_json({
        "firstName": "Rick",
        "lastName": "Deckard",
        "dateOfBirth": "2094-02-01",
        "externalId": "5"
    })
    assert pat.id is None
    _db.session.add(pat)
    _db.session.commit()
    assert pat.id > 0
    assert pat.created >= now

    mod_time = datetime.datetime.utcnow()
    pat.first_name += " Junior"
    _db.session.commit()
    assert pat.updated >= mod_time
    assert pat.to_json() == {
        "firstName": "Rick Junior",
        "lastName": "Deckard",
        "dateOfBirth": "2094-02-01",
        "externalId": "5"
    }
Пример #16
0
def index():
    form = PatientForm()
    patients = Patient.query.all()
    #
    # if form.refresh.data:
    #     flash(u'Làm sạch thông tin OK')

    if form.view_all.data:
        patients = Patient.query.all()

    elif form.add_new.data:
        if form.validate_on_submit():
            new_patient = Patient(form.patient_name.data,
                                  form.patient_phone.data,
                                  form.patient_age.data,
                                  form.patient_gender.data,
                                  form.patient_address.data,
                                  form.patient_history.data,
                                  form.patient_family_history.data)
            db.session.add(new_patient)
            db.session.commit()

            # patients = [new_patient]
            flash(u'Thêm mới thành công:' + form.patient_name.data)
        else:
            flash(u"Error: Vui lòng điền thông tin")

    elif form.update.data:
        if form.validate_on_submit():
            updated_patient = models.Patient.query.filter_by(id=int(form.patient_id.data)).first()

            updated_patient.patient_name = form.patient_name.data
            updated_patient.patient_phone = form.patient_phone.data
            updated_patient.patient_age = form.patient_age.data
            updated_patient.patient_gender = form.patient_gender.data
            updated_patient.patient_address = form.patient_address.data
            updated_patient.patient_history = form.patient_history.data
            updated_patient.patient_family_history = form.patient_family_history.data
            db.session.commit()

            # patients = [updated_patient]
            flash(u'Cập nhật thành công: ' + form.patient_name.data)
        else:
            flash(u"Error: Vui lòng điền thông tin")

    elif form.delete.data:
        if form.validate_on_submit():
            delete_patient = models.Patient.query.filter_by(id=int(form.patient_id.data)).first()

            db.session.delete(delete_patient)
            db.session.commit()

            patients = [delete_patient]
            flash(u'Xóa thành công:' + form.patient_name.data)
        else:
            flash(u"Error: Vui lòng điền thông tin")

    return render_template('index.html',
                           form=form,
                           patients=patients)
Пример #17
0
 def deserialize(self, session):
     race_ext, ethnicity_ext = None, None
     for ext in self.raw_data.get("extension", []):
         if (
             ext["url"]
             == "http://hl7.org/fhir/us/core/StructureDefinition/us-core-race"
         ):
             race_ext = ext
         if (
             ext["url"]
             == "http://hl7.org/fhir/us/core/StructureDefinition/us-core-ethnicity"
         ):
             ethnicity_ext = ext
     return Patient(
         source_id=self.raw_data["id"],
         birth_date=self.raw_data["birthDate"],
         gender=self.raw_data["gender"],
         country=self.raw_data["address"][0]["country"]
         if "address" in self.raw_data and "country" in self.raw_data["address"][0]
         else None,
         race_code=race_ext["valueCodeableConcept"]["coding"][0]["code"]
         if race_ext
         else None,
         race_code_system=race_ext["valueCodeableConcept"]["coding"][0]["system"]
         if race_ext
         else None,
         ethnicity_code=ethnicity_ext["valueCodeableConcept"]["coding"][0]["code"]
         if ethnicity_ext
         else None,
         ethnicity_code_system=ethnicity_ext["valueCodeableConcept"]["coding"][0][
             "system"
         ]
         if ethnicity_ext
         else None,
     )
def importDatabase(filename, user):
    '''Imports the uploaded excel file to the database than deletes the excel file
    '''
    df = pd.read_excel(
        os.path.join(current_app.config['UPLOAD_FOLDER'], filename))
    user_id = _request_ctx_stack.top.current_user.get('sub')
    classifier = Classifier.query.filter_by(user_id=user_id).first()

    rows = df.shape[1]

    for index, row in df.iterrows():
        new_patient = Patient(user_id=user,
                              status="undiag",
                              diagnose=str(row[row.size - 1]))
        for idx, r in enumerate(row):
            if (idx != row.size - 1):
                feature = Feature(featureName=df.columns[idx],
                                  featureValue=str(r),
                                  classifier_id=classifier.id)
                new_patient.features.append(feature)

        db.session.add(new_patient)
        db.session.commit()

    r = Feature.query.with_entities(
        Feature.featureName).filter_by(classifier_id=classifier.id).distinct()
    classifier.numberOfFeatureTypes = r.count()
    db.session.add(classifier)
    db.session.commit()

    os.remove(os.path.join(current_app.config['UPLOAD_FOLDER'], filename))
Пример #19
0
def read_all(m: Type[M], **kwargs) -> List[M]:
    """
    Queries the database for all Patients and Reaedings

    :param m: Type of the model to query for
    :param kwargs: Keyword arguments mapping column names to values to parameterize the
                   query (e.g., ``patientId="abc"``)
    :return: A list of models from the database
    """
    # relates to api/android/patients
    if m.schema() == Patient.schema():
        if not kwargs:
            # get all the patients
            patient_list = read_all_patients_db()
            # get all reading + referral + followup
            reading_list = read_all_readings_db(True, None)

            # O(n+m) loop. *Requires* patients and readings to be sorted by patientId
            readingIdx = 0
            for p in patient_list:
                while (readingIdx < len(reading_list)
                       and reading_list[readingIdx]["patientId"]
                       == p["patientId"]):
                    p["readings"].append(reading_list[readingIdx])
                    readingIdx += 1

            return patient_list

        return m.query.filter_by(**kwargs).all()

    else:
        if not kwargs:
            return m.query.all()
        return m.query.filter_by(**kwargs).all()
Пример #20
0
    def add(self, contract_id, clinic_id):
        contract = Contract.query.filter_by(id=contract_id).first()

        if not contract:
            patient_info = self.medsenger_api.get_patient_info(contract_id)

            try:
                patient_id = int(patient_info['id'])
            except:
                raise Exception("No patient info, contract_id = {}".format(contract_id))

            patient = Patient.query.filter_by(id=patient_id).first()
            if not patient:
                patient = Patient(id=patient_id)
                self.db.session.add(patient)

            contract = Contract(id=contract_id, patient_id=patient.id, clinic_id=clinic_id)
            self.db.session.add(contract)

        contract.is_active = True
        contract.clinic_id = clinic_id
        contract.agent_token = self.medsenger_api.get_agent_token(contract_id).get('agent_token')

        self.__commit__()

        return contract
Пример #21
0
def new_post():
    if (current_user.role != 'desk'):
        return render_template('auth/accessDenied.html')

    if request.method == 'POST':
        patient_ssnId = request.form['ssnId']
        patient_name = request.form['name']
        patient_age = request.form['age']
        patient_admissionDate = request.form['admissionDate']
        patient_bedType = request.form['bedType']
        patient_address = request.form['address']
        patient_city = request.form['city']
        patient_state = request.form['state']
        newPatient = Patient(ssnId=patient_ssnId,
                             name=patient_name,
                             age=patient_age,
                             admissionDate=patient_admissionDate,
                             bedType=patient_bedType,
                             address=patient_address,
                             city=patient_city,
                             state=patient_state)
        db.session.add(newPatient)
        db.session.commit()
        flash('Patient created')
        return redirect('/patients')
    else:
        return render_template('deskExec/newPatient.html')
def importDatabase(filename, user):
    '''Imports the uploaded excel file to the database than deletes the excel file
    '''
    df = pd.read_excel(
        os.path.join(current_app.config['UPLOAD_FOLDER'], filename))

    for index, row in df.iterrows():
        new_patient = Patient(user_id=user,
                              status="undiag",
                              diagnose=str(row[3]))
        featureA = Feature(featureName='A',
                           featureValue=str(row[0]),
                           classifier_id=1)
        featureB = Feature(featureName='B',
                           featureValue=str(row[1]),
                           classifier_id=1)
        featureC = Feature(featureName='C',
                           featureValue=str(row[2]),
                           classifier_id=1)
        new_patient.features.append(featureA)
        new_patient.features.append(featureB)
        new_patient.features.append(featureC)
        db.session.add(new_patient)
        db.session.commit()

    os.remove(os.path.join(current_app.config['UPLOAD_FOLDER'], filename))
Пример #23
0
def registration_details():
    """Remember to specify login required for only Secretaries."""
    if request.method == 'POST':
        first_name = request.form['first_name']
        last_name = request.form['last_name']
        dob = request.form['dob']
        street = request.form['street']
        town = request.form['town']
        parish = request.form['parish']
        phone_num = request.form['phone_num']

        patient_id = str(uuid.uuid4().fields[-1])[:8]

        flash('Paient Registerd')

        patient = Patient(id=patient_id,
                          dob=dob,
                          first_name=first_name,
                          last_name=last_name,
                          street=street,
                          town=town,
                          parish=parish,
                          phone_num=phone_num)
        db.session.add(patient)
        db.session.commit()
        return redirect(url_for('home'))
    """Render the website's registration_details page."""
    return render_template('registration_details.html')
Пример #24
0
def read_all_admin_view(m: Type[M], **kwargs) -> List[M]:
    """
    Queries the database for all Patients or Referrals

    :param m: Type of the model to query for
    :param kwargs: limit, page, search, sortBy, sortDir

    :return: A list of models from the database
    """

    search_param = (None if kwargs.get("search", None) == "" else kwargs.get(
        "search", None))
    sql_str = SQL.get_sql_string(search_param, **kwargs)
    sql_str_table = SQL.get_sql_table_operations(m)

    if m.schema() == Patient.schema():
        if search_param is not None:
            return db_session.execute(sql_str_table + sql_str)
        else:
            return db_session.execute(sql_str_table + sql_str)

    if m.schema() == Referral.schema():
        if search_param is not None:
            return db_session.execute(sql_str_table + sql_str)
        else:
            return db_session.execute(sql_str_table + sql_str)
Пример #25
0
def create_edited_patient(hospital_id,patient_id):
    query = db.select(Patient).where(Patient.id==patient_id)
    patient = db.session.execute(query).first()[0]
    updated_patient = Patient(patient_id, patient.name,
        patient.surname,
        patient.dni,
        patient.hospital_id)
    return render_template("edit.html",hospital=hospital_id, patient= updated_patient)
Пример #26
0
 def putItem(self, PatientName):
     PatientId = "p-" + uuid.uuid4().hex
     info = {
         DATASTORE_COLUMN_PATIENT_ID: PatientId,
         DATASTORE_COLUMN_PATIENT_NAME: PatientName
     }
     Patient().createPatient(info)
     return PatientId
Пример #27
0
def populate_database(num_patients, min_checkins, max_checkins):
    """
    Generates a number of Patients and a number of CheckIns per patient and
    stores them in the database.

    Arguments
    num_patients    -- the number of patients to generate
    min_checkins -- the minimum number of CheckIns to generate per Patient
    max_checkins -- the maximum number of CheckIns to generate per Patient

    """
    departments = [
        Department(department_name="Cardiology"),
        Department(department_name="Emergency"),
        Department(department_name="Gynecology"),
        Department(department_name="Pediatrics"),
        Department(department_name="Obstetrics"),
        Department(department_name="Oncology"),
        Department(department_name="Orthopedics"),
        Department(department_name="Neurology")
    ]

    for i in xrange(num_patients):
        patient = Patient(**generate_patient())
        patient.departments.append(choice(departments))
        db.add(patient)

        for j in xrange(randrange(min_checkins, max_checkins)):
            checkin = CheckIn(**generate_checkin())
            checkin.patient_nhi = patient.nhi

            lci = patient.latest_checkin_time
            vid = checkin.checkin_time

            lci = vid if lci is None or vid > lci else lci
            patient.latest_checkin_time = lci

            db.add(checkin)

        for k in xrange(randrange(0, 3)):
            appointment = Appointment(**generate_appointment())
            appointment.patient_nhi = patient.nhi

            db.add(appointment)

    db.commit()
Пример #28
0
def save_patient(patient_data, user):
    patient = Patient(
        id=patient_data['id'],
        first_name=patient_data['first_name'],
        last_name=patient_data['last_name'],
        email=patient_data['email'],
        birthday=patient_data['date_of_birth'],
        doctor=user.doctor
    )
    if Patient.objects.filter(pk=patient_data['id']).exists():
        patient.save(
            update_fields=['first_name', 'last_name', 'email', 'birthday']
        )
    else:
        patient.save()

    return patient
Пример #29
0
def handle_patient():
    """
    Create person and retrieve all users
    """
    # POST request

    if request.method == 'POST':
        body = request.get_json()
        if body is None:
            raise APIException(
                "You need to specify the request body as a json object",
                status_code=400)
        if ('first_name' not in body or 'last_name' not in body
                or 'date' not in body or 'birth_date' not in body
                or 'gender' not in body or 'address' not in body
                or 'email' not in body or 'phone_number' not in body
                or 'id_number' not in body):
            raise APIException('Please check your input', status_code=400)
        print(body['date'])
        user1 = Patient(date=datetime.strptime(body['date'], "%m-%d-%Y"),
                        first_name=body['first_name'],
                        last_name=body['last_name'],
                        birth_date=datetime.strptime(body['birth_date'],
                                                     "%m-%d-%Y"),
                        gender=body['gender'],
                        address=body['address'],
                        email=body['email'],
                        phone_number=body['phone_number'],
                        id_number=body['id_number'],
                        doctor_id=get_jwt_identity())
        try:
            db.session.add(user1)
            db.session.commit()
            return jsonify(user1.serialize()), 201
        except Exception as error:
            db.session.rollback()
            print(error)
            return "bad request", 400
    # GET request
    if request.method == 'GET':
        all_people = Patient.query.filter_by(
            doctor_id=get_jwt_identity()).all()
        all_people = list(map(lambda x: x.serialize(), all_people))
        return jsonify(all_people), 200
    return "Invalid Method", 404
Пример #30
0
def create_patient():
    'Api end-point for creating a new user'
    if not request.form: 
        return ''
    db.session.add(Patient(**request.form))
    db.session.commit()
    p = db.session.query(Patient).order_by(Patient.patient_id.desc()).first()
    url = url_for('patients.view_patient', patient_id=p.patient_id)
    return redirect(url, code=302)
Пример #31
0
    def _get_all_patients(self):
        url = 'https://drchrono.com/api/patients'

        # Fetch the objects one "page" at a time until they are all loaded
        while url:
            data = requests.get(url, headers=self.headers).json()
            for item in data['results']:
                Patient().save_from_dict(item)
            url = data['next']  # Value = None on the last page
Пример #32
0
def create_patient(user_data):
    user = Patient(
            first_name = user_data["first_name"],
            last_name = user_data["last_name"],
            email = user_data["email"],
            phone_number = user_data["phone_number"],
            password_hash = create_password_hash( user_data["password"] )
        )

    return user
Пример #33
0
 def test_patient_model(self):
     """Does basic model work?"""
     p = Patient(first_name="Nonkoff",
                 last_name="Jegrold",
                 date_of_birth=datetime.date(1999, 1, 19))
     db.session.add(p)
     db.session.commit()
     """Doctor should have no patients & no medications"""
     self.assertEqual(len(p.medications), 0)
     self.assertEqual(len(p.medications_given), 0)
Пример #34
0
 def _get_patient(self, mongo_patient):
     cancer_images = self._get_cancer_images(mongo_patient)
     return Patient(id=str(mongo_patient["_id"]),
                    name=mongo_patient["name"],
                    image=mongo_patient["image"],
                    is_diagnosed=mongo_patient["is_diagnosed"],
                    has_cancer=mongo_patient["has_cancer"],
                    registration_date=mongo_patient["registration_date"],
                    diagnosis_date=mongo_patient["diagnosis_date"],
                    cancer_images=cancer_images)
Пример #35
0
    def setUp(self):
        """Create test client, add sample data."""
        db.drop_all()
        db.create_all()

        d1 = Doctor(first_name="John", last_name="Fulcan")
        d2 = Doctor(first_name="Mike", last_name="NightRider")

        db.session.add(d1)
        db.session.add(d2)

        p1 = Patient(first_name="Blub",
                     last_name="Booper",
                     date_of_birth=datetime.date(1999, 1, 19))
        p2 = Patient(first_name="Jak",
                     last_name="Alomaty",
                     date_of_birth=datetime.date(2001, 3, 21))

        db.session.add(p1)
        db.session.add(p2)

        n1 = Nurse(first_name='Marko', last_name="jamie")
        n2 = Nurse(first_name='Jimbo', last_name="Kilayin")

        db.session.add(n1)
        db.session.add(n2)

        db.session.commit()

        d1 = Doctor.query.get(1)
        d2 = Doctor.query.get(2)
        p1 = Patient.query.get(1)
        p2 = Patient.query.get(2)

        self.d1 = d1
        self.d2 = d2
        self.p1 = p1
        self.p2 = p2
        self.n1 = n1
        self.n2 = n2

        self.client = app.test_client()
Пример #36
0
def register_patient(unregistered_patient: UnregisteredPatient):
    """Register patient and returns saved record."""
    vaccination_delay = timedelta(days=len([letter for letter
                                            in unregistered_patient.name + unregistered_patient.surname
                                            if letter.isalpha()]))
    patient = Patient(name=unregistered_patient.name, surname=unregistered_patient.surname,
                      id=len(app.patients) + 1,
                      vaccination_date=(date.today() + vaccination_delay))
    app.patients.append(patient)
    logger.info(f'Added {patient=}')
    return patient
Пример #37
0
def submit(request):
    from models import id_generator

    postKeyReturn = check_post_key(request)
    if postKeyReturn is not True:
        return postKeyReturn

    # Because the post is not indexed we have to check the key
    if len(unicode(request.body)) == 0:
        return HttpResponseBadRequest()

    # Check if it really json
    try:
        json_object = json.loads(unicode(request.body))
    except ValueError as e:
        print e  # TODO: use real logging
        # The json is not valid
        return HttpResponseBadRequest()

    pat = Patient()

    uid = id_generator()

    # Check if the uid exists
    while Patient.objects.filter(uid__iexact=uid).count() == 1:
        uid = id_generator()

    pat.uid = uid
    pat.first_name = json_object.get("first_name") or None
    pat.last_name = json_object.get("last_name") or None
    pat.moh_id = json_object.get("moh_id") or None
    pat.enter_number = json_object.get("enter_number") or None
    pat.caregiver_number = json_object.get("caregiver_number") or None

    pat.json = unicode(json_object)

    # Message is sent through the save method
    pat.save()

    return HttpResponse(uid)
Пример #38
0
def populate_database(num_patients, min_vital_infos, max_vital_infos):
    """
    Generates a number of Patients and a number of VitalInfos per patient and
    stores them in the database.

    Arguments
    num_patients    -- the number of patients to generate
    min_vital_infos -- the minimum number of VitalInfos to generate per Patient
    max_vital_infos -- the maximum number of VitalInfos to generate per Patient

    """
    departments = [
        Department(department_name="Cardiology"),
        Department(department_name="Emergency"),
        Department(department_name="Gynecology"),
        Department(department_name="Pediatrics"),
        Department(department_name="Obstetrics"),
        Department(department_name="Oncology"),
        Department(department_name="Orthopedics"),
        Department(department_name="Neurology")
    ]

    for i in xrange(num_patients):
        patient = Patient(**generate_patient())
        patient.departments.append(choice(departments))
        db.add(patient)
        db.commit()

        for j in xrange(randrange(min_vital_infos, max_vital_infos)):
            vitalinfo = VitalInfo(**generate_vital_info())
            vitalinfo.patient_nhi = patient.nhi

            lci = patient.latest_check_in
            vid = vitalinfo.check_in_time

            lci = vid if lci is None or vid > lci else lci
            patient.latest_check_in = lci

            db.add(vitalinfo)
            db.commit()
Пример #39
0
    def remove(self,event):

        remove_dial = wx.MessageDialog(None, u'Tem certeza que deseja excluir este paciente?', 'Sair',
            wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
        ret = remove_dial.ShowModal()
        if ret == wx.ID_YES:
            patient1 = Patient.get_by(id=int(self.idTextCtrl.GetValue()))
            patient1.delete()
            session.commit()
            remove_dial.Destroy()
            self.refreshIndex(None)
            self.getNext(None)

        else:
            event.Veto()
Пример #40
0
def handle_uploaded_file(f):
    file_name = f.name
    file_size = f.size
    result = 'Success' 
    first_line = True
    all_patients = Patient.objects.all()
    for line in f:
        # The first line of the file will always be headers
        if not first_line:
            # The data will always be separated by tabs
            split = line.split('\t') 
            if len(split) == 14:
                patient_id = split[0]
                for p in all_patients:
                    if p.id == patient_id:
                        p.delete()
                patient = Patient(id=patient_id, height=get_value(split[1]), 
                              egplandt=get_date(split[2]), 
                              egpregdt=get_date(split[3]),
                              egstage4dt=get_date(split[4]), 
                              egcd4dt=get_date(split[5]), 
                              egcd4v=get_value(split[6]), 
                              edate=get_date(split[7]),
                              egweight=get_value(split[8]), 
                              enroldt=get_date(split[9]),
                              lastdt=get_date(split[10]), 
                              returndt=get_date(split[11]),
                              startdt=get_date(split[12]), 
                              startgprg=trim(split[13]))
                #TODO: there will be one more field coming
                patient.save()
            else:
                result = 'At least one line of the file did not have the correct number of entries and was not added'
        else:
            first_line = False
    return result
Пример #41
0
def new_patient():
    name = request.json.get('name')
    surname = request.json.get('surname')
    patronymic = request.json.get('patronymic')
    email = request.json.get('email')
    phone = request.json.get('phone')

    try:
        patient = Patient.query.filter_by(email=email).first()
        if patient is None:
            patient = Patient.from_json({ 'name': name,
                                          'surname': surname,
                                          'patronymic': patronymic,
                                          'email': email,
                                          'phone': phone})
            db.session.add(patient)
            db.session.commit()
        return jsonify({'patient_id': patient.to_json().get('patient_id')}), 201
    except:
        return '', 500
Пример #42
0
def get_patient_for_user(appt, user, access_token):
    patient = appt['patient']
    p = None
    try:
        p = Patient.objects.get(drchrono_id=patient)
    except Patient.DoesNotExist:
        patient_uri = drchrono_base_url + patients_url + '/' + str(patient)
        patient_data = requests.get(
            patient_uri,
            headers={'Authorization': 'Bearer %s' % access_token}
        ).json()
        p = Patient()
        p.drchrono_id = patient
        p.first_name = patient_data.get('first_name')
        p.last_name = patient_data.get('last_name')
        p.email = patient_data.get('email')
        p.gender = patient_data.get('gender')
        p.race = patient_data.get('race')
        p.photo = patient_data.get('photo')
        p.drchrono_doctor_id = patient_data.get('doctor')
        p.user_id = user.id
        p.save()
    return p
Пример #43
0
def add(req):
    patient = Patient()
    patient.setReq(req.POST)
    patient.save()
Пример #44
0
    def save(self,event):
        if self.idTextCtrl.GetValue() != '':

            if self.valida(int(self.idTextCtrl.GetValue()),self.nameTextCtrl.GetValue(),self.dateOfBirthTextCtrl.GetValue(),
                           self.telephoneTextCtrl.GetValue(),self.telephone2TextCtrl.GetValue(),self.treatmentStartTextCtrl.GetValue(),
                           self.budgetByTextCtrl.GetValue(),self.registrationFormTextCtrl.GetValue()):

                patient1 = Patient.get_by(id=self.idTextCtrl.GetValue())

                patient1.name = self.nameTextCtrl.GetValue().title()
                patient1.dateOfBirth = self.dateOfBirthTextCtrl.GetValue()
                patient1.rg = self.rgTextCtrl.GetValue()
                patient1.cpf = self.cpfTextCtrl.GetValue()
                patient1.telephone = self.telephoneTextCtrl.GetValue()
                patient1.telephone2 = self.telephone2TextCtrl.GetValue()
                patient1.treatmentStart = self.treatmentStartTextCtrl.GetValue()
                patient1.budgetBy = self.budgetByTextCtrl.GetValue()
                patient1.registrationForm = self.registrationFormTextCtrl.GetValue()

                session.commit()
                self.refreshIndex(self.idTextCtrl.GetValue())
                self.message = wx.MessageDialog(None, u'Paciente alterado com sucesso!', 'Info', wx.OK)
                self.message.ShowModal()

                self.nameTextCtrl.SetEditable(False)
                self.dateOfBirthTextCtrl.SetEditable(False)
                self.rgTextCtrl.SetEditable(False)
                self.cpfTextCtrl.SetEditable(False)
                self.telephoneTextCtrl.SetEditable(False)
                self.telephone2TextCtrl.SetEditable(False)
                self.treatmentStartTextCtrl.SetEditable(False)
                self.budgetByTextCtrl.SetEditable(False)
                self.registrationFormTextCtrl.SetEditable(False)

                self.toolBar.EnableTool(ID_TOOLBAR_PATIENT_FIRST, True)
                self.toolBar.EnableTool(ID_TOOLBAR_PATIENT_LAST, True)
                self.toolBar.EnableTool(ID_TOOLBAR_PATIENT_PREVIOUS, True)
                self.toolBar.EnableTool(ID_TOOLBAR_PATIENT_NEXT, True)
                self.toolBar.EnableTool(ID_TOOLBAR_PATIENT_NEW, True)
                self.toolBar.EnableTool(ID_TOOLBAR_PATIENT_SAVE, False)
                self.toolBar.EnableTool(ID_TOOLBAR_PATIENT_REMOVE, True)
                self.toolBar.EnableTool(ID_TOOLBAR_PATIENT_EDIT, True)
                self.toolBar.EnableTool(ID_TOOLBAR_PATIENT_FIND, True)
                self.toolBar.EnableTool(ID_TOOLBAR_PATIENT_CANCEL, False)
        else:

            if self.valida(self.idTextCtrl.GetValue(),self.nameTextCtrl.GetValue(),self.dateOfBirthTextCtrl.GetValue(),
                           self.telephoneTextCtrl.GetValue(),self.telephone2TextCtrl.GetValue(),self.treatmentStartTextCtrl.GetValue(),
                           self.budgetByTextCtrl.GetValue(),self.registrationFormTextCtrl.GetValue()):

                patient1 = Patient(name=self.nameTextCtrl.GetValue().title(),dateOfBirth=self.dateOfBirthTextCtrl.GetValue(),
                                   rg=self.rgTextCtrl.GetValue(),cpf=self.cpfTextCtrl.GetValue(),
                                   telephone=self.telephoneTextCtrl.GetValue(),telephone2=self.telephone2TextCtrl.GetValue(),
                                   treatmentStart=self.treatmentStartTextCtrl.GetValue(),budgetBy=self.budgetByTextCtrl.GetValue(),
                                   registrationForm=self.registrationFormTextCtrl.GetValue())

                session.commit()

                self.refreshIndex(patient1.id)
                self.idTextCtrl.SetValue(unicode(patient1.id))
                self.message = wx.MessageDialog(None, u'Paciente cadastrado com sucesso!', 'Info', wx.OK)
                self.message.ShowModal()

                self.nameTextCtrl.SetEditable(False)
                self.dateOfBirthTextCtrl.SetEditable(False)
                self.rgTextCtrl.SetEditable(False)
                self.cpfTextCtrl.SetEditable(False)
                self.telephoneTextCtrl.SetEditable(False)
                self.telephone2TextCtrl.SetEditable(False)
                self.treatmentStartTextCtrl.SetEditable(False)
                self.budgetByTextCtrl.SetEditable(False)
                self.registrationFormTextCtrl.SetEditable(False)

                self.toolBar.EnableTool(ID_TOOLBAR_PATIENT_FIRST, True)
                self.toolBar.EnableTool(ID_TOOLBAR_PATIENT_LAST, True)
                self.toolBar.EnableTool(ID_TOOLBAR_PATIENT_PREVIOUS, True)
                self.toolBar.EnableTool(ID_TOOLBAR_PATIENT_NEXT, True)
                self.toolBar.EnableTool(ID_TOOLBAR_PATIENT_NEW, True)
                self.toolBar.EnableTool(ID_TOOLBAR_PATIENT_SAVE, False)
                self.toolBar.EnableTool(ID_TOOLBAR_PATIENT_REMOVE, True)
                self.toolBar.EnableTool(ID_TOOLBAR_PATIENT_EDIT, True)
                self.toolBar.EnableTool(ID_TOOLBAR_PATIENT_FIND, True)
                self.toolBar.EnableTool(ID_TOOLBAR_PATIENT_CANCEL, False)