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
+4
View File
@@ -12,8 +12,10 @@ from app.chemists.router import router as chemists_router
from app.csv_data.router import router as csv_data_router
from app.doctors.router import router as doctors_router
from app.organization.router import router as organization_router
from app.pdf.router import router as directory_pdf_router
from app.products.router import router as products_router
from app.reports.router import router as reports_router
from app.stockists.router import router as stockists_router
from app.users.router import router as users_router
api_router = APIRouter()
@@ -22,7 +24,9 @@ api_router.include_router(users_router)
api_router.include_router(organization_router)
api_router.include_router(doctors_router)
api_router.include_router(chemists_router)
api_router.include_router(stockists_router)
api_router.include_router(csv_data_router)
api_router.include_router(products_router)
api_router.include_router(reports_router)
api_router.include_router(audit_router)
api_router.include_router(directory_pdf_router)
+9 -9
View File
@@ -1,11 +1,11 @@
"""The approval workflow for the revised business requirement.
DRAFT --submit(MR)--> PENDING_AM
RETURNED --submit(MR)--> PENDING_AM
PENDING_AM --approve(AM)--> APPROVED (terminal, immutable)
PENDING_AM --return(AM)--> RETURNED
DRAFT --submit(MR)--> PENDING_ABM
RETURNED --submit(MR)--> PENDING_ABM
PENDING_ABM --approve(ABM)--> APPROVED (terminal, immutable)
PENDING_ABM --return(ABM)--> RETURNED
The Area Manager is the final approver; there is no General Manager stage.
The Area Business Manager is the final approver; there is no Assistant General Manager stage.
"""
from dataclasses import dataclass
@@ -24,11 +24,11 @@ class Transition:
TRANSITIONS: tuple[Transition, ...] = (
Transition(DCRStatus.DRAFT, WorkflowAction.SUBMIT, DCRStatus.PENDING_AM, Role.MR),
Transition(DCRStatus.RETURNED, WorkflowAction.SUBMIT, DCRStatus.PENDING_AM, Role.MR),
Transition(DCRStatus.PENDING_AM, WorkflowAction.APPROVE, DCRStatus.APPROVED, Role.AM),
Transition(DCRStatus.DRAFT, WorkflowAction.SUBMIT, DCRStatus.PENDING_ABM, Role.MR),
Transition(DCRStatus.RETURNED, WorkflowAction.SUBMIT, DCRStatus.PENDING_ABM, Role.MR),
Transition(DCRStatus.PENDING_ABM, WorkflowAction.APPROVE, DCRStatus.APPROVED, Role.ABM),
Transition(
DCRStatus.PENDING_AM, WorkflowAction.RETURN, DCRStatus.RETURNED, Role.AM,
DCRStatus.PENDING_ABM, WorkflowAction.RETURN, DCRStatus.RETURNED, Role.ABM,
requires_reason=True,
),
)
+2 -2
View File
@@ -32,10 +32,10 @@ async def get_audit_history(
if dcr is None:
raise NotFoundError("Report not found")
await assert_can_view_dcr(db, current_user, dcr)
elif current_user.role not in (Role.ADMIN, Role.GM):
elif current_user.role not in (Role.ADMIN, Role.AGM):
from app.common.exceptions import ForbiddenError
raise ForbiddenError("Only ADMIN or GM may read non-report audit history")
raise ForbiddenError("Only ADMIN or AGM may read non-report audit history")
return await AuditService(db).history_for(entity_type, entity_id)
+9 -9
View File
@@ -3,8 +3,8 @@
Layer 1 (`require_role`) answers "WHAT may this role do?".
Layer 2 (`assert_can_*`) answers "WHOSE data may this specific user touch?".
Most RBAC bugs live in the gap between those two questions: "AM" is a role, but
"AM *of this headquarters*" is a scope. Both checks are mandatory on scoped
Most RBAC bugs live in the gap between those two questions: "ABM" is the stored role code
for an ABM, but "ABM *of this headquarters*" is a scope. Both checks are mandatory on scoped
endpoints, and every one has a negative test asserting 403 (X1-X3).
"""
@@ -64,7 +64,7 @@ def require_role(*allowed: Role):
async def active_hq_ids_for_am(db: AsyncSession, am_user_id: uuid.UUID) -> set[uuid.UUID]:
"""Headquarters this Area Manager currently manages (`effective_to IS NULL`)."""
"""Headquarters this Area Business Manager currently manages (`effective_to IS NULL`)."""
stmt = select(AMHeadquarters.headquarters_id).where(
AMHeadquarters.area_manager_user_id == am_user_id,
AMHeadquarters.effective_to.is_(None),
@@ -73,10 +73,10 @@ async def active_hq_ids_for_am(db: AsyncSession, am_user_id: uuid.UUID) -> set[u
async def visible_hq_ids(db: AsyncSession, user: User) -> set[uuid.UUID] | None:
"""Headquarters the user may see. `None` means "all" (GM and ADMIN)."""
if user.role in (Role.GM, Role.ADMIN):
"""Headquarters the user may see. `None` means "all" (AGM and ADMIN)."""
if user.role in (Role.AGM, Role.ADMIN):
return None
if user.role == Role.AM:
if user.role == Role.ABM:
return await active_hq_ids_for_am(db, user.id)
if user.role in FIELD_ROLES:
return user.covered_headquarter_ids
@@ -94,13 +94,13 @@ async def assert_can_view_dcr(db: AsyncSession, user: User, dcr) -> None:
"""Layer 2 for reports.
ADMIN may inspect report content for support and administration, but cannot act on
reports because every transition endpoint still requires the AM role.
reports because every transition endpoint still requires the ABM role code (ABM).
"""
if user.role in (Role.GM, Role.ADMIN):
if user.role in (Role.AGM, Role.ADMIN):
return
if user.role in FIELD_ROLES and dcr.mr_user_id == user.id:
return
if user.role == Role.AM:
if user.role == Role.ABM:
if dcr.headquarters_id in await active_hq_ids_for_am(db, user.id):
return
raise ForbiddenError("Report outside your data scope")
+1 -1
View File
@@ -26,7 +26,7 @@ class Chemist(Base, UUIDMixin, TimestampMixin):
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)
#: PENDING until the Area Manager approves one an MR added; only APPROVED ones are listed or visited.
#: PENDING until the Area Business Manager approves one an MR added; only APPROVED ones are listed or visited.
approval_status: Mapped[str] = mapped_column(
String(10), default=MasterApproval.APPROVED.value, server_default=MasterApproval.APPROVED.value, nullable=False
)
+31 -9
View File
@@ -18,8 +18,19 @@ 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)
) -> list[ChemistRead]:
service = ChemistService(db)
chemists = await service.list_for(current_user)
names = await service.assigned_mr_names([c.id for c in chemists])
return [
ChemistRead.model_validate(c).model_copy(
update={
"assigned_mr_id": names[c.id][0] if c.id in names else None,
"assigned_mr_name": names[c.id][1] if c.id in names else None,
}
)
for c in chemists
]
@router.post("", response_model=ChemistRead, status_code=status.HTTP_201_CREATED)
@@ -29,7 +40,7 @@ async def create_chemist(
current_user: User = Depends(require_role(Role.ADMIN, Role.MR)),
db: AsyncSession = Depends(get_db),
) -> Chemist:
"""An Administrator, or an MR within their own headquarters (AM and GM cannot)."""
"""An Administrator, or an MR within their own headquarters (ABM and AGM cannot)."""
return await ChemistService(db).create(payload, current_user, client_ip(request))
@@ -44,12 +55,23 @@ async def update_chemist(
return await ChemistService(db).update(chemist_id, payload, current_user, client_ip(request))
@router.delete("/{chemist_id}/assign", status_code=status.HTTP_204_NO_CONTENT)
async def unassign_chemist(
chemist_id: uuid.UUID,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> None:
"""Administrator only: leave the chemist with no MR."""
await ChemistService(db).unassign(chemist_id, 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)),
current_user: User = Depends(require_role(Role.ADMIN, Role.AGM, Role.ABM)),
db: AsyncSession = Depends(get_db),
):
assignment = await ChemistService(db).assign_to_mr(
@@ -67,8 +89,8 @@ async def assign_chemist(
async def list_chemist_requests(
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
) -> list[Chemist]:
"""Chemists an MR added that wait for the Area Manager: an MR sees their own (with any
rejected and why), an Area Manager what waits for them, the administrator and GM all."""
"""Chemists 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 ChemistService(db).requests_for(current_user)
@@ -76,10 +98,10 @@ async def list_chemist_requests(
async def approve_chemist(
chemist_id: uuid.UUID,
request: Request,
current_user: User = Depends(require_role(Role.AM, Role.ADMIN)),
current_user: User = Depends(require_role(Role.ABM, Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> Chemist:
"""The Area Manager of its headquarters adds it to the list, assigned to the MR who asked."""
"""The Area Business Manager of its headquarters adds it to the list, assigned to the MR who asked."""
return await ChemistService(db).review(chemist_id, True, None, current_user, client_ip(request))
@@ -88,7 +110,7 @@ async def reject_chemist(
chemist_id: uuid.UUID,
payload: RejectMaster,
request: Request,
current_user: User = Depends(require_role(Role.AM, Role.ADMIN)),
current_user: User = Depends(require_role(Role.ABM, Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> Chemist:
return await ChemistService(db).review(chemist_id, False, payload.reason, current_user, client_ip(request))
+4
View File
@@ -12,6 +12,7 @@ class ChemistCreate(BaseModel):
class ChemistUpdate(BaseModel):
headquarters_id: uuid.UUID | None = None
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)
@@ -32,4 +33,7 @@ class ChemistRead(BaseModel):
rejection_reason: str | None
requested_by_name: str | None
created_at: datetime
#: Filled by the list endpoint only.
assigned_mr_name: str | None = None
assigned_mr_id: uuid.UUID | None = None
+38 -5
View File
@@ -10,12 +10,13 @@ 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 import master_approval
from app.common.master_edit import commit_unique, end_assignments, move_headquarters
from app.common.enums import AuditAction, EntityType, MasterApproval, Role, FIELD_ROLES
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"]
_AUDIT_FIELDS = ["headquarters_id", "name", "shop_address", "contact_number", "is_active"]
class ChemistService:
@@ -27,7 +28,7 @@ class ChemistService:
await assert_can_view_hq(self.db, actor, data.headquarters_id)
values = data.model_dump()
# Added by an MR: it waits for the Area Manager. One they were refused is sent again.
# Added by an MR: it waits for the Area Business Manager. One they were refused is sent again.
twin = None
if actor.role in FIELD_ROLES:
twin = await master_approval.rejected_twin(
@@ -97,7 +98,11 @@ class ChemistService:
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():
changes = data.model_dump(exclude_unset=True)
new_hq = changes.pop("headquarters_id", None)
if new_hq is not None:
await move_headquarters(self.db, actor, chemist, new_hq, ChemistAssignment, "chemist_id")
for field, value in changes.items():
setattr(chemist, field, value)
await self.audit.log(
@@ -109,7 +114,7 @@ class ChemistService:
after=snapshot(chemist, _AUDIT_FIELDS),
ip_address=ip,
)
await self.db.commit()
await commit_unique(self.db, "A chemist with this name already exists at this address in this headquarters")
return chemist
async def list_for(self, actor: User) -> list[Chemist]:
@@ -133,6 +138,34 @@ class ChemistService:
stmt = stmt.where(Chemist.headquarters_id.in_(allowed or [None]))
return list((await self.db.execute(stmt)).scalars().all())
async def assigned_mr_names(self, chemist_ids: list[uuid.UUID]) -> dict[uuid.UUID, tuple[uuid.UUID, str]]:
"""The MR (id, name) each chemist is currently assigned to, by chemist id."""
if not chemist_ids:
return {}
stmt = (
select(ChemistAssignment.chemist_id, User.id, User.full_name)
.join(User, User.id == ChemistAssignment.mr_user_id)
.where(ChemistAssignment.chemist_id.in_(chemist_ids), ChemistAssignment.effective_to.is_(None))
)
return {chemist_id: (mr_id, name) for chemist_id, mr_id, name in (await self.db.execute(stmt)).all()}
async def unassign(self, chemist_id: uuid.UUID, actor: User, ip: str | None = None) -> None:
"""Take the chemist away from its MR, leaving it unassigned."""
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)
if await end_assignments(self.db, ChemistAssignment, "chemist_id", chemist_id):
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.CHEMIST,
entity_id=chemist_id,
action=AuditAction.UPDATE,
after={"unassigned": True},
ip_address=ip,
)
await self.db.commit()
async def assign_to_mr(
self,
chemist_id: uuid.UUID,
@@ -146,7 +179,7 @@ class ChemistService:
raise NotFoundError("Chemist not found")
await assert_can_view_hq(self.db, actor, chemist.headquarters_id)
if chemist.approval_status != MasterApproval.APPROVED:
raise ValidationError("This chemist is still waiting for the Area Manager's approval")
raise ValidationError("This chemist is still waiting for the Area Business Manager's approval")
mr = await self.db.get(User, mr_user_id)
if mr is None:
+13 -12
View File
@@ -9,18 +9,18 @@ from enum import StrEnum
class Role(StrEnum):
"""Operational roles (MR/AM/GM) plus the technical ADMIN role.
"""Operational roles (MR, ABM, AGM; stored as MR/ABM/AGM) plus technical ADMIN.
ADMIN sits OUTSIDE the business hierarchy. It provisions users and masters but
can never approve a report or read report content (report §8, SEC-2).
ADMIN sits OUTSIDE the business hierarchy. It provisions users and masters and
may monitor reports, but can never approve one (report §8, SEC-2).
"""
ADMIN = "ADMIN"
GM = "GM"
AM = "AM"
AGM = "AGM"
ABM = "ABM"
MR = "MR"
#: Senior Field Executive: does an MR's work (daily reports, forms, doctors, chemists) and
#: reports to the same Area Manager, but may cover several headquarters.
#: reports to the same Area Business Manager, but may cover several headquarters.
SFE = "SFE"
@@ -29,25 +29,25 @@ FIELD_ROLES: frozenset[Role] = frozenset({Role.MR, Role.SFE})
class DCRStatus(StrEnum):
"""MR submits, the Area Manager approves or returns it.
"""MR submits, the Area Business Manager approves or returns it.
`RETURNED` captures the correction loop, and `APPROVED` remains terminal and
immutable. There is no General Manager step.
immutable. There is no Assistant General Manager step.
"""
DRAFT = "DRAFT"
PENDING_AM = "PENDING_AM"
PENDING_ABM = "PENDING_ABM"
RETURNED = "RETURNED"
APPROVED = "APPROVED"
class ReportType(StrEnum):
"""An MR files two reports a day, each approved by the Area Manager on its own.
"""An MR files two reports a day, each approved by the Area Business Manager on its own.
PLAN — in the morning: which doctors and chemists the MR intends to visit, and when.
ACTUAL — at the end of the day: the visits that happened, plus a short note for every
planned visit that did not. It can be started only once the plan is approved.
SELF — an Area Manager's own end-of-day report of the visits they made. It needs no
SELF — an Area Business Manager's own end-of-day report of the visits they made. It needs no
plan and no approval: submitting it makes it final.
"""
@@ -84,7 +84,7 @@ class ConversionStatus(StrEnum):
class MasterApproval(StrEnum):
"""A doctor or chemist an MR adds waits for their Area Manager before anyone can use it."""
"""A doctor or chemist an MR adds waits for their Area Business Manager before anyone can use it."""
PENDING = "PENDING"
APPROVED = "APPROVED"
@@ -109,6 +109,7 @@ class EntityType(StrEnum):
HEADQUARTERS = "headquarters"
DOCTOR = "doctor"
CHEMIST = "chemist"
STOCKIST = "stockist"
DCR = "dcr"
PRODUCT = "product"
#: A row of a company form (the table is named in the entry's data).
+18 -10
View File
@@ -1,11 +1,11 @@
"""Approval of the doctors and chemists an MR adds.
"""Approval of the doctors, chemists and stockists an MR adds.
MR adds one --> PENDING --approve(AM)--> APPROVED (listed, and visitable by that MR)
--reject(AM)---> REJECTED (the MR sees why; adding it again re-sends it)
MR adds one --> PENDING --approve(ABM)--> APPROVED (listed, and visitable by that MR)
--reject(ABM)---> REJECTED (the MR sees why; adding it again re-sends it)
Only APPROVED masters are listed or may be visited. The administrator's own additions are
APPROVED at once. The reviewer is the Area Manager of the master's headquarters (or the
administrator); the General Manager may look but not act.
APPROVED at once. The reviewer is the Area Business Manager of the master's headquarters (or the
administrator); the Assistant General Manager may look but not act.
"""
import uuid
@@ -34,14 +34,22 @@ async def rejected_twin(db: AsyncSession, model: Any, match: dict[str, Any]) ->
async def resubmit(
db: AsyncSession, record: Any, values: dict[str, Any], actor: User, assignment_model: Any, fk: str
db: AsyncSession,
record: Any,
values: dict[str, Any],
actor: User,
assignment_model: Any | None = None,
fk: str | None = None,
) -> None:
"""Re-send a rejected record with the MR's new details, assigned to that MR."""
"""Re-send a rejected record with the MR's new details, assigned to that MR (stockists have no
per-MR assignment: they belong to the headquarters)."""
for field, value in values.items():
setattr(record, field, value)
record.approval_status = MasterApproval.PENDING
record.requested_by_user_id = actor.id
record.rejection_reason = None
if assignment_model is None or fk is None:
return
today = date.today()
current = (
await db.execute(
@@ -59,7 +67,7 @@ async def resubmit(
async def requests_for(db: AsyncSession, model: Any, actor: User) -> list[Any]:
"""An MR: what they asked for that is still waiting or was rejected.
An Area Manager: what waits for them. Administrator and GM: everything waiting."""
An Area Business Manager: what waits for them. Administrator and AGM: everything waiting."""
stmt = select(model).order_by(model.created_at.desc())
if actor.role in FIELD_ROLES:
return list(
@@ -92,8 +100,8 @@ async def review(
record = await db.get(model, record_id)
if record is None:
raise NotFoundError(f"{entity_type.value.capitalize()} not found")
if actor.role not in (Role.AM, Role.ADMIN):
raise ForbiddenError("Only the Area Manager approves a new doctor or chemist")
if actor.role not in (Role.ABM, Role.ADMIN):
raise ForbiddenError("Only the Area Business Manager approves a new doctor, chemist or stockist")
await assert_can_view_hq(db, actor, record.headquarters_id)
target = MasterApproval.APPROVED if approve else MasterApproval.REJECTED
if record.approval_status == target:
+69
View File
@@ -0,0 +1,69 @@
"""Shared rules for an administrator editing a doctor, chemist or stockist."""
import uuid
from datetime import date
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth.dependencies import assert_can_view_hq
from app.common.exceptions import ConflictError, NotFoundError
from app.organization.models import Headquarters
from app.users.models import User
async def move_headquarters(
db: AsyncSession,
actor: User,
item,
new_hq_id: uuid.UUID,
assignment_model=None,
fk_field: str | None = None,
) -> None:
"""Move ``item`` to another headquarters. A current MR assignment ends when that MR does not
work the new headquarters, since an MR may only hold masters of the headquarters they cover."""
if new_hq_id == item.headquarters_id:
return
if await db.get(Headquarters, new_hq_id) is None:
raise NotFoundError("Headquarters not found")
await assert_can_view_hq(db, actor, new_hq_id)
item.headquarters_id = new_hq_id
if assignment_model is None:
return
current = (
await db.execute(
select(assignment_model).where(
getattr(assignment_model, fk_field) == item.id,
assignment_model.effective_to.is_(None),
)
)
).scalars().all()
for row in current:
mr = await db.get(User, row.mr_user_id)
if mr is None or new_hq_id not in mr.covered_headquarter_ids:
row.effective_to = date.today()
async def end_assignments(db: AsyncSession, assignment_model, fk_field: str, item_id: uuid.UUID) -> int:
"""Close every current MR assignment of one master; returns how many were closed."""
current = (
await db.execute(
select(assignment_model).where(
getattr(assignment_model, fk_field) == item_id,
assignment_model.effective_to.is_(None),
)
)
).scalars().all()
for row in current:
row.effective_to = date.today()
return len(current)
async def commit_unique(db: AsyncSession, message: str) -> None:
"""Commit, turning a unique-constraint clash (same name and address in a headquarters) into a 409."""
try:
await db.commit()
except IntegrityError as exc:
await db.rollback()
raise ConflictError(message) from exc
+10 -10
View File
@@ -1,6 +1,6 @@
"""Approval workflow for the company forms that carry an Area Manager signature.
"""Approval workflow for the company forms that carry an Area Business Manager signature.
draft --request(MR)--> pending --approve(AM)--> approved
draft --request(MR)--> pending --approve(ABM)--> approved
pending / approved --any change to the rows--> draft (a signature never covers edited data)
Every MR has their own copy of each form, so approval is per (form, MR). The request goes to the Area
@@ -24,13 +24,13 @@ APPROVAL_TABLES = {"standard_tour_plan", "tour_plan", "fare_chart", "expense_sta
async def owners_in_scope(db: AsyncSession, user: User) -> list[User]:
"""The MRs whose forms this user may see: themselves, their headquarters' MRs, or (admin, GM) all."""
"""The MRs whose forms this user may see: themselves, their headquarters' MRs, or (admin, AGM) all."""
stmt = select(User).where(User.role.in_(FIELD_ROLES), User.is_active.is_(True)).order_by(User.full_name)
if user.role in FIELD_ROLES:
stmt = stmt.where(User.id == user.id)
elif user.role == Role.AM:
elif user.role == Role.ABM:
stmt = stmt.where(User.headquarters_id.in_(await active_hq_ids_for_am(db, user.id)))
elif user.role not in (Role.ADMIN, Role.GM):
elif user.role not in (Role.ADMIN, Role.AGM):
return []
return list((await db.execute(stmt)).scalars())
@@ -49,7 +49,7 @@ async def assert_owner_in_scope(db: AsyncSession, user: User, owner_id: uuid.UUI
for owner in await owners_in_scope(db, user):
if owner.id == owner_id:
return owner
if user.role in (Role.ADMIN, Role.GM) or (await db.get(User, owner_id)) is None:
if user.role in (Role.ADMIN, Role.AGM) or (await db.get(User, owner_id)) is None:
raise NotFoundError("Medical representative not found", {"id": str(owner_id)})
raise ForbiddenError("This form belongs to a medical representative outside your headquarters")
@@ -70,7 +70,7 @@ async def _get_or_create(db: AsyncSession, table_name: str, owner_id: uuid.UUID)
async def list_approvals(db: AsyncSession, user: User) -> list[tuple[FormApproval, User, str | None]]:
"""(approval, MR, headquarters name) for what `user` can see.
An MR always gets all three forms ("draft" until they act); an Area Manager or admin only
An MR always gets all three forms ("draft" until they act); an Area Business Manager or admin only
gets forms that have been sent, since a draft is nothing for them to act on.
"""
owners = {o.id: o for o in await owners_in_scope(db, user)}
@@ -99,10 +99,10 @@ async def _row_count(db: AsyncSession, table_name: str, owner_id: uuid.UUID) ->
async def request_approval(db: AsyncSession, table_name: str, actor: User) -> FormApproval:
if await assigned_area_manager(db, actor) is None:
raise ValidationError("No Area Manager is assigned to your headquarters yet. Ask the administrator to assign one.")
raise ValidationError("No Area Business Manager is assigned to your headquarters yet. Ask the administrator to assign one.")
row = await _get_or_create(db, table_name, actor.id)
if row.status == "pending":
return row # already with the Area Manager — a second click changes nothing
return row # already with the Area Business Manager — a second click changes nothing
if row.status == "approved":
raise ConflictError("This form is already approved. Change a row to send it again.")
if await _row_count(db, table_name, actor.id) == 0:
@@ -115,7 +115,7 @@ async def request_approval(db: AsyncSession, table_name: str, actor: User) -> Fo
async def approve(db: AsyncSession, table_name: str, owner_id: uuid.UUID, actor: User) -> FormApproval:
await assert_owner_in_scope(db, actor, owner_id) # only the Area Manager assigned to this MR's headquarters
await assert_owner_in_scope(db, actor, owner_id) # only the Area Business Manager assigned to this MR's headquarters
row = await _get_or_create(db, table_name, owner_id)
if row.status == "approved":
return row # a double click
+2 -2
View File
@@ -1,4 +1,4 @@
"""Approval state of the company forms that carry an Area Manager signature."""
"""Approval state of the company forms that carry an Area Business Manager signature."""
import uuid
from datetime import datetime
@@ -9,7 +9,7 @@ from sqlalchemy.orm import Mapped, mapped_column
from app.database.base import Base
#: draft = not sent yet, pending = the MR asked for approval, approved = the Area Manager signed.
#: draft = not sent yet, pending = the MR asked for approval, approved = the Area Business Manager signed.
FORM_APPROVAL_STATUSES = ("draft", "pending", "approved")
+58 -23
View File
@@ -24,7 +24,7 @@ SERIAL_COLUMNS = {"serial_no", "doctor_sr_no", "chemist_sr_no"}
IDENTITY_COLUMNS = {"name", "employee_name", "headquarter"}
APPROVAL_TABLES = approvals.APPROVAL_TABLES
HIDDEN_TABLES = {"daily_call_report_csv"}
#: Forms where every row belongs to one MR (and is approved by that MR's Area Manager).
#: Forms where every row belongs to one MR (and is approved by that MR's Area Business Manager).
OWNED_TABLES = APPROVAL_TABLES
@@ -60,6 +60,10 @@ async def _reject_repeat(
raise ConflictError("An identical row already exists in this form")
#: Forms where the same row may legitimately be added again (e.g. a place visited repeatedly).
REPEATABLE_ROW_TABLES = {"standard_tour_plan"}
#: Tables whose printed Sl. No. starts over at 1 for each month rather than running on
#: forever — a shared master list (e.g. Sales Projection's product list) refilled every
#: month, not one MR's own running form.
@@ -173,6 +177,35 @@ async def _apply_sales_projection_product(
return values
#: Sales and Stock Statement products spelt differently from the Sales Projection list (compared as _pts_key).
_STOCK_PRODUCT_ALIASES = {"AMOCLODAXCV625": "AMOCLADOXCV625", "BONTRASTRONG": "BONETRASTRONG", "BONTRAMAX+": "BONETRAMAX+"}
def _pts_key(name: object) -> str:
"""A product name compared without case, spaces or hyphens ("Penorenz-MR-4" = "PENORENZ-MR 4")."""
key = re.sub(r"[^A-Z0-9+]", "", str(name or "").upper())
return _STOCK_PRODUCT_ALIASES.get(key, key)
async def _with_product_pts(
table_name: str, rows: list[dict[str, object]], db: AsyncSession
) -> list[dict[str, object]]:
"""Sales and Stock Statement: VALUE IN PTS shows the product's PTS from the Sales Projection list."""
if table_name != "sales_and_stock_statement" or not rows:
return rows
result = await db.execute(
text('SELECT product_name, pts FROM "sales_projection" WHERE COALESCE(btrim(pts), \'\') <> \'\' ORDER BY source_row_number')
)
prices: dict[str, str] = {}
for product_name, pts in result.all():
prices.setdefault(_pts_key(product_name), str(pts).strip())
for row in rows:
pts = prices.get(_pts_key(row.get("product_name")))
if pts is not None:
row["value_in_pts"] = pts
return rows
#: Expense Statement: the TOTAL column is always fare + daily allowance + postage + other expenses.
EXPENSE_AMOUNTS = ("fare", "da_hq", "da_ex", "da_out", "postage", "other_expense")
@@ -201,7 +234,7 @@ async def _owner_condition(
table_name: str, current_user: User, db: AsyncSession, owner_id: uuid.UUID | None
) -> tuple[list[str], dict[str, object]]:
"""Limit an approval form's rows to the MRs this user may see: an MR sees only their own,
an Area Manager only the MRs of their headquarters, an admin anyone (or one chosen MR)."""
an Area Business Manager only the MRs of their headquarters, an admin anyone (or one chosen MR)."""
if table_name not in OWNED_TABLES:
return [], {}
if current_user.role in FIELD_ROLES:
@@ -211,7 +244,7 @@ async def _owner_condition(
if owner_id is not None:
await approvals.assert_owner_in_scope(db, current_user, owner_id)
return ["owner_user_id = :owner"], {"owner": owner_id}
if current_user.role == Role.AM:
if current_user.role == Role.ABM:
return ["owner_user_id = ANY(:owners)"], {"owners": [o.id for o in await approvals.owners_in_scope(db, current_user)]}
return [], {}
@@ -231,7 +264,7 @@ async def _row_owner(table_name: str, row_id: uuid.UUID, current_user: User, db:
return owner_id
if current_user.role in FIELD_ROLES and owner_id != current_user.id:
raise ForbiddenError("This row belongs to another medical representative")
if current_user.role == Role.AM:
if current_user.role == Role.ABM:
if owner_id is None:
raise ForbiddenError("This row is outside your headquarters")
await approvals.assert_owner_in_scope(db, current_user, owner_id)
@@ -343,7 +376,7 @@ async def _load_per_mr_rows(
if who in people:
item["name"], item["headquarter"] = people[who][0], people[who][1] or ""
out.append(item)
return await _present_rows_for_user(out, current_user, db)
return await _with_product_pts(table_name, await _present_rows_for_user(out, current_user, db), db)
def _month_of_every_product(rows: list[dict[str, object]], month: str, columns: Iterable[str]) -> list[dict[str, object]]:
@@ -369,7 +402,7 @@ def _month_of_every_product(rows: list[dict[str, object]], month: str, columns:
def _available_csv_tables(current_user: User) -> list[str]:
visible = [name for name in FORM_ORDER if name not in HIDDEN_TABLES]
if current_user.role == Role.AM:
if current_user.role == Role.ABM:
return [name for name in visible if name in APPROVAL_TABLES]
return visible
@@ -377,12 +410,12 @@ def _available_csv_tables(current_user: User) -> list[str]:
def _ensure_table_access(table_name: str, current_user: User) -> None:
if table_name in HIDDEN_TABLES:
raise ForbiddenError("This CSV form is not available for export.", {"table": table_name})
if current_user.role == Role.AM and table_name not in APPROVAL_TABLES:
raise ForbiddenError("Area Manager can only access approval forms.", {"table": table_name})
if current_user.role == Role.ABM and table_name not in APPROVAL_TABLES:
raise ForbiddenError("Area Business Manager can only access approval forms.", {"table": table_name})
@router.get("/tables")
async def list_csv_tables(current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM, Role.GM))) -> list[dict[str, object]]:
async def list_csv_tables(current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.ABM, Role.AGM))) -> list[dict[str, object]]:
return [{"name": name, "label": CSV_LABELS[name], "columns": list(TABLES[name])} for name in _available_csv_tables(current_user)]
@@ -427,16 +460,16 @@ def _approval_table(table_name: str) -> str:
@router.get("/approvals")
async def list_form_approvals(
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM, Role.GM)),
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.ABM, Role.AGM)),
) -> list[dict[str, object]]:
"""Approval state of the forms that carry an Area Manager signature, limited to the MRs this user may see."""
"""Approval state of the forms that carry an Area Business Manager signature, limited to the MRs this user may see."""
return [_approval_out(r, owner, hq) for r, owner, hq in await approvals.list_approvals(db, current_user)]
@router.get("/owners")
async def list_form_owners(
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM, Role.GM)),
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.ABM, Role.AGM)),
) -> list[dict[str, object]]:
"""The medical representatives whose forms this user may open."""
hq = {h.id: h.name for h in (await db.execute(select(Headquarters))).scalars()}
@@ -452,7 +485,7 @@ async def request_form_approval(
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role(Role.MR)),
) -> dict[str, object]:
"""The MR sends a form to the Area Manager."""
"""The MR sends a form to the Area Business Manager."""
row = await approvals.request_approval(db, _approval_table(table_name), current_user)
return _approval_out(row, current_user, await _hq_name(db, current_user))
@@ -462,9 +495,9 @@ async def approve_form(
table_name: str,
owner_id: uuid.UUID = Query(description="The MR whose form is being approved"),
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role(Role.AM)),
current_user: User = Depends(require_role(Role.ABM)),
) -> dict[str, object]:
"""The Area Manager signs an MR's form — only the one who manages that MR's headquarters."""
"""The Area Business Manager signs an MR's form — only the one who manages that MR's headquarters."""
row = await approvals.approve(db, _approval_table(table_name), owner_id, current_user)
owner = await db.get(User, owner_id)
return _approval_out(row, owner, await _hq_name(db, owner))
@@ -475,7 +508,7 @@ async def list_csv_rows(
table_name: str,
owner_id: uuid.UUID | None = None,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM, Role.GM)),
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.ABM, Role.AGM)),
) -> list[dict[str, object]]:
_ensure_table_access(table_name, current_user)
return await _load_rows(table_name, db, current_user, owner_id)
@@ -508,7 +541,9 @@ async def create_csv_row(
values = _apply_expense_total(values)
if not _has_user_data(table_name, values):
raise ValidationError("Add at least one value before creating a row")
await _reject_repeat(table_name, values, db, owner.id if owner else None)
# An MR may list the same place in the Standard Tour Plan more than once.
if table_name not in REPEATABLE_ROW_TABLES:
await _reject_repeat(table_name, values, db, owner.id if owner else None)
next_row = (await db.execute(text(f'SELECT COALESCE(MAX(source_row_number), 0) + 1 FROM "{table_name}"'))).scalar_one()
for column in columns:
if column in SERIAL_COLUMNS:
@@ -524,7 +559,7 @@ async def create_csv_row(
await _renumber_rows(table_name, db)
await approvals.invalidate(db, table_name, owner.id if owner else None)
await db.commit()
return await _get_row(table_name, row_id, db)
return (await _with_product_pts(table_name, [await _get_row(table_name, row_id, db)], db))[0]
async def _stored_owner(table_name: str, row_id: uuid.UUID, db: AsyncSession) -> uuid.UUID | None:
@@ -562,7 +597,7 @@ async def _start_own_row(
)
await _renumber_rows(table_name, db)
await db.commit()
return await _get_row(table_name, row_id, db)
return (await _with_product_pts(table_name, [await _get_row(table_name, row_id, db)], db))[0]
@router.patch("/{table_name}/rows/{row_id}")
@@ -596,7 +631,7 @@ async def update_csv_row(table_name: str, row_id: uuid.UUID, payload: dict[str,
raise NotFoundError("CSV row not found", {"id": str(row_id)})
await approvals.invalidate(db, table_name, row_owner)
await db.commit()
return await _get_row(table_name, row_id, db)
return (await _with_product_pts(table_name, [await _get_row(table_name, row_id, db)], db))[0]
@router.delete("/{table_name}/rows/{row_id}", status_code=status.HTTP_204_NO_CONTENT)
@@ -689,12 +724,12 @@ async def download_csv_row_pdf(
table_name: str,
row_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM, Role.GM)),
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.ABM, Role.AGM)),
) -> Response:
_ensure_table_access(table_name, current_user)
row_owner = await _row_owner(table_name, row_id, current_user, db)
row = await _get_row(table_name, row_id, db)
row = (await _present_rows_for_user([row], current_user, db))[0]
row = (await _with_product_pts(table_name, await _present_rows_for_user([row], current_user, db), db))[0]
approval_status, am_name, approved_at = await _signature(table_name, row_owner, db)
return Response(
_pdf_bytes(table_name, CSV_LABELS[table_name], row, approval_status, am_name, approved_at),
@@ -709,7 +744,7 @@ async def download_csv_table_pdfs(
owner_id: uuid.UUID | None = None,
month: str | None = None,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM, Role.GM)),
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.ABM, Role.AGM)),
) -> Response:
"""The whole form, or only one month of it (for the forms that have a month)."""
_ensure_table_access(table_name, current_user)
+4 -1
View File
@@ -13,7 +13,8 @@ from app.database.base import Base
from app.doctors.models import Doctor, DoctorAssignment
from app.organization.models import AMHeadquarters, Company, Headquarters
from app.products.models import Product
from app.reports.models import ChemistCall, DailyCallReport, DoctorCall, MissedVisit
from app.reports.models import ChemistCall, DailyCallReport, DoctorCall, MissedVisit, StockistCall
from app.stockists.models import Stockist
from app.users.models import User, UserExtraHeadquarters # noqa: F401
__all__ = [
@@ -32,6 +33,8 @@ __all__ = [
"DailyCallReport",
"DoctorCall",
"MissedVisit",
"StockistCall",
"User",
"Product",
"Stockist",
]
+1 -1
View File
@@ -40,7 +40,7 @@ class Doctor(Base, UUIDMixin, TimestampMixin):
#: Core doctors are the high-value targets tracked for conversion.
is_core_doctor: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
#: PENDING until the Area Manager approves one an MR added; only APPROVED ones are listed or visited.
#: PENDING until the Area Business Manager approves one an MR added; only APPROVED ones are listed or visited.
approval_status: Mapped[str] = mapped_column(
String(10), default=MasterApproval.APPROVED.value, server_default=MasterApproval.APPROVED.value, nullable=False
)
+27 -10
View File
@@ -17,9 +17,15 @@ router = APIRouter(prefix="/doctors", tags=["doctors"])
@router.get("", response_model=list[DoctorRead])
async def list_doctors(
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
) -> list[Doctor]:
) -> list[DoctorRead]:
"""S5 — an MR gets only their assigned doctors; managers get their HQ scope."""
return await DoctorService(db).list_for(current_user)
rows = await DoctorService(db).list_for(current_user)
return [
DoctorRead.model_validate(doctor).model_copy(
update={"assigned_mr_name": assigned_mr_name, "assigned_mr_id": mr_id}
)
for doctor, assigned_mr_name, mr_id in rows
]
@router.post("", response_model=DoctorRead, status_code=status.HTTP_201_CREATED)
@@ -29,7 +35,7 @@ async def create_doctor(
current_user: User = Depends(require_role(Role.ADMIN, Role.MR)),
db: AsyncSession = Depends(get_db),
) -> Doctor:
"""An Administrator, or an MR within their own headquarters (AM and GM cannot)."""
"""An Administrator, or an MR within their own headquarters (ABM and AGM cannot)."""
return await DoctorService(db).create(payload, current_user, client_ip(request))
@@ -44,15 +50,26 @@ async def update_doctor(
return await DoctorService(db).update(doctor_id, payload, current_user, client_ip(request))
@router.delete("/{doctor_id}/assign", status_code=status.HTTP_204_NO_CONTENT)
async def unassign_doctor(
doctor_id: uuid.UUID,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> None:
"""Administrator only: leave the doctor with no MR."""
await DoctorService(db).unassign(doctor_id, current_user, client_ip(request))
@router.post("/{doctor_id}/assign", status_code=status.HTTP_201_CREATED)
async def assign_doctor(
doctor_id: uuid.UUID,
payload: AssignToMR,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN, Role.GM, Role.AM)),
current_user: User = Depends(require_role(Role.ADMIN, Role.AGM, Role.ABM)),
db: AsyncSession = Depends(get_db),
):
"""An AM may assign only within their own headquarters — enforced by data scope."""
"""An ABM may assign only within their own headquarters — enforced by data scope."""
assignment = await DoctorService(db).assign_to_mr(
doctor_id, payload.mr_user_id, payload.effective_from, current_user, client_ip(request)
)
@@ -68,8 +85,8 @@ async def assign_doctor(
async def list_doctor_requests(
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
) -> list[Doctor]:
"""Doctors an MR added that wait for the Area Manager: an MR sees their own (with any
rejected and why), an Area Manager what waits for them, the administrator and GM all."""
"""Doctors 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 DoctorService(db).requests_for(current_user)
@@ -77,10 +94,10 @@ async def list_doctor_requests(
async def approve_doctor(
doctor_id: uuid.UUID,
request: Request,
current_user: User = Depends(require_role(Role.AM, Role.ADMIN)),
current_user: User = Depends(require_role(Role.ABM, Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> Doctor:
"""The Area Manager of its headquarters adds it to the list, assigned to the MR who asked."""
"""The Area Business Manager of its headquarters adds it to the list, assigned to the MR who asked."""
return await DoctorService(db).review(doctor_id, True, None, current_user, client_ip(request))
@@ -89,7 +106,7 @@ async def reject_doctor(
doctor_id: uuid.UUID,
payload: RejectMaster,
request: Request,
current_user: User = Depends(require_role(Role.AM, Role.ADMIN)),
current_user: User = Depends(require_role(Role.ABM, Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> Doctor:
return await DoctorService(db).review(doctor_id, False, payload.reason, current_user, client_ip(request))
+4 -1
View File
@@ -24,6 +24,7 @@ class DoctorCreate(BaseModel):
class DoctorUpdate(BaseModel):
headquarters_id: uuid.UUID | None = None
name: str | None = Field(default=None, min_length=2, max_length=200)
clinic_address: str | None = Field(default=None, min_length=2, max_length=500)
speciality: str | None = Field(default=None, max_length=100)
@@ -49,6 +50,8 @@ class DoctorRead(BaseModel):
date_of_birth: date | None
is_core_doctor: bool
is_active: bool
assigned_mr_name: str | None = None
assigned_mr_id: uuid.UUID | None = None
#: PENDING / APPROVED / REJECTED — see app/common/master_approval.py.
approval_status: str
rejection_reason: str | None
@@ -62,6 +65,6 @@ class AssignToMR(BaseModel):
class RejectMaster(BaseModel):
"""Why the Area Manager refused a doctor or chemist an MR added — shown to that MR."""
"""Why the Area Business Manager refused a doctor or chemist an MR added — shown to that MR."""
reason: str = Field(min_length=3, max_length=500)
+50 -22
View File
@@ -1,13 +1,14 @@
import uuid
from datetime import date
from sqlalchemy import select
from sqlalchemy import and_, 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.master_edit import commit_unique, end_assignments, move_headquarters
from app.common.enums import AuditAction, EntityType, MasterApproval, Role, FIELD_ROLES
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
from app.common.utils import snapshot
@@ -16,6 +17,7 @@ from app.doctors.schemas import DoctorCreate, DoctorUpdate
from app.users.models import User
_AUDIT_FIELDS = [
"headquarters_id",
"name",
"clinic_address",
"speciality",
@@ -35,7 +37,7 @@ class DoctorService:
await assert_can_view_hq(self.db, actor, data.headquarters_id)
values = data.model_dump()
# Added by an MR: it waits for the Area Manager. One they were refused is sent again.
# Added by an MR: it waits for the Area Business Manager. One they were refused is sent again.
twin = None
if actor.role in FIELD_ROLES:
twin = await master_approval.rejected_twin(
@@ -105,7 +107,11 @@ class DoctorService:
await assert_can_view_hq(self.db, actor, doctor.headquarters_id)
before = snapshot(doctor, _AUDIT_FIELDS)
for field, value in data.model_dump(exclude_unset=True).items():
changes = data.model_dump(exclude_unset=True)
new_hq = changes.pop("headquarters_id", None)
if new_hq is not None:
await move_headquarters(self.db, actor, doctor, new_hq, DoctorAssignment, "doctor_id")
for field, value in changes.items():
setattr(doctor, field, value)
await self.audit.log(
@@ -117,30 +123,52 @@ class DoctorService:
after=snapshot(doctor, _AUDIT_FIELDS),
ip_address=ip,
)
await self.db.commit()
await commit_unique(self.db, "A doctor with this name already exists at this clinic in this headquarters")
return doctor
async def list_for(self, actor: User) -> list[Doctor]:
async def list_for(self, actor: User) -> list[tuple[Doctor, str | None, uuid.UUID | None]]:
"""An MR sees ONLY doctors currently assigned to them (R5)."""
if actor.role in FIELD_ROLES:
stmt = (
select(Doctor)
.join(DoctorAssignment, DoctorAssignment.doctor_id == Doctor.id)
.where(
DoctorAssignment.mr_user_id == actor.id,
stmt = (
select(Doctor, User.full_name, User.id)
.outerjoin(
DoctorAssignment,
and_(
DoctorAssignment.doctor_id == Doctor.id,
DoctorAssignment.effective_to.is_(None),
Doctor.is_active.is_(True),
Doctor.approval_status == MasterApproval.APPROVED,
)
.order_by(Doctor.name)
),
)
return list((await self.db.execute(stmt)).scalars().all())
.outerjoin(User, User.id == DoctorAssignment.mr_user_id)
.where(Doctor.approval_status == MasterApproval.APPROVED)
.order_by(Doctor.name)
)
if actor.role in FIELD_ROLES:
stmt = stmt.where(
DoctorAssignment.mr_user_id == actor.id,
Doctor.is_active.is_(True),
)
else:
allowed = await visible_hq_ids(self.db, actor)
if allowed is not None:
stmt = stmt.where(Doctor.headquarters_id.in_(allowed or [None]))
rows = (await self.db.execute(stmt)).all()
return [(doctor, assigned_mr_name, mr_id) for doctor, assigned_mr_name, mr_id in rows]
allowed = await visible_hq_ids(self.db, actor)
stmt = select(Doctor).where(Doctor.approval_status == MasterApproval.APPROVED).order_by(Doctor.name)
if allowed is not None:
stmt = stmt.where(Doctor.headquarters_id.in_(allowed or [None]))
return list((await self.db.execute(stmt)).scalars().all())
async def unassign(self, doctor_id: uuid.UUID, actor: User, ip: str | None = None) -> None:
"""Take the doctor away from its MR, leaving it unassigned."""
doctor = await self.db.get(Doctor, doctor_id)
if doctor is None:
raise NotFoundError("Doctor not found")
await assert_can_view_hq(self.db, actor, doctor.headquarters_id)
if await end_assignments(self.db, DoctorAssignment, "doctor_id", doctor_id):
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.DOCTOR,
entity_id=doctor_id,
action=AuditAction.UPDATE,
after={"unassigned": True},
ip_address=ip,
)
await self.db.commit()
async def assign_to_mr(
self,
@@ -155,7 +183,7 @@ class DoctorService:
raise NotFoundError("Doctor not found")
await assert_can_view_hq(self.db, actor, doctor.headquarters_id)
if doctor.approval_status != MasterApproval.APPROVED:
raise ValidationError("This doctor is still waiting for the Area Manager's approval")
raise ValidationError("This doctor is still waiting for the Area Business Manager's approval")
mr = await self.db.get(User, mr_user_id)
if mr is None:
+1 -1
View File
@@ -50,7 +50,7 @@ def create_app() -> FastAPI:
version="0.1.0",
description=(
"Pharmaceutical field-force reporting — MVP. "
"Daily Call Reports with AM final approval, GM monitoring, "
"Daily Call Reports with ABM final approval, AGM monitoring, "
"locked PDFs and audit trails."
),
docs_url="/docs",
+4 -4
View File
@@ -3,7 +3,7 @@
Design notes (report §13.2):
- `area_territory` was merged into `headquarters` — the brief states HQ *is* the
territory, and two tables for one concept invites drift.
- An MR's Area Manager is DERIVED through the headquarters, not stored on the MR.
- An MR's Area Business Manager is DERIVED through the headquarters, not stored on the MR.
An HQ handover therefore re-points every MR in that HQ with no data migration.
"""
@@ -54,10 +54,10 @@ class Headquarters(Base, UUIDMixin, TimestampMixin):
class AMHeadquarters(Base, UUIDMixin, TimestampMixin):
"""Which Area Manager currently manages which headquarters.
"""Which Area Business Manager currently manages which headquarters.
`effective_to IS NULL` means "current". A headquarters may have several Area Managers
and an Area Manager several headquarters; the partial unique index only stops the same
`effective_to IS NULL` means "current". A headquarters may have several Area Business Managers
and an Area Business Manager several headquarters; the partial unique index only stops the same
pair being active twice.
"""
+4 -4
View File
@@ -24,16 +24,16 @@ router = APIRouter(prefix="/headquarters", tags=["organization"])
async def list_headquarters(
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
) -> list[Headquarters]:
"""Scoped: an MR sees their own HQ, an AM sees theirs, GM/Admin see all."""
"""Scoped: an MR sees their own HQ, an ABM sees theirs, AGM/Admin see all."""
return await OrganizationService(db).list_headquarters(current_user)
@router.get("/area-managers", response_model=list[AMHeadquartersRead])
async def list_area_manager_mappings(
current_user: User = Depends(require_role(Role.ADMIN, Role.GM)),
current_user: User = Depends(require_role(Role.ADMIN, Role.AGM)),
db: AsyncSession = Depends(get_db),
):
"""Which Area Manager currently manages which headquarters (one row per pair)."""
"""Which Area Business Manager currently manages which headquarters (one row per pair)."""
return await OrganizationService(db).list_area_manager_mappings(current_user)
@@ -45,7 +45,7 @@ async def set_area_manager_headquarters(
current_user: User = Depends(require_role(Role.ADMIN)),
db: AsyncSession = Depends(get_db),
):
"""Replace the set of headquarters an Area Manager manages (any number)."""
"""Replace the set of headquarters an Area Business Manager manages (any number)."""
return await OrganizationService(db).set_area_manager_headquarters(
area_manager_user_id,
payload.headquarters_ids,
+1 -1
View File
@@ -43,7 +43,7 @@ class AssignAreaManager(BaseModel):
class SetAreaManagerHeadquarters(BaseModel):
"""The complete list of headquarters an Area Manager should manage (may be empty)."""
"""The complete list of headquarters an Area Business Manager should manage (may be empty)."""
headquarters_ids: list[uuid.UUID] = Field(default_factory=list, max_length=500)
effective_from: date | None = None
+7 -7
View File
@@ -60,7 +60,7 @@ class OrganizationService:
return list((await self.db.execute(stmt)).scalars().all())
async def list_area_manager_mappings(self, actor: User) -> list[AMHeadquarters]:
"""Current (open) Area Manager to headquarters mappings, for display."""
"""Current (open) Area Business Manager to headquarters mappings, for display."""
stmt = (
select(AMHeadquarters)
.join(Headquarters, Headquarters.id == AMHeadquarters.headquarters_id)
@@ -79,7 +79,7 @@ class OrganizationService:
actor: User,
ip: str | None = None,
) -> list[AMHeadquarters]:
"""Make `headquarters_ids` exactly the set of headquarters this AM manages.
"""Make `headquarters_ids` exactly the set of headquarters this ABM manages.
Headquarters missing from the list are released, new ones are added. Other Area
Managers of the same headquarters keep it: a headquarters may have several.
@@ -87,9 +87,9 @@ class OrganizationService:
manager = await self.db.get(User, am_user_id)
if manager is None or manager.company_id != actor.company_id:
raise NotFoundError("User not found")
if manager.role != Role.AM:
if manager.role != Role.ABM:
raise ValidationError(
"Only a user with the AM role can manage a headquarters",
"Only an ABM can manage a headquarters",
{"user_role": manager.role.value},
)
@@ -165,7 +165,7 @@ class OrganizationService:
actor: User,
ip: str | None = None,
) -> AMHeadquarters:
"""Add an Area Manager to a headquarters, beside any it already has.
"""Add an Area Business Manager to a headquarters, beside any it already has.
Assigning the same pair twice changes nothing (`uq_active_am_hq_pair`).
"""
@@ -176,9 +176,9 @@ class OrganizationService:
manager = await self.db.get(User, am_user_id)
if manager is None:
raise NotFoundError("User not found")
if manager.role != Role.AM:
if manager.role != Role.ABM:
raise ValidationError(
"Only a user with the AM role can manage a headquarters",
"Only an ABM can manage a headquarters",
{"user_role": manager.role.value},
)
+35 -6
View File
@@ -80,7 +80,7 @@ FORMS: dict[str, FormSpec] = {
Col("From", "from_location", 25.0),
Col("To", "to_location", 23.2),
Col("POB", "pob", 15.3, "center"),
Col("Stockiest Visit", "stockiest_visit", 15.2, "center"),
Col("Stockist Visit", "stockiest_visit", 15.2, "center"),
),
serial_field="serial_no",
serial_dot=True,
@@ -231,6 +231,17 @@ _PLAN_CHEMIST_COLS = (
Col("NAME OF THE CHEMIST", "chemist_name", 52.8),
Col("PLANNED TIME", "planned_time", 37.0, "center"),
)
# Stockist visits: printed only when the report has any, so other reports keep their layout.
_STOCKIST_COLS = (
_serial("SR. NO.", 10.2),
Col("NAME OF THE STOCKIST", "stockist_name", 32.8),
Col("POB", "pob", 57.0),
)
_PLAN_STOCKIST_COLS = (
_serial("SR. NO.", 10.2),
Col("NAME OF THE STOCKIST", "stockist_name", 52.8),
Col("PLANNED TIME", "planned_time", 37.0, "center"),
)
# End-of-day report: the planned visits that were not made, and why.
_MISSED_COLS = (
_serial("SR. NO.", 8.6),
@@ -576,13 +587,14 @@ def build_dcr_context(
chemist_calls,
approval: dict[str, str] | None = None,
missed: list[Row] | None = None,
stockist_calls=(),
) -> dict[str, object]:
"""The approved Daily Call Report, laid out exactly like the printed company form.
Same template family, headings, column widths and number of ruled lines as the
``daily_call_report_csv`` company form: 10 doctor lines and 5 chemist lines, filled
from the top in visit order; more visits simply continue on the next page. The only
additions are the signatures: the MR's name, and (once approved) the Area Manager's
additions are the signatures: the MR's name, and (once approved) the Area Business Manager's
approval signature with its date and time.
A morning day plan uses the same form with a PLANNED TIME column in place of the
@@ -592,8 +604,8 @@ def build_dcr_context(
report_type = getattr(dcr, "report_type", None)
report_type = getattr(report_type, "value", report_type)
if report_type == "PLAN":
return _build_plan_context(dcr, doctor_calls, chemist_calls, approval)
is_self = report_type == "SELF" # an Area Manager's own report: no approval signature
return _build_plan_context(dcr, doctor_calls, chemist_calls, approval, stockist_calls)
is_self = report_type == "SELF" # an Area Business Manager's own report: no approval signature
doctors = [
{
"doctor_name": c.doctor.name,
@@ -605,6 +617,7 @@ def build_dcr_context(
for c in doctor_calls
]
chemists = [{"chemist_name": c.chemist.name, "pob": c.pob or ""} for c in chemist_calls]
stockists = [{"stockist_name": c.stockist.name, "pob": c.pob or ""} for c in stockist_calls]
meta = [
[("NAME:", dcr.mr.full_name), ("Date:", dcr.report_date.strftime("%d/%m/%Y"))],
[("HEADQUARTER:", dcr.headquarters.name), ("Month:", dcr.report_date.strftime("%B %Y"))],
@@ -619,12 +632,17 @@ def build_dcr_context(
"grids": {
"doctors": _grid(_DOCTOR_COLS, doctors, min_rows=10),
"chemists": _grid(_CHEMIST_COLS, chemists, min_rows=5, table_width=84),
**(
{"stockists": _grid(_STOCKIST_COLS, stockists, min_rows=0, table_width=84)}
if stockists
else {}
),
**({"missed": _grid(_MISSED_COLS, missed, min_rows=0)} if missed else {}),
},
"is_plan": False,
"stockist_visit": dcr.stockist_visit or "",
"order_value": dcr.order_value or "",
"signer_label": "Area Manager Signature" if is_self else "MR Signature",
"signer_label": "Area Business Manager Signature" if is_self else "MR Signature",
"mr_signed": f"{dcr.mr.full_name} ({dcr.mr.employee_code})",
"approval": approval, # {"name": ..., "at": "dd/mm/yyyy HH:MM"} or None
}
@@ -635,7 +653,9 @@ def _products(names: list[str] | str | None) -> str:
return names if isinstance(names, str) else ", ".join(names or [])
def _build_plan_context(dcr, doctor_calls, chemist_calls, approval) -> dict[str, object]:
def _build_plan_context(
dcr, doctor_calls, chemist_calls, approval, stockist_calls=()
) -> dict[str, object]:
doctors = [
{
"doctor_name": c.doctor.name,
@@ -649,6 +669,10 @@ def _build_plan_context(dcr, doctor_calls, chemist_calls, approval) -> dict[str,
{"chemist_name": c.chemist.name, "planned_time": c.visit_time.strftime("%H:%M")}
for c in chemist_calls
]
stockists = [
{"stockist_name": c.stockist.name, "planned_time": c.visit_time.strftime("%H:%M")}
for c in stockist_calls
]
meta = [
[("NAME:", dcr.mr.full_name), ("Date:", dcr.report_date.strftime("%d/%m/%Y"))],
[("HEADQUARTER:", dcr.headquarters.name), ("Month:", dcr.report_date.strftime("%B %Y"))],
@@ -663,6 +687,11 @@ def _build_plan_context(dcr, doctor_calls, chemist_calls, approval) -> dict[str,
"grids": {
"doctors": _grid(_PLAN_DOCTOR_COLS, doctors, min_rows=10),
"chemists": _grid(_PLAN_CHEMIST_COLS, chemists, min_rows=5, table_width=84),
**(
{"stockists": _grid(_PLAN_STOCKIST_COLS, stockists, min_rows=0, table_width=84)}
if stockists
else {}
),
},
"is_plan": True,
"stockist_visit": "",
+31
View File
@@ -0,0 +1,31 @@
"""Printable list of the Doctors & Chemists directory.
The browser sends the rows it already shows (the user's own scope, filters and search), so
this prints nothing the user cannot already see; it only lays them out on the company letterhead."""
from fastapi import APIRouter, Depends, Response
from pydantic import BaseModel, Field
from app.auth.dependencies import get_current_user
from app.pdf.service import csv_table_pdf_bytes
from app.users.models import User
router = APIRouter(prefix="/directory", tags=["directory"])
class DirectoryPdf(BaseModel):
title: str = Field(min_length=1, max_length=60)
columns: list[str] = Field(min_length=1, max_length=12)
rows: list[dict[str, str]] = Field(max_length=5000)
@router.post("/pdf")
async def directory_pdf(payload: DirectoryPdf, _: User = Depends(get_current_user)) -> Response:
columns = tuple(c for c in payload.columns if c.isidentifier())
rows = [{c: r.get(c, "") for c in columns} for r in payload.rows]
name = "".join(ch for ch in payload.title.lower() if ch.isalnum()) or "directory"
return Response(
csv_table_pdf_bytes(f"directory_{name}", payload.title, columns, rows),
media_type="application/pdf",
headers={"Content-Disposition": f'inline; filename="{name}.pdf"'},
)
+3 -2
View File
@@ -142,7 +142,7 @@ def _approval_signature_line(
table_name: str,
approval_status: str | None = None,
am_name: str | None = None,
am_role: str = "Area Manager",
am_role: str = "Area Business Manager",
) -> str:
return approval_signature_line(table_name, approval_status, am_name)
@@ -154,7 +154,7 @@ def csv_table_pdf_bytes(
rows: list[dict[str, object]],
approval_status: str | None = None,
am_name: str | None = None,
am_role: str = "Area Manager",
am_role: str = "Area Business Manager",
approved_at: str | None = None,
renumber: bool = False,
) -> bytes:
@@ -210,6 +210,7 @@ class PDFService:
sorted(dcr.chemist_calls, key=lambda c: c.visit_time),
await self._approval(dcr),
missed,
sorted(dcr.stockist_calls, key=lambda c: c.visit_time),
)
async def render_bytes(self, dcr: DailyCallReport) -> bytes:
+5 -1
View File
@@ -21,6 +21,10 @@
{{ grid(grids.doctors, left=True) }}
<h2 class="section">{{ "CHEMISTS TO VISIT" if is_plan else "CHEMIST VISIT" }}</h2>
{{ grid(grids.chemists, left=True) }}
{% if grids.stockists %}
<h2 class="section">{{ "STOCKISTS TO VISIT" if is_plan else "STOCKIST VISIT" }}</h2>
{{ grid(grids.stockists, left=True) }}
{% endif %}
{% if is_plan %}
{% if mr_remarks %}<div class="visit"><div><b>REMARKS :</b> {{ mr_remarks }}</div></div>{% endif %}
{% else %}
@@ -46,7 +50,7 @@
{% if approval %}
<div class="sign-label">APPROVAL SIGNATURE:</div>
<div class="signed">{{ approval.name }}</div>
<div class="signed-when">Area Manager &middot; {{ approval.at }}</div>
<div class="signed-when">Area Business Manager &middot; {{ approval.at }}</div>
{% endif %}
</td>
</tr>
+5 -1
View File
@@ -11,7 +11,11 @@ Website: {{ company_website }} E-Mail: {{ company_email }} PHONE: {{ company_p
{{ grids.chemists.headers | join(' | ') }}
{% for r in grids.chemists.rows %}{{ r.cells | join(' | ') }}
{% endfor %}
{% if grids.missed %}PLANNED VISITS NOT MADE
{% if grids.stockists %}{{ "STOCKISTS TO VISIT" if is_plan else "STOCKIST VISIT" }}
{{ grids.stockists.headers | join(' | ') }}
{% for r in grids.stockists.rows %}{{ r.cells | join(' | ') }}
{% endfor %}
{% endif %}{% if grids.missed %}PLANNED VISITS NOT MADE
{{ grids.missed.headers | join(' | ') }}
{% for r in grids.missed.rows %}{{ r.cells | join(' | ') }}
{% endfor %}
+1 -1
View File
@@ -45,7 +45,7 @@
<div class="sign-right">{{ text }}</div>
{% endmacro %}
{# Tour plan, standard tour plan and fare chart: MR signature plus the AM approval. #}
{# Tour plan, standard tour plan and fare chart: MR signature plus the ABM approval. #}
{% macro sign_approval(approval) %}
<table class="sign-approval">
<tr>
+37 -7
View File
@@ -5,8 +5,8 @@ doctors and chemists they intend to visit, and an end-of-day ACTUAL report of th
that happened. Both share this table and its call rows; the ACTUAL report points at its
plan, and records why any planned visit was missed in ``missed_visit``.
An Area Manager files a SELF report of their own visits in the same table; ``mr_user_id``
is then the Area Manager (the report's owner), and submitting it makes it final."""
An Area Business Manager files a SELF report of their own visits in the same table; ``mr_user_id``
is then the Area Business Manager (the report's owner), and submitting it makes it final."""
import uuid
from datetime import date, datetime, time
@@ -73,7 +73,7 @@ class DailyCallReport(Base, UUIDMixin, TimestampMixin):
nullable=False,
)
#: SNAPSHOT of the reviewing AM / approving GM, so an HQ handover never rewrites
#: SNAPSHOT of the reviewing ABM / overseeing AGM, so an HQ handover never rewrites
#: history (report §5.5).
current_am_user_id: Mapped[uuid.UUID | None] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="RESTRICT")
@@ -104,6 +104,9 @@ class DailyCallReport(Base, UUIDMixin, TimestampMixin):
chemist_calls: Mapped[list["ChemistCall"]] = relationship(
back_populates="dcr", cascade="all, delete-orphan", lazy="selectin"
)
stockist_calls: Mapped[list["StockistCall"]] = relationship(
back_populates="dcr", cascade="all, delete-orphan", lazy="selectin"
)
missed_visits: Mapped[list["MissedVisit"]] = relationship(
back_populates="dcr", cascade="all, delete-orphan", lazy="selectin"
)
@@ -184,18 +187,42 @@ class ChemistCall(Base, UUIDMixin, TimestampMixin):
chemist: Mapped["Chemist"] = relationship(lazy="selectin") # noqa: F821
class MissedVisit(Base, UUIDMixin, TimestampMixin):
"""Why a doctor or chemist on the approved plan was not visited that day.
class StockistCall(Base, UUIDMixin, TimestampMixin):
__tablename__ = "stockist_call"
__table_args__ = (
UniqueConstraint("dcr_id", "stockist_id", name="uq_call_dcr_stockist"),
)
Belongs to the end-of-day report; exactly one of doctor/chemist is set.
dcr_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True),
ForeignKey("daily_call_report.id", ondelete="CASCADE"),
nullable=False,
)
stockist_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("stockist.id", ondelete="RESTRICT"), nullable=False
)
visit_time: Mapped[time] = mapped_column(Time, nullable=False)
#: Order booked with the stockist on this visit.
pob: Mapped[str | None] = mapped_column(String(100))
remarks: Mapped[str | None] = mapped_column(Text)
dcr: Mapped["DailyCallReport"] = relationship(back_populates="stockist_calls")
stockist: Mapped["Stockist"] = relationship(lazy="selectin") # noqa: F821
class MissedVisit(Base, UUIDMixin, TimestampMixin):
"""Why a doctor, chemist or stockist on the approved plan was not visited that day.
Belongs to the end-of-day report; exactly one of doctor/chemist/stockist is set.
"""
__tablename__ = "missed_visit"
__table_args__ = (
UniqueConstraint("dcr_id", "doctor_id", name="uq_missed_dcr_doctor"),
UniqueConstraint("dcr_id", "chemist_id", name="uq_missed_dcr_chemist"),
UniqueConstraint("dcr_id", "stockist_id", name="uq_missed_dcr_stockist"),
CheckConstraint(
"(doctor_id IS NULL) <> (chemist_id IS NULL)", name="ck_missed_one_target"
"num_nonnulls(doctor_id, chemist_id, stockist_id) = 1", name="ck_missed_one_target"
),
)
@@ -210,6 +237,9 @@ class MissedVisit(Base, UUIDMixin, TimestampMixin):
chemist_id: Mapped[uuid.UUID | None] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("chemist.id", ondelete="RESTRICT")
)
stockist_id: Mapped[uuid.UUID | None] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("stockist.id", ondelete="RESTRICT")
)
reason: Mapped[str] = mapped_column(Text, nullable=False)
dcr: Mapped["DailyCallReport"] = relationship(back_populates="missed_visits")
+5 -1
View File
@@ -6,7 +6,7 @@ from sqlalchemy.orm import selectinload
from app.common.enums import DCRStatus, ReportType
from app.common.repository import BaseRepository
from app.reports.models import ChemistCall, DailyCallReport, DoctorCall
from app.reports.models import ChemistCall, DailyCallReport, DoctorCall, StockistCall
class DCRRepository(BaseRepository[DailyCallReport]):
@@ -19,6 +19,7 @@ class DCRRepository(BaseRepository[DailyCallReport]):
.options(
selectinload(DailyCallReport.doctor_calls).selectinload(DoctorCall.doctor),
selectinload(DailyCallReport.chemist_calls).selectinload(ChemistCall.chemist),
selectinload(DailyCallReport.stockist_calls).selectinload(StockistCall.stockist),
selectinload(DailyCallReport.missed_visits),
selectinload(DailyCallReport.mr),
selectinload(DailyCallReport.headquarters),
@@ -29,6 +30,9 @@ class DCRRepository(BaseRepository[DailyCallReport]):
selectinload(DailyCallReport.plan)
.selectinload(DailyCallReport.chemist_calls)
.selectinload(ChemistCall.chemist),
selectinload(DailyCallReport.plan)
.selectinload(DailyCallReport.stockist_calls)
.selectinload(StockistCall.stockist),
selectinload(DailyCallReport.actual),
)
# The session keeps objects after commit (expire_on_commit=False), so without this the
+23 -9
View File
@@ -12,6 +12,7 @@ from app.pdf.service import PDFService
from app.reports.schemas import (
ApproveRequest,
ChemistCallCreate,
StockistCallCreate,
DCRCreate,
DCRListItem,
DCRRead,
@@ -111,7 +112,7 @@ async def download_pdf(
async def create_report(
payload: DCRCreate,
request: Request,
current_user: User = Depends(require_role(Role.MR, Role.AM)),
current_user: User = Depends(require_role(Role.MR, Role.ABM)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
return to_read(await DCRService(db).create(payload, current_user, client_ip(request)))
@@ -122,7 +123,7 @@ async def update_report(
dcr_id: uuid.UUID,
payload: DCRUpdate,
request: Request,
current_user: User = Depends(require_role(Role.MR, Role.AM)),
current_user: User = Depends(require_role(Role.MR, Role.ABM)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
return to_read(
@@ -137,7 +138,7 @@ async def add_doctor_call(
dcr_id: uuid.UUID,
payload: DoctorCallCreate,
request: Request,
current_user: User = Depends(require_role(Role.MR, Role.AM)),
current_user: User = Depends(require_role(Role.MR, Role.ABM)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
return to_read(
@@ -150,7 +151,7 @@ async def add_chemist_call(
dcr_id: uuid.UUID,
payload: ChemistCallCreate,
request: Request,
current_user: User = Depends(require_role(Role.MR, Role.AM)),
current_user: User = Depends(require_role(Role.MR, Role.ABM)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
return to_read(
@@ -158,12 +159,25 @@ async def add_chemist_call(
)
@router.post("/{dcr_id}/calls/stockist", response_model=DCRRead, status_code=201)
async def add_stockist_call(
dcr_id: uuid.UUID,
payload: StockistCallCreate,
request: Request,
current_user: User = Depends(require_role(Role.MR, Role.ABM)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
return to_read(
await DCRService(db).add_stockist_call(dcr_id, payload, current_user, client_ip(request))
)
@router.delete("/{dcr_id}/calls/{call_id}", response_model=DCRRead)
async def delete_call(
dcr_id: uuid.UUID,
call_id: uuid.UUID,
request: Request,
current_user: User = Depends(require_role(Role.MR, Role.AM)),
current_user: User = Depends(require_role(Role.MR, Role.ABM)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
return to_read(
@@ -207,7 +221,7 @@ async def clear_missed_reason(
async def submit(
dcr_id: uuid.UUID,
request: Request,
current_user: User = Depends(require_role(Role.MR, Role.AM)),
current_user: User = Depends(require_role(Role.MR, Role.ABM)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
return to_read(await DCRService(db).submit(dcr_id, current_user, client_ip(request)))
@@ -218,7 +232,7 @@ async def return_report(
dcr_id: uuid.UUID,
payload: ReturnRequest,
request: Request,
current_user: User = Depends(require_role(Role.AM)),
current_user: User = Depends(require_role(Role.ABM)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
return to_read(
@@ -233,10 +247,10 @@ async def approve(
dcr_id: uuid.UUID,
payload: ApproveRequest,
request: Request,
current_user: User = Depends(require_role(Role.AM)),
current_user: User = Depends(require_role(Role.ABM)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
"""Area Manager final approval (headquarters scope is enforced by the service)."""
"""Area Business Manager final approval (headquarters scope is enforced by the service)."""
return to_read(
await DCRService(db).approve(dcr_id, payload.comment, current_user, client_ip(request))
)
+24 -4
View File
@@ -52,6 +52,13 @@ class ChemistCallCreate(BaseModel):
remarks: str | None = Field(default=None, max_length=2000)
class StockistCallCreate(BaseModel):
stockist_id: uuid.UUID
visit_time: time
pob: str | None = Field(default=None, max_length=100)
remarks: str | None = Field(default=None, max_length=2000)
class DoctorCallRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
@@ -80,10 +87,21 @@ class ChemistCallRead(BaseModel):
remarks: str | None
class StockistCallRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
stockist_id: uuid.UUID
stockist_name: str
visit_time: time
pob: str | None
remarks: str | None
class DCRCreate(BaseModel):
report_date: date
report_type: ReportType = ReportType.ACTUAL
#: SELF reports only: which of the Area Manager's headquarters the visits were in.
#: SELF reports only: which of the Area Business Manager's headquarters the visits were in.
headquarters_id: uuid.UUID | None = None
mr_remarks: str | None = Field(default=None, max_length=2000)
doctor_calls: list[DoctorCallCreate] = Field(default_factory=list)
@@ -97,10 +115,11 @@ class DCRUpdate(BaseModel):
class MissedVisitSet(BaseModel):
"""Why one planned doctor OR chemist was not visited (end-of-day report only)."""
"""Why one planned doctor, chemist OR stockist was not visited (end-of-day report only)."""
doctor_id: uuid.UUID | None = None
chemist_id: uuid.UUID | None = None
stockist_id: uuid.UUID | None = None
reason: str = Field(min_length=3, max_length=500)
@@ -111,7 +130,7 @@ class PlannedVisitRead(BaseModel):
PENDING — neither yet (the report cannot be submitted while any remain).
"""
kind: Literal["DOCTOR", "CHEMIST"]
kind: Literal["DOCTOR", "CHEMIST", "STOCKIST"]
target_id: uuid.UUID
name: str
is_core_doctor: bool
@@ -176,6 +195,7 @@ class DCRRead(BaseModel):
approved_at: datetime | None
doctor_calls: list[DoctorCallRead]
chemist_calls: list[ChemistCallRead]
stockist_calls: list[StockistCallRead]
#: End-of-day report only: the approved plan, line by line, with what became of it.
planned_visits: list[PlannedVisitRead]
@@ -184,6 +204,6 @@ class StatusCounts(BaseModel):
"""Header counts on the list screens — the cheap replacement for dashboards."""
DRAFT: int = 0
PENDING_AM: int = 0
PENDING_ABM: int = 0
RETURNED: int = 0
APPROVED: int = 0
+21 -2
View File
@@ -7,6 +7,7 @@ from app.reports.schemas import (
DCRRead,
DoctorCallRead,
PlannedVisitRead,
StockistCallRead,
)
@@ -15,8 +16,12 @@ def planned_visits(dcr: DailyCallReport) -> list[PlannedVisitRead]:
plan = dcr.plan
if plan is None:
return []
visited = {c.doctor_id for c in dcr.doctor_calls} | {c.chemist_id for c in dcr.chemist_calls}
missed = {m.doctor_id or m.chemist_id: m for m in dcr.missed_visits}
visited = (
{c.doctor_id for c in dcr.doctor_calls}
| {c.chemist_id for c in dcr.chemist_calls}
| {c.stockist_id for c in dcr.stockist_calls}
)
missed = {m.doctor_id or m.chemist_id or m.stockist_id: m for m in dcr.missed_visits}
def line(kind, target_id, name, is_core, planned_time) -> PlannedVisitRead:
note = missed.get(target_id)
@@ -38,6 +43,9 @@ def planned_visits(dcr: DailyCallReport) -> list[PlannedVisitRead]:
] + [
line("CHEMIST", c.chemist_id, c.chemist.name, False, c.visit_time)
for c in plan.chemist_calls
] + [
line("STOCKIST", c.stockist_id, c.stockist.name, False, c.visit_time)
for c in plan.stockist_calls
]
return sorted(lines, key=lambda x: x.planned_time)
@@ -91,6 +99,17 @@ def to_read(dcr: DailyCallReport) -> DCRRead:
)
for c in sorted(dcr.chemist_calls, key=lambda x: x.visit_time)
],
stockist_calls=[
StockistCallRead(
id=c.id,
stockist_id=c.stockist_id,
stockist_name=c.stockist.name,
visit_time=c.visit_time,
pob=c.pob,
remarks=c.remarks,
)
for c in sorted(dcr.stockist_calls, key=lambda x: x.visit_time)
],
planned_visits=planned_visits(dcr),
)
+125 -34
View File
@@ -7,16 +7,19 @@ Plan / end-of-day rules (P1-P5):
P1 A PLAN lists the visits the MR intends to make; it carries no outcomes, and its
times are planned times, so they may be later than "now".
P2 An ACTUAL (end-of-day) report can be created only once the PLAN for that date is
APPROVED by the Area Manager; it is linked to that plan.
P3 Every planned doctor/chemist must, before submit, either have a visit recorded on
APPROVED by the Area Business Manager; it is linked to that plan.
P3 Every planned doctor/chemist/stockist must, before submit, either have a visit recorded on
the end-of-day report or a short note saying why it was missed.
P4 Recording a visit for a doctor/chemist drops any "missed" note for them.
P5 Visits not on the plan may still be added to the end-of-day report.
Area Manager's own report (S1-S3):
S1 An Area Manager files one SELF report per date, for one headquarters they manage;
Area Business Manager's own report (S1-S3):
S1 An Area Business Manager files one SELF report per date, for one headquarters they manage;
it needs no plan.
S2 Its visits may be to any active doctor or chemist of that headquarters.
S2 Its visits may be to any active doctor, chemist or stockist of that headquarters.
Stockists are not assigned to an MR: an MR (or SFE) may visit any active stockist of the
headquarters they cover.
S3 There is no approval: submitting it makes it final (APPROVED, locked, PDF stored).
"""
@@ -51,9 +54,16 @@ from app.common.exceptions import (
from app.common.utils import local_now, local_today, snapshot, utcnow
from app.config.settings import settings
from app.doctors.models import Doctor, DoctorAssignment
from app.reports.models import ChemistCall, DailyCallReport, DoctorCall, MissedVisit
from app.reports.models import ChemistCall, DailyCallReport, DoctorCall, MissedVisit, StockistCall
from app.reports.repository import DCRRepository
from app.reports.schemas import ChemistCallCreate, DCRCreate, DoctorCallCreate, MissedVisitSet
from app.reports.schemas import (
ChemistCallCreate,
DCRCreate,
DoctorCallCreate,
MissedVisitSet,
StockistCallCreate,
)
from app.stockists.models import Stockist
from app.reports.serializers import planned_visits
from app.users.models import User
@@ -73,7 +83,7 @@ _AUDIT_FIELDS = [
#: Who files (and alone may edit or submit) each type of report.
_OWNER_ROLE = {ReportType.PLAN: FIELD_ROLES, ReportType.ACTUAL: FIELD_ROLES, ReportType.SELF: frozenset({Role.AM})}
_OWNER_ROLE = {ReportType.PLAN: FIELD_ROLES, ReportType.ACTUAL: FIELD_ROLES, ReportType.SELF: frozenset({Role.ABM})}
_LABEL = {
ReportType.PLAN: "Daily Call Report (Plan)",
ReportType.ACTUAL: "Daily Call Report (Done)",
@@ -146,8 +156,23 @@ class DCRService:
)
return set((await self.db.execute(stmt)).scalars().all())
async def _allowed_stockist_ids(self, dcr: DailyCallReport) -> set[uuid.UUID]:
"""Active stockists of the report's headquarters (SELF), or of every headquarters
the MR / SFE covers."""
hq_ids = (
{dcr.headquarters_id}
if dcr.report_type == ReportType.SELF
else dcr.mr.covered_headquarter_ids or {dcr.headquarters_id}
)
stmt = select(Stockist.id).where(
Stockist.headquarters_id.in_(hq_ids),
Stockist.is_active.is_(True),
Stockist.approval_status == MasterApproval.APPROVED,
)
return set((await self.db.execute(stmt)).scalars().all())
async def _assigned_doctor_ids(self, mr_user_id: uuid.UUID) -> set[uuid.UUID]:
# A doctor the MR added is visitable only once the Area Manager has approved it.
# A doctor the MR added is visitable only once the Area Business Manager has approved it.
stmt = (
select(DoctorAssignment.doctor_id)
.join(Doctor, Doctor.id == DoctorAssignment.doctor_id)
@@ -230,6 +255,25 @@ class DCRService:
remarks=payload.remarks,
)
async def _build_stockist_call(
self, dcr: DailyCallReport, payload: StockistCallCreate, allowed: set[uuid.UUID]
) -> StockistCall:
if payload.stockist_id not in allowed:
raise ValidationError(
"Stockist is not in this report's headquarters"
if dcr.report_type == ReportType.SELF
else "Stockist is not in a headquarters you cover",
{"stockist_id": str(payload.stockist_id)},
)
is_plan = dcr.report_type == ReportType.PLAN
return StockistCall(
dcr_id=dcr.id,
stockist_id=payload.stockist_id,
visit_time=payload.visit_time,
pob=None if is_plan else _clean(payload.pob),
remarks=payload.remarks,
)
# ------------------------------------------------------------------
# Commands
# ------------------------------------------------------------------
@@ -238,8 +282,8 @@ class DCRService:
self, data: DCRCreate, actor: User, ip: str | None = None
) -> DailyCallReport:
if data.report_type == ReportType.SELF:
if actor.role != Role.AM:
raise ForbiddenError("Only an Area Manager files a Daily Call Report (Self)")
if actor.role != Role.ABM:
raise ForbiddenError("Only an Area Business Manager files a Daily Call Report (Self)")
headquarters_id = await self._self_report_hq(actor, data.headquarters_id)
elif actor.role not in FIELD_ROLES:
raise ForbiddenError("Only an MR files a Daily Call Report (Plan) or (Done)")
@@ -403,6 +447,36 @@ class DCRService:
await self.db.commit()
return await self.repo.get_full(dcr.id)
async def add_stockist_call(
self, dcr_id: uuid.UUID, payload: StockistCallCreate, actor: User, ip: str | None = None
) -> DailyCallReport:
dcr = await self._get_owned_editable(dcr_id, actor)
allowed = await self._allowed_stockist_ids(dcr)
call = await self._build_stockist_call(dcr, payload, allowed)
self._validate_visit_time(dcr, payload.visit_time)
self.db.add(call)
try:
await self.db.flush()
except IntegrityError as exc:
await self.db.rollback()
raise ConflictError(
"This stockist has already been called on this report",
{"stockist_id": str(payload.stockist_id), "cause": "uq_call_dcr_stockist"},
) from exc
await self._drop_missed_note(dcr, stockist_id=payload.stockist_id)
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.DCR,
entity_id=dcr.id,
action=AuditAction.UPDATE,
after={"added_stockist_call": str(payload.stockist_id)},
ip_address=ip,
)
await self.db.commit()
return await self.repo.get_full(dcr.id)
def _validate_visit_time(self, dcr: DailyCallReport, visit_time) -> None:
"""V11 — a visit time on today's report cannot be in the future (P1: plans excepted)."""
if dcr.report_type != ReportType.PLAN and dcr.report_date == local_today():
@@ -417,7 +491,11 @@ class DCRService:
self, dcr_id: uuid.UUID, call_id: uuid.UUID, actor: User, ip: str | None = None
) -> DailyCallReport:
dcr = await self._get_owned_editable(dcr_id, actor)
call = await self.db.get(DoctorCall, call_id) or await self.db.get(ChemistCall, call_id)
call = (
await self.db.get(DoctorCall, call_id)
or await self.db.get(ChemistCall, call_id)
or await self.db.get(StockistCall, call_id)
)
if call is None or call.dcr_id != dcr.id:
raise NotFoundError("Call not found on this report", {"call_id": str(call_id)})
await self.db.delete(call)
@@ -435,30 +513,36 @@ class DCRService:
async def set_missed_reason(
self, dcr_id: uuid.UUID, payload: MissedVisitSet, actor: User, ip: str | None = None
) -> DailyCallReport:
"""P3 — record (or reword) why a planned doctor/chemist was not visited."""
"""P3 — record (or reword) why a planned doctor/chemist/stockist was not visited."""
dcr = await self._get_owned_editable(dcr_id, actor)
if dcr.report_type != ReportType.ACTUAL or dcr.plan is None:
raise ValidationError("Missed-visit notes belong on a Daily Call Report (Done)")
if (payload.doctor_id is None) == (payload.chemist_id is None):
raise ValidationError("Give exactly one of doctor_id or chemist_id")
targets = [t for t in (payload.doctor_id, payload.chemist_id, payload.stockist_id) if t]
if len(targets) != 1:
raise ValidationError("Give exactly one of doctor_id, chemist_id or stockist_id")
reason = _clean(payload.reason)
if reason is None:
raise ValidationError("Say briefly why the visit was missed")
target_id = payload.doctor_id or payload.chemist_id
target_id = targets[0]
line = next((p for p in planned_visits(dcr) if p.target_id == target_id), None)
if line is None:
raise ValidationError(
"This doctor or chemist is not on the plan", {"target_id": str(target_id)}
"This doctor, chemist or stockist is not on the plan", {"target_id": str(target_id)}
)
if line.status == "VISITED":
raise ConflictError(
"A visit is already recorded for this doctor or chemist; remove it first",
"A visit is already recorded for this doctor, chemist or stockist; remove it first",
{"target_id": str(target_id)},
)
note = next(
(m for m in dcr.missed_visits if (m.doctor_id or m.chemist_id) == target_id), None
(
m
for m in dcr.missed_visits
if (m.doctor_id or m.chemist_id or m.stockist_id) == target_id
),
None,
)
before = {"reason": note.reason} if note else None
if note is None:
@@ -467,6 +551,7 @@ class DCRService:
dcr_id=dcr.id,
doctor_id=payload.doctor_id,
chemist_id=payload.chemist_id,
stockist_id=payload.stockist_id,
reason=reason,
)
)
@@ -499,7 +584,10 @@ class DCRService:
entity_type=EntityType.DCR,
entity_id=dcr.id,
action=AuditAction.DELETE,
before={"missed_visit": str(note.doctor_id or note.chemist_id), "reason": note.reason},
before={
"missed_visit": str(note.doctor_id or note.chemist_id or note.stockist_id),
"reason": note.reason,
},
ip_address=ip,
)
await self.db.commit()
@@ -522,7 +610,7 @@ class DCRService:
if dcr.report_type == ReportType.SELF:
return await self._finalise_self_report(dcr, actor, ip)
if dcr.status == DCRStatus.PENDING_AM:
if dcr.status == DCRStatus.PENDING_ABM:
return dcr # already submitted (a double click): nothing more to do
transition = assert_transition(dcr.status, WorkflowAction.SUBMIT, actor.role)
@@ -552,7 +640,7 @@ class DCRService:
async def _finalise_self_report(
self, dcr: DailyCallReport, actor: User, ip: str | None
) -> DailyCallReport:
"""S3 — an Area Manager's own report is final once submitted; nobody approves it."""
"""S3 — an Area Business Manager's own report is final once submitted; nobody approves it."""
if dcr.status == DCRStatus.APPROVED:
return dcr # already submitted (a double click)
assert_editable(dcr.status)
@@ -606,9 +694,9 @@ class DCRService:
async def approve(
self, dcr_id: uuid.UUID, comment: str | None, actor: User, ip: str | None = None
) -> DailyCallReport:
"""Area Manager final approval. APPROVED is terminal and immutable."""
"""Area Business Manager final approval. APPROVED is terminal and immutable."""
dcr = await self._get_in_scope(dcr_id, actor)
if dcr.status == DCRStatus.APPROVED and actor.role == Role.AM:
if dcr.status == DCRStatus.APPROVED and actor.role == Role.ABM:
return dcr # already approved (a double click): the report stays as it is
transition = assert_transition(dcr.status, WorkflowAction.APPROVE, actor.role)
@@ -661,9 +749,9 @@ class DCRService:
async def list_for(
self, actor: User, headquarters_id: uuid.UUID | None = None, **filters
) -> list[DailyCallReport]:
# An Area Manager's SELF list is their own reports, not their headquarters'.
# An Area Business Manager's SELF list is their own reports, not their headquarters'.
if actor.role in FIELD_ROLES or (
actor.role == Role.AM and filters.get("report_type") == ReportType.SELF
actor.role == Role.ABM and filters.get("report_type") == ReportType.SELF
):
return await self.repo.list_scoped(mr_user_id=actor.id, **filters)
hq_ids = await self._hq_scope(actor, headquarters_id)
@@ -692,7 +780,7 @@ class DCRService:
return dcr
async def _self_report_hq(self, actor: User, headquarters_id: uuid.UUID | None) -> uuid.UUID:
"""S1 — one of the headquarters this Area Manager manages; implied when there is one."""
"""S1 — one of the headquarters this Area Business Manager manages; implied when there is one."""
managed = await active_hq_ids_for_am(self.db, actor.id)
if headquarters_id is None and len(managed) == 1:
return next(iter(managed))
@@ -711,14 +799,14 @@ class DCRService:
def _check_submit_contents(self, dcr: DailyCallReport) -> None:
if dcr.report_type == ReportType.PLAN:
if not dcr.doctor_calls and not dcr.chemist_calls:
raise ValidationError("Plan at least one doctor or chemist visit to submit")
if not dcr.doctor_calls and not dcr.chemist_calls and not dcr.stockist_calls:
raise ValidationError("Plan at least one doctor, chemist or stockist visit to submit")
return
# P3 — every planned visit is either recorded or explained.
pending = [p for p in planned_visits(dcr) if p.status == "PENDING"]
if pending:
raise ValidationError(
"Record a visit or add a missed-visit note for every planned doctor and chemist",
"Record a visit or add a missed-visit note for every planned doctor, chemist and stockist",
{"pending": [p.name for p in pending]},
)
# V4 — at least one doctor call, unless the planned visits were all explained.
@@ -737,7 +825,7 @@ class DCRService:
if plan.status != DCRStatus.APPROVED:
raise ValidationError(
"Your Daily Call Report (Plan) for this date must be approved "
"by the Area Manager first",
"by the Area Business Manager first",
{"report_date": report_date.isoformat(), "plan_status": plan.status.value},
)
return plan
@@ -747,18 +835,21 @@ class DCRService:
dcr: DailyCallReport,
doctor_id: uuid.UUID | None = None,
chemist_id: uuid.UUID | None = None,
stockist_id: uuid.UUID | None = None,
) -> None:
"""P4 — a recorded visit replaces any note saying it was missed."""
for note in dcr.missed_visits:
if (doctor_id and note.doctor_id == doctor_id) or (
chemist_id and note.chemist_id == chemist_id
if (
(doctor_id and note.doctor_id == doctor_id)
or (chemist_id and note.chemist_id == chemist_id)
or (stockist_id and note.stockist_id == stockist_id)
):
await self.db.delete(note)
async def _current_am_for_hq(self, headquarters_id: uuid.UUID) -> uuid.UUID | None:
from app.organization.models import AMHeadquarters
# Recorded only; any Area Manager of the headquarters may act on the report.
# Recorded only; any Area Business Manager of the headquarters may act on the report.
stmt = (
select(AMHeadquarters.area_manager_user_id)
.where(
+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
)
+2 -2
View File
@@ -1,4 +1,4 @@
"""One person's whole picture for the General Manager and Admin: who they are, where they
"""One person's whole picture for the Assistant General Manager and Admin: who they are, where they
work, who they report to, their doctors and chemists, their reports and their company forms."""
import uuid
@@ -139,7 +139,7 @@ async def user_overview(db: AsyncSession, actor: User, user_id: uuid.UUID) -> di
data["reports"]["recent"] = [to_list_item(r).model_dump(mode="json") for r in recent]
data["forms"] = await _forms(db, user)
elif user.role == Role.AM:
elif user.role == Role.ABM:
managed = (
await db.execute(
select(Headquarters)
+3 -3
View File
@@ -24,17 +24,17 @@ async def my_profile(
@router.get("/{user_id}/overview")
async def user_overview(
user_id: uuid.UUID,
current_user: User = Depends(require_role(Role.ADMIN, Role.GM)),
current_user: User = Depends(require_role(Role.ADMIN, Role.AGM)),
db: AsyncSession = Depends(get_db),
) -> dict:
"""The whole picture of one person, for the General Manager and Admin."""
"""The whole picture of one person, for the Assistant General Manager and Admin."""
return await overview.user_overview(db, current_user, user_id)
@router.get("", response_model=list[UserRead])
async def list_users(
role: Role | None = None,
current_user: User = Depends(require_role(Role.ADMIN, Role.GM)),
current_user: User = Depends(require_role(Role.ADMIN, Role.AGM)),
db: AsyncSession = Depends(get_db),
) -> list[User]:
return await UserService(db).list_users(current_user, role)
+2 -2
View File
@@ -36,7 +36,7 @@ class UserUpdate(BaseModel):
#: A new password. Signs the user out everywhere and clears a lockout.
password: str | None = Field(default=None, min_length=8, max_length=128)
phone: str | None = Field(default=None, max_length=20)
#: Admin-only. Moving to MR needs `headquarters_id`; leaving MR or AM ends that role's
#: Admin-only. Moving to MR needs `headquarters_id`; leaving MR or ABM ends that role's
#: assignments, and the user is signed out so they sign in again with the new role.
role: Role | None = None
headquarters_id: uuid.UUID | None = None
@@ -61,7 +61,7 @@ class UserRead(BaseModel):
class MyProfile(BaseModel):
"""S4 — the MR profile screen. Includes the DERIVED reporting Area Manager."""
"""S4 — the MR profile screen. Includes the DERIVED reporting Area Business Manager."""
id: uuid.UUID
full_name: str
+4 -4
View File
@@ -175,14 +175,14 @@ class UserService:
return user
async def _end_role_assignments(self, user_id: uuid.UUID, old_role: Role) -> dict[str, int]:
"""Close what the old role held: an MR's doctors and chemists, an AM's headquarters."""
"""Close what the old role held: an MR's doctors and chemists, an ABM's headquarters."""
today = date.today()
if old_role in FIELD_ROLES:
targets = [
("doctors", DoctorAssignment, DoctorAssignment.mr_user_id),
("chemists", ChemistAssignment, ChemistAssignment.mr_user_id),
]
elif old_role == Role.AM:
elif old_role == Role.ABM:
targets = [("headquarters", AMHeadquarters, AMHeadquarters.area_manager_user_id)]
else:
return {}
@@ -204,7 +204,7 @@ class UserService:
return list((await self.db.execute(stmt)).scalars().all())
async def my_profile(self, user: User) -> MyProfile:
"""S4 — includes the reporting Area Manager DERIVED through the headquarters."""
"""S4 — includes the reporting Area Business Manager DERIVED through the headquarters."""
hq_code = hq_name = None
manager_id = manager_name = None
@@ -221,7 +221,7 @@ class UserService:
AMHeadquarters.effective_to.is_(None),
)
)
# A headquarters may have several Area Managers: name every one.
# A headquarters may have several Area Business Managers: name every one.
managers = list((await self.db.execute(stmt.order_by(User.full_name))).scalars())
if managers:
manager_id = managers[0].id