Exemplo n.º 1
0
def _assert_permission(patient_record: PatientRecord, user: UKRDCUser):
    units = Permissions.unit_codes(user.permissions)
    if Permissions.UNIT_WILDCARD in units:
        return

    if patient_record.sendingfacility not in units:
        raise PermissionsError()
Exemplo n.º 2
0
def _assert_permission(message: Message, user: UKRDCUser):
    units = Permissions.unit_codes(user.permissions)
    if Permissions.UNIT_WILDCARD in units:
        return

    if message.facility not in units:
        raise PermissionsError()
Exemplo n.º 3
0
def _apply_query_permissions(query: Query, user: UKRDCUser):
    units = Permissions.unit_codes(user.permissions)
    if Permissions.UNIT_WILDCARD in units:
        return query

    return (query.join(LinkRecord).join(Person).join(PidXRef).filter(
        PidXRef.sending_facility.in_(units)))
Exemplo n.º 4
0
def superuser():
    return UKRDCUser(
        id="TEST_ID",
        cid="PYTEST",
        email="TEST@UKRDC_FASTAPI",
        permissions=Permissions.all(),
        scopes=["openid", "profile", "email", "offline_access"],
    )
Exemplo n.º 5
0
def _assert_permission(person: Person, user: UKRDCUser):
    units = Permissions.unit_codes(user.permissions)
    if Permissions.UNIT_WILDCARD in units:
        return

    if person_belongs_to_units(person, units):
        return

    raise PermissionsError()
Exemplo n.º 6
0
def test_user():
    return UKRDCUser(
        id="TEST_ID",
        cid="PYTEST",
        email="TEST@UKRDC_FASTAPI",
        permissions=[
            *Permissions.all()[:-1], "ukrdc:unit:TEST_SENDING_FACILITY_1"
        ],
        scopes=["openid", "profile", "email", "offline_access"],
    )
Exemplo n.º 7
0
def get_errors_history(
    ukrdc3: Session,
    statsdb: Session,
    facility_code: str,
    user: UKRDCUser,
    since: Optional[datetime.date] = None,
    until: Optional[datetime.date] = None,
) -> list[HistoryPoint]:
    """Get a day-by-day error count for a particular facility/unit

    Args:
        ukrdc3 (Session): SQLAlchemy session
        statsdb (Session): SQLAlchemy session
        errorsdb (Session): SQLAlchemy session
        facility_code (str): Facility/unit code
        user (UKRDCUser): Logged-in user
        since (Optional[datetime.date]): Filter start date. Defaults to None.
        until (Optional[datetime.date]): Filter end date. Defaults to None.

    Returns:
        list[HistoryPoint]: Time-series error data
    """
    code = (
        ukrdc3.query(Code)
        .filter(Code.coding_standard == "RR1+", Code.code == facility_code)
        .first()
    )

    if not code:
        raise HTTPException(404, detail="Facility not found")

    # Assert permissions
    units = Permissions.unit_codes(user.permissions)
    if (Permissions.UNIT_WILDCARD not in units) and (code.code not in units):
        raise PermissionsError()

    # Get cached statistics
    history = statsdb.query(ErrorHistory).filter(ErrorHistory.facility == facility_code)

    # Default to last year
    history = history.filter(
        ErrorHistory.date
        >= (since or (datetime.datetime.utcnow() - datetime.timedelta(days=365)))
    )

    # Optionally filter by end date
    if until:
        history = history.filter(ErrorHistory.date <= until)

    points = [
        HistoryPoint(time=point.date, count=point.count) for point in history.all()
    ]

    return points
Exemplo n.º 8
0
def _assert_permission(record: MasterRecord, user: UKRDCUser):
    units = Permissions.unit_codes(user.permissions)
    if Permissions.UNIT_WILDCARD in units:
        return

    link: LinkRecord
    for link in record.link_records:
        person: Person = link.person
        if person_belongs_to_units(person, units):
            return

    raise PermissionsError()
Exemplo n.º 9
0
def get_facility(
    ukrdc3: Session,
    statsdb: Session,
    facility_code: str,
    user: UKRDCUser,
) -> FacilityDetailsSchema:
    """Get a summary of a particular facility/unit

    Args:
        ukrdc3 (Session): SQLAlchemy session
        facility_code (str): Facility/unit code
        user (UKRDCUser): Logged-in user

    Returns:
        FacilityDetailsSchema: Matched facility
    """
    facility = ukrdc3.query(Facility).filter(Facility.code == facility_code).first()

    if not facility:
        raise HTTPException(404, detail="Facility not found")

    # Assert permissions
    units = Permissions.unit_codes(user.permissions)
    if (Permissions.UNIT_WILDCARD not in units) and (facility.code not in units):
        raise PermissionsError()

    # Get cached statistics
    stats = (
        statsdb.query(FacilityStats)
        .filter(FacilityStats.facility == facility_code)
        .first()
    )

    return FacilityDetailsSchema(
        id=facility.code,
        description=facility.description,
        statistics=_expand_facility_statistics(stats),
        data_flow=FacilityDataFlowSchema(
            pkb_in=facility.pkb_in,
            pkb_out=facility.pkb_out,
            pkb_message_exclusions=facility.pkb_msg_exclusions or [],
        ),
    )
