diff --git a/server/api/alembic/versions/8f2ffbc5c2e8_add_request_type_table.py b/server/api/alembic/versions/8f2ffbc5c2e8_add_request_type_table.py index 4174cb7da..8b2de3c37 100644 --- a/server/api/alembic/versions/8f2ffbc5c2e8_add_request_type_table.py +++ b/server/api/alembic/versions/8f2ffbc5c2e8_add_request_type_table.py @@ -50,6 +50,7 @@ CREATE UNIQUE INDEX ON service_requests(request_id); CREATE UNIQUE INDEX ON service_requests(srnumber); CREATE INDEX ON service_requests(created_date); + CREATE INDEX ON service_requests(closed_date); CREATE INDEX ON service_requests(type_id); CREATE INDEX ON service_requests(council_id); CREATE INDEX ON service_requests(region_id); diff --git a/server/api/code/lacity_data_api/models/request_type.py b/server/api/code/lacity_data_api/models/request_type.py index 35d7a138d..60479c36f 100644 --- a/server/api/code/lacity_data_api/models/request_type.py +++ b/server/api/code/lacity_data_api/models/request_type.py @@ -14,6 +14,41 @@ class RequestType(db.Model): color = db.Column(db.String) data_code = db.Column(db.String) + @classmethod + @cached(cache=Cache.REDIS, + endpoint=CACHE_ENDPOINT, + namespace="types", + key="stats", + serializer=serializers.PickleSerializer(), + ) + async def get_type_stats(cls): + + query = db.text(""" + SELECT + service_requests.type_id, + request_types.type_name, + min(closed_date - created_date), + percentile_disc(0.25) within group + (order by closed_date - created_date) as q1, + percentile_disc(0.5) within group + (order by closed_date - created_date) as median, + percentile_disc(0.75) within group + (order by closed_date - created_date) as q3, + max(closed_date - created_date) + FROM + service_requests + JOIN + request_types ON request_types.type_id = service_requests.type_id + WHERE + service_requests.closed_date <= CURRENT_DATE AND + service_requests.closed_date >= service_requests.created_date + GROUP BY + service_requests.type_id, request_types.type_name + """) + + result = await db.all(query) + return result + @cached(cache=Cache.REDIS, endpoint=CACHE_ENDPOINT, diff --git a/server/api/code/lacity_data_api/routers/request_types.py b/server/api/code/lacity_data_api/routers/request_types.py index 9e488fbe2..963fa68f9 100644 --- a/server/api/code/lacity_data_api/routers/request_types.py +++ b/server/api/code/lacity_data_api/routers/request_types.py @@ -11,6 +11,12 @@ async def get_all_request_types(): return await RequestType.query.gino.all() +@router.get("/stats") +async def get_request_stats(): + result = await RequestType.get_type_stats() + return result + + @router.get("/{id}") async def get_request_type(id: int): result = await RequestType.get_or_404(id)