50 lines
1.9 KiB
Python
50 lines
1.9 KiB
Python
from sqlmodel import Session, select
|
|
import src.models as models
|
|
|
|
def get_all(session: Session) -> list[models.ShipmentPublic]:
|
|
statement = select(models.Shipment)
|
|
return session.exec(statement).all()
|
|
|
|
def get_one(session: Session, shipment_id: int) -> models.ShipmentPublic:
|
|
return session.get(models.Shipment, shipment_id)
|
|
|
|
def create_one(session: Session, shipment: models.ShipmentCreate) -> models.ShipmentPublic:
|
|
products = session.exec(select(models.Product).where(models.Product.id.in_(shipment.product_ids))).all()
|
|
shipment_create = shipment.model_dump(exclude_unset=True, exclude={'product_ids'})
|
|
new_shipment = models.Shipment(**shipment_create, products=products)
|
|
session.add(new_shipment)
|
|
session.commit()
|
|
session.refresh(new_shipment)
|
|
return new_shipment
|
|
|
|
def update_one(session: Session, id: int, shipment: models.ShipmentUpdate) -> models.ShipmentPublic:
|
|
statement = select(models.Shipment).where(models.Shipment.id == id)
|
|
result = session.exec(statement)
|
|
new_shipment = result.first()
|
|
if not new_shipment:
|
|
return None
|
|
|
|
products_to_add = session.exec(select(models.Product).where(models.Product.id.in_(shipment.product_ids))).all()
|
|
new_shipment.products.clear()
|
|
for add in products_to_add:
|
|
new_shipment.products.append(add)
|
|
|
|
shipment_updates = shipment.model_dump(exclude_unset=True, exclude={"product_ids"})
|
|
for key, value in shipment_updates.items():
|
|
setattr(new_shipment, key, value)
|
|
|
|
session.add(new_shipment)
|
|
session.commit()
|
|
session.refresh(new_shipment)
|
|
return new_shipment
|
|
|
|
def delete_one(session: Session, id: int) -> models.ShipmentPublic:
|
|
statement = select(models.Shipment).where(models.Shipment.id == id)
|
|
result = session.exec(statement)
|
|
shipment = result.first()
|
|
if not shipment:
|
|
return None
|
|
result = models.ShipmentPublic.model_validate(shipment)
|
|
session.delete(shipment)
|
|
session.commit()
|
|
return result |