From 13cb1e5ab8489a45ac8e0179c29e06ca04c80abe Mon Sep 17 00:00:00 2001
From: Madiwka <madi.turgunov.03@gmail.com>
Date: Sat, 4 Nov 2023 13:39:38 +0600
Subject: [PATCH] Images can now be uploaded. more work to be done on this in
 the future

---
 app/apis/v1/route_maintenancejob.py | 11 ++++++-----
 app/db/models/carpart.py            |  4 ++--
 app/db/models/fuelingtask.py        |  6 +++---
 app/db/models/maintenancejob.py     |  2 ++
 app/db/models/vehicle.py            |  1 +
 app/db/repository/maintenancejob.py |  7 ++++++-
 app/schemas/carpart.py              | 18 +++++++++++-------
 app/schemas/fuelingtask.py          | 16 +++++++++++-----
 app/schemas/maintenancejob.py       |  3 +++
 9 files changed, 45 insertions(+), 23 deletions(-)

diff --git a/app/apis/v1/route_maintenancejob.py b/app/apis/v1/route_maintenancejob.py
index 92f1ccd..00222e0 100644
--- a/app/apis/v1/route_maintenancejob.py
+++ b/app/apis/v1/route_maintenancejob.py
@@ -1,4 +1,4 @@
-from fastapi import Depends, APIRouter, HTTPException, status
+from fastapi import Depends, APIRouter, File, Form, HTTPException, UploadFile, status
 from sqlalchemy.orm import Session
 from db.session import get_db
 from db.repository.maintenancejob import (
@@ -10,7 +10,7 @@ from db.repository.maintenancejob import (
 )
 from typing import List
 from schemas.maintenancejob import CreateMaintenanceJob, OutputMaintenanceJob
-from schemas.carpart import CreateCarPart
+from schemas.carpart import CreateCarPart, ShowCarPart
 from db.models.user import User
 from apis.v1.route_auth import get_current_user
 
@@ -34,9 +34,9 @@ def create_maintenancejob(
     return maintenancejob_res
 
 
-@router.post("/carpart", status_code=status.HTTP_201_CREATED)
+@router.post("/carpart", response_model = ShowCarPart ,status_code=status.HTTP_201_CREATED)
 def create_carpart(
-    car_part: CreateCarPart,
+    car_part: CreateCarPart = Depends(),
     db: Session = Depends(get_db),
     current_user: User = Depends(get_current_user),
 ):
@@ -44,8 +44,9 @@ def create_carpart(
         raise HTTPException(
             status_code=403, detail="You are not authorized to perform this action"
         )
-
+    print("So it begins...")
     car_part_res = create_car_part(car_part=car_part, db=db)
+    print("So it ends...")
     return car_part_res
 
 
diff --git a/app/db/models/carpart.py b/app/db/models/carpart.py
index b721c51..e7fa9f6 100644
--- a/app/db/models/carpart.py
+++ b/app/db/models/carpart.py
@@ -1,4 +1,4 @@
-from sqlalchemy import Column, Integer, String, ForeignKey
+from sqlalchemy import Column, Integer, String, ForeignKey, LargeBinary
 from sqlalchemy.orm import relationship
 from db.base import Base
 
@@ -11,5 +11,5 @@ class CarPart(Base):
     Name = Column(String, nullable=False)
     Number = Column(String, nullable=False)
     Condition = Column(String, nullable=False)
-    ImageURL = Column(String, nullable=False)
+    ImageURL = Column(LargeBinary, nullable=False)
     Cost = Column(Integer, nullable=False)
diff --git a/app/db/models/fuelingtask.py b/app/db/models/fuelingtask.py
index 8b3c7ba..28fa89f 100644
--- a/app/db/models/fuelingtask.py
+++ b/app/db/models/fuelingtask.py
@@ -1,4 +1,4 @@
-from sqlalchemy import Column, Integer, String, ForeignKey, DateTime
+from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, LargeBinary
 from sqlalchemy.orm import relationship
 from db.base import Base
 
@@ -13,8 +13,8 @@ class FuelingTask(Base):
     Cost = Column(Integer, nullable=False)
     FuelRefilled = Column(Integer, nullable=False)
     GasStationName = Column(String, nullable=False)
-    ImageBefore = Column(String, nullable=False)
-    ImageAfter = Column(String, nullable=False)
+    ImageBefore = Column(LargeBinary, nullable=False)
+    ImageAfter = Column(LargeBinary, nullable=False)
     CreatedBy = relationship(
         "User", back_populates="fuelingTasks", foreign_keys="FuelingTask.CreatedById"
     )
diff --git a/app/db/models/maintenancejob.py b/app/db/models/maintenancejob.py
index 12dbc41..8b046b7 100644
--- a/app/db/models/maintenancejob.py
+++ b/app/db/models/maintenancejob.py
@@ -8,6 +8,8 @@ class MaintenanceJob(Base):
     # a list of weak entities of class CarPart
     CarParts = relationship("CarPart", back_populates="parent")
     CreatedBy = relationship("User", back_populates="maintenanceJobs")
+    VehicleID = Column(ForeignKey("vehicle.Id"), nullable=False)
+    Vehicle = relationship("Vehicle", back_populates="maintenanceJobs")
     Description = Column(String, nullable=False)
     Date = Column(DateTime, nullable=False)
     MaintenanceWorker = Column(ForeignKey("user.Id"), nullable=False)
diff --git a/app/db/models/vehicle.py b/app/db/models/vehicle.py
index e5a390b..343a72a 100644
--- a/app/db/models/vehicle.py
+++ b/app/db/models/vehicle.py
@@ -23,4 +23,5 @@ class Vehicle(Base):
     DriverHistory = Column(ARRAY(Integer), nullable=True)
     driver = relationship("User", back_populates="vehicle")
     auction = relationship("Auction", back_populates="vehicle")
+    maintenanceJobs = relationship("MaintenanceJob", back_populates="Vehicle")
      
diff --git a/app/db/repository/maintenancejob.py b/app/db/repository/maintenancejob.py
index 73d9825..de4668b 100644
--- a/app/db/repository/maintenancejob.py
+++ b/app/db/repository/maintenancejob.py
@@ -11,6 +11,7 @@ def create_new_maintenancejob(
     maintenancejob_object = MaintenanceJob(
         MaintenanceWorker=maintenanceworker,
         Description=maintenancejob.Description,
+        VehicleID=maintenancejob.VehicleID,
         Date=maintenancejob.Date,
     )
     print("OBJECT CREATED")
@@ -26,13 +27,15 @@ def create_car_part(car_part: CreateCarPart, db: Session):
         Name=car_part.Name,
         Number=car_part.Number,
         Condition=car_part.Condition,
-        ImageURL=car_part.ImageURL,
+        ImageURL=car_part.image.file.read(),
         Cost=car_part.Cost,
     )
     print("OBJECT CREATED")
     db.add(car_part_object)
     db.commit()
+    print("OBJECT SAVED")
     db.refresh(car_part_object)
+    print("OBJECT REFRESHED")
     return car_part_object
 
 
@@ -51,6 +54,7 @@ def get_all_maintenance_jobs(db: Session):
         job_dict["CarPartsList"] = [part.__dict__ for part in job.CarParts]
         job_dict["TotalCost"] = calculate_total_cost(job.CarParts)
         job_dict["AssignedTo"] = job.CreatedBy.__dict__
+        job_dict["Vehicle"] = job.Vehicle.__dict__
         result.append(job_dict)
     return maintenancejobs
 
@@ -64,6 +68,7 @@ def get_maintenance_job(maintenancejob_id: int, db: Session):
     maintenancejob.TotalCost = calculate_total_cost(maintenancejob.CarParts)
     # print(result.TotalCost)
     maintenancejob.AssignedTo = maintenancejob.CreatedBy.__dict__
+    maintenancejob.Vehicle = maintenancejob.Vehicle.__dict__
     print(maintenancejob.AssignedTo)
     print("DB Access complete")
     return maintenancejob
diff --git a/app/schemas/carpart.py b/app/schemas/carpart.py
index 18dc875..7417003 100644
--- a/app/schemas/carpart.py
+++ b/app/schemas/carpart.py
@@ -1,13 +1,18 @@
+
+from fastapi import Form, UploadFile
 from pydantic import BaseModel, Field
+from dataclasses import dataclass
 
 
 class CreateCarPart(BaseModel):
-    ParentId: int = Field(...)
-    Name: str = Field(...)
-    Number: str = Field(...)
-    Condition: str = Field(...)
-    ImageURL: str = Field(...)
-    Cost: int = Field(...)
+    ParentId: int = Form(...)
+    Name: str = Form(...)
+    Number: str = Form(...)
+    Condition: str = Form(...)
+    Cost: int = Form(...)
+    image: UploadFile = Form(...)
+    
+
 
 
 class ShowCarPart(BaseModel):
@@ -15,5 +20,4 @@ class ShowCarPart(BaseModel):
     Name: str = Field(...)
     Number: str = Field(...)
     Condition: str = Field(...)
-    ImageURL: str = Field(...)
     Cost: int = Field(...)
diff --git a/app/schemas/fuelingtask.py b/app/schemas/fuelingtask.py
index 80357e0..388b259 100644
--- a/app/schemas/fuelingtask.py
+++ b/app/schemas/fuelingtask.py
@@ -9,8 +9,11 @@ class CreateFuelingTask(BaseModel):
     Cost: int = Field(...)
     FuelRefilled: int = Field(...)
     GasStationName: str = Field(...)
-    ImageBefore: str = Field(...)
-    ImageAfter: str = Field(...)
+    ImageBefore: bytearray = Field(...)
+    ImageAfter: bytearray = Field(...)
+    model_config={
+        "arbitrary_types_allowed": True
+    }
 
 class OutputFuelingTask(BaseModel):
     VehicleId: int = Field(...)
@@ -19,6 +22,9 @@ class OutputFuelingTask(BaseModel):
     Cost: int = Field(...)
     FuelRefilled: int = Field(...)
     GasStationName: str = Field(...)
-    ImageBefore: str = Field(...)
-    ImageAfter: str = Field(...)
-    Driver: ShowDriver | None
\ No newline at end of file
+    ImageBefore: bytearray = Field(...)
+    ImageAfter: bytearray = Field(...)
+    Driver: ShowDriver | None
+    model_config={
+        "arbitrary_types_allowed": True
+    }
\ No newline at end of file
diff --git a/app/schemas/maintenancejob.py b/app/schemas/maintenancejob.py
index 17950a1..3d9f0bc 100644
--- a/app/schemas/maintenancejob.py
+++ b/app/schemas/maintenancejob.py
@@ -3,10 +3,12 @@ from datetime import datetime
 from typing import List, Optional
 from schemas.carpart import ShowCarPart
 from schemas.user import ShowUser
+from schemas.vehicle import OutputVehicle
 
 
 class CreateMaintenanceJob(BaseModel):
     Description: str = Field(...)
+    VehicleID: int = Field(...)
     Date: datetime = Field(...)
 
 
@@ -16,4 +18,5 @@ class OutputMaintenanceJob(BaseModel):
     Date: datetime
     CarPartsList: Optional[List[ShowCarPart]]
     TotalCost: int
+    Vehicle: OutputVehicle
     AssignedTo: ShowUser