Exemplo n.º 1
0
    def post():
        json = request.get_json(force=True)

        # Populate the dateAssessed and healthCareWorkerId fields of the followup
        json["dateAssessed"] = get_current_time()
        user = util.current_user()
        json["healthcareWorkerId"] = user.id

        error_message = assessments.validate(json)
        if error_message is not None:
            abort(400, message=error_message)

        # TODO: validate that assessment's reading id references an actual reading and
        #   return 404 if it doesn't

        follow_up = marshal.unmarshal(FollowUp, json)

        crud.create(follow_up)

        # Creating an assessment also marks any referral attached to the associated
        # reading as "assessed"
        if follow_up.reading.referral:
            follow_up.reading.referral.isAssessed = True
            data.db_session.commit()

        return follow_up.id, 201
Exemplo n.º 2
0
    def post():
        json = request.get_json(force=True)

        # Populate the dateAssessed and healthCareWorkerId fields of the followup
        json["dateAssessed"] = get_current_time()
        user = util.current_user()
        json["healthcareWorkerId"] = user.id

        error_message = assessments.validate(json)
        if error_message is not None:
            abort(400, message=error_message)

        follow_up = marshal.unmarshal(FollowUp, json)

        # Check that reading id which doesn’t reference an existing reading in the database
        reading = crud.read(Reading, readingId=follow_up.readingId)
        if not reading:
            abort(404, message=f"No reading with id {follow_up.readingId}")

        crud.create(follow_up)

        # Creating an assessment also marks any referral attached to the associated
        # reading as "assessed"
        if follow_up.reading.referral:
            follow_up.reading.referral.isAssessed = True
            data.db_session.commit()

        return follow_up.id, 201
    def post():
        json = request.get_json(force=True)
        error_message = patients.validate(json)
        if error_message is not None:
            abort(400, message=error_message)
        patient = marshal.unmarshal(Patient, json)

        if crud.read(Patient, patientId=patient.patientId):
            abort(409, message=f"A patient already exists with id: {patient.patientId}")

        # Resolve invariants and set the creation timestamp for the patient ensuring
        # that both the created and lastEdited fields have the exact same value.
        invariant.resolve_reading_invariants(patient)
        creation_time = get_current_time()
        patient.created = creation_time
        patient.lastEdited = creation_time

        crud.create(patient, refresh=True)

        # Associate the patient with the user who created them
        user = util.current_user()
        assoc.associate_by_user_role(patient, user)

        # If the patient has any readings, and those readings have referrals, we
        # associate the patient with the facilities they were referred to
        for reading in patient.readings:
            referral = reading.referral
            if referral and not assoc.has_association(patient, referral.healthFacility):
                assoc.associate(patient, facility=referral.healthFacility)
                # The associate function performs a database commit, since this will
                # wipe out the patient we want to return we must refresh it.
                data.db_session.refresh(patient)
        return marshal.marshal(patient), 201
Exemplo n.º 4
0
    def post():
        json = request.get_json(force=True)
        error_message = facilities.validate(json)
        if error_message is not None:
            abort(400, message=error_message)

        facility = marshal.unmarshal(HealthFacility, json)
        crud.create(facility)
        return marshal.marshal(facility), 201
Exemplo n.º 5
0
    def post():
        # Get all patients for this user
        timestamp: int = request.args.get("since", None, type=int)
        if not timestamp:
            abort(400, message="'since' query parameter is required")

        #  ~~~~~~~~~~~~~~~~~~~~~~ new Logic ~~~~~~~~~~~~~~~~~~~~~~~~~~
        json = request.get_json(force=True)
        patients_on_server_chache = set()
        for r in json:
            if r.get("patientId") not in patients_on_server_chache:
                patient_on_server = crud.read(Patient,
                                              patientId=r.get("patientId"))
                if patient_on_server is None:
                    continue
                else:
                    patients_on_server_chache.add(patient_on_server.patientId)

            if crud.read(Reading, readingId=r.get("readingId")):
                continue
            else:
                error_message = readings.validate(r)
                if error_message is not None:
                    abort(400, message=error_message)
                reading = marshal.unmarshal(Reading, r)
                invariant.resolve_reading_invariants(reading)
                crud.create(reading, refresh=True)

        user = util.current_user()
        #     TODO: create custome DB calls for referral and followup

        all_patients = view.patient_view_for_user(user)
        new_readings = []
        new_referral = []
        new_followup = []
        for p in all_patients:
            for r in p["readings"]:
                if r["dateTimeTaken"] > timestamp:
                    new_readings.append(r)
                if (r["referral"] and r["referral"]["dateReferred"] > timestamp
                        and r["dateTimeTaken"] < timestamp):
                    new_referral.append(r["referral"])
                if (r["followup"] and r["followup"]["dateAssessed"] > timestamp
                        and r["dateTimeTaken"] < timestamp):
                    new_followup.append(r["followup"])

        return {
            "total": len(new_readings) + len(new_referral) + len(new_followup),
            "readings": new_readings,
            "newReferralsForOldReadings": new_referral,
            "newFollowupsForOldReadings": new_followup,
        }
    def post():

        # Get key-value pairs from parser and remove pairs with a None value
        data = Root.parser.parse_args()
        data = util.filterPairsWithNone(data)

        # Create a DB Model instance for the new facility and load into DB
        facility = marshal.unmarshal(HealthFacility, data)
        crud.create(facility)

        # Get back a dict for return
        facilityDict = marshal.marshal(
            crud.read(HealthFacility,
                      healthFacilityName=data["healthFacilityName"]))
        return facilityDict, 201
