Server backup 2026-11-07 of uncommitted work in projects/pharma-web-celtic

Snapshot of the working tree on srv1071960 (branch main), taken during
server cleanup. .env files, node_modules, builds, logs and media were excluded.
This commit is contained in:
Shubhankar45
2026-11-07 05:43:12 +00:00
parent b001e2d03c
commit 0d30c58bf0
98 changed files with 1878 additions and 573 deletions
+1
View File
@@ -0,0 +1 @@
+46
View File
@@ -0,0 +1,46 @@
"""Stockist master data."""
import uuid
from sqlalchemy import Boolean, ForeignKey, String, UniqueConstraint
from sqlalchemy.dialects.postgresql import UUID as PGUUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.common.enums import MasterApproval
from app.database.base import Base, TimestampMixin, UUIDMixin
class Stockist(Base, UUIDMixin, TimestampMixin):
__tablename__ = "stockist"
__table_args__ = (
UniqueConstraint(
"headquarters_id", "name", "address", name="uq_stockist_hq_name_address"
),
)
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)
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)
approval_status: Mapped[str] = mapped_column(
String(10), default=MasterApproval.APPROVED.value, server_default=MasterApproval.APPROVED.value, nullable=False
)
requested_by_user_id: Mapped[uuid.UUID | None] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="SET NULL")
)
rejection_reason: Mapped[str | None] = mapped_column(String(500))
requested_by: Mapped["User | None"] = relationship( # noqa: F821
lazy="selectin", foreign_keys=[requested_by_user_id]
)
@property
def requested_by_name(self) -> str | None:
return self.requested_by.full_name if self.requested_by else None
@property
def shop_address(self) -> str:
return self.address
+82
View File
@@ -0,0 +1,82 @@
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.common.enums import Role
from app.database.session import get_db
from app.doctors.schemas import RejectMaster
from app.stockists.models import Stockist
from app.stockists.schemas import StockistCreate, StockistRead, StockistUpdate
from app.stockists.service import StockistService
from app.users.models import User
router = APIRouter(prefix="/stockists", tags=["stockists"])
@router.get("", response_model=list[StockistRead])
async def list_stockists(
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
) -> list[StockistRead]:
service = StockistService(db)
stockists = await service.list_for(current_user)
names = await service.mr_names_by_hq({s.headquarters_id for s in stockists})
return [
StockistRead.model_validate(s).model_copy(update={"assigned_mr_name": names.get(s.headquarters_id)})
for s in stockists
]
@router.post("", response_model=StockistRead, status_code=status.HTTP_201_CREATED)
async def create_stockist(
payload: StockistCreate,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN, Role.MR)),
db: AsyncSession = Depends(get_db),
) -> Stockist:
"""An Administrator (listed at once), or an MR within their own headquarters (waits for the
Area Business Manager)."""
return await StockistService(db).create(payload, current_user, client_ip(request))
@router.patch("/{stockist_id}", response_model=StockistRead)
async def update_stockist(
stockist_id: uuid.UUID,
payload: StockistUpdate,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> Stockist:
return await StockistService(db).update(stockist_id, payload, current_user, client_ip(request))
@router.get("/requests", response_model=list[StockistRead])
async def list_stockist_requests(
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
) -> list[Stockist]:
"""Stockists an MR added that wait for the Area Business Manager: an MR sees their own (with any
rejected and why), an Area Business Manager what waits for them, the administrator and AGM all."""
return await StockistService(db).requests_for(current_user)
@router.post("/{stockist_id}/approve", response_model=StockistRead)
async def approve_stockist(
stockist_id: uuid.UUID,
request: Request,
current_user: User = Depends(require_role(Role.ABM, Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> Stockist:
return await StockistService(db).review(stockist_id, True, None, current_user, client_ip(request))
@router.post("/{stockist_id}/reject", response_model=StockistRead)
async def reject_stockist(
stockist_id: uuid.UUID,
payload: RejectMaster,
request: Request,
current_user: User = Depends(require_role(Role.ABM, Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> Stockist:
return await StockistService(db).review(stockist_id, False, payload.reason, current_user, client_ip(request))
+58
View File
@@ -0,0 +1,58 @@
import uuid
from datetime import datetime
from pydantic import BaseModel, ConfigDict, Field, computed_field, model_validator
class StockistCreate(BaseModel):
headquarters_id: uuid.UUID
name: str = Field(min_length=2, max_length=200)
address: str | None = Field(default=None, min_length=2, max_length=500)
shop_address: str | None = Field(default=None, min_length=2, max_length=500)
contact_number: str | None = Field(default=None, max_length=20)
@model_validator(mode="after")
def resolve_address(self) -> "StockistCreate":
if not self.address and not self.shop_address:
raise ValueError("Address is required")
if not self.address:
self.address = self.shop_address
return self
class StockistUpdate(BaseModel):
headquarters_id: uuid.UUID | None = None
name: str | None = Field(default=None, min_length=2, max_length=200)
address: str | None = Field(default=None, min_length=2, max_length=500)
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
@model_validator(mode="after")
def resolve_address(self) -> "StockistUpdate":
if self.address is None and self.shop_address is not None:
self.address = self.shop_address
return self
class StockistRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
headquarters_id: uuid.UUID
name: str
address: str
contact_number: str | None
is_active: bool
approval_status: str
rejection_reason: str | None
requested_by_name: str | None
created_at: datetime
#: Filled by the list endpoint only: the MRs working this stockist's headquarters.
assigned_mr_name: str | None = None
@computed_field
@property
def shop_address(self) -> str:
return self.address
+154
View File
@@ -0,0 +1,154 @@
import uuid
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.common import master_approval
from app.common.enums import FIELD_ROLES, AuditAction, EntityType, MasterApproval
from app.common.exceptions import ConflictError, NotFoundError
from app.common.master_edit import commit_unique, move_headquarters
from app.common.utils import snapshot
from app.stockists.models import Stockist
from app.stockists.schemas import StockistCreate, StockistUpdate
from app.users.models import User, UserExtraHeadquarters
_AUDIT_FIELDS = ["headquarters_id", "name", "address", "contact_number", "is_active"]
class StockistService:
def __init__(self, db: AsyncSession) -> None:
self.db = db
self.audit = AuditService(db)
async def create(self, data: StockistCreate, actor: User, ip: str | None = None) -> Stockist:
await assert_can_view_hq(self.db, actor, data.headquarters_id)
values = data.model_dump(exclude_unset=True)
if "address" not in values and "shop_address" in values:
values["address"] = values.pop("shop_address")
else:
values.pop("shop_address", None)
# Added by an MR: it waits for the Area Business Manager. One they were refused is sent again.
if actor.role in FIELD_ROLES:
twin = await master_approval.rejected_twin(
self.db, Stockist, {k: values[k] for k in ("headquarters_id", "name", "address")}
)
if twin is not None:
await master_approval.resubmit(self.db, twin, values, actor)
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.STOCKIST,
entity_id=twin.id,
action=AuditAction.SUBMIT,
after=snapshot(twin, _AUDIT_FIELDS),
ip_address=ip,
)
await self.db.commit()
await self.db.refresh(twin)
return twin
stockist = Stockist(
**values,
approval_status=master_approval.initial_status(actor),
requested_by_user_id=actor.id if actor.role in FIELD_ROLES else None,
)
self.db.add(stockist)
try:
await self.db.flush()
except IntegrityError as exc:
await self.db.rollback()
raise ConflictError(
"A stockist with this name already exists at this address in this headquarters",
{"cause": "uq_stockist_hq_name_address"},
) from exc
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.STOCKIST,
entity_id=stockist.id,
action=AuditAction.CREATE,
after=snapshot(stockist, _AUDIT_FIELDS),
ip_address=ip,
)
await self.db.commit()
await self.db.refresh(stockist)
return stockist
async def update(
self, stockist_id: uuid.UUID, data: StockistUpdate, actor: User, ip: str | None = None
) -> Stockist:
stockist = await self.db.get(Stockist, stockist_id)
if stockist is None:
raise NotFoundError("Stockist not found")
await assert_can_view_hq(self.db, actor, stockist.headquarters_id)
before = snapshot(stockist, _AUDIT_FIELDS)
update_data = data.model_dump(exclude_unset=True)
new_hq = update_data.pop("headquarters_id", None)
if new_hq is not None:
await move_headquarters(self.db, actor, stockist, new_hq)
if "shop_address" in update_data and "address" not in update_data:
update_data["address"] = update_data.pop("shop_address")
else:
update_data.pop("shop_address", None)
for field, value in update_data.items():
setattr(stockist, field, value)
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.STOCKIST,
entity_id=stockist.id,
action=AuditAction.UPDATE,
before=before,
after=snapshot(stockist, _AUDIT_FIELDS),
ip_address=ip,
)
await commit_unique(self.db, "A stockist with this name already exists at this address in this headquarters")
return stockist
async def mr_names_by_hq(self, hq_ids: set[uuid.UUID]) -> dict[uuid.UUID, str]:
"""Stockists are not assigned to one MR: the active MRs / SFEs working each headquarters
(their own headquarters or an extra one), comma-joined, by headquarters id."""
if not hq_ids:
return {}
field = (User.is_active.is_(True), User.role.in_(list(FIELD_ROLES)))
primary = select(User.headquarters_id, User.full_name).where(User.headquarters_id.in_(hq_ids), *field)
extra = (
select(UserExtraHeadquarters.headquarters_id, User.full_name)
.join(User, User.id == UserExtraHeadquarters.user_id)
.where(UserExtraHeadquarters.headquarters_id.in_(hq_ids), *field)
)
names: dict[uuid.UUID, set[str]] = {}
for stmt in (primary, extra):
for hq_id, name in (await self.db.execute(stmt)).all():
names.setdefault(hq_id, set()).add(name)
return {hq_id: ", ".join(sorted(n)) for hq_id, n in names.items()}
async def list_for(self, actor: User) -> list[Stockist]:
allowed = await visible_hq_ids(self.db, actor)
stmt = (
select(Stockist)
.where(Stockist.approval_status == MasterApproval.APPROVED)
.order_by(Stockist.name)
)
if actor.role in FIELD_ROLES:
stmt = stmt.where(Stockist.is_active.is_(True))
if allowed is not None:
stmt = stmt.where(Stockist.headquarters_id.in_(allowed or [None]))
return list((await self.db.execute(stmt)).scalars().all())
async def requests_for(self, actor: User) -> list[Stockist]:
return await master_approval.requests_for(self.db, Stockist, actor)
async def review(
self, stockist_id: uuid.UUID, approve: bool, reason: str | None, actor: User, ip: str | None = None
) -> Stockist:
return await master_approval.review(
self.db, Stockist, EntityType.STOCKIST, stockist_id, approve, reason, actor, ip
)