Production

This commit is contained in:
Shubhankar45
2026-09-22 06:23:46 +00:00
commit 8fdd20b29f
217 changed files with 31212 additions and 0 deletions
View File
+52
View File
@@ -0,0 +1,52 @@
"""Chemist master data and chemist → MR assignment (same shape as doctors)."""
import uuid
from datetime import date
from sqlalchemy import Boolean, Date, ForeignKey, Index, String, UniqueConstraint, text
from sqlalchemy.dialects.postgresql import UUID as PGUUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.database.base import Base, TimestampMixin, UUIDMixin
class Chemist(Base, UUIDMixin, TimestampMixin):
__tablename__ = "chemist"
__table_args__ = (
UniqueConstraint(
"headquarters_id", "name", "shop_address", name="uq_chemist_hq_name_shop"
),
)
headquarters_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("headquarters.id", ondelete="RESTRICT"), nullable=False
)
name: Mapped[str] = mapped_column(String(200), nullable=False)
shop_address: Mapped[str] = mapped_column(String(500), nullable=False)
contact_number: Mapped[str | None] = mapped_column(String(20))
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
assignments: Mapped[list["ChemistAssignment"]] = relationship(back_populates="chemist")
class ChemistAssignment(Base, UUIDMixin, TimestampMixin):
__tablename__ = "chemist_assignment"
__table_args__ = (
Index(
"uq_active_chemist_assignment",
"chemist_id",
unique=True,
postgresql_where=text("effective_to IS NULL"),
),
)
chemist_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("chemist.id", ondelete="CASCADE"), nullable=False
)
mr_user_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="RESTRICT"), nullable=False
)
effective_from: Mapped[date] = mapped_column(Date, nullable=False)
effective_to: Mapped[date | None] = mapped_column(Date)
chemist: Mapped["Chemist"] = relationship(back_populates="assignments")
+62
View File
@@ -0,0 +1,62 @@
import uuid
from fastapi import APIRouter, Depends, Request, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth.dependencies import client_ip, get_current_user, require_role
from app.chemists.models import Chemist
from app.chemists.schemas import ChemistCreate, ChemistRead, ChemistUpdate
from app.chemists.service import ChemistService
from app.common.enums import Role
from app.database.session import get_db
from app.doctors.schemas import AssignToMR
from app.users.models import User
router = APIRouter(prefix="/chemists", tags=["chemists"])
@router.get("", response_model=list[ChemistRead])
async def list_chemists(
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
) -> list[Chemist]:
return await ChemistService(db).list_for(current_user)
@router.post("", response_model=ChemistRead, status_code=status.HTTP_201_CREATED)
async def create_chemist(
payload: ChemistCreate,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> Chemist:
return await ChemistService(db).create(payload, current_user, client_ip(request))
@router.patch("/{chemist_id}", response_model=ChemistRead)
async def update_chemist(
chemist_id: uuid.UUID,
payload: ChemistUpdate,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> Chemist:
return await ChemistService(db).update(chemist_id, payload, current_user, client_ip(request))
@router.post("/{chemist_id}/assign", status_code=status.HTTP_201_CREATED)
async def assign_chemist(
chemist_id: uuid.UUID,
payload: AssignToMR,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN, Role.GM, Role.AM)),
db: AsyncSession = Depends(get_db),
):
assignment = await ChemistService(db).assign_to_mr(
chemist_id, payload.mr_user_id, payload.effective_from, current_user, client_ip(request)
)
return {
"id": assignment.id,
"chemist_id": assignment.chemist_id,
"mr_user_id": assignment.mr_user_id,
"effective_from": assignment.effective_from,
}
+28
View File
@@ -0,0 +1,28 @@
import uuid
from pydantic import BaseModel, ConfigDict, Field
class ChemistCreate(BaseModel):
headquarters_id: uuid.UUID
name: str = Field(min_length=2, max_length=200)
shop_address: str = Field(min_length=2, max_length=500)
contact_number: str | None = Field(default=None, max_length=20)
class ChemistUpdate(BaseModel):
name: str | None = Field(default=None, min_length=2, max_length=200)
shop_address: str | None = Field(default=None, min_length=2, max_length=500)
contact_number: str | None = Field(default=None, max_length=20)
is_active: bool | None = None
class ChemistRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
headquarters_id: uuid.UUID
name: str
shop_address: str
contact_number: str | None
is_active: bool
+143
View File
@@ -0,0 +1,143 @@
import uuid
from datetime import date
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.audit.service import AuditService
from app.auth.dependencies import assert_can_view_hq, visible_hq_ids
from app.chemists.models import Chemist, ChemistAssignment
from app.chemists.schemas import ChemistCreate, ChemistUpdate
from app.common.enums import AuditAction, EntityType, Role
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
from app.common.utils import snapshot
from app.users.models import User
_AUDIT_FIELDS = ["name", "shop_address", "contact_number", "is_active"]
class ChemistService:
def __init__(self, db: AsyncSession) -> None:
self.db = db
self.audit = AuditService(db)
async def create(self, data: ChemistCreate, actor: User, ip: str | None = None) -> Chemist:
await assert_can_view_hq(self.db, actor, data.headquarters_id)
chemist = Chemist(**data.model_dump())
self.db.add(chemist)
try:
await self.db.flush()
except IntegrityError as exc:
await self.db.rollback()
raise ConflictError(
"A chemist with this name already exists at this address in this headquarters",
{"cause": "uq_chemist_hq_name_shop"},
) from exc
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.CHEMIST,
entity_id=chemist.id,
action=AuditAction.CREATE,
after=snapshot(chemist, _AUDIT_FIELDS),
ip_address=ip,
)
await self.db.commit()
return chemist
async def update(
self, chemist_id: uuid.UUID, data: ChemistUpdate, actor: User, ip: str | None = None
) -> Chemist:
chemist = await self.db.get(Chemist, chemist_id)
if chemist is None:
raise NotFoundError("Chemist not found")
await assert_can_view_hq(self.db, actor, chemist.headquarters_id)
before = snapshot(chemist, _AUDIT_FIELDS)
for field, value in data.model_dump(exclude_unset=True).items():
setattr(chemist, field, value)
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.CHEMIST,
entity_id=chemist.id,
action=AuditAction.UPDATE,
before=before,
after=snapshot(chemist, _AUDIT_FIELDS),
ip_address=ip,
)
await self.db.commit()
return chemist
async def list_for(self, actor: User) -> list[Chemist]:
if actor.role == Role.MR:
stmt = (
select(Chemist)
.join(ChemistAssignment, ChemistAssignment.chemist_id == Chemist.id)
.where(
ChemistAssignment.mr_user_id == actor.id,
ChemistAssignment.effective_to.is_(None),
Chemist.is_active.is_(True),
)
.order_by(Chemist.name)
)
return list((await self.db.execute(stmt)).scalars().all())
allowed = await visible_hq_ids(self.db, actor)
stmt = select(Chemist).order_by(Chemist.name)
if allowed is not None:
stmt = stmt.where(Chemist.headquarters_id.in_(allowed or [None]))
return list((await self.db.execute(stmt)).scalars().all())
async def assign_to_mr(
self,
chemist_id: uuid.UUID,
mr_user_id: uuid.UUID,
effective_from: date | None,
actor: User,
ip: str | None = None,
) -> ChemistAssignment:
chemist = await self.db.get(Chemist, chemist_id)
if chemist is None:
raise NotFoundError("Chemist not found")
await assert_can_view_hq(self.db, actor, chemist.headquarters_id)
mr = await self.db.get(User, mr_user_id)
if mr is None:
raise NotFoundError("MR not found")
if mr.role != Role.MR:
raise ValidationError("Chemists can only be assigned to an MR")
if mr.headquarters_id != chemist.headquarters_id:
raise ValidationError("MR and chemist belong to different headquarters")
start = effective_from or date.today()
existing = (
await self.db.execute(
select(ChemistAssignment).where(
ChemistAssignment.chemist_id == chemist_id,
ChemistAssignment.effective_to.is_(None),
)
)
).scalars().all()
for row in existing:
if row.mr_user_id == mr_user_id:
return row
row.effective_to = start
await self.db.flush()
assignment = ChemistAssignment(
chemist_id=chemist_id, mr_user_id=mr_user_id, effective_from=start
)
self.db.add(assignment)
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.CHEMIST,
entity_id=chemist_id,
action=AuditAction.ASSIGN,
after={"mr_user_id": str(mr_user_id), "effective_from": start.isoformat()},
ip_address=ip,
)
await self.db.commit()
return assignment