Exemplo n.º 10
0
def get_patients_latest_errors(
    ukrdc3: Session,
    errorsdb: Session,
    statsdb: Session,
    facility_code: str,
    user: UKRDCUser,
) -> Query:
    """Retrieve the most recent error messages for each patient currently receiving errors.

    Args:
        ukrdc3 (Session): SQLAlchemy session
        errorsdb (Session): SQLAlchemy session
        statsdb (Session): SQLAlchemy session
        facility_code (str): Facility/unit code
        user (UKRDCUser): Logged-in user

    Returns:
        Query: SQLAlchemy query
    """
    facility = ukrdc3.query(Facility).filter(Facility.code == facility_code).first()

    if not facility:
        raise HTTPException(404, detail="Facility not found")

    # Assert permissions
    units = Permissions.unit_codes(user.permissions)
    if (Permissions.UNIT_WILDCARD not in units) and (facility.code not in units):
        raise PermissionsError()

    # Get message IDs of patients latest errors
    latest_error_ids = [
        row.id
        for row in (
            statsdb.query(PatientsLatestErrors)
            .filter(PatientsLatestErrors.facility == facility.code)
            .all()
        )
    ]

    return errorsdb.query(Message).filter(Message.id.in_(latest_error_ids))
Exemplo n.º 11
0
async def test_user(client):
    response = await client.get(f"{configuration.base_url}/v1/system/user/")
    assert response.json().get("email") == "TEST@UKRDC_FASTAPI"
    assert set(response.json().get("permissions")) == set(Permissions.all())
Exemplo n.º 12
0
def _apply_query_permissions(query: Query, user: UKRDCUser):
    units = Permissions.unit_codes(user.permissions)
    if Permissions.UNIT_WILDCARD in units:
        return query

    return query.filter(PatientRecord.sendingfacility.in_(units))
Exemplo n.º 13
0
import json
import os

from sqlalchemy.orm import Session
from ukrdc_sqla.empi import MasterRecord

from ukrdc_fastapi.dependencies.auth import Permissions, UKRDCUser
from ukrdc_fastapi.dependencies.database import JtraceSession
from ukrdc_fastapi.query.masterrecords import get_masterrecords_related_to_masterrecord

USER = UKRDCUser(id="", email="", scopes=[], permissions=Permissions.all())


def find_ukrdc_dupes(jtrace: Session):
    rfile = "dupes.json"

    if os.path.isfile(rfile):
        with open(rfile, "r") as f:
            results = json.load(f)
        print("Loaded results:")
        print(results)
    else:
        results = {"cleared": [], "failed": {}}

    print("Fetching records")
    records: MasterRecord = jtrace.query(MasterRecord).filter(
        MasterRecord.id.notin_(results["cleared"]))

    for record in records:
        print(f"Processing record {record.id}")
        related_ukrdc_records = get_masterrecords_related_to_masterrecord(
Exemplo n.º 14
0
def _apply_query_permissions(query: Query, user: UKRDCUser):
    units = Permissions.unit_codes(user.permissions)
    if Permissions.UNIT_WILDCARD in units:
        return query

    return query.filter(Message.facility.in_(units))
Exemplo n.º 15
0
def get_facilities(
    ukrdc3: Session, statsdb: Session, user: UKRDCUser, include_empty: bool = False
) -> list[FacilityDetailsSchema]:
    """Get a list of all unit/facility summaries available to the current user

    Args:
        ukrdc3 (Session): SQLALchemy session
        statsdb (Session): SQLALchemy session
        user (UKRDCUser): Logged-in user object

    Returns:
        list[FacilityDetailsSchema]: List of units/facilities
    """

    facilities = ukrdc3.query(Facility)

    # Filter results by unit permissions
    units = Permissions.unit_codes(user.permissions)
    if Permissions.UNIT_WILDCARD not in units:
        facilities = facilities.filter(Facility.code.in_(units))

    # Execute statement to retreive available facilities list for this user
    available_facilities = facilities.all()

    # Create a list to store our response
    facility_list: list[FacilityDetailsSchema] = []

    # Fetch stats for facilities we're listing
    facility_stats_dict: dict[str, FacilityStats] = {
        row.facility: row
        for row in statsdb.query(FacilityStats)
        .filter(
            FacilityStats.facility.in_(
                [facility.code for facility in available_facilities]
            )
        )
        .all()
    }

    for facility in available_facilities:
        # Find the stats for this specific favility
        stats = facility_stats_dict.get(facility.code)
        # If stats exist, expand them and add this facility to the response

        # Always include all facilities if include_empty==True
        # Otherwise, only include facilities with patients
        if include_empty or (stats and (stats.total_patients or 0) > 0):
            facility_list.append(
                FacilityDetailsSchema(
                    id=facility.code,
                    description=facility.description,
                    statistics=_expand_facility_statistics(stats),
                    data_flow=FacilityDataFlowSchema(
                        pkb_in=facility.pkb_in,
                        pkb_out=facility.pkb_out,
                        pkb_message_exclusions=facility.pkb_msg_exclusions or [],
                    ),
                )
            )

    return facility_list