Exemplo n.º 7
0
    def post():
        json = request.get_json(force=True)
        error_message = referrals.validate(json)
        if error_message is not None:
            abort(400, message=error_message)

        referral = marshal.unmarshal(Referral, json)
        crud.create(referral)

        # Creating a referral also associates the corresponding patient to the health
        # facility they were referred to.
        patient = referral.patient
        facility = referral.healthFacility
        if not assoc.has_association(patient, facility):
            assoc.associate(patient, facility=facility)

        return marshal.marshal(referral), 201
Exemplo n.º 8
0
    def post():
        json = request.get_json(force=True)
        error_message = readings.validate(json)
        if error_message is not None:
            abort(400, message=error_message)

        reading = marshal.unmarshal(Reading, json)

        if crud.read(Reading, readingId=reading.readingId):
            abort(
                409,
                message=f"A reading already exists with id: {reading.readingId}"
            )

        invariant.resolve_reading_invariants(reading)
        crud.create(reading, refresh=True)
        return marshal.marshal(reading), 201
Exemplo n.º 9
0
    def _do_create(self, **kwargs) -> Any:
        import data
        from config import flask_bcrypt
        from models import User, Role

        d = dict(**kwargs)
        role_name = d["role"]
        del d["role"]  # not an actual user field so delete if from the args

        # Hash the user's password so that they can login
        d["password"] = flask_bcrypt.generate_password_hash(d["password"])

        user = marshal.unmarshal(User, d)
        crud.create(user)
        role = crud.read(Role, name=role_name)
        user.roleIds = [role]
        data.db_session.commit()
        return user
Exemplo n.º 10
0
def associate(patient: Patient,
              facility: HealthFacility = None,
              user: User = None):
    """
    Creates an association between a patient and facility, patient and user, or patient,
    user and facility.

    :param patient: A patient
    :param facility: A facility
    :param user: A user
    :except IntegrityError: If an existing entry already exists in the database
    """
    if not facility and not user:
        raise ValueError(f"either a facility or user must be provided")

    association = PatientAssociations(
        patientId=patient.patientId,
        healthFacilityName=facility.healthFacilityName if facility else None,
        userId=user.id if user else None,
    )
    crud.create(association)
Exemplo n.º 11
0
def create_patient_reading_referral(
    patientId,
    readingId,
    userId,
    name,
    age,
    sex,
    villageNum,
    isPregnant=False,
    gestAgeUnit=None,
    gestTimestamp=None,
):
    import data.crud as crud
    import data.marshal as marshal
    from models import Patient

    """
    Creates a patient in the database.
    """
    if isPregnant:
        patient = {
            "patientId": patientId,
            "patientName": name,
            "gestationalAgeUnit": gestAgeUnit,
            "gestationalTimestamp": gestTimestamp,
            "villageNumber": villageNum,
            "patientSex": sex,
            "isPregnant": "true",
        }
    else:
        patient = {
            "patientId": patientId,
            "patientName": name,
            "villageNumber": villageNum,
            "patientSex": sex,
            "isPregnant": "false",
        }

    reading = {
        "userId": userId,
        "patientId": patientId,
        "dateTimeTaken": 1551447833,
        "readingId": readingId,
        "bpSystolic": 50,
        "bpDiastolic": 60,
        "heartRateBPM": 70,
        "symptoms": "FEVERISH",
    }

    # health facility name based on one defined in seed_minimal()
    referral = {
        "patientId": patientId,
        "readingId": readingId,
        "dateReferred": reading["dateTimeTaken"]
        + int(timedelta(days=10).total_seconds()),
        "referralHealthFacilityName": "H0000",
        "comment": "They need help!",
    }

    reading["referral"] = referral
    patient["readings"] = [reading]
    model = marshal.unmarshal(Patient, patient)
    crud.create(model)