56 lines
1.7 KiB
Python
56 lines
1.7 KiB
Python
from typing import Optional, List
|
|
from datetime import date
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.models.batch import Batch
|
|
|
|
|
|
class BatchRepository:
|
|
def __init__(self, db: AsyncSession):
|
|
self.db = db
|
|
|
|
async def get_by_id(self, batch_id: int) -> Optional[Batch]:
|
|
result = await self.db.execute(select(Batch).where(Batch.id == batch_id))
|
|
return result.scalar_one_or_none()
|
|
|
|
async def get_by_medicine_id(self, medicine_id: int) -> List[Batch]:
|
|
result = await self.db.execute(
|
|
select(Batch)
|
|
.where(Batch.medicine_id == medicine_id)
|
|
.order_by(Batch.expiry_date)
|
|
)
|
|
return list(result.scalars().all())
|
|
|
|
async def get_expiring_before(self, target_date: date) -> List[Batch]:
|
|
result = await self.db.execute(
|
|
select(Batch)
|
|
.where(
|
|
Batch.expiry_date <= target_date,
|
|
Batch.is_expired == False,
|
|
Batch.quantity > 0
|
|
)
|
|
)
|
|
return list(result.scalars().all())
|
|
|
|
async def create(self, data: dict) -> Batch:
|
|
batch = Batch(**data)
|
|
self.db.add(batch)
|
|
await self.db.flush()
|
|
return batch
|
|
|
|
async def update(self, batch_id: int, data: dict) -> Optional[Batch]:
|
|
batch = await self.get_by_id(batch_id)
|
|
if not batch:
|
|
return None
|
|
for key, value in data.items():
|
|
setattr(batch, key, value)
|
|
await self.db.flush()
|
|
return batch
|
|
|
|
async def delete(self, batch_id: int) -> bool:
|
|
batch = await self.get_by_id(batch_id)
|
|
if not batch:
|
|
return False
|
|
await self.db.delete(batch)
|
|
return True |