from datetime import datetime from sqlalchemy.orm import Session from db.models.drivetask import DriveTask from db.models.user import User from db.models.fuelingtask import FuelingTask from db.models.maintenancejob import MaintenanceJob from db.repository.maintenancejob import calculate_total_cost def get_repot_jobsdone_by_driver(driver_id: int, db: Session): driver = db.query(User).filter(User.Id == driver_id).first() if not driver: return "notdriver" if driver.Role != "Driver": return "notdriver" tasks = db.query(DriveTask).filter((DriveTask.DriverId == driver_id) & (DriveTask.Status == "Completed")).all() #order tasks by completion date tasks.sort(key=lambda x: x.EndDateTime) #for each task, add TOTAL distance driven at the time of completion dist = 0 taskslist = [] for task in tasks: dist += task.DistanceCovered taskslist.append(task.__dict__) taskslist[-1]["DistanceAtTime"] = dist res = {} res["tasks"] = taskslist res["Driver"] = driver.__dict__ res["Driver"]["AssignedVehicle"] = driver.vehicle dist = 0 for task in tasks: dist += task.DistanceCovered res["TotalDistance"] = dist timespent = 0.0 for task in tasks: edate = task.EndDateTime sdate = task.StartDateTime if type(edate) == str: edate = datetime.strptime(edate, "%Y-%m-%d %H:%M:%S.%f") timetaken = edate - sdate timespent += timetaken.total_seconds() #time spent in hours and minutes hours = timespent // 3600 minutes = (timespent % 3600) // 60 res["TotalTime"] = str(hours) + " hours " + str(minutes) + " minutes" #add fuel expenditures fuel = db.query(FuelingTask).filter(FuelingTask.DriverId == driver_id).all() fuel.sort(key=lambda x: x.Date) totalfuelspent = 0 fuelspent = [] for f in fuel: fuelpoint = {} totalfuelspent += f.FuelRefilled fuelpoint["fuelrefilled"] = f.FuelRefilled fuelpoint["total"] = totalfuelspent fuelpoint["date"] = f.Date fuelspent.append(fuelpoint) res["FuelSpent"] = fuelspent res["TotalFuelSpent"] = totalfuelspent #add maintenance costs mainten = db.query(MaintenanceJob).filter(MaintenanceJob.VehicleDriverId == driver_id).all() mainten.sort(key=lambda x: x.Date) totalmaintenspent = 0 maintenspent = [] for m in mainten: maintenpoint = {} cost = calculate_total_cost(m.CarParts) totalmaintenspent += cost maintenpoint["cost"] = cost maintenpoint["total"] = totalmaintenspent maintenpoint["date"] = m.Date maintenspent.append(maintenpoint) res["MaintenanceSpent"] = maintenspent res["TotalMaintenanceSpent"] = totalmaintenspent return res