89 lines
2.8 KiB
Python
89 lines
2.8 KiB
Python
import uuid
|
|
from typing import Sequence
|
|
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.models.drug_shipment import DrugShipment
|
|
from app.schemas.drug_shipment import DrugShipmentCreate, DrugShipmentUpdate
|
|
|
|
|
|
async def create_shipment(
|
|
db: AsyncSession,
|
|
study_id: uuid.UUID,
|
|
shipment_in: DrugShipmentCreate,
|
|
created_by: uuid.UUID | None,
|
|
) -> DrugShipment:
|
|
shipment = DrugShipment(
|
|
study_id=study_id,
|
|
direction=shipment_in.direction,
|
|
center_id=shipment_in.center_id,
|
|
site_name=shipment_in.site_name or "",
|
|
ship_date=shipment_in.ship_date,
|
|
receive_date=shipment_in.receive_date,
|
|
quantity=shipment_in.quantity,
|
|
batch_no=shipment_in.batch_no,
|
|
carrier=shipment_in.carrier,
|
|
tracking_no=shipment_in.tracking_no,
|
|
status=shipment_in.status,
|
|
remark=shipment_in.remark,
|
|
created_by=created_by,
|
|
)
|
|
db.add(shipment)
|
|
await db.commit()
|
|
await db.refresh(shipment)
|
|
return shipment
|
|
|
|
|
|
async def get_shipment(db: AsyncSession, shipment_id: uuid.UUID) -> DrugShipment | None:
|
|
result = await db.execute(select(DrugShipment).where(DrugShipment.id == shipment_id))
|
|
return result.scalar_one_or_none()
|
|
|
|
|
|
async def list_shipments(
|
|
db: AsyncSession,
|
|
study_id: uuid.UUID,
|
|
center_id: uuid.UUID | None = None,
|
|
center_ids: set[uuid.UUID] | None = None,
|
|
site_name: str | None = None,
|
|
tracking_no: str | None = None,
|
|
direction: str | None = None,
|
|
status: str | None = None,
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
) -> Sequence[DrugShipment]:
|
|
stmt = select(DrugShipment).where(DrugShipment.study_id == study_id)
|
|
if center_ids is not None:
|
|
if not center_ids:
|
|
return []
|
|
stmt = stmt.where(DrugShipment.center_id.in_(center_ids))
|
|
if center_id:
|
|
stmt = stmt.where(DrugShipment.center_id == center_id)
|
|
if site_name:
|
|
stmt = stmt.where(DrugShipment.site_name.ilike(f"%{site_name}%"))
|
|
if tracking_no:
|
|
stmt = stmt.where(DrugShipment.tracking_no.ilike(f"%{tracking_no}%"))
|
|
if direction:
|
|
stmt = stmt.where(DrugShipment.direction == direction)
|
|
if status:
|
|
stmt = stmt.where(DrugShipment.status == status)
|
|
stmt = stmt.order_by(DrugShipment.created_at.desc()).offset(skip).limit(limit)
|
|
result = await db.execute(stmt)
|
|
return result.scalars().all()
|
|
|
|
|
|
async def update_shipment(
|
|
db: AsyncSession, shipment: DrugShipment, shipment_in: DrugShipmentUpdate
|
|
) -> DrugShipment:
|
|
update_data = shipment_in.model_dump(exclude_unset=True)
|
|
for key, value in update_data.items():
|
|
setattr(shipment, key, value)
|
|
await db.commit()
|
|
await db.refresh(shipment)
|
|
return shipment
|
|
|
|
|
|
async def delete_shipment(db: AsyncSession, shipment: DrugShipment) -> None:
|
|
await db.delete(shipment)
|
|
await db.commit()
|