diff --git a/api/database/flights.py b/api/database/flights.py index a3252a6..8faf352 100644 --- a/api/database/flights.py +++ b/api/database/flights.py @@ -1,4 +1,5 @@ import logging +from datetime import datetime from bson import ObjectId from fastapi import HTTPException @@ -29,6 +30,41 @@ async def retrieve_flights(user: str = "", sort: str = "date", order: int = -1) return flights +async def retrieve_totals(user: str, start_date: datetime = None, end_date: datetime = None) -> dict: + """ + Retrieve total times for the given user + :param user: + :return: + """ + match = {"user": ObjectId(user)} + + if start_date is not None: + match.setdefault("date", {}).setdefault("$gte", start_date) + if end_date is not None: + match.setdefault("date", {}).setdefault("$lte", end_date) + + cursor = flight_collection.aggregate([ + {"$match": match}, + {"$group": { + "_id": None, + "total_time": {"$sum": "$time_total"}, + "total_solo": {"$sum": "$time_solo"}, + "total_night": {"$sum": "$time_night"}, + "total_pic": {"$sum": "$time_pic"}, + "total_sic": {"$sum": "$time_sic"}, + } + }, + {"$project": {"_id": 0}}, + ]) + + result = await cursor.to_list(length=None) + + if not result: + raise HTTPException(404, "No flights found") + + return result[0] + + async def retrieve_flight(id: str) -> FlightDisplaySchema: """ Get detailed information about the given flight diff --git a/api/routes/flights.py b/api/routes/flights.py index be7c692..6f5b837 100644 --- a/api/routes/flights.py +++ b/api/routes/flights.py @@ -1,5 +1,6 @@ import json import logging +from datetime import datetime from typing import Dict, Union, List from fastapi import APIRouter, HTTPException, Depends @@ -53,6 +54,25 @@ async def get_flights_by_date(user: UserDisplaySchema = Depends(get_current_user return flights_ordered +@router.get('/totals', summary="Get total statistics for the current user", status_code=200, response_model=dict) +async def get_flight_totals(user: UserDisplaySchema = Depends(get_current_user), start_date: str = "", + end_date: str = "") -> dict: + """ + Get the total statistics for the currently logged-in user + + :param user: Current user + :param start_date: Only count statistics after this date (optional) + :param end_date: Only count statistics before this date (optional) + :return: Dict of totals + """ + try: + start = datetime.strptime(start_date, "%Y-%m-%d") if start_date != "" else None + end = datetime.strptime(end_date, "%Y-%m-%d") if end_date != "" else None + except (TypeError, ValueError): + raise HTTPException(400, "Date range not processable") + return await db.retrieve_totals(user.id, start, end) + + @router.get('/all', summary="Get all flights logged by all users", status_code=200, dependencies=[Depends(admin_required)], response_model=list[FlightConciseSchema]) async def get_all_flights(sort: str = "date", order: int = -1) -> list[FlightConciseSchema]: