Production

This commit is contained in:
Shubhankar45
2026-09-22 06:23:46 +00:00
commit 8fdd20b29f
217 changed files with 31212 additions and 0 deletions
View File
View File
View File
+28
View File
@@ -0,0 +1,28 @@
"""Mount point for every v1 module router.
Versioning matters here because of the Phase-3 mobile app: an installed app cannot be
force-updated, so v1 must stay frozen once it ships and breaking changes go to v2.
"""
from fastapi import APIRouter
from app.audit.router import router as audit_router
from app.auth.router import router as auth_router
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.products.router import router as products_router
from app.reports.router import router as reports_router
from app.users.router import router as users_router
api_router = APIRouter()
api_router.include_router(auth_router)
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(csv_data_router)
api_router.include_router(products_router)
api_router.include_router(reports_router)
api_router.include_router(audit_router)
View File
+84
View File
@@ -0,0 +1,84 @@
"""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
The Area Manager is the final approver; there is no General Manager stage.
"""
from dataclasses import dataclass
from app.common.enums import EDITABLE_STATUSES, DCRStatus, Role, WorkflowAction
from app.common.exceptions import ForbiddenError, InvalidStateTransitionError
@dataclass(frozen=True)
class Transition:
from_status: DCRStatus
action: WorkflowAction
to_status: DCRStatus
allowed_role: Role
requires_reason: bool = False
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.PENDING_AM, WorkflowAction.RETURN, DCRStatus.RETURNED, Role.AM,
requires_reason=True,
),
)
_INDEX: dict[tuple[DCRStatus, WorkflowAction], Transition] = {
(t.from_status, t.action): t for t in TRANSITIONS
}
def find_transition(status: DCRStatus, action: WorkflowAction) -> Transition | None:
return _INDEX.get((status, action))
def assert_transition(status: DCRStatus, action: WorkflowAction, role: Role) -> Transition:
"""Validate a requested move and return the transition to apply.
Raises InvalidStateTransitionError (409) if the move does not exist from this
status, and ForbiddenError (403) if it exists but this role may not make it.
ADMIN never matches any transition — SEC-2: the System Administrator can never
approve a report.
"""
transition = find_transition(status, action)
if transition is None:
raise InvalidStateTransitionError(
f"Cannot {action.value.lower()} a report in status {status.value}",
{
"current_status": status.value,
"attempted_action": action.value,
"allowed_actions": sorted(
t.action.value for t in TRANSITIONS if t.from_status == status
),
},
)
if transition.allowed_role != role:
raise ForbiddenError(
f"Role {role.value} may not {action.value.lower()} this report",
{"required_role": transition.allowed_role.value, "your_role": role.value},
)
return transition
def assert_editable(status: DCRStatus) -> None:
"""V9/V10 — report data may only change in DRAFT or RETURNED."""
if status not in EDITABLE_STATUSES:
from app.common.exceptions import ReportLockedError
raise ReportLockedError(
f"A report in status {status.value} cannot be modified",
{
"current_status": status.value,
"editable_statuses": sorted(s.value for s in EDITABLE_STATUSES),
},
)
View File
+46
View File
@@ -0,0 +1,46 @@
"""Append-only audit log.
`approval_history` and `comments` were NOT created as separate tables (report §13.2).
Approval history is a filtered query over this table; every comment in this system
attaches to a state change, so it lives in `audit_log.comment`.
SEC-3: the application must never be granted UPDATE or DELETE on this table. See
`scripts/harden_audit.sql`.
"""
import uuid
from datetime import datetime
from typing import Any
from sqlalchemy import DateTime, Enum, ForeignKey, String, Text, func
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.dialects.postgresql import UUID as PGUUID
from sqlalchemy.orm import Mapped, mapped_column
from app.common.enums import AuditAction, EntityType
from app.database.base import Base, UUIDMixin
class AuditLog(Base, UUIDMixin):
__tablename__ = "audit_log"
actor_user_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="RESTRICT"), nullable=False
)
entity_type: Mapped[EntityType] = mapped_column(
Enum(EntityType, name="entity_type_enum", native_enum=False, length=30),
nullable=False,
index=True,
)
entity_id: Mapped[uuid.UUID] = mapped_column(PGUUID(as_uuid=True), nullable=False, index=True)
action: Mapped[AuditAction] = mapped_column(
Enum(AuditAction, name="audit_action_enum", native_enum=False, length=20), nullable=False
)
before_data: Mapped[dict[str, Any] | None] = mapped_column(JSONB)
after_data: Mapped[dict[str, Any] | None] = mapped_column(JSONB)
#: The manager's reason — business context no automatic row-versioner can capture.
comment: Mapped[str | None] = mapped_column(Text)
ip_address: Mapped[str | None] = mapped_column(String(45))
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), nullable=False, index=True
)
+68
View File
@@ -0,0 +1,68 @@
import uuid
from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
from app.audit.schemas import ApprovalHistoryItem, AuditLogRead
from app.audit.service import AuditService
from app.auth.dependencies import assert_can_view_dcr, get_current_user
from app.common.enums import EntityType, Role
from app.common.exceptions import NotFoundError
from app.database.session import get_db
from app.reports.repository import DCRRepository
from app.users.models import User
router = APIRouter(prefix="/audit", tags=["audit"])
@router.get("", response_model=list[AuditLogRead])
async def get_audit_history(
entity_type: EntityType = Query(...),
entity_id: uuid.UUID = Query(...),
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""Scoped audit history.
For a report, the caller must be able to view the report itself — the audit log is
not a side door around the data-scope rules.
"""
if entity_type == EntityType.DCR:
dcr = await DCRRepository(db).get(entity_id)
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):
from app.common.exceptions import ForbiddenError
raise ForbiddenError("Only ADMIN or GM may read non-report audit history")
return await AuditService(db).history_for(entity_type, entity_id)
@router.get("/dcr/{dcr_id}/approval-history", response_model=list[ApprovalHistoryItem])
async def approval_history(
dcr_id: uuid.UUID,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
) -> list[ApprovalHistoryItem]:
""""Approval history" is a filtered view over audit_log, not a second table."""
dcr = await DCRRepository(db).get(dcr_id)
if dcr is None:
raise NotFoundError("Report not found")
await assert_can_view_dcr(db, current_user, dcr)
entries = await AuditService(db).approval_history_for(dcr_id)
items: list[ApprovalHistoryItem] = []
for entry in entries:
actor = await db.get(User, entry.actor_user_id)
items.append(
ApprovalHistoryItem(
action=entry.action,
actor_name=actor.full_name if actor else "Unknown",
actor_role=actor.role.value if actor else "-",
comment=entry.comment,
at=entry.created_at,
)
)
return items
+32
View File
@@ -0,0 +1,32 @@
import uuid
from datetime import datetime
from typing import Any
from pydantic import BaseModel, ConfigDict
from app.common.enums import AuditAction, EntityType
class AuditLogRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
actor_user_id: uuid.UUID
entity_type: EntityType
entity_id: uuid.UUID
action: AuditAction
comment: str | None
before_data: dict[str, Any] | None
after_data: dict[str, Any] | None
ip_address: str | None
created_at: datetime
class ApprovalHistoryItem(BaseModel):
"""The approval trail as shown on S7 and printed in the PDF."""
action: AuditAction
actor_name: str
actor_role: str
comment: str | None
at: datetime
+80
View File
@@ -0,0 +1,80 @@
"""Explicit, application-level audit logging.
Deliberately NOT automatic row-versioning (report §14.3 C4): an automatic versioner
records *what* changed but cannot record *why* — and the manager's return reason is
the single most important thing in this audit trail.
Every `log()` call happens inside the caller's transaction, so a state change and its
audit row commit together or not at all (V12).
"""
import uuid
from typing import Any
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.audit.models import AuditLog
from app.common.enums import AuditAction, EntityType
class AuditService:
def __init__(self, db: AsyncSession) -> None:
self.db = db
async def log(
self,
*,
actor_user_id: uuid.UUID,
entity_type: EntityType,
entity_id: uuid.UUID,
action: AuditAction,
before: dict[str, Any] | None = None,
after: dict[str, Any] | None = None,
comment: str | None = None,
ip_address: str | None = None,
) -> AuditLog:
entry = AuditLog(
actor_user_id=actor_user_id,
entity_type=entity_type,
entity_id=entity_id,
action=action,
before_data=before,
after_data=after,
comment=comment,
ip_address=ip_address,
)
self.db.add(entry)
# Flush, not commit — the caller owns the transaction boundary.
await self.db.flush()
return entry
async def history_for(
self, entity_type: EntityType, entity_id: uuid.UUID
) -> list[AuditLog]:
stmt = (
select(AuditLog)
.where(AuditLog.entity_type == entity_type, AuditLog.entity_id == entity_id)
.order_by(AuditLog.created_at.asc())
)
return list((await self.db.execute(stmt)).scalars().all())
async def approval_history_for(self, dcr_id: uuid.UUID) -> list[AuditLog]:
""""Approval history" is a FILTERED QUERY, not a second table (report §13.2)."""
workflow_actions = [
AuditAction.CREATE,
AuditAction.SUBMIT,
AuditAction.FORWARD,
AuditAction.RETURN,
AuditAction.APPROVE,
]
stmt = (
select(AuditLog)
.where(
AuditLog.entity_type == EntityType.DCR,
AuditLog.entity_id == dcr_id,
AuditLog.action.in_(workflow_actions),
)
.order_by(AuditLog.created_at.asc())
)
return list((await self.db.execute(stmt)).scalars().all())
View File
+111
View File
@@ -0,0 +1,111 @@
"""The permission core — two layers.
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
endpoints, and every one has a negative test asserting 403 (X1-X3).
"""
import uuid
from fastapi import Depends, Request
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth.security import decode_access_token
from app.common.enums import Role
from app.common.exceptions import ForbiddenError, UnauthorizedError
from app.database.session import get_db
from app.organization.models import AMHeadquarters
from app.users.models import User
bearer_scheme = HTTPBearer(auto_error=False)
async def get_current_user(
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
db: AsyncSession = Depends(get_db),
) -> User:
if credentials is None:
raise UnauthorizedError("Missing bearer token")
payload = decode_access_token(credentials.credentials)
try:
user_id = uuid.UUID(payload["sub"])
except (KeyError, ValueError) as exc:
raise UnauthorizedError("Malformed token subject") from exc
user = await db.get(User, user_id)
if user is None:
raise UnauthorizedError("User no longer exists")
# SEC-5: checked on EVERY request, not only at login.
if not user.is_active:
raise UnauthorizedError("User account is deactivated")
return user
def require_role(*allowed: Role):
"""Layer 1. Usage: `user: User = Depends(require_role(Role.MR))`."""
async def _check(user: User = Depends(get_current_user)) -> User:
if user.role not in allowed:
raise ForbiddenError(
"Role not permitted for this action",
{"your_role": user.role.value, "required": [r.value for r in allowed]},
)
return user
return _check
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`)."""
stmt = select(AMHeadquarters.headquarters_id).where(
AMHeadquarters.area_manager_user_id == am_user_id,
AMHeadquarters.effective_to.is_(None),
)
return set((await db.execute(stmt)).scalars().all())
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):
return None
if user.role == Role.AM:
return await active_hq_ids_for_am(db, user.id)
if user.role == Role.MR:
return {user.headquarters_id} if user.headquarters_id else set()
return set()
async def assert_can_view_hq(db: AsyncSession, user: User, headquarters_id: uuid.UUID) -> None:
allowed = await visible_hq_ids(db, user)
if allowed is None or headquarters_id in allowed:
return
raise ForbiddenError("Headquarters outside your data scope")
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.
"""
if user.role in (Role.GM, Role.ADMIN):
return
if user.role == Role.MR and dcr.mr_user_id == user.id:
return
if user.role == Role.AM:
if dcr.headquarters_id in await active_hq_ids_for_am(db, user.id):
return
raise ForbiddenError("Report outside your data scope")
def client_ip(request: Request) -> str | None:
forwarded = request.headers.get("x-forwarded-for")
if forwarded:
return forwarded.split(",")[0].strip()
return request.client.host if request.client else None
+26
View File
@@ -0,0 +1,26 @@
"""Server-side refresh tokens.
Stored server-side (not stateless) precisely so they can be REVOKED — a departing MR
must lose access immediately (SEC-5).
"""
import uuid
from datetime import datetime
from sqlalchemy import Boolean, DateTime, ForeignKey, String
from sqlalchemy.dialects.postgresql import UUID as PGUUID
from sqlalchemy.orm import Mapped, mapped_column
from app.database.base import Base, TimestampMixin, UUIDMixin
class RefreshToken(Base, UUIDMixin, TimestampMixin):
__tablename__ = "refresh_token"
user_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="CASCADE"), nullable=False, index=True
)
#: SHA-256 of the token — a database leak must not yield usable tokens.
token_hash: Mapped[str] = mapped_column(String(64), nullable=False, unique=True, index=True)
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
revoked: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
+34
View File
@@ -0,0 +1,34 @@
from fastapi import APIRouter, Depends, Request, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth.dependencies import client_ip, get_current_user
from app.auth.schemas import CurrentUser, LoginRequest, RefreshRequest, TokenPair
from app.auth.service import AuthService
from app.database.session import get_db
from app.users.models import User
router = APIRouter(prefix="/auth", tags=["auth"])
@router.post("/login", response_model=TokenPair)
async def login(
payload: LoginRequest, request: Request, db: AsyncSession = Depends(get_db)
) -> TokenPair:
return await AuthService(db).login(payload.email, payload.password, client_ip(request))
@router.post("/refresh", response_model=TokenPair)
async def refresh(payload: RefreshRequest, db: AsyncSession = Depends(get_db)) -> TokenPair:
return await AuthService(db).refresh(payload.refresh_token)
@router.post("/logout", status_code=status.HTTP_204_NO_CONTENT)
async def logout(
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
) -> None:
await AuthService(db).logout(current_user.id)
@router.get("/me", response_model=CurrentUser)
async def me(current_user: User = Depends(get_current_user)) -> User:
return current_user
+33
View File
@@ -0,0 +1,33 @@
import uuid
from pydantic import BaseModel, ConfigDict, EmailStr, Field
from app.common.enums import Role
class LoginRequest(BaseModel):
email: EmailStr
password: str = Field(min_length=1)
class TokenPair(BaseModel):
access_token: str
refresh_token: str
token_type: str = "bearer"
expires_in: int
class RefreshRequest(BaseModel):
refresh_token: str
class CurrentUser(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
email: str
full_name: str
employee_code: str
role: Role
headquarters_id: uuid.UUID | None
is_active: bool
+65
View File
@@ -0,0 +1,65 @@
"""Password hashing and JWT encoding/decoding."""
import hashlib
import secrets
import uuid
from datetime import UTC, datetime, timedelta
from typing import Any
from argon2 import PasswordHasher
from argon2.exceptions import VerificationError, VerifyMismatchError
from jose import JWTError, jwt
from app.common.exceptions import UnauthorizedError
from app.config.settings import settings
_hasher = PasswordHasher()
def utcnow() -> datetime:
return datetime.now(UTC)
def hash_password(plain: str) -> str:
return _hasher.hash(plain)
def verify_password(plain: str, hashed: str) -> bool:
try:
_hasher.verify(hashed, plain)
return True
except (VerifyMismatchError, VerificationError):
return False
def create_access_token(user_id: uuid.UUID, role: str) -> str:
now = utcnow()
payload: dict[str, Any] = {
"sub": str(user_id),
"role": role,
"type": "access",
"iat": now,
"exp": now + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES),
"jti": secrets.token_urlsafe(16),
}
return jwt.encode(payload, settings.SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
def decode_access_token(token: str) -> dict[str, Any]:
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.JWT_ALGORITHM])
except JWTError as exc:
raise UnauthorizedError("Invalid or expired token") from exc
if payload.get("type") != "access":
raise UnauthorizedError("Wrong token type")
return payload
def generate_refresh_token() -> tuple[str, str]:
"""Return (plaintext_token, sha256_hash). Only the hash is stored."""
raw = secrets.token_urlsafe(48)
return raw, hash_refresh_token(raw)
def hash_refresh_token(raw: str) -> str:
return hashlib.sha256(raw.encode()).hexdigest()
+100
View File
@@ -0,0 +1,100 @@
import uuid
from datetime import timedelta
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.audit.service import AuditService
from app.auth.models import RefreshToken
from app.auth.schemas import TokenPair
from app.auth.security import (
create_access_token,
generate_refresh_token,
hash_refresh_token,
utcnow,
verify_password,
)
from app.common.enums import AuditAction, EntityType
from app.common.exceptions import UnauthorizedError
from app.config.settings import settings
from app.users.models import User
class AuthService:
def __init__(self, db: AsyncSession) -> None:
self.db = db
self.audit = AuditService(db)
async def login(self, email: str, password: str, ip: str | None = None) -> TokenPair:
stmt = select(User).where(User.email == email)
user = (await self.db.execute(stmt)).scalar_one_or_none()
# Same message for unknown user and wrong password — do not leak which.
if user is None or not verify_password(password, user.password_hash):
if user is not None:
user.failed_login_attempts += 1
await self.db.commit()
raise UnauthorizedError("Invalid email or password")
if not user.is_active:
raise UnauthorizedError("User account is deactivated")
# SEC-10 — lock out after repeated failures.
if user.failed_login_attempts >= settings.LOGIN_MAX_FAILED_ATTEMPTS:
raise UnauthorizedError("Account locked after too many failed attempts")
user.failed_login_attempts = 0
await self.audit.log(
actor_user_id=user.id,
entity_type=EntityType.USER,
entity_id=user.id,
action=AuditAction.LOGIN,
ip_address=ip,
)
pair = await self._issue_tokens(user)
await self.db.commit()
return pair
async def refresh(self, raw_token: str) -> TokenPair:
token_hash = hash_refresh_token(raw_token)
stmt = select(RefreshToken).where(RefreshToken.token_hash == token_hash)
stored = (await self.db.execute(stmt)).scalar_one_or_none()
if stored is None or stored.revoked or stored.expires_at < utcnow():
raise UnauthorizedError("Invalid or expired refresh token")
user = await self.db.get(User, stored.user_id)
if user is None or not user.is_active:
raise UnauthorizedError("User no longer active")
# Rotate: the presented token is burned as the new one is issued.
stored.revoked = True
pair = await self._issue_tokens(user)
await self.db.commit()
return pair
async def logout(self, user_id: uuid.UUID) -> None:
"""Revoke every refresh token for this user."""
stmt = select(RefreshToken).where(
RefreshToken.user_id == user_id, RefreshToken.revoked.is_(False)
)
for token in (await self.db.execute(stmt)).scalars().all():
token.revoked = True
await self.db.commit()
async def _issue_tokens(self, user: User) -> TokenPair:
access = create_access_token(user.id, user.role.value)
raw_refresh, refresh_hash = generate_refresh_token()
self.db.add(
RefreshToken(
user_id=user.id,
token_hash=refresh_hash,
expires_at=utcnow() + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS),
)
)
await self.db.flush()
return TokenPair(
access_token=access,
refresh_token=raw_refresh,
expires_in=settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60,
)
View File
+52
View File
@@ -0,0 +1,52 @@
"""Chemist master data and chemist → MR assignment (same shape as doctors)."""
import uuid
from datetime import date
from sqlalchemy import Boolean, Date, ForeignKey, Index, String, UniqueConstraint, text
from sqlalchemy.dialects.postgresql import UUID as PGUUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.database.base import Base, TimestampMixin, UUIDMixin
class Chemist(Base, UUIDMixin, TimestampMixin):
__tablename__ = "chemist"
__table_args__ = (
UniqueConstraint(
"headquarters_id", "name", "shop_address", name="uq_chemist_hq_name_shop"
),
)
headquarters_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("headquarters.id", ondelete="RESTRICT"), nullable=False
)
name: Mapped[str] = mapped_column(String(200), nullable=False)
shop_address: Mapped[str] = mapped_column(String(500), nullable=False)
contact_number: Mapped[str | None] = mapped_column(String(20))
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
assignments: Mapped[list["ChemistAssignment"]] = relationship(back_populates="chemist")
class ChemistAssignment(Base, UUIDMixin, TimestampMixin):
__tablename__ = "chemist_assignment"
__table_args__ = (
Index(
"uq_active_chemist_assignment",
"chemist_id",
unique=True,
postgresql_where=text("effective_to IS NULL"),
),
)
chemist_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("chemist.id", ondelete="CASCADE"), nullable=False
)
mr_user_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="RESTRICT"), nullable=False
)
effective_from: Mapped[date] = mapped_column(Date, nullable=False)
effective_to: Mapped[date | None] = mapped_column(Date)
chemist: Mapped["Chemist"] = relationship(back_populates="assignments")
+62
View File
@@ -0,0 +1,62 @@
import uuid
from fastapi import APIRouter, Depends, Request, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth.dependencies import client_ip, get_current_user, require_role
from app.chemists.models import Chemist
from app.chemists.schemas import ChemistCreate, ChemistRead, ChemistUpdate
from app.chemists.service import ChemistService
from app.common.enums import Role
from app.database.session import get_db
from app.doctors.schemas import AssignToMR
from app.users.models import User
router = APIRouter(prefix="/chemists", tags=["chemists"])
@router.get("", response_model=list[ChemistRead])
async def list_chemists(
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
) -> list[Chemist]:
return await ChemistService(db).list_for(current_user)
@router.post("", response_model=ChemistRead, status_code=status.HTTP_201_CREATED)
async def create_chemist(
payload: ChemistCreate,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> Chemist:
return await ChemistService(db).create(payload, current_user, client_ip(request))
@router.patch("/{chemist_id}", response_model=ChemistRead)
async def update_chemist(
chemist_id: uuid.UUID,
payload: ChemistUpdate,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> Chemist:
return await ChemistService(db).update(chemist_id, payload, current_user, client_ip(request))
@router.post("/{chemist_id}/assign", status_code=status.HTTP_201_CREATED)
async def assign_chemist(
chemist_id: uuid.UUID,
payload: AssignToMR,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN, Role.GM, Role.AM)),
db: AsyncSession = Depends(get_db),
):
assignment = await ChemistService(db).assign_to_mr(
chemist_id, payload.mr_user_id, payload.effective_from, current_user, client_ip(request)
)
return {
"id": assignment.id,
"chemist_id": assignment.chemist_id,
"mr_user_id": assignment.mr_user_id,
"effective_from": assignment.effective_from,
}
+28
View File
@@ -0,0 +1,28 @@
import uuid
from pydantic import BaseModel, ConfigDict, Field
class ChemistCreate(BaseModel):
headquarters_id: uuid.UUID
name: str = Field(min_length=2, max_length=200)
shop_address: str = Field(min_length=2, max_length=500)
contact_number: str | None = Field(default=None, max_length=20)
class ChemistUpdate(BaseModel):
name: str | None = Field(default=None, min_length=2, max_length=200)
shop_address: str | None = Field(default=None, min_length=2, max_length=500)
contact_number: str | None = Field(default=None, max_length=20)
is_active: bool | None = None
class ChemistRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
headquarters_id: uuid.UUID
name: str
shop_address: str
contact_number: str | None
is_active: bool
+143
View File
@@ -0,0 +1,143 @@
import uuid
from datetime import date
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.audit.service import AuditService
from app.auth.dependencies import assert_can_view_hq, visible_hq_ids
from app.chemists.models import Chemist, ChemistAssignment
from app.chemists.schemas import ChemistCreate, ChemistUpdate
from app.common.enums import AuditAction, EntityType, Role
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
from app.common.utils import snapshot
from app.users.models import User
_AUDIT_FIELDS = ["name", "shop_address", "contact_number", "is_active"]
class ChemistService:
def __init__(self, db: AsyncSession) -> None:
self.db = db
self.audit = AuditService(db)
async def create(self, data: ChemistCreate, actor: User, ip: str | None = None) -> Chemist:
await assert_can_view_hq(self.db, actor, data.headquarters_id)
chemist = Chemist(**data.model_dump())
self.db.add(chemist)
try:
await self.db.flush()
except IntegrityError as exc:
await self.db.rollback()
raise ConflictError(
"A chemist with this name already exists at this address in this headquarters",
{"cause": "uq_chemist_hq_name_shop"},
) from exc
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.CHEMIST,
entity_id=chemist.id,
action=AuditAction.CREATE,
after=snapshot(chemist, _AUDIT_FIELDS),
ip_address=ip,
)
await self.db.commit()
return chemist
async def update(
self, chemist_id: uuid.UUID, data: ChemistUpdate, actor: User, ip: str | None = None
) -> Chemist:
chemist = await self.db.get(Chemist, chemist_id)
if chemist is None:
raise NotFoundError("Chemist not found")
await assert_can_view_hq(self.db, actor, chemist.headquarters_id)
before = snapshot(chemist, _AUDIT_FIELDS)
for field, value in data.model_dump(exclude_unset=True).items():
setattr(chemist, field, value)
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.CHEMIST,
entity_id=chemist.id,
action=AuditAction.UPDATE,
before=before,
after=snapshot(chemist, _AUDIT_FIELDS),
ip_address=ip,
)
await self.db.commit()
return chemist
async def list_for(self, actor: User) -> list[Chemist]:
if actor.role == Role.MR:
stmt = (
select(Chemist)
.join(ChemistAssignment, ChemistAssignment.chemist_id == Chemist.id)
.where(
ChemistAssignment.mr_user_id == actor.id,
ChemistAssignment.effective_to.is_(None),
Chemist.is_active.is_(True),
)
.order_by(Chemist.name)
)
return list((await self.db.execute(stmt)).scalars().all())
allowed = await visible_hq_ids(self.db, actor)
stmt = select(Chemist).order_by(Chemist.name)
if allowed is not None:
stmt = stmt.where(Chemist.headquarters_id.in_(allowed or [None]))
return list((await self.db.execute(stmt)).scalars().all())
async def assign_to_mr(
self,
chemist_id: uuid.UUID,
mr_user_id: uuid.UUID,
effective_from: date | None,
actor: User,
ip: str | None = None,
) -> ChemistAssignment:
chemist = await self.db.get(Chemist, chemist_id)
if chemist is None:
raise NotFoundError("Chemist not found")
await assert_can_view_hq(self.db, actor, chemist.headquarters_id)
mr = await self.db.get(User, mr_user_id)
if mr is None:
raise NotFoundError("MR not found")
if mr.role != Role.MR:
raise ValidationError("Chemists can only be assigned to an MR")
if mr.headquarters_id != chemist.headquarters_id:
raise ValidationError("MR and chemist belong to different headquarters")
start = effective_from or date.today()
existing = (
await self.db.execute(
select(ChemistAssignment).where(
ChemistAssignment.chemist_id == chemist_id,
ChemistAssignment.effective_to.is_(None),
)
)
).scalars().all()
for row in existing:
if row.mr_user_id == mr_user_id:
return row
row.effective_to = start
await self.db.flush()
assignment = ChemistAssignment(
chemist_id=chemist_id, mr_user_id=mr_user_id, effective_from=start
)
self.db.add(assignment)
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.CHEMIST,
entity_id=chemist_id,
action=AuditAction.ASSIGN,
after={"mr_user_id": str(mr_user_id), "effective_from": start.isoformat()},
ip_address=ip,
)
await self.db.commit()
return assignment
View File
+83
View File
@@ -0,0 +1,83 @@
"""Domain enumerations.
Roles are a fixed enum on `user.role`, not a `role` table — with 4 roles that never
change at runtime a lookup table adds a join to every request and buys nothing.
(See report §13.2.)
"""
from enum import StrEnum
class Role(StrEnum):
"""Operational roles (MR/AM/GM) plus the technical ADMIN role.
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 = "ADMIN"
GM = "GM"
AM = "AM"
MR = "MR"
class DCRStatus(StrEnum):
"""MR submits, the Area Manager approves or returns it.
`RETURNED` captures the correction loop, and `APPROVED` remains terminal and
immutable. There is no General Manager step.
"""
DRAFT = "DRAFT"
PENDING_AM = "PENDING_AM"
RETURNED = "RETURNED"
APPROVED = "APPROVED"
#: Statuses in which the owning MR may still change report data (V9).
EDITABLE_STATUSES: frozenset[DCRStatus] = frozenset(
{DCRStatus.DRAFT, DCRStatus.RETURNED}
)
class WorkflowAction(StrEnum):
SUBMIT = "SUBMIT"
RETURN = "RETURN"
APPROVE = "APPROVE"
class CallOutcome(StrEnum):
MET = "MET"
NOT_AVAILABLE = "NOT_AVAILABLE"
RESCHEDULED = "RESCHEDULED"
class ConversionStatus(StrEnum):
"""Core-doctor conversion. Stored as a column on doctor_call, not a table."""
NOT_STARTED = "NOT_STARTED"
IN_PROGRESS = "IN_PROGRESS"
CONVERTED = "CONVERTED"
LOST = "LOST"
class AuditAction(StrEnum):
CREATE = "CREATE"
UPDATE = "UPDATE"
DELETE = "DELETE"
SUBMIT = "SUBMIT"
FORWARD = "FORWARD"
RETURN = "RETURN"
APPROVE = "APPROVE"
ASSIGN = "ASSIGN"
LOGIN = "LOGIN"
DEACTIVATE = "DEACTIVATE"
class EntityType(StrEnum):
USER = "user"
HEADQUARTERS = "headquarters"
DOCTOR = "doctor"
CHEMIST = "chemist"
DCR = "dcr"
PRODUCT = "product"
+67
View File
@@ -0,0 +1,67 @@
"""Application error hierarchy → one consistent JSON error envelope."""
from typing import Any
class AppError(Exception):
"""Base for every error the application raises deliberately."""
status_code: int = 400
code: str = "APP_ERROR"
def __init__(self, message: str, details: dict[str, Any] | None = None) -> None:
self.message = message
self.details = details or {}
super().__init__(message)
def to_dict(self) -> dict[str, Any]:
return {
"error": {
"code": self.code,
"message": self.message,
"details": self.details,
}
}
class NotFoundError(AppError):
status_code = 404
code = "NOT_FOUND"
class ForbiddenError(AppError):
"""Raised for both role failures and data-scope failures.
Deliberately 403 and not 404: the negative-scope tests (X1-X3) assert 403, so a
scope bug cannot hide behind an ambiguous "not found".
"""
status_code = 403
code = "FORBIDDEN"
class UnauthorizedError(AppError):
status_code = 401
code = "UNAUTHORIZED"
class ConflictError(AppError):
status_code = 409
code = "CONFLICT"
class ValidationError(AppError):
status_code = 422
code = "VALIDATION_ERROR"
class InvalidStateTransitionError(AppError):
status_code = 409
code = "INVALID_STATE_TRANSITION"
class ReportLockedError(AppError):
"""V10 — an APPROVED report can never be modified by any role."""
status_code = 409
code = "REPORT_LOCKED"
+35
View File
@@ -0,0 +1,35 @@
"""Generic data-access base. Repositories hold queries only — never business rules."""
import uuid
from typing import Generic, TypeVar
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.common.exceptions import NotFoundError
from app.database.base import Base
ModelT = TypeVar("ModelT", bound=Base)
class BaseRepository(Generic[ModelT]):
model: type[ModelT]
def __init__(self, db: AsyncSession) -> None:
self.db = db
async def get(self, entity_id: uuid.UUID) -> ModelT | None:
return await self.db.get(self.model, entity_id)
async def get_or_404(self, entity_id: uuid.UUID) -> ModelT:
entity = await self.get(entity_id)
if entity is None:
raise NotFoundError(f"{self.model.__name__} not found", {"id": str(entity_id)})
return entity
async def list_all(self) -> list[ModelT]:
return list((await self.db.execute(select(self.model))).scalars().all())
def add(self, entity: ModelT) -> ModelT:
self.db.add(entity)
return entity
+45
View File
@@ -0,0 +1,45 @@
"""Small shared helpers."""
import uuid
from datetime import UTC, date, datetime, time
from typing import Any
from zoneinfo import ZoneInfo
from sqlalchemy import inspect
def utcnow() -> datetime:
return datetime.now(UTC)
def local_now() -> datetime:
"""Current time in the company's timezone (`APP_TIMEZONE`), timezone-aware."""
from app.config.settings import settings
return datetime.now(ZoneInfo(settings.APP_TIMEZONE))
def local_today() -> date:
"""Today's date in the company's timezone — the server clock runs on UTC."""
return local_now().date()
def _jsonable(value: Any) -> Any:
if isinstance(value, uuid.UUID):
return str(value)
if isinstance(value, datetime | date | time):
return value.isoformat()
if hasattr(value, "value"): # StrEnum and friends
return value.value
return value
def snapshot(instance: Any, fields: list[str] | None = None) -> dict[str, Any]:
"""Serialise an ORM instance's column values for the audit log's JSONB columns.
Only loaded column attributes are read, so this never triggers lazy IO inside a
transaction that is about to commit.
"""
mapper = inspect(instance).mapper
names = fields or [c.key for c in mapper.column_attrs]
return {name: _jsonable(getattr(instance, name, None)) for name in names}
View File
+67
View File
@@ -0,0 +1,67 @@
"""Application settings. Everything comes from the environment — no secrets in code."""
from functools import lru_cache
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_file=".env", env_file_encoding="utf-8", extra="ignore"
)
# --- Application ---------------------------------------------------
APP_NAME: str = "Celtic Life Science Pvt Ltd"
PDF_COMPANY_NAME: str = "CELTIC LIFE SCIENCE PVT LTD"
PDF_COMPANY_ADDRESS: str = "PLOT NO -D/3, KHARVEL NAGAR, UNIT-3, BHUBANESWAR ODISHA-751001"
PDF_COMPANY_WEBSITE: str = "www.celticlifescience.com"
PDF_COMPANY_EMAIL: str = "info@celticlifescience.com"
PDF_COMPANY_PHONE: str = "9090024999"
API_V1_PREFIX: str = "/api/v1"
ENVIRONMENT: str = "development"
DEBUG: bool = False
# --- Database ------------------------------------------------------
DATABASE_URL: str = "postgresql+asyncpg://pharma:pharma@localhost:5432/pharma"
DB_ECHO: bool = False
# --- Authentication ------------------------------------------------
# SECRET_KEY MUST be overridden in production.
SECRET_KEY: str = "change-me-in-production-this-is-not-a-secret"
JWT_ALGORITHM: str = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES: int = 15
REFRESH_TOKEN_EXPIRE_DAYS: int = 7
LOGIN_MAX_FAILED_ATTEMPTS: int = 10
# Business timezone: "today" and visit-time checks use this, not the server's UTC clock.
APP_TIMEZONE: str = "Asia/Kolkata"
# --- Business rules (see report §21 — confirm with client) ----------
# A10 / Q8: how many days back an MR may file a report.
BACKDATING_WINDOW_DAYS: int = Field(default=7, ge=0, le=90)
# A16 / Q9: report for date D must be submitted by end of D + this many days.
SUBMISSION_DEADLINE_DAYS: int = Field(default=1, ge=0, le=30)
# V8: minimum length of a manager's return reason.
MIN_RETURN_REASON_LENGTH: int = 10
# --- Storage -------------------------------------------------------
PDF_STORAGE_PATH: str = "./storage/pdf"
# --- CORS ----------------------------------------------------------
CORS_ORIGINS: list[str] = Field(
default_factory=lambda: ["https://celtic.upskalor.com", "https://www.celtic.upskalor.com", "http://localhost:5173", "http://localhost:3000"]
)
@property
def sync_database_url(self) -> str:
"""Alembic runs synchronously through psycopg, not the async API driver."""
return self.DATABASE_URL.replace("+asyncpg", "+psycopg")
@lru_cache
def get_settings() -> Settings:
return Settings()
settings = get_settings()
+140
View File
@@ -0,0 +1,140 @@
"""Approval workflow for the company forms that carry an Area Manager signature.
draft --request(MR)--> pending --approve(AM)--> 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
Manager who manages that MR's headquarters, and nobody else can approve it. Only a form that has
rows can be sent, and only a form that has been sent can be approved.
"""
import uuid
from sqlalchemy import select, text
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth.dependencies import active_hq_ids_for_am
from app.common.enums import Role
from app.common.exceptions import ConflictError, ForbiddenError, NotFoundError, ValidationError
from app.csv_data.models import FormApproval
from app.organization.models import AMHeadquarters, Headquarters
from app.users.models import User
APPROVAL_TABLES = {"standard_tour_plan", "tour_plan", "fare_chart"}
async def owners_in_scope(db: AsyncSession, user: User) -> list[User]:
"""The MRs whose forms this user may see: themselves, the MRs of their headquarters, or (admin) all."""
stmt = select(User).where(User.role == Role.MR, User.is_active.is_(True)).order_by(User.full_name)
if user.role == Role.MR:
stmt = stmt.where(User.id == user.id)
elif user.role == Role.AM:
stmt = stmt.where(User.headquarters_id.in_(await active_hq_ids_for_am(db, user.id)))
elif user.role != Role.ADMIN:
return []
return list((await db.execute(stmt)).scalars())
async def assigned_area_manager(db: AsyncSession, owner: User) -> uuid.UUID | None:
if owner.headquarters_id is None:
return None
stmt = select(AMHeadquarters.area_manager_user_id).where(
AMHeadquarters.headquarters_id == owner.headquarters_id, AMHeadquarters.effective_to.is_(None)
)
return (await db.execute(stmt)).scalars().first()
async def assert_owner_in_scope(db: AsyncSession, user: User, owner_id: uuid.UUID) -> User:
"""The MR `owner_id`, if `user` is allowed to see their forms; anything else is refused."""
for owner in await owners_in_scope(db, user):
if owner.id == owner_id:
return owner
if user.role == Role.ADMIN 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")
async def get_approval(db: AsyncSession, table_name: str, owner_id: uuid.UUID) -> FormApproval | None:
return await db.get(FormApproval, (table_name, owner_id))
async def _get_or_create(db: AsyncSession, table_name: str, owner_id: uuid.UUID) -> FormApproval:
row = await get_approval(db, table_name, owner_id)
if row is None:
row = FormApproval(table_name=table_name, owner_user_id=owner_id, status="draft")
db.add(row)
await db.flush()
return row
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
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)}
hq_names = {h.id: h.name for h in (await db.execute(select(Headquarters))).scalars()}
existing = {
(r.table_name, r.owner_user_id): r
for r in (await db.execute(select(FormApproval).where(FormApproval.owner_user_id.in_(owners)))).scalars()
}
out: list[tuple[FormApproval, User, str | None]] = []
if user.role == Role.MR:
for name in sorted(APPROVAL_TABLES):
out.append((existing.get((name, user.id)) or FormApproval(table_name=name, owner_user_id=user.id, status="draft"), user, hq_names.get(user.headquarters_id)))
return out
for (name, owner_id), row in sorted(existing.items()):
if row.status != "draft":
out.append((row, owners[owner_id], hq_names.get(owners[owner_id].headquarters_id)))
return out
async def _row_count(db: AsyncSession, table_name: str, owner_id: uuid.UUID) -> int:
# table_name is only ever one of the fixed APPROVAL_TABLES, never user input.
return (
await db.execute(text(f'SELECT COUNT(*) FROM "{table_name}" WHERE owner_user_id = :o'), {"o": owner_id})
).scalar_one()
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.")
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
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:
raise ValidationError("Add at least one row before sending the form for approval")
row.status = "pending"
row.requested_by_user_id = actor.id
await db.commit()
await db.refresh(row)
return row
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
row = await _get_or_create(db, table_name, owner_id)
if row.status == "approved":
return row # a double click
if row.status != "pending" or await _row_count(db, table_name, owner_id) == 0:
raise ConflictError("Nothing is waiting for approval on this form")
row.status = "approved"
row.approved_by_user_id = actor.id
row.approved_by_name = actor.full_name
await db.commit()
await db.refresh(row)
return row
async def invalidate(db: AsyncSession, table_name: str, owner_id: uuid.UUID | None) -> None:
"""The MR's rows changed: any earlier approval no longer applies. The caller commits."""
if table_name not in APPROVAL_TABLES or owner_id is None:
return
row = await get_approval(db, table_name, owner_id)
if row is not None and row.status != "draft":
row.status = "draft"
row.approved_by_user_id = None
row.approved_by_name = None
+27
View File
@@ -0,0 +1,27 @@
"""Allow-listed imported CSV tables and their database columns."""
TABLES: dict[str, tuple[str, ...]] = {
"sales_projection": ("name", "headquarter", "report_date", "month", "serial_no", "product_name", "pts", "secondary_qty", "value", "closing", "secondary_value", "aug_sales", "value_2"),
"weekly_report": ("employee_name", "report_date", "headquarter", "month", "no_of_days_worked", "no_of_doctor_called", "no_of_chemist_called", "pob_booked", "secondary_sales", "pob_objective", "secondary_objective", "product_offer_scheme_booked", "product_offer_scheme_objective"),
"field_activity_report": ("name", "headquarter", "month", "report_date", "station_worked", "no_of_doctors_called", "no_of_chemists_pds_called", "doctor_call_avg", "chemist_call_avg"),
"fare_chart": ("name", "headquarter", "serial_no", "report_date", "from_location", "to_location", "kilometers_km"),
"daily_call_report_csv": ("name", "headquarter", "report_date", "month", "doctor_sr_no", "doctor_name", "qualification", "product_promote", "product_sample", "remarks", "chemist_sr_no", "chemist_name", "pob", "stockist_visit", "order_value"),
"core_dr_call_conversion": ("name", "headquarter", "month", "doctor_name", "date_of_visit", "product_targeted", "status"),
"area_covered": ("name", "headquarter", "month", "sale_status", "area_to_cover", "sale_objective", "status"),
"sales_and_stock_statement": ("name", "headquarter", "report_date", "month", "serial_no", "product_name", "opening", "receipt", "sale", "closing", "value_in_pts"),
"tour_plan": ("name", "headquarter", "serial_no", "report_date", "from_location", "to_location", "pob", "stockiest_visit"),
"standard_tour_plan": ("name", "headquarter", "serial_no", "place"),
}
CSV_LABELS = {
"weekly_report": "Weekly Report",
"field_activity_report": "Field Activity Report",
"fare_chart": "Fare Chart",
"daily_call_report_csv": "Daily Call Report CSV",
"core_dr_call_conversion": "Core Doctor Call Conversion",
"area_covered": "Area Covered",
"sales_and_stock_statement": "Sales and Stock Statement",
"tour_plan": "Tour Plan",
"standard_tour_plan": "Standard Tour Plan",
"sales_projection": "Sales Projection",
}
+37
View File
@@ -0,0 +1,37 @@
"""Approval state of the company forms that carry an Area Manager signature."""
import uuid
from datetime import datetime
from sqlalchemy import DateTime, ForeignKey, String, func
from sqlalchemy.dialects.postgresql import UUID as PGUUID
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.
FORM_APPROVAL_STATUSES = ("draft", "pending", "approved")
class FormApproval(Base):
"""One row per (approval form, MR): each MR's tour plan, standard tour plan and fare chart is approved on its own."""
__tablename__ = "form_approval"
table_name: Mapped[str] = mapped_column(String(64), primary_key=True)
#: The MR whose rows these are.
owner_user_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="CASCADE"), primary_key=True
)
status: Mapped[str] = mapped_column(String(10), nullable=False, default="draft", server_default="draft")
requested_by_user_id: Mapped[uuid.UUID | None] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="SET NULL")
)
approved_by_user_id: Mapped[uuid.UUID | None] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="SET NULL")
)
#: The name printed on the PDF. A snapshot, so renaming the user never rewrites a signature.
approved_by_name: Mapped[str | None] = mapped_column(String(200))
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False
)
+493
View File
@@ -0,0 +1,493 @@
import re
import uuid
from collections.abc import Iterable
from zoneinfo import ZoneInfo
from fastapi import APIRouter, Body, Depends, Query, status
from fastapi.responses import Response
from sqlalchemy import select, text
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth.dependencies import require_role
from app.common.enums import Role
from app.common.exceptions import ConflictError, ForbiddenError, NotFoundError, ValidationError
from app.config.settings import settings
from app.csv_data import approval as approvals
from app.csv_data.config import CSV_LABELS, TABLES
from app.database.session import get_db
from app.users.models import User
from app.organization.models import Headquarters
router = APIRouter(prefix="/csv-data", tags=["CSV data"])
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).
OWNED_TABLES = APPROVAL_TABLES
def _table(table_name: str) -> tuple[str, ...]:
if table_name not in TABLES:
raise NotFoundError("CSV table not found", {"table": table_name})
return TABLES[table_name]
def _clean_payload(table_name: str, payload: dict[str, object]) -> dict[str, str | None]:
columns = _table(table_name)
unknown = set(payload) - set(columns)
if unknown:
raise ValidationError("Unknown CSV column", {"columns": sorted(unknown)})
return {column: None if payload.get(column) is None else str(payload.get(column, "")) for column in columns}
def _has_user_data(table_name: str, values: dict[str, str | None]) -> bool:
return any(value and column not in SERIAL_COLUMNS for column, value in values.items())
async def _reject_repeat(
table_name: str, values: dict[str, str | None], db: AsyncSession, owner_id: uuid.UUID | None = None
) -> None:
"""A row identical to one already in the form is a repeat (a double click), not new data."""
compared = [c for c in _table(table_name) if c not in SERIAL_COLUMNS]
conditions = " AND ".join(f"COALESCE(\"{c}\", '') = :c_{i}" for i, c in enumerate(compared))
params: dict[str, object] = {f"c_{i}": (values.get(c) or "") for i, c in enumerate(compared)}
if owner_id is not None:
conditions += " AND owner_user_id = :owner"
params["owner"] = owner_id
if (await db.execute(text(f'SELECT 1 FROM "{table_name}" WHERE {conditions} LIMIT 1'), params)).first():
raise ConflictError("An identical row already exists in this form")
async def _renumber_rows(table_name: str, db: AsyncSession) -> None:
columns = _table(table_name)
# An MR's own form is numbered 1, 2, 3… whoever else has rows in the same table.
partition = "PARTITION BY owner_user_id " if table_name in OWNED_TABLES else ""
serial_updates = ""
for column in columns:
if column in SERIAL_COLUMNS:
serial_updates += f', "{column}" = numbered.serial::text'
await db.execute(
text(
f'''WITH numbered AS (
SELECT id,
ROW_NUMBER() OVER (ORDER BY source_row_number, id) AS row_number,
ROW_NUMBER() OVER ({partition}ORDER BY source_row_number, id) AS serial
FROM "{table_name}"
)
UPDATE "{table_name}" AS target
SET source_row_number = numbered.row_number{serial_updates}
FROM numbered
WHERE target.id = numbered.id'''
)
)
async def _apply_mr_identity(
values: dict[str, str | None], subject: User | None, db: AsyncSession
) -> dict[str, str | None]:
"""Fill NAME / HEADQUARTER from the MR the row is for (the signed-in MR, or the one an admin picked)."""
if subject is None or subject.role != Role.MR:
return values
headquarters_name = None
if subject.headquarters_id:
headquarters = await db.get(Headquarters, subject.headquarters_id)
headquarters_name = headquarters.name if headquarters else None
for column in values:
if column in {"name", "employee_name"}:
values[column] = subject.full_name
elif column == "headquarter":
values[column] = headquarters_name
return values
async def _present_rows_for_user(
rows: list[dict[str, object]], current_user: User, db: AsyncSession
) -> list[dict[str, object]]:
"""Show account identity from the session without changing imported data.
Admins must see the source values and every row. MRs use the imported rows as
their working data, but identity columns must always reflect the logged-in MR.
"""
if current_user.role != Role.MR:
return rows
headquarters_name = None
if current_user.headquarters_id:
headquarters = await db.get(Headquarters, current_user.headquarters_id)
headquarters_name = headquarters.name if headquarters else None
presented: list[dict[str, object]] = []
for row in rows:
item = dict(row)
if "name" in item:
item["name"] = current_user.full_name
if "employee_name" in item:
item["employee_name"] = current_user.full_name
if "headquarter" in item:
item["headquarter"] = headquarters_name or ""
presented.append(item)
return presented
async def _apply_sales_projection_product(
values: dict[str, str | None], db: AsyncSession, current_user: User | None = None
) -> dict[str, str | None]:
if values.get("product_name") is None:
return values
if current_user is not None and current_user.role == Role.ADMIN:
# Admin maintains the product list itself: any product name and PTS may be entered.
if not (values.get("product_name") or "").strip():
raise ValidationError("Enter a product name")
return values
result = await db.execute(
text(
'SELECT pts FROM "sales_projection" '
'WHERE product_name = :product_name LIMIT 1'
),
{"product_name": values["product_name"]},
)
pts = result.scalar_one_or_none()
if pts is None:
raise ValidationError(
"Choose a product from the Sales Projection product list",
{"product_name": values["product_name"]},
)
values["pts"] = str(pts)
return values
def _select(table_name: str, columns: Iterable[str]) -> str:
selected = ", ".join(f'"{column}"' for column in columns)
return f'SELECT id, source_row_number, {selected} FROM "{table_name}"'
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)."""
if table_name not in OWNED_TABLES:
return [], {}
if current_user.role == Role.MR:
if owner_id not in (None, current_user.id):
raise ForbiddenError("You can only see your own forms")
return ["owner_user_id = :owner"], {"owner": current_user.id}
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:
return ["owner_user_id = ANY(:owners)"], {"owners": [o.id for o in await approvals.owners_in_scope(db, current_user)]}
return [], {}
async def _row_owner(table_name: str, row_id: uuid.UUID, current_user: User, db: AsyncSession) -> uuid.UUID | None:
"""Who owns this row, after checking `current_user` is allowed to touch it."""
if table_name not in OWNED_TABLES:
return None
found = (await db.execute(text(f'SELECT owner_user_id FROM "{table_name}" WHERE id = :id'), {"id": row_id})).first()
if found is None:
raise NotFoundError("CSV row not found", {"id": str(row_id)})
owner_id = found[0]
if current_user.role == Role.MR and owner_id != current_user.id:
raise ForbiddenError("This row belongs to another medical representative")
if current_user.role == Role.AM:
if owner_id is None:
raise ForbiddenError("This row is outside your headquarters")
await approvals.assert_owner_in_scope(db, current_user, owner_id)
return owner_id
def _month_filter(table_name: str, month: str | None) -> tuple[list[str], dict[str, object]]:
if not month or not month.strip():
return [], {}
if "month" not in _table(table_name):
raise ValidationError("This form has no month to filter by", {"table": table_name})
return ["lower(btrim(COALESCE(\"month\", ''))) = :month"], {"month": month.strip().lower()}
async def _load_rows(
table_name: str, db: AsyncSession, current_user: User, owner_id: uuid.UUID | None = None, month: str | None = None
) -> list[dict[str, object]]:
columns = _table(table_name)
conditions, params = await _owner_condition(table_name, current_user, db, owner_id)
more, extra = _month_filter(table_name, month)
where = f" WHERE {' AND '.join(conditions + more)}" if conditions or more else ""
result = await db.execute(text(f"{_select(table_name, columns)}{where} ORDER BY source_row_number"), {**params, **extra})
return await _present_rows_for_user([dict(row) for row in result.mappings().all()], current_user, db)
def _available_csv_tables(current_user: User) -> list[str]:
visible = [name for name in TABLES if name not in HIDDEN_TABLES]
if current_user.role == Role.AM:
return [name for name in visible if name in APPROVAL_TABLES]
return visible
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})
@router.get("/tables")
async def list_csv_tables(current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM))) -> list[dict[str, object]]:
return [{"name": name, "label": CSV_LABELS[name], "columns": list(TABLES[name])} for name in _available_csv_tables(current_user)]
async def _signature(
table_name: str, owner_id: uuid.UUID | None, db: AsyncSession
) -> tuple[str | None, str | None, str | None]:
"""(status, approver name, approval date/time) for the PDF's signature — decided here, never by the browser.
It is the approval of the one MR whose rows the PDF holds; a PDF mixing several MRs is never signed."""
if table_name not in APPROVAL_TABLES:
return None, None, None
row = await approvals.get_approval(db, table_name, owner_id) if owner_id else None
if row is None or row.status != "approved":
return "pending", None, None
when = row.updated_at.astimezone(ZoneInfo(settings.APP_TIMEZONE)).strftime("%d/%m/%Y %H:%M") if row.updated_at else None
return "approved", row.approved_by_name, when
def _approval_out(row, owner: User, headquarters_name: str | None = None) -> dict[str, object]:
return {
"table_name": row.table_name,
"owner_user_id": str(owner.id),
"owner_name": owner.full_name,
"headquarters_name": headquarters_name,
"status": row.status,
"approved_by_name": row.approved_by_name,
"updated_at": row.updated_at.isoformat() if row.updated_at else None,
}
async def _hq_name(db: AsyncSession, user: User) -> str | None:
headquarters = await db.get(Headquarters, user.headquarters_id) if user.headquarters_id else None
return headquarters.name if headquarters else None
def _approval_table(table_name: str) -> str:
if table_name not in APPROVAL_TABLES:
raise NotFoundError("This form has no approval step", {"table": table_name})
return table_name
@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)),
) -> list[dict[str, object]]:
"""Approval state of the forms that carry an Area 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)),
) -> 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()}
return [
{"id": str(o.id), "name": o.full_name, "employee_code": o.employee_code, "headquarters_name": hq.get(o.headquarters_id)}
for o in await approvals.owners_in_scope(db, current_user)
]
@router.post("/{table_name}/approval/request")
async def request_form_approval(
table_name: str,
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."""
row = await approvals.request_approval(db, _approval_table(table_name), current_user)
return _approval_out(row, current_user, await _hq_name(db, current_user))
@router.post("/{table_name}/approval/approve")
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)),
) -> dict[str, object]:
"""The Area 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))
@router.get("/{table_name}/rows")
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)),
) -> list[dict[str, object]]:
_ensure_table_access(table_name, current_user)
return await _load_rows(table_name, db, current_user, owner_id)
@router.post("/{table_name}/rows", status_code=status.HTTP_201_CREATED)
async def create_csv_row(
table_name: str,
payload: dict[str, object] = Body(...),
owner_id: uuid.UUID | None = None,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role(Role.MR, Role.ADMIN)),
) -> dict[str, object]:
columns = _table(table_name)
values = _clean_payload(table_name, payload)
owner: User | None = None
if table_name in OWNED_TABLES:
if current_user.role == Role.MR:
owner = current_user
elif owner_id is None:
raise ValidationError("Choose which medical representative this row is for")
else:
owner = await approvals.assert_owner_in_scope(db, current_user, owner_id)
values = await _apply_mr_identity(values, owner or current_user, db)
if table_name == "sales_projection":
values = await _apply_sales_projection_product(values, db, current_user)
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)
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:
values[column] = str(next_row)
extra_ids, extra_params = (["owner_user_id"], [":owner_user_id"]) if owner else ([], [])
identifiers = ", ".join(["id", "source_row_number", *extra_ids, *[f'"{column}"' for column in columns]])
parameters = ", ".join([":id", ":source_row_number", *extra_params, *[f":{column}" for column in columns]])
values.update(id=uuid.uuid4(), source_row_number=next_row)
if owner:
values["owner_user_id"] = owner.id
result = await db.execute(text(f'INSERT INTO "{table_name}" ({identifiers}) VALUES ({parameters}) RETURNING id'), values)
row_id = result.scalar_one()
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)
@router.patch("/{table_name}/rows/{row_id}")
async def update_csv_row(table_name: str, row_id: uuid.UUID, payload: dict[str, object] = Body(...), db: AsyncSession = Depends(get_db), current_user: User = Depends(require_role(Role.MR, Role.ADMIN))) -> dict[str, object]:
values = _clean_payload(table_name, payload)
row_owner = await _row_owner(table_name, row_id, current_user, db)
values = await _apply_mr_identity(values, current_user, db)
if table_name == "sales_projection":
values = await _apply_sales_projection_product(values, db, current_user)
changes = {column: value for column, value in values.items() if column in payload}
if not changes:
raise ValidationError("At least one CSV column is required")
if not _has_user_data(table_name, {**values, **changes}):
raise ValidationError("A row must contain at least one value")
changes = {column: value for column, value in changes.items() if column not in SERIAL_COLUMNS}
if not changes:
raise ValidationError("Serial numbers are generated automatically")
assignments = ", ".join(f'"{column}" = :{column}' for column in changes)
result = await db.execute(text(f'UPDATE "{table_name}" SET {assignments} WHERE id = :id RETURNING id'), {**changes, "id": row_id})
if result.scalar_one_or_none() is None:
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)
@router.delete("/{table_name}/rows/{row_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_csv_row(table_name: str, row_id: uuid.UUID, db: AsyncSession = Depends(get_db), current_user: User = Depends(require_role(Role.MR, Role.ADMIN))) -> None:
_table(table_name)
row_owner = await _row_owner(table_name, row_id, current_user, db)
result = await db.execute(text(f'DELETE FROM "{table_name}" WHERE id = :id'), {"id": row_id})
if result.rowcount == 0:
raise NotFoundError("CSV row not found", {"id": str(row_id)})
await _renumber_rows(table_name, db)
await approvals.invalidate(db, table_name, row_owner)
await db.commit()
async def _get_row(table_name: str, row_id: uuid.UUID, db: AsyncSession) -> dict[str, object]:
columns = _table(table_name)
result = await db.execute(text(f'{_select(table_name, columns)} WHERE id = :id'), {"id": row_id})
row = result.mappings().one_or_none()
if row is None:
raise NotFoundError("CSV row not found", {"id": str(row_id)})
return dict(row)
def _pdf_bytes(
table_name: str,
table_label: str,
row: dict[str, object],
approval_status: str | None = None,
am_name: str | None = None,
approved_at: str | None = None,
) -> bytes:
from app.pdf.service import csv_table_pdf_bytes
return csv_table_pdf_bytes(
table_name,
table_label,
_table(table_name),
[row],
approval_status,
am_name,
approved_at=approved_at,
)
@router.get("/{table_name}/rows/{row_id}/pdf")
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)),
) -> 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]
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),
media_type="application/pdf",
headers={"Content-Disposition": f'attachment; filename="{table_name}-{row_id}.pdf"'},
)
@router.get("/{table_name}/pdf")
async def download_csv_table_pdfs(
table_name: str,
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)),
) -> Response:
"""The whole form, or only one month of it (for the forms that have a month)."""
_ensure_table_access(table_name, current_user)
columns = _table(table_name)
rows = await _load_rows(table_name, db, current_user, owner_id, month)
if month and month.strip() and not rows:
raise NotFoundError(f"There are no rows for {month.strip()} in this form", {"month": month})
# The signature is that of the single MR whose rows these are; a PDF of several MRs is unsigned.
subject = current_user.id if current_user.role == Role.MR else owner_id
approval_status, am_name, approved_at = await _signature(table_name, subject, db)
from app.pdf.service import csv_table_pdf_bytes
suffix = re.sub(r"[^a-z]", "", month.lower()) if month else ""
filename = f"{table_name}-{suffix}.pdf" if suffix else f"{table_name}.pdf"
pdf = csv_table_pdf_bytes(
table_name,
CSV_LABELS[table_name],
columns,
rows,
approval_status,
am_name,
approved_at=approved_at,
)
return Response(
pdf,
media_type="application/pdf",
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
)
View File
+36
View File
@@ -0,0 +1,36 @@
"""Single import point for every ORM model.
Alembic autogenerate and SQLAlchemy's string-based relationship resolution both need
every mapper registered before use. Import this module, never individual model
modules, when you need "all of them".
"""
from app.audit.models import AuditLog
from app.auth.models import RefreshToken
from app.chemists.models import Chemist, ChemistAssignment
from app.csv_data.models import FormApproval
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
from app.users.models import User
__all__ = [
"Base",
"AuditLog",
"RefreshToken",
"Chemist",
"FormApproval",
"ChemistAssignment",
"Doctor",
"DoctorAssignment",
"AMHeadquarters",
"Company",
"Headquarters",
"ChemistCall",
"DailyCallReport",
"DoctorCall",
"User",
"Product",
]
+30
View File
@@ -0,0 +1,30 @@
"""Declarative base and shared column mixins."""
import uuid
from datetime import datetime
from sqlalchemy import DateTime, func
from sqlalchemy.dialects.postgresql import UUID as PGUUID
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
class UUIDMixin:
id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), primary_key=True, default=uuid.uuid4
)
class TimestampMixin:
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), nullable=False
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
server_default=func.now(),
onupdate=func.now(),
nullable=False,
)
+34
View File
@@ -0,0 +1,34 @@
"""Engine, session factory and the `get_db` request dependency.
One transaction per request: the dependency opens a session, the service layer
commits on success, and any escaping exception rolls the whole request back — so a
state change and its audit row can never be persisted separately.
"""
from collections.abc import AsyncGenerator
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from app.config.settings import settings
engine = create_async_engine(
settings.DATABASE_URL,
echo=settings.DB_ECHO,
pool_pre_ping=True,
)
AsyncSessionLocal = async_sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False,
autoflush=False,
)
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with AsyncSessionLocal() as session:
try:
yield session
except Exception:
await session.rollback()
raise
View File
+65
View File
@@ -0,0 +1,65 @@
"""Doctor master data and doctor → MR assignment.
Master data belongs to a HEADQUARTERS, not to an MR (A2). Assignment is a separate,
dated table so that when an MR leaves, the doctor list survives.
`core_doctor_conversion` was not created as a table (report §13.2): it would store
one enum per call, which is a column — `doctor.is_core_doctor` +
`doctor_call.conversion_status`.
"""
import uuid
from datetime import date
from sqlalchemy import Boolean, Date, ForeignKey, Index, String, UniqueConstraint, text
from sqlalchemy.dialects.postgresql import UUID as PGUUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.database.base import Base, TimestampMixin, UUIDMixin
class Doctor(Base, UUIDMixin, TimestampMixin):
__tablename__ = "doctor"
__table_args__ = (
# Deduplication guard: two MRs must not create two records for one doctor.
UniqueConstraint(
"headquarters_id", "name", "clinic_address", name="uq_doctor_hq_name_clinic"
),
)
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)
speciality: Mapped[str | None] = mapped_column(String(100))
qualification: Mapped[str | None] = mapped_column(String(100))
clinic_address: Mapped[str] = mapped_column(String(500), nullable=False)
contact_number: Mapped[str | None] = mapped_column(String(20))
#: 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)
assignments: Mapped[list["DoctorAssignment"]] = relationship(back_populates="doctor")
class DoctorAssignment(Base, UUIDMixin, TimestampMixin):
__tablename__ = "doctor_assignment"
__table_args__ = (
Index(
"uq_active_doctor_assignment",
"doctor_id",
unique=True,
postgresql_where=text("effective_to IS NULL"),
),
)
doctor_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("doctor.id", ondelete="CASCADE"), nullable=False
)
mr_user_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="RESTRICT"), nullable=False
)
effective_from: Mapped[date] = mapped_column(Date, nullable=False)
effective_to: Mapped[date | None] = mapped_column(Date)
doctor: Mapped["Doctor"] = relationship(back_populates="assignments")
+64
View File
@@ -0,0 +1,64 @@
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.models import Doctor
from app.doctors.schemas import AssignToMR, DoctorCreate, DoctorRead, DoctorUpdate
from app.doctors.service import DoctorService
from app.users.models import User
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]:
"""S5 — an MR gets only their assigned doctors; managers get their HQ scope."""
return await DoctorService(db).list_for(current_user)
@router.post("", response_model=DoctorRead, status_code=status.HTTP_201_CREATED)
async def create_doctor(
payload: DoctorCreate,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> Doctor:
"""Only an Administrator can create a doctor (MR, AM and GM cannot)."""
return await DoctorService(db).create(payload, current_user, client_ip(request))
@router.patch("/{doctor_id}", response_model=DoctorRead)
async def update_doctor(
doctor_id: uuid.UUID,
payload: DoctorUpdate,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> Doctor:
return await DoctorService(db).update(doctor_id, payload, 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)),
db: AsyncSession = Depends(get_db),
):
"""An AM 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)
)
return {
"id": assignment.id,
"doctor_id": assignment.doctor_id,
"mr_user_id": assignment.mr_user_id,
"effective_from": assignment.effective_from,
}
+43
View File
@@ -0,0 +1,43 @@
import uuid
from datetime import date
from pydantic import BaseModel, ConfigDict, Field
class DoctorCreate(BaseModel):
headquarters_id: uuid.UUID
name: str = Field(min_length=2, max_length=200)
clinic_address: str = Field(min_length=2, max_length=500)
speciality: str | None = Field(default=None, max_length=100)
qualification: str | None = Field(default=None, max_length=100)
contact_number: str | None = Field(default=None, max_length=20)
is_core_doctor: bool = False
class DoctorUpdate(BaseModel):
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)
qualification: str | None = Field(default=None, max_length=100)
contact_number: str | None = Field(default=None, max_length=20)
is_core_doctor: bool | None = None
is_active: bool | None = None
class DoctorRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
headquarters_id: uuid.UUID
name: str
clinic_address: str
speciality: str | None
qualification: str | None
contact_number: str | None
is_core_doctor: bool
is_active: bool
class AssignToMR(BaseModel):
mr_user_id: uuid.UUID
effective_from: date | None = None
+152
View File
@@ -0,0 +1,152 @@
import uuid
from datetime import date
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.audit.service import AuditService
from app.auth.dependencies import assert_can_view_hq, visible_hq_ids
from app.common.enums import AuditAction, EntityType, Role
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
from app.common.utils import snapshot
from app.doctors.models import Doctor, DoctorAssignment
from app.doctors.schemas import DoctorCreate, DoctorUpdate
from app.users.models import User
_AUDIT_FIELDS = ["name", "clinic_address", "speciality", "is_core_doctor", "is_active"]
class DoctorService:
def __init__(self, db: AsyncSession) -> None:
self.db = db
self.audit = AuditService(db)
async def create(self, data: DoctorCreate, actor: User, ip: str | None = None) -> Doctor:
# A2/A3 — masters are owned by ADMIN/GM. An MR cannot create a doctor.
await assert_can_view_hq(self.db, actor, data.headquarters_id)
doctor = Doctor(**data.model_dump())
self.db.add(doctor)
try:
await self.db.flush()
except IntegrityError as exc:
await self.db.rollback()
raise ConflictError(
"A doctor with this name already exists at this clinic in this headquarters",
{"cause": "uq_doctor_hq_name_clinic"},
) from exc
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.DOCTOR,
entity_id=doctor.id,
action=AuditAction.CREATE,
after=snapshot(doctor, _AUDIT_FIELDS),
ip_address=ip,
)
await self.db.commit()
return doctor
async def update(
self, doctor_id: uuid.UUID, data: DoctorUpdate, actor: User, ip: str | None = None
) -> Doctor:
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)
before = snapshot(doctor, _AUDIT_FIELDS)
for field, value in data.model_dump(exclude_unset=True).items():
setattr(doctor, field, value)
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.DOCTOR,
entity_id=doctor.id,
action=AuditAction.UPDATE,
before=before,
after=snapshot(doctor, _AUDIT_FIELDS),
ip_address=ip,
)
await self.db.commit()
return doctor
async def list_for(self, actor: User) -> list[Doctor]:
"""An MR sees ONLY doctors currently assigned to them (R5)."""
if actor.role == Role.MR:
stmt = (
select(Doctor)
.join(DoctorAssignment, DoctorAssignment.doctor_id == Doctor.id)
.where(
DoctorAssignment.mr_user_id == actor.id,
DoctorAssignment.effective_to.is_(None),
Doctor.is_active.is_(True),
)
.order_by(Doctor.name)
)
return list((await self.db.execute(stmt)).scalars().all())
allowed = await visible_hq_ids(self.db, actor)
stmt = select(Doctor).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 assign_to_mr(
self,
doctor_id: uuid.UUID,
mr_user_id: uuid.UUID,
effective_from: date | None,
actor: User,
ip: str | None = None,
) -> DoctorAssignment:
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)
mr = await self.db.get(User, mr_user_id)
if mr is None:
raise NotFoundError("MR not found")
if mr.role != Role.MR:
raise ValidationError("Doctors can only be assigned to an MR")
# An MR may only be given doctors from their own headquarters.
if mr.headquarters_id != doctor.headquarters_id:
raise ValidationError(
"MR and doctor belong to different headquarters",
{
"mr_headquarters_id": str(mr.headquarters_id),
"doctor_headquarters_id": str(doctor.headquarters_id),
},
)
start = effective_from or date.today()
existing = (
await self.db.execute(
select(DoctorAssignment).where(
DoctorAssignment.doctor_id == doctor_id,
DoctorAssignment.effective_to.is_(None),
)
)
).scalars().all()
for row in existing:
if row.mr_user_id == mr_user_id:
return row
row.effective_to = start
await self.db.flush()
assignment = DoctorAssignment(
doctor_id=doctor_id, mr_user_id=mr_user_id, effective_from=start
)
self.db.add(assignment)
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.DOCTOR,
entity_id=doctor_id,
action=AuditAction.ASSIGN,
after={"mr_user_id": str(mr_user_id), "effective_from": start.isoformat()},
ip_address=ip,
)
await self.db.commit()
return assignment
+113
View File
@@ -0,0 +1,113 @@
"""Application factory: router mount, middleware, exception handlers."""
import logging
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from app.api.v1.router import api_router
from app.common.exceptions import AppError
from app.config.settings import settings
from app.database import all_models # noqa: F401 - registers every mapper
from app.pdf.service import pdf_engine_ready
logging.basicConfig(
level=logging.DEBUG if settings.DEBUG else logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
logger = logging.getLogger(__name__)
def _preflight() -> None:
"""Refuse to start a production instance that would silently misbehave."""
production = settings.ENVIRONMENT.lower() == "production"
if not pdf_engine_ready():
if production:
raise RuntimeError("WeasyPrint system libraries are required in production")
logger.warning("WeasyPrint is unavailable: PDFs will be plain text, not the form layout.")
weak_key = settings.SECRET_KEY.startswith("change-me") or len(settings.SECRET_KEY) < 32
if production and weak_key:
raise RuntimeError("SECRET_KEY must be a random value of at least 32 characters")
@asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
_preflight()
yield
def create_app() -> FastAPI:
app = FastAPI(
lifespan=lifespan,
title=settings.APP_NAME,
version="0.1.0",
description=(
"Pharmaceutical field-force reporting — MVP. "
"Daily Call Reports with AM final approval, GM monitoring, "
"locked PDFs and audit trails."
),
docs_url="/docs",
redoc_url="/redoc",
openapi_url="/openapi.json",
)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ---- one consistent error envelope -------------------------------
@app.exception_handler(AppError)
async def app_error_handler(_: Request, exc: AppError) -> JSONResponse:
return JSONResponse(status_code=exc.status_code, content=exc.to_dict())
@app.exception_handler(RequestValidationError)
async def validation_handler(_: Request, exc: RequestValidationError) -> JSONResponse:
# Pydantic puts the original exception object in `ctx`, which is not JSON
# serialisable — strip it, or the error handler itself becomes a 500.
errors = [
{k: v for k, v in error.items() if k != "ctx"}
| (
{"reason": str(error["ctx"].get("error"))}
if isinstance(error.get("ctx"), dict) and "error" in error["ctx"]
else {}
)
for error in exc.errors()
]
return JSONResponse(
status_code=422,
content=jsonable_encoder(
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Request payload failed validation",
"details": {"errors": errors},
}
}
),
)
app.include_router(api_router, prefix=settings.API_V1_PREFIX)
@app.get("/health", tags=["meta"])
async def health() -> dict[str, str]:
return {
"status": "ok",
"environment": settings.ENVIRONMENT,
"pdf_engine": "weasyprint" if pdf_engine_ready() else "fallback",
}
return app
app = create_app()
View File
+85
View File
@@ -0,0 +1,85 @@
"""Company, Headquarters and the Area-Manager ↔ Headquarters mapping.
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 HQ handover therefore re-points every MR in that HQ with no data migration.
"""
import uuid
from datetime import date
from sqlalchemy import Date, ForeignKey, Index, String, UniqueConstraint, text
from sqlalchemy.dialects.postgresql import UUID as PGUUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.database.base import Base, TimestampMixin, UUIDMixin
class Company(Base, UUIDMixin, TimestampMixin):
"""Tenant root. Single company in the MVP (A17), but `company_id` is carried on
every table so multi-tenancy needs no migration later."""
__tablename__ = "company"
name: Mapped[str] = mapped_column(String(200), nullable=False)
address: Mapped[str | None] = mapped_column(String(500))
is_active: Mapped[bool] = mapped_column(default=True, nullable=False)
headquarters: Mapped[list["Headquarters"]] = relationship(back_populates="company")
class Headquarters(Base, UUIDMixin, TimestampMixin):
"""A territory/location. NOT a login role (R8)."""
__tablename__ = "headquarters"
__table_args__ = (
UniqueConstraint("company_id", "code", name="uq_hq_company_code"),
)
company_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("company.id", ondelete="RESTRICT"), nullable=False
)
code: Mapped[str] = mapped_column(String(20), nullable=False)
name: Mapped[str] = mapped_column(String(200), nullable=False)
district: Mapped[str | None] = mapped_column(String(100))
state: Mapped[str | None] = mapped_column(String(100))
is_active: Mapped[bool] = mapped_column(default=True, nullable=False)
company: Mapped["Company"] = relationship(back_populates="headquarters")
am_mappings: Mapped[list["AMHeadquarters"]] = relationship(
back_populates="headquarters"
)
class AMHeadquarters(Base, UUIDMixin, TimestampMixin):
"""Which Area Manager currently manages which headquarters.
`effective_to IS NULL` means "current". A partial unique index guarantees at most
one active Area Manager per headquarters at any time.
"""
__tablename__ = "am_headquarters"
__table_args__ = (
Index(
"uq_active_am_per_hq",
"headquarters_id",
unique=True,
postgresql_where=text("effective_to IS NULL"),
),
)
area_manager_user_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="RESTRICT"), nullable=False
)
headquarters_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True),
ForeignKey("headquarters.id", ondelete="RESTRICT"),
nullable=False,
)
effective_from: Mapped[date] = mapped_column(Date, nullable=False)
effective_to: Mapped[date | None] = mapped_column(Date)
headquarters: Mapped["Headquarters"] = relationship(back_populates="am_mappings")
area_manager: Mapped["User"] = relationship() # noqa: F821
+88
View File
@@ -0,0 +1,88 @@
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.organization.models import Headquarters
from app.organization.schemas import (
AMHeadquartersRead,
AssignAreaManager,
HeadquartersCreate,
HeadquartersRead,
SetAreaManagerHeadquarters,
)
from app.organization.service import OrganizationService
from app.users.models import User
router = APIRouter(prefix="/headquarters", tags=["organization"])
@router.get("", response_model=list[HeadquartersRead])
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."""
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)),
db: AsyncSession = Depends(get_db),
):
"""Which Area Manager currently manages which headquarters (one row per pair)."""
return await OrganizationService(db).list_area_manager_mappings(current_user)
@router.put("/area-managers/{area_manager_user_id}", response_model=list[AMHeadquartersRead])
async def set_area_manager_headquarters(
area_manager_user_id: uuid.UUID,
payload: SetAreaManagerHeadquarters,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN)),
db: AsyncSession = Depends(get_db),
):
"""Replace the set of headquarters an Area Manager manages (any number)."""
return await OrganizationService(db).set_area_manager_headquarters(
area_manager_user_id,
payload.headquarters_ids,
payload.effective_from,
current_user,
client_ip(request),
)
@router.post("", response_model=HeadquartersRead, status_code=status.HTTP_201_CREATED)
async def create_headquarters(
payload: HeadquartersCreate,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> Headquarters:
return await OrganizationService(db).create_headquarters(
payload, current_user, client_ip(request)
)
@router.post(
"/{headquarters_id}/area-manager",
response_model=AMHeadquartersRead,
status_code=status.HTTP_201_CREATED,
)
async def assign_area_manager(
headquarters_id: uuid.UUID,
payload: AssignAreaManager,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN)),
db: AsyncSession = Depends(get_db),
):
return await OrganizationService(db).assign_area_manager(
headquarters_id,
payload.area_manager_user_id,
payload.effective_from,
current_user,
client_ip(request),
)
+59
View File
@@ -0,0 +1,59 @@
import uuid
from datetime import date
from pydantic import BaseModel, ConfigDict, Field
class CompanyCreate(BaseModel):
name: str = Field(min_length=2, max_length=200)
address: str | None = Field(default=None, max_length=500)
class CompanyRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
name: str
address: str | None
is_active: bool
class HeadquartersCreate(BaseModel):
code: str = Field(min_length=1, max_length=20)
name: str = Field(min_length=2, max_length=200)
district: str | None = Field(default=None, max_length=100)
state: str | None = Field(default=None, max_length=100)
class HeadquartersRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
company_id: uuid.UUID
code: str
name: str
district: str | None
state: str | None
is_active: bool
class AssignAreaManager(BaseModel):
area_manager_user_id: uuid.UUID
effective_from: date | None = None
class SetAreaManagerHeadquarters(BaseModel):
"""The complete list of headquarters an Area Manager should manage (may be empty)."""
headquarters_ids: list[uuid.UUID] = Field(default_factory=list, max_length=500)
effective_from: date | None = None
class AMHeadquartersRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
area_manager_user_id: uuid.UUID
headquarters_id: uuid.UUID
effective_from: date
effective_to: date | None
+228
View File
@@ -0,0 +1,228 @@
import uuid
from datetime import date
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.audit.service import AuditService
from app.auth.dependencies import visible_hq_ids
from app.common.enums import AuditAction, EntityType, Role
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
from app.organization.models import AMHeadquarters, Company, Headquarters
from app.organization.schemas import HeadquartersCreate
from app.users.models import User
class OrganizationService:
def __init__(self, db: AsyncSession) -> None:
self.db = db
self.audit = AuditService(db)
async def create_headquarters(
self, data: HeadquartersCreate, actor: User, ip: str | None = None
) -> Headquarters:
if await self.db.get(Company, actor.company_id) is None:
raise NotFoundError("Company not found")
hq = Headquarters(
company_id=actor.company_id,
code=data.code.upper(),
name=data.name,
district=data.district,
state=data.state,
)
self.db.add(hq)
try:
await self.db.flush()
except IntegrityError as exc:
await self.db.rollback()
raise ConflictError(
"A headquarters with this code already exists", {"code": data.code}
) from exc
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.HEADQUARTERS,
entity_id=hq.id,
action=AuditAction.CREATE,
after={"code": hq.code, "name": hq.name},
ip_address=ip,
)
await self.db.commit()
return hq
async def list_headquarters(self, actor: User) -> list[Headquarters]:
allowed = await visible_hq_ids(self.db, actor)
stmt = select(Headquarters).where(Headquarters.company_id == actor.company_id)
if allowed is not None:
stmt = stmt.where(Headquarters.id.in_(allowed or [None]))
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."""
stmt = (
select(AMHeadquarters)
.join(Headquarters, Headquarters.id == AMHeadquarters.headquarters_id)
.where(
Headquarters.company_id == actor.company_id,
AMHeadquarters.effective_to.is_(None),
)
)
return list((await self.db.execute(stmt)).scalars().all())
async def set_area_manager_headquarters(
self,
am_user_id: uuid.UUID,
headquarters_ids: list[uuid.UUID],
effective_from: date | None,
actor: User,
ip: str | None = None,
) -> list[AMHeadquarters]:
"""Make `headquarters_ids` exactly the set of headquarters this AM manages.
Headquarters missing from the list are released, new ones are added. If a new
headquarters already has another AM, that mapping is closed first (one active AM
per headquarters stays true). An AM may manage any number of headquarters.
"""
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:
raise ValidationError(
"Only a user with the AM role can manage a headquarters",
{"user_role": manager.role.value},
)
wanted = set(headquarters_ids)
if wanted:
found = set(
(
await self.db.execute(
select(Headquarters.id).where(
Headquarters.id.in_(wanted),
Headquarters.company_id == actor.company_id,
)
)
).scalars()
)
if found != wanted:
raise NotFoundError("Headquarters not found")
start = effective_from or date.today()
mine = {
row.headquarters_id: row
for row in (
await self.db.execute(
select(AMHeadquarters).where(
AMHeadquarters.area_manager_user_id == am_user_id,
AMHeadquarters.effective_to.is_(None),
)
)
).scalars()
}
released = set(mine) - wanted
added = wanted - set(mine)
for hq_id in released:
mine[hq_id].effective_to = start
if added:
for row in (
await self.db.execute(
select(AMHeadquarters).where(
AMHeadquarters.headquarters_id.in_(added),
AMHeadquarters.effective_to.is_(None),
)
)
).scalars():
row.effective_to = start
await self.db.flush()
for hq_id in added:
self.db.add(
AMHeadquarters(
area_manager_user_id=am_user_id,
headquarters_id=hq_id,
effective_from=start,
)
)
if added or released:
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.USER,
entity_id=am_user_id,
action=AuditAction.ASSIGN,
before={"headquarters_ids": sorted(str(h) for h in mine)},
after={"headquarters_ids": sorted(str(h) for h in wanted)},
ip_address=ip,
)
await self.db.commit()
return await self.list_area_manager_mappings_for(am_user_id)
async def list_area_manager_mappings_for(self, am_user_id: uuid.UUID) -> list[AMHeadquarters]:
stmt = select(AMHeadquarters).where(
AMHeadquarters.area_manager_user_id == am_user_id,
AMHeadquarters.effective_to.is_(None),
)
return list((await self.db.execute(stmt)).scalars().all())
async def assign_area_manager(
self,
headquarters_id: uuid.UUID,
am_user_id: uuid.UUID,
effective_from: date | None,
actor: User,
ip: str | None = None,
) -> AMHeadquarters:
"""Assign an AM to an HQ, closing any existing active mapping first.
The partial unique index `uq_active_am_per_hq` is the real guarantee that only
one Area Manager is active per headquarters at a time.
"""
hq = await self.db.get(Headquarters, headquarters_id)
if hq is None:
raise NotFoundError("Headquarters not found")
manager = await self.db.get(User, am_user_id)
if manager is None:
raise NotFoundError("User not found")
if manager.role != Role.AM:
raise ValidationError(
"Only a user with the AM role can manage a headquarters",
{"user_role": manager.role.value},
)
start = effective_from or date.today()
existing = (
await self.db.execute(
select(AMHeadquarters).where(
AMHeadquarters.headquarters_id == headquarters_id,
AMHeadquarters.effective_to.is_(None),
)
)
).scalars().all()
for row in existing:
if row.area_manager_user_id == am_user_id:
return row
row.effective_to = start
await self.db.flush()
mapping = AMHeadquarters(
area_manager_user_id=am_user_id,
headquarters_id=headquarters_id,
effective_from=start,
)
self.db.add(mapping)
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.HEADQUARTERS,
entity_id=headquarters_id,
action=AuditAction.ASSIGN,
after={"area_manager_user_id": str(am_user_id), "effective_from": start.isoformat()},
ip_address=ip,
)
await self.db.commit()
return mapping
View File
+453
View File
@@ -0,0 +1,453 @@
"""View models for the company-form PDFs (tour plan, fare chart, sales & stock, ...).
Pure Python — no WeasyPrint, no database — so every form's layout data can be unit
tested anywhere. ``build_form_context`` turns the stored rows of one CSV table into
the context its template under ``templates/forms/`` renders.
Each form here is a copy of the company's printed form: the same title, the same
column headings in the same order, the same column proportions and the same number of
ruled lines. Stored rows fill those lines from the top; the rest stay blank for
handwriting, and rows beyond the printed length simply continue on the next page.
The templates own the look; this module owns *what* each form shows.
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
DATE_FIELDS = {"report_date", "date_of_visit"}
APPROVAL_FORMS = {"standard_tour_plan", "tour_plan", "fare_chart"}
SERIAL = "#" # pseudo-field: the running "Sl.No." column
_ALIGN = {"left": "l", "center": "c", "right": "r"}
Row = dict[str, object]
Meta = tuple[str, str] | None # (printed label, column) — None leaves the slot empty
@dataclass(frozen=True)
class Col:
header: str
field: str
width: float # percent of the table
align: str = "left"
@dataclass(frozen=True)
class FormSpec:
template: str
title: str
meta: tuple[tuple[Meta, Meta], ...]
columns: tuple[Col, ...] = ()
min_rows: int = 25
serial_field: str | None = None
serial_dot: bool = False # "1." (tour plan, fare chart) instead of "1"
table_width: float = 100 # percent of the printed width
full_letterhead: bool = True # address, web and phone lines under the company name
def _serial(header: str, width: float) -> Col:
return Col(header, SERIAL, width, "center")
_NAME_HQ = ((("NAME:", "name"), None), (("HEADQUARTER:", "headquarter"), None))
_NAME_HQ_DATE_MONTH = (
(("NAME:", "name"), ("Date:", "report_date")),
(("HEADQUARTER:", "headquarter"), ("Month:", "month")),
)
_NAME_HQ_MONTH = (
(("NAME :", "name"), None),
(("HEADQUARTER:", "headquarter"), ("MONTH:", "month")),
)
FORMS: dict[str, FormSpec] = {
"standard_tour_plan": FormSpec(
"standard_tour_plan",
"STANDARD TOUR PLAN",
_NAME_HQ,
(_serial("Sl.No.", 11.4), Col("PLACE", "place", 88.6, "center")),
serial_field="serial_no",
serial_dot=True,
table_width=83,
),
"tour_plan": FormSpec(
"tour_plan",
"TOUR PLAN",
_NAME_HQ,
(
_serial("Sl.No.", 9.4),
Col("Date", "report_date", 11.9, "center"),
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"),
),
serial_field="serial_no",
serial_dot=True,
),
"fare_chart": FormSpec(
"fare_chart",
"FARE CHART",
_NAME_HQ,
(
_serial("Sl.No.", 9.4),
Col("Date", "report_date", 15.3, "center"),
Col("From", "from_location", 30.2),
Col("To", "to_location", 27.1),
Col("Kilometers (KM)", "kilometers_km", 17.6, "center"),
),
serial_field="serial_no",
serial_dot=True,
),
"area_covered": FormSpec(
"area_covered",
"AREA COVERED",
_NAME_HQ_MONTH,
(
Col("SALE STATUS", "sale_status", 34.0),
Col("AREA TO COVER", "area_to_cover", 24.3),
Col("SALE OBJECTIVE", "sale_objective", 20.8),
Col("STATUS", "status", 20.9, "center"),
),
min_rows=28,
full_letterhead=False,
),
"core_dr_call_conversion": FormSpec(
"core_dr_call_conversion",
"CORE Dr. CALL & CONVERSION",
_NAME_HQ_MONTH,
(
Col("DOCTOR NAME", "doctor_name", 38.3),
Col("DATE OF VISIT", "date_of_visit", 14.7, "center"),
Col("PRODUCT TARGETED", "product_targeted", 30.4),
Col("STATUS", "status", 16.6, "center"),
),
min_rows=28,
full_letterhead=False,
),
"field_activity_report": FormSpec(
"field_activity_report",
"FIELD ACTIVITY REPORT",
_NAME_HQ_MONTH,
(
Col("DATE", "report_date", 14.5, "center"),
Col("STATION WORKED", "station_worked", 36.6),
Col("NO. OF DOCTORS CALLED", "no_of_doctors_called", 19.8, "center"),
Col("NO. OF CHEMISTS/PDS CALLED", "no_of_chemists_pds_called", 29.1, "center"),
),
min_rows=25,
table_width=83,
full_letterhead=False,
),
"sales_and_stock_statement": FormSpec(
"sales_and_stock_statement",
"SALES AND STOCK STATEMENT",
_NAME_HQ_DATE_MONTH,
(
_serial("Sl.No.", 7.0),
Col("Name of the Product", "product_name", 22.6),
Col("Opening", "opening", 15.0, "center"),
Col("Receipt", "receipt", 14.7, "center"),
Col("Sale", "sale", 15.0, "center"),
Col("Closing", "closing", 12.2, "center"),
Col("Value in PTS", "value_in_pts", 13.5, "center"),
),
min_rows=26,
serial_field="serial_no",
),
"sales_projection": FormSpec(
"sales_projection",
"SALES PROJECTION",
_NAME_HQ_MONTH,
(
_serial("SL. No.", 7.1),
Col("NAME OF THE PRODUCT", "product_name", 22.7),
Col("PTS", "pts", 10.7, "center"),
Col("SEC. QTY", "secondary_qty", 9.1, "center"),
Col("VALUE", "value", 9.6, "center"),
Col("CLOSING", "closing", 11.6, "center"),
Col("SEC. VALUE", "secondary_value", 10.1, "center"),
Col("AUG. SALES", "aug_sales", 9.6, "center"),
Col("VALUE", "value_2", 9.5, "center"),
),
min_rows=26,
serial_field="serial_no",
full_letterhead=False,
),
"daily_call_report_csv": FormSpec(
"daily_call_report_csv",
"DAILY CALL REPORT",
_NAME_HQ_DATE_MONTH,
),
"weekly_report": FormSpec(
"weekly_report",
"Weekly Report",
(
(("EMPLOYEE NAME:", "employee_name"), ("DATE :", "report_date")),
(("HEADQUARTER :", "headquarter"), ("MONTH:", "month")),
),
full_letterhead=False,
),
}
# Daily Call Report: a doctor-call table and a chemist-visit table share one stored row.
_DOCTOR_COLS = (
_serial("SR. NO.", 8.6),
Col("DR. NAME", "doctor_name", 27.5),
Col("QUALIFICATION", "qualification", 14.9),
Col("PRODUCT PROMOTE", "product_promote", 14.6),
Col("PRODUCT SAMPLE", "product_sample", 18.2),
Col("REMARKS", "remarks", 16.2),
)
_DOCTOR_FIELDS = tuple(c.field for c in _DOCTOR_COLS if c.field != SERIAL)
_CHEMIST_COLS = (
_serial("SR. NO.", 10.2),
Col("NAME OF THE CHEMIST", "chemist_name", 32.8),
Col("POB", "pob", 57.0),
)
_CHEMIST_FIELDS = tuple(c.field for c in _CHEMIST_COLS if c.field != SERIAL)
_WEEKLY_SUMMARY = (
("No. of Days Worked", "no_of_days_worked"),
("No. of Doctor Called", "no_of_doctor_called"),
("No. of Chemist Called", "no_of_chemist_called"),
("POB Booked", "pob_booked"),
("Secondary Sales", "secondary_sales"),
("POB Objective", "pob_objective"),
("Secondary Objective", "secondary_objective"),
)
_WEEKLY_SCHEMES = (
("Product – Offer Scheme Booked", "product_offer_scheme_booked"),
("Product – Offer Scheme Objective", "product_offer_scheme_objective"),
)
# --------------------------------------------------------------------- helpers
def _text(value: object) -> str:
return "" if value is None else str(value).strip()
def _display(field: str, value: object) -> str:
"""Stored text as printed; ISO dates become dd/mm/yyyy, anything else is untouched."""
text = _text(value)
if field in DATE_FIELDS and text:
try:
return date.fromisoformat(text[:10]).strftime("%d/%m/%Y")
except ValueError:
return text
return text
def _distinct(rows: list[Row], field: str) -> str:
"""Every different stored value of a column, in order — never just the first row's."""
seen: list[str] = []
for row in rows:
value = _display(field, row.get(field))
if value and value not in seen:
seen.append(value)
return ", ".join(seen)
def _has(row: Row, fields: tuple[str, ...]) -> bool:
return any(_text(row.get(field)) for field in fields)
def _grid(
cols: tuple[Col, ...],
rows: list[Row],
*,
min_rows: int,
serial_field: str | None = None,
serial_dot: bool = False,
table_width: float = 100,
) -> dict[str, object]:
"""One printed table: header, stored rows, then blank ruled lines up to ``min_rows``."""
suffix = "." if serial_dot else ""
body = []
next_serial = 1
for index in range(max(min_rows, len(rows))):
row = rows[index] if index < len(rows) else None
cells: list[str] = []
for col in cols:
if col.field == SERIAL:
# A stored number wins (single-row PDFs keep their real serial); blank
# lines carry on counting from the last printed number.
number = _text(row.get(serial_field)) if row and serial_field else ""
number = number or str(next_serial)
next_serial = int(number) + 1 if number.isdigit() else next_serial + 1
cells.append(number + suffix)
else:
cells.append(_display(col.field, row.get(col.field)) if row else "")
body.append({"cells": cells, "blank": row is None})
return {
"headers": [c.header for c in cols],
"aligns": [_ALIGN[c.align] for c in cols],
"widths": [f"{c.width}%" for c in cols],
"rows": body,
"width": f"{table_width}%",
}
def _meta_rows(
meta: tuple[tuple[Meta, Meta], ...], rows: list[Row]
) -> list[list[tuple[str, str] | None]]:
return [
[(slot[0], _distinct(rows, slot[1])) if slot else None for slot in pair] for pair in meta
]
def approval_signature_line(
table_name: str, approval_status: str | None = None, am_name: str | None = None
) -> str:
if table_name not in APPROVAL_FORMS:
return ""
approved = (approval_status or "pending").lower() == "approved"
name = (am_name or "").strip()
return f"APPROVAL SIGNATURE: {name}" if approved and name else "APPROVAL SIGNATURE: PENDING"
# --------------------------------------------------------------------- builder
def build_form_context(
table_name: str,
label: str,
columns: tuple[str, ...],
rows: list[Row],
approval_status: str | None = None,
am_name: str | None = None,
approved_at: str | None = None,
) -> dict[str, object]:
"""Everything a form template needs, for all stored rows of ``table_name``."""
spec = FORMS.get(table_name)
grids: dict[str, dict[str, object]] = {}
extra: dict[str, object] = {}
if spec is None: # unknown table: print every stored column generically
identity = {"name", "employee_name", "headquarter", "month"}
spec = FormSpec(
"generic",
label.upper(),
tuple(
(
(f"{c.replace('_', ' ').upper()}:", c) if c in identity else None,
None,
)
for c in columns
if c in identity
),
)
cols = tuple(
Col(c.replace("_", " ").upper(), c, 100 / max(1, len(columns)))
for c in columns
if c not in {"id", "source_row_number"}
)
grids["main"] = _grid(cols, rows, min_rows=0)
elif spec.template == "daily_call_report_csv":
doctors = [r for r in rows if _has(r, _DOCTOR_FIELDS)]
chemists = [r for r in rows if _has(r, _CHEMIST_FIELDS)]
grids["doctors"] = _grid(_DOCTOR_COLS, doctors, min_rows=10, serial_field="doctor_sr_no")
grids["chemists"] = _grid(
_CHEMIST_COLS, chemists, min_rows=5, serial_field="chemist_sr_no", table_width=84
)
extra["stockist_visit"] = _distinct(rows, "stockist_visit")
extra["order_value"] = _distinct(rows, "order_value")
elif spec.template == "weekly_report":
extra["reports"] = [
{
"meta_rows": _meta_rows(spec.meta, [r]),
"summary": [(lbl, _text(r.get(f))) for lbl, f in _WEEKLY_SUMMARY],
"schemes": [(lbl, _text(r.get(f))) for lbl, f in _WEEKLY_SCHEMES],
}
for r in rows or [{}]
]
else:
grids["main"] = _grid(
spec.columns,
rows,
min_rows=spec.min_rows,
serial_field=spec.serial_field,
serial_dot=spec.serial_dot,
table_width=spec.table_width,
)
if table_name == "field_activity_report":
extra["doctor_call_avg"] = _distinct(rows, "doctor_call_avg")
extra["chemist_call_avg"] = _distinct(rows, "chemist_call_avg")
approval = None
if table_name in APPROVAL_FORMS:
line = approval_signature_line(table_name, approval_status, am_name)
value = line.split(": ", 1)[1]
approval = {
"line": line, "label": "APPROVAL SIGNATURE:", "value": value,
"when": approved_at if value != "PENDING" and approved_at else "",
# Once approved, the MR's own signature line carries their name too.
"mr_name": _distinct(rows, "name") if value != "PENDING" else "",
}
if spec.template == "weekly_report":
meta: list[list[tuple[str, str] | None]] = []
else:
meta = _meta_rows(spec.meta, rows)
return {
"template": spec.template,
"label": label,
"title": spec.title,
"full_letterhead": spec.full_letterhead,
"title_suffix": next((s[1] for pair in meta for s in pair if s and s[1]), ""),
"meta_rows": meta,
"grids": grids,
"approval": approval,
**extra,
}
# ------------------------------------------------------------- the filed Daily Call Report
_OUTCOME_NOTE = {"NOT_AVAILABLE": "Not available", "RESCHEDULED": "Rescheduled"}
def _doctor_remarks(call) -> str:
"""The remarks column; a visit that did not happen is flagged, since the form has no outcome column."""
note = _OUTCOME_NOTE.get(getattr(call.call_outcome, "value", str(call.call_outcome)), "")
return ". ".join(part for part in (note, (call.remarks or "").strip()) if part)
def build_dcr_context(dcr, doctor_calls, chemist_calls, approval: dict[str, str] | None = None) -> 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
approval signature with its date and time.
"""
doctors = [
{
"doctor_name": c.doctor.name,
"qualification": c.doctor.qualification or "",
"product_promote": c.product_promote or "",
"product_sample": c.product_sample or "",
"remarks": _doctor_remarks(c),
}
for c in doctor_calls
]
chemists = [{"chemist_name": c.chemist.name, "pob": c.pob or ""} for c in chemist_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"))],
]
return {
"template": "dcr",
"label": "Daily Call Report",
"title": "DAILY CALL REPORT",
"title_suffix": f"{dcr.mr.full_name} — {dcr.report_date.strftime('%d/%m/%Y')}",
"full_letterhead": True,
"meta_rows": meta,
"grids": {
"doctors": _grid(_DOCTOR_COLS, doctors, min_rows=10),
"chemists": _grid(_CHEMIST_COLS, chemists, min_rows=5, table_width=84),
},
"stockist_visit": dcr.stockist_visit or "",
"order_value": dcr.order_value or "",
"mr_signed": f"{dcr.mr.full_name} ({dcr.mr.employee_code})",
"approval": approval, # {"name": ..., "at": "dd/mm/yyyy HH:MM"} or None
}
+236
View File
@@ -0,0 +1,236 @@
"""Approved-report and company-form PDF generation.
WeasyPrint (BSD-3-Clause) renders Jinja2 HTML templates, so every layout is plain
HTML/CSS that anyone on the team can edit. The approved Daily Call Report and every
company form (tour plan, fare chart, sales & stock, ...) extend
``templates/forms/_form_base.html``, because each is a copy of the company's printed form;
each has its own template (``dcr.html`` or one under ``templates/forms/``). What a form
shows is decided in ``app.pdf.forms``.
WeasyPrint needs system libraries (Pango, HarfBuzz) and DejaVu fonts. They are pinned in
the Dockerfile. If they are genuinely absent (a bare dev machine, CI without the apt
step) the service falls back to a minimal built-in writer so the workflow still
completes and tests still run — and logs a loud warning, because that fallback
produces a plain-text PDF, not the designed layout. Production must have WeasyPrint;
``pdf_engine_ready()`` lets the health check and startup log say so.
"""
import logging
import uuid
from html.parser import HTMLParser
from pathlib import Path
from zoneinfo import ZoneInfo
from jinja2 import Environment, FileSystemLoader, select_autoescape
from sqlalchemy.ext.asyncio import AsyncSession
from app.audit.service import AuditService
from app.common.enums import AuditAction, EntityType
from app.config.settings import settings
from app.pdf.forms import approval_signature_line, build_dcr_context, build_form_context
from app.reports.models import DailyCallReport
from app.users.models import User
logger = logging.getLogger(__name__)
_TEMPLATE_DIR = Path(__file__).parent / "templates"
_env = Environment(
loader=FileSystemLoader(_TEMPLATE_DIR),
autoescape=select_autoescape(["html"]),
)
_env.globals.update(
company_name=settings.PDF_COMPANY_NAME,
company_address=settings.PDF_COMPANY_ADDRESS,
company_website=settings.PDF_COMPANY_WEBSITE,
company_email=settings.PDF_COMPANY_EMAIL,
company_phone=settings.PDF_COMPANY_PHONE,
)
try: # pragma: no cover - depends on system libraries
from weasyprint import HTML as _WeasyHTML
WEASYPRINT_AVAILABLE = True
except Exception: # noqa: BLE001 - ImportError or OSError from missing libs
_WeasyHTML = None
WEASYPRINT_AVAILABLE = False
def pdf_engine_ready() -> bool:
"""True when the designed (WeasyPrint) layout can be rendered."""
return WEASYPRINT_AVAILABLE
def _minimal_pdf(text: str) -> bytes:
"""Fallback renderer: a valid single-page PDF containing plain text.
Used ONLY when WeasyPrint's system libraries are unavailable. It exists so the
approval workflow and its tests never depend on native libraries being present.
"""
lines = [ln[:95] for ln in text.splitlines()][:52]
content = ["BT", "/F1 9 Tf", "40 780 Td", "11 TL"]
for line in lines:
escaped = line.replace("\\", r"\\").replace("(", r"\(").replace(")", r"\)")
content.append(f"({escaped}) Tj T*")
content.append("ET")
stream = "\n".join(content).encode("latin-1", "replace")
objects = [
b"<< /Type /Catalog /Pages 2 0 R >>",
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] "
b"/Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>",
b"<< /Length " + str(len(stream)).encode() + b" >>\nstream\n" + stream + b"\nendstream",
b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
]
out = bytearray(b"%PDF-1.4\n")
offsets = [0]
for i, body in enumerate(objects, start=1):
offsets.append(len(out))
out += f"{i} 0 obj\n".encode() + body + b"\nendobj\n"
xref_pos = len(out)
out += f"xref\n0 {len(objects) + 1}\n".encode()
out += b"0000000000 65535 f \n"
for off in offsets[1:]:
out += f"{off:010d} 00000 n \n".encode()
out += (
f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\n"
f"startxref\n{xref_pos}\n%%EOF\n"
).encode()
return bytes(out)
class _TextExtractor(HTMLParser):
"""Flattens a rendered form to lines of text for the plain-text fallback."""
_SKIP = {"style", "title", "script"}
_BREAK = {"tr", "div", "h1", "h2", "p", "br", "table"}
def __init__(self) -> None:
super().__init__()
self.parts: list[str] = []
self._skipping = 0
def handle_starttag(self, tag: str, attrs: list) -> None:
if tag in self._SKIP:
self._skipping += 1
def handle_endtag(self, tag: str) -> None:
if tag in self._SKIP:
self._skipping -= 1
elif tag in {"td", "th"}:
self.parts.append(" | ")
elif tag in self._BREAK:
self.parts.append("\n")
def handle_data(self, data: str) -> None:
if not self._skipping and data.strip():
self.parts.append(" ".join(data.split()) + " ")
def _html_to_text(html: str) -> str:
parser = _TextExtractor()
parser.feed(html)
lines = ("".join(parser.parts)).splitlines()
cleaned = (" ".join(line.split()).strip(" |") for line in lines)
return "\n".join(line for line in cleaned if line)
def _approval_signature_line(
table_name: str,
approval_status: str | None = None,
am_name: str | None = None,
am_role: str = "Area Manager",
) -> str:
return approval_signature_line(table_name, approval_status, am_name)
def csv_table_pdf_bytes(
table_name: str,
table_label: str,
columns: tuple[str, ...],
rows: list[dict[str, object]],
approval_status: str | None = None,
am_name: str | None = None,
am_role: str = "Area Manager",
approved_at: str | None = None,
) -> bytes:
"""Render every stored row of an imported table on its own company-form layout."""
context = build_form_context(
table_name, table_label, columns, rows, approval_status, am_name, approved_at
)
html = _env.get_template(f"forms/{context['template']}.html").render(**context)
if WEASYPRINT_AVAILABLE:
return _WeasyHTML(string=html).write_pdf()
logger.warning(
"WeasyPrint unavailable — using the plain-text fallback renderer for %s. "
"Install Pango/HarfBuzz (see Dockerfile) before production use.",
table_name,
)
return _minimal_pdf(_html_to_text(html))
def csv_pdf_bytes(table_label: str, row: dict[str, object]) -> bytes:
"""Render one imported table row for the row-level PDF action."""
columns = tuple(key for key in row if key not in {"id", "source_row_number"})
return csv_table_pdf_bytes("row", table_label, columns, [row])
class PDFService:
def __init__(self, db: AsyncSession) -> None:
self.db = db
self.audit = AuditService(db)
async def _approval(self, dcr: DailyCallReport) -> dict[str, str] | None:
"""Who approved the report and when, from the audit trail — the signature cannot be typed in."""
if dcr.approved_at is None:
return None
approvals = [h for h in await self.audit.approval_history_for(dcr.id) if h.action == AuditAction.APPROVE]
if not approvals:
return None
approver = await self.db.get(User, approvals[-1].actor_user_id)
if approver is None:
return None
when = dcr.approved_at.astimezone(ZoneInfo(settings.APP_TIMEZONE)).strftime("%d/%m/%Y %H:%M")
return {"name": approver.full_name, "at": when}
async def _context(self, dcr: DailyCallReport) -> dict:
return build_dcr_context(
dcr,
sorted(dcr.doctor_calls, key=lambda c: c.visit_time),
sorted(dcr.chemist_calls, key=lambda c: c.visit_time),
await self._approval(dcr),
)
async def render_bytes(self, dcr: DailyCallReport) -> bytes:
"""The report as a PDF in the current layout — a pure function of the stored report."""
context = await self._context(dcr)
html = _env.get_template("dcr.html").render(**context)
if WEASYPRINT_AVAILABLE:
return _WeasyHTML(string=html).write_pdf()
logger.warning(
"WeasyPrint unavailable — using the plain-text fallback renderer. "
"Install Pango/cairo (see Dockerfile) before production use."
)
return _minimal_pdf(_env.get_template("dcr.txt").render(**context))
async def render_and_store(self, dcr: DailyCallReport, approver: User) -> str:
pdf_bytes = await self.render_bytes(dcr)
directory = Path(settings.PDF_STORAGE_PATH) / str(dcr.report_date.year)
directory.mkdir(parents=True, exist_ok=True)
path = directory / f"DCR-{dcr.report_date.isoformat()}-{dcr.id}.pdf"
path.write_bytes(pdf_bytes)
await self.audit.log(
actor_user_id=approver.id,
entity_type=EntityType.DCR,
entity_id=dcr.id,
action=AuditAction.UPDATE,
after={"pdf_generated": str(path)},
)
return str(path)
+46
View File
@@ -0,0 +1,46 @@
{# The approved Daily Call Report — a copy of the company's printed form, filled in. #}
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid %}
{% block form_styles %}
h1.title { margin: 6mm 0 3mm; font-size: 13pt; text-decoration: none; letter-spacing: .3px; }
table.grid th { height: 7.5mm; font-size: 9pt; }
table.grid td { font-size: 10pt; }
h2.section { margin: 6mm 0 1.5mm; text-align: center; font-size: 11pt; }
.visit { margin: 6mm 0 0 14mm; font-size: 10.5pt; line-height: 1.7; }
.visit b { display: inline-block; min-width: 30mm; }
table.dcr-sign { width: 100%; margin-top: 12mm; border-collapse: collapse; page-break-inside: avoid; }
table.dcr-sign td { vertical-align: top; padding: 0; }
table.dcr-sign td.mr { width: 52%; padding-left: 14mm; }
.sign-label { font-size: 10.5pt; font-weight: bold; }
.signed { display: inline-block; min-width: 62mm; margin-top: 4mm; padding-bottom: 1mm; border-bottom: .7pt solid #000; font-family: "Liberation Serif", "Times New Roman", serif; font-style: italic; font-size: 12pt; }
.signed-when { margin-top: 1.2mm; font-size: 8.5pt; }
{% endblock %}
{% block form %}
{{ grid(grids.doctors, left=True) }}
<h2 class="section">CHEMIST VISIT</h2>
{{ grid(grids.chemists, left=True) }}
<div class="visit">
<div><b>STOCKIST VISIT :</b> {{ stockist_visit }}</div>
<div><b>ORDER :</b> {{ order_value }}</div>
</div>
{% endblock %}
{% block signature %}
<table class="dcr-sign">
<tr>
<td class="mr">
<div class="sign-label">MR Signature</div>
<div class="signed">{{ mr_signed }}</div>
</td>
<td class="am">
{% 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>
{% endif %}
</td>
</tr>
</table>
{% endblock %}
+19
View File
@@ -0,0 +1,19 @@
{{ company_name }}
{{ company_address }}
Website: {{ company_website }} E-Mail: {{ company_email }} PHONE: {{ company_phone }}
DAILY CALL REPORT
{% for pair in meta_rows %}{% for slot in pair %}{% if slot %}{{ slot[0] }} {{ slot[1] }} {% endif %}{% endfor %}
{% endfor %}
SR.NO | DR. NAME | QUALIFICATION | PRODUCT PROMOTE | PRODUCT SAMPLE | REMARKS
{% for r in grids.doctors.rows %}{{ r.cells | join(' | ') }}
{% endfor %}
CHEMIST VISIT
SR.NO | NAME OF THE CHEMIST | POB
{% for r in grids.chemists.rows %}{{ r.cells | join(' | ') }}
{% endfor %}
STOCKIST VISIT : {{ stockist_visit }}
ORDER : {{ order_value }}
MR Signature: {{ mr_signed }}
{% if approval %}APPROVAL SIGNATURE: {{ approval.name }} ({{ approval.at }})
{% endif %}
+108
View File
@@ -0,0 +1,108 @@
{# Base for every company form. Standalone on purpose: the forms copy the printed
originals and must not inherit the DCR report's look (base.html). #}
{% from "forms/_macros.html" import letterhead, meta_block, grid, sign_right, sign_approval %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{ label }}{% if title_suffix %} — {{ title_suffix }}{% endif %}</title>
<style>
@page {
size: A4;
margin: 12mm 16mm;
{% block page_box %}{% endblock %}
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: Carlito, Calibri, "Liberation Sans", "DejaVu Sans", sans-serif;
font-size: 11.5pt;
line-height: 1.2;
color: #000;
}
.company { text-align: center; }
.company .name {
font-family: "Liberation Sans", Arial, Helvetica, "DejaVu Sans", sans-serif;
font-size: 21pt;
font-weight: bold;
line-height: 1.15;
color: #000;
}
.company .line { font-size: 11pt; line-height: 1.35; }
h1.title {
margin: 7mm 0 4mm;
text-align: center;
font-size: 18pt;
line-height: 1.1;
text-decoration: underline;
}
table.meta { width: 100%; border-collapse: collapse; margin: 0 0 2.5mm; }
table.meta td { padding: .6mm 0; font-size: 12pt; vertical-align: top; }
table.meta td.ml { width: 62%; padding-left: 1.5mm; }
table.grid { border-collapse: collapse; table-layout: fixed; margin: 0 auto; }
table.grid.left { margin: 0; }
table.grid th, table.grid td { border: .7pt solid #000; padding: 0 1.6mm; }
table.grid th {
background: #fff;
height: 9mm;
font-size: 11.5pt;
line-height: 1.15;
text-align: center;
}
table.grid td {
height: 6.4mm;
font-size: 11.5pt;
line-height: 1.15;
vertical-align: middle;
overflow-wrap: anywhere;
}
table.grid tr { page-break-inside: avoid; }
th.l, td.l { text-align: left; }
th.c, td.c { text-align: center; }
th.r, td.r { text-align: right; }
/* A fill-in line: the printed underscore rule, holding the value when there is one. */
.ln {
display: inline-block;
min-width: 42mm;
height: 4.4mm;
border-bottom: .7pt solid #000;
text-align: center;
font-weight: normal;
vertical-align: bottom;
}
.sign-right {
margin: 16mm 0 0 68%;
font-size: 10.5pt;
font-weight: bold;
page-break-inside: avoid;
}
table.sign-approval { width: 100%; margin-top: 14mm; border-collapse: collapse; page-break-inside: avoid; }
table.sign-approval td { padding: 0; font-size: 8.5pt; font-weight: bold; }
table.sign-approval td:first-child { width: 56%; }
table.sign-approval .sign-when { margin: 1.5mm 0 0 0; font-size: 8pt; font-weight: normal; text-align: right; }
table.sign-approval .ln { font-size: 9pt; }
{% block form_styles %}{% endblock %}
</style>
</head>
<body>
{% block body %}
{{ letterhead(full_letterhead) }}
<h1 class="title">{{ title }}</h1>
{{ meta_block(meta_rows) }}
{% block form %}{% endblock %}
{% block signature %}{{ sign_right() }}{% endblock %}
{% endblock %}
</body>
</html>
+56
View File
@@ -0,0 +1,56 @@
{# Building blocks shared by the company-form PDFs. Each mirrors a part of the printed form. #}
{% macro letterhead(full) %}
<div class="company">
<div class="name">{{ company_name }}</div>
{% if full %}
<div class="line">{{ company_address }}</div>
<div class="line">Website: {{ company_website }} E-Mail:{{ company_email }}</div>
<div class="line">PHONE: {{ company_phone }}</div>
{% endif %}
</div>
{% endmacro %}
{# NAME / HEADQUARTER on the left, DATE / MONTH on the right — empty slots stay empty. #}
{% macro meta_block(rows) %}
{% if rows %}
<table class="meta">
{% for pair in rows %}
<tr>
{% for slot in pair %}
<td class="{{ 'ml' if loop.first else 'mr' }}">{% if slot %}<b>{{ slot[0] }}</b> {{ slot[1] }}{% endif %}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
{% endif %}
{% endmacro %}
{% macro grid(g, left=False) %}
<table class="grid{% if left %} left{% endif %}" style="width:{{ g.width }}">
<colgroup>{% for w in g.widths %}<col style="width:{{ w }}">{% endfor %}</colgroup>
<thead>
<tr>{% for h in g.headers %}<th>{{ h }}</th>{% endfor %}</tr>
</thead>
<tbody>
{% for r in g.rows %}
<tr>{% for c in r.cells %}<td class="{{ g.aligns[loop.index0] }}">{{ c }}</td>{% endfor %}</tr>
{% endfor %}
</tbody>
</table>
{% endmacro %}
{# "SIGNATURE" alone, low on the right — the sales / activity / call-report forms. #}
{% macro sign_right(text="SIGNATURE") %}
<div class="sign-right">{{ text }}</div>
{% endmacro %}
{# Tour plan, standard tour plan and fare chart: MR signature plus the AM approval. #}
{% macro sign_approval(approval) %}
<table class="sign-approval">
<tr>
<td>SIGNATURE: <span class="ln">{{ approval.mr_name }}</span></td>
<td>{{ approval.label }} <span class="ln">{{ approval.value }}</span>{% if approval.when %}<div class="sign-when">{{ approval.when }}</div>{% endif %}</td>
</tr>
</table>
{% endmacro %}
+11
View File
@@ -0,0 +1,11 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid %}
{% block form_styles %}
h1.title { margin: 0 0 5mm; font-size: 10pt; }
table.grid th { font-family: "Liberation Sans", Arial, "DejaVu Sans", sans-serif; font-size: 10pt; }
{% endblock %}
{% block form %}
{{ grid(grids.main) }}
{% endblock %}
@@ -0,0 +1,11 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid %}
{% block form_styles %}
h1.title { margin: 0 0 5mm; font-size: 10pt; }
table.grid th { font-family: "Liberation Sans", Arial, "DejaVu Sans", sans-serif; font-size: 10pt; }
{% endblock %}
{% block form %}
{{ grid(grids.main) }}
{% endblock %}
@@ -0,0 +1,24 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid %}
{% block form_styles %}
h1.title { margin: 6mm 0 3mm; font-size: 13pt; text-decoration: none; letter-spacing: .3px; }
table.grid th { height: 7.5mm; font-size: 9pt; }
table.grid td { font-size: 10pt; }
h2.section { margin: 6mm 0 1.5mm; text-align: center; font-size: 11pt; }
.visit { margin: 6mm 0 0 14mm; font-size: 10.5pt; line-height: 1.7; }
.visit b { display: inline-block; min-width: 30mm; }
.sign-left { margin: 12mm 0 0 14mm; font-size: 10.5pt; font-weight: bold; }
{% endblock %}
{% block form %}
{{ grid(grids.doctors, left=True) }}
<h2 class="section">CHEMIST VISIT</h2>
{{ grid(grids.chemists, left=True) }}
<div class="visit">
<div><b>STOCKIST VISIT :</b> {{ stockist_visit }}</div>
<div><b>ORDER :</b> {{ order_value }}</div>
</div>
{% endblock %}
{% block signature %}<div class="sign-left">MR Signature</div>{% endblock %}
+8
View File
@@ -0,0 +1,8 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid, sign_approval %}
{% block form %}
{{ grid(grids.main) }}
{% endblock %}
{% block signature %}{{ sign_approval(approval) }}{% endblock %}
@@ -0,0 +1,20 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid, sign_right %}
{% block form_styles %}
h1.title { margin: 0 0 5mm; font-size: 13pt; }
table.grid th { font-family: "Liberation Sans", Arial, "DejaVu Sans", sans-serif; font-size: 10pt; }
table.avg { width: 100%; margin-top: 7mm; border-collapse: collapse; }
table.avg td { padding: 0; font-family: "Liberation Sans", Arial, "DejaVu Sans", sans-serif; font-size: 9.5pt; font-weight: bold; white-space: nowrap; }
table.avg .ln { min-width: 44mm; }
{% endblock %}
{% block form %}
{{ grid(grids.main) }}
<table class="avg">
<tr>
<td>DOCTOR CALL AVG <span class="ln">{{ doctor_call_avg }}</span></td>
<td>CHEMIST CALL AVG. <span class="ln">{{ chemist_call_avg }}</span></td>
</tr>
</table>
{% endblock %}
+6
View File
@@ -0,0 +1,6 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid %}
{% block form %}
{{ grid(grids.main) }}
{% endblock %}
@@ -0,0 +1,11 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid %}
{% block form_styles %}
h1.title { font-size: 14pt; margin: 6mm 0 3mm; }
table.grid th { font-size: 11pt; }
{% endblock %}
{% block form %}
{{ grid(grids.main) }}
{% endblock %}
@@ -0,0 +1,20 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid %}
{# Arial throughout, title tucked directly under the company name — as printed. #}
{% block form_styles %}
.company .name { font-size: 20pt; }
h1.title {
margin: 0 0 4mm;
font-family: "Liberation Sans", Arial, "DejaVu Sans", sans-serif;
font-size: 14pt;
}
table.grid th, table.grid td { font-family: "Liberation Sans", Arial, "DejaVu Sans", sans-serif; }
table.grid th { height: 10mm; font-size: 9.5pt; }
table.grid td { font-size: 9.5pt; }
table.grid td:nth-child(2) { font-weight: bold; }
{% endblock %}
{% block form %}
{{ grid(grids.main) }}
{% endblock %}
@@ -0,0 +1,8 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid, sign_approval %}
{% block form %}
{{ grid(grids.main, left=True) }}
{% endblock %}
{% block signature %}{{ sign_approval(approval) }}{% endblock %}
+8
View File
@@ -0,0 +1,8 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid, sign_approval %}
{% block form %}
{{ grid(grids.main) }}
{% endblock %}
{% block signature %}{{ sign_approval(approval) }}{% endblock %}
@@ -0,0 +1,64 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import letterhead, sign_right %}
{# The weekly report is boxed: the whole page carries a border, as printed. #}
{% block page_box %}margin: 8mm; padding: 9mm 8mm 6mm; border: .8pt solid #000;{% endblock %}
{% macro items(rows, label_width) %}
<table class="items">
{% for label, value in rows %}
<tr>
<td class="bul">o</td>
<td class="lbl" style="width:{{ label_width }}">{{ label }}</td>
<td>: <span class="ln">{{ value }}</span></td>
</tr>
{% endfor %}
</table>
{% endmacro %}
{% block form_styles %}
.weekly + .weekly { page-break-before: always; }
.weekly h1.title { margin: 2mm 0 0; font-family: "Liberation Sans", Arial, "DejaVu Sans", sans-serif; font-size: 11pt; }
table.wmeta { width: 100%; margin: 9mm 0 7mm; border: .75pt solid #000; border-collapse: collapse; }
table.wmeta td { padding: 1.4mm 3mm; font-size: 10.5pt; }
table.wmeta td:first-child { width: 68%; }
.weekly h2 {
margin: 0 0 .6mm;
font-family: "Liberation Serif", "Times New Roman", "DejaVu Serif", serif;
font-size: 11.5pt;
}
.weekly h2.gap { margin-top: 2mm; }
table.items { width: 100%; margin: 0 0 4mm; border: .75pt solid #000; border-collapse: collapse; }
table.items td {
padding: .5mm 0;
font-family: "Liberation Serif", "Times New Roman", "DejaVu Serif", serif;
font-size: 11pt;
line-height: 1.25;
white-space: nowrap;
}
table.items tr:last-child td { padding-bottom: 2mm; }
table.items td.bul { width: 9mm; padding-left: 3mm; font-family: "Liberation Mono", "Courier New", monospace; }
table.items .ln { min-width: 60mm; text-align: left; height: 4.6mm; }
.weekly .sign-right { margin-top: 26mm; font-size: 10.5pt; }
{% endblock %}
{% block body %}
{% for report in reports %}
<div class="weekly">
{{ letterhead(false) }}
<h1 class="title" style="text-decoration: underline">{{ title }}</h1>
<table class="wmeta">
{% for pair in report.meta_rows %}
<tr>
{% for slot in pair %}<td><b>{{ slot[0] }}</b> {{ slot[1] }}</td>{% endfor %}
</tr>
{% endfor %}
</table>
<h2>1. Work Summary &amp; Sales Performance</h2>
{{ items(report.summary, "40mm") }}
<h2 class="gap">2. Additional Schemes &amp; Projects</h2>
{{ items(report.schemes, "64mm") }}
{{ sign_right("Signature") }}
</div>
{% endfor %}
{% endblock %}
+1
View File
@@ -0,0 +1 @@
"""Product master domain."""
+22
View File
@@ -0,0 +1,22 @@
"""Company-owned product master used by every report that references a product."""
import uuid
from sqlalchemy import Boolean, ForeignKey, String, UniqueConstraint
from sqlalchemy.dialects.postgresql import UUID as PGUUID
from sqlalchemy.orm import Mapped, mapped_column
from app.database.base import Base, TimestampMixin, UUIDMixin
class Product(Base, UUIDMixin, TimestampMixin):
__tablename__ = "product"
__table_args__ = (UniqueConstraint("company_id", "name", name="uq_product_company_name"),)
company_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("company.id", ondelete="RESTRICT"), nullable=False
)
name: Mapped[str] = mapped_column(String(200), nullable=False)
pack: Mapped[str | None] = mapped_column(String(100))
unit: Mapped[str | None] = mapped_column(String(50))
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
+92
View File
@@ -0,0 +1,92 @@
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.products.models import Product
from app.products.schemas import (
ProductCreate,
ProductRead,
ProductUpdate,
StockInventoryCreate,
StockInventoryRead,
StockInventoryUpdate,
)
from app.products.service import ProductService
from app.users.models import User
router = APIRouter(prefix="/products", tags=["products"])
@router.get("", response_model=list[ProductRead])
async def list_products(
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
) -> list[Product]:
return await ProductService(db).list_for(current_user)
@router.get("/stock-inventory", response_model=list[StockInventoryRead])
async def list_stock_inventory(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
) -> list[StockInventoryRead]:
return await ProductService(db).list_stock_inventory()
@router.post(
"/stock-inventory", response_model=StockInventoryRead, status_code=status.HTTP_201_CREATED
)
async def create_stock_item(
payload: StockInventoryCreate,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> StockInventoryRead:
return await ProductService(db).create_stock_item(payload, current_user, client_ip(request))
@router.patch("/stock-inventory/{item_id}", response_model=StockInventoryRead)
async def update_stock_item(
item_id: int,
payload: StockInventoryUpdate,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> StockInventoryRead:
return await ProductService(db).update_stock_item(
item_id, payload, current_user, client_ip(request)
)
@router.delete("/stock-inventory/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_stock_item(
item_id: int,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> None:
await ProductService(db).delete_stock_item(item_id, current_user, client_ip(request))
@router.post("", response_model=ProductRead, status_code=status.HTTP_201_CREATED)
async def create_product(
payload: ProductCreate,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> Product:
return await ProductService(db).create(payload, current_user, client_ip(request))
@router.patch("/{product_id}", response_model=ProductRead)
async def update_product(
product_id: uuid.UUID,
payload: ProductUpdate,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> Product:
return await ProductService(db).update(product_id, payload, current_user, client_ip(request))
+50
View File
@@ -0,0 +1,50 @@
import uuid
from pydantic import BaseModel, ConfigDict, Field
class ProductCreate(BaseModel):
name: str = Field(min_length=2, max_length=200)
pack: str | None = Field(default=None, max_length=100)
unit: str | None = Field(default=None, max_length=50)
class ProductUpdate(BaseModel):
name: str | None = Field(default=None, min_length=2, max_length=200)
pack: str | None = Field(default=None, max_length=100)
unit: str | None = Field(default=None, max_length=50)
is_active: bool | None = None
class ProductRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
company_id: uuid.UUID
name: str
pack: str | None
unit: str | None
is_active: bool
class StockInventoryRead(BaseModel):
id: int
serial_no: int
product_name: str
pack: str | None
quantity: str | None
unit: str | None
class StockInventoryCreate(BaseModel):
product_name: str = Field(min_length=2, max_length=200)
pack: str | None = Field(default=None, max_length=100)
quantity: str | None = Field(default=None, max_length=50)
unit: str | None = Field(default=None, max_length=50)
class StockInventoryUpdate(BaseModel):
product_name: str | None = Field(default=None, min_length=2, max_length=200)
pack: str | None = Field(default=None, max_length=100)
quantity: str | None = Field(default=None, max_length=50)
unit: str | None = Field(default=None, max_length=50)
+193
View File
@@ -0,0 +1,193 @@
import uuid
from sqlalchemy import select, text
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.audit.service import AuditService
from app.common.enums import AuditAction, EntityType, Role
from app.common.exceptions import ConflictError, NotFoundError
from app.common.utils import snapshot
from app.products.models import Product
from app.products.schemas import (
ProductCreate,
ProductUpdate,
StockInventoryCreate,
StockInventoryRead,
StockInventoryUpdate,
)
from app.users.models import User
_AUDIT_FIELDS = ["name", "pack", "unit", "is_active"]
class ProductService:
def __init__(self, db: AsyncSession) -> None:
self.db, self.audit = db, AuditService(db)
async def list_for(self, actor: User) -> list[Product]:
stmt = select(Product).where(Product.company_id == actor.company_id).order_by(Product.name)
if actor.role == Role.MR:
stmt = stmt.where(Product.is_active.is_(True))
return list((await self.db.execute(stmt)).scalars().all())
async def list_stock_inventory(self) -> list[StockInventoryRead]:
result = await self.db.execute(
text(
"""
SELECT id, serial_no, product_name, pack, quantity, unit
FROM stock_inventory
ORDER BY serial_no
"""
)
)
return [StockInventoryRead.model_validate(row) for row in result.mappings()]
async def _stock_row(self, item_id: int) -> StockInventoryRead:
result = await self.db.execute(
text(
"SELECT id, serial_no, product_name, pack, quantity, unit "
"FROM stock_inventory WHERE id = :id"
),
{"id": item_id},
)
row = result.mappings().one_or_none()
if row is None:
raise NotFoundError("Stock item not found")
return StockInventoryRead.model_validate(row)
async def _assert_stock_name_free(self, name: str, except_id: int | None = None) -> None:
"""A product appears once in the stock list — this also absorbs a double-submitted form."""
taken = (
await self.db.execute(
text(
"SELECT 1 FROM stock_inventory WHERE lower(btrim(product_name)) = lower(btrim(:name)) "
"AND (CAST(:skip AS INTEGER) IS NULL OR id <> :skip) LIMIT 1"
),
{"name": name, "skip": except_id},
)
).first()
if taken:
raise ConflictError("This product is already in the stock list", {"product_name": name})
async def create_stock_item(
self, data: StockInventoryCreate, actor: User, ip: str | None = None
) -> StockInventoryRead:
await self._assert_stock_name_free(data.product_name)
result = await self.db.execute(
text(
"""
INSERT INTO stock_inventory (serial_no, product_name, pack, quantity, unit)
VALUES (
(SELECT COALESCE(MAX(serial_no), 0) + 1 FROM stock_inventory),
:product_name, :pack, :quantity, :unit
)
RETURNING id
"""
),
data.model_dump(),
)
item = await self._stock_row(result.scalar_one())
await self._audit_stock(actor, item, None, item.model_dump(), AuditAction.CREATE, ip)
await self.db.commit()
return item
async def update_stock_item(
self, item_id: int, data: StockInventoryUpdate, actor: User, ip: str | None = None
) -> StockInventoryRead:
before = await self._stock_row(item_id)
changes = data.model_dump(exclude_unset=True)
if changes.get("product_name") is None:
changes.pop("product_name", None)
if "product_name" in changes:
await self._assert_stock_name_free(changes["product_name"], except_id=item_id)
if changes:
assignments = ", ".join(f"{column} = :{column}" for column in changes)
await self.db.execute(
text(f"UPDATE stock_inventory SET {assignments} WHERE id = :id"),
{**changes, "id": item_id},
)
after = await self._stock_row(item_id)
await self._audit_stock(
actor, after, before.model_dump(), after.model_dump(), AuditAction.UPDATE, ip
)
await self.db.commit()
return after
async def delete_stock_item(self, item_id: int, actor: User, ip: str | None = None) -> None:
before = await self._stock_row(item_id)
await self.db.execute(text("DELETE FROM stock_inventory WHERE id = :id"), {"id": item_id})
# keep the printed "No." column gap-free, like the company forms do
await self.db.execute(
text(
"""
WITH numbered AS (
SELECT id, ROW_NUMBER() OVER (ORDER BY serial_no, id) AS n FROM stock_inventory
)
UPDATE stock_inventory s SET serial_no = numbered.n
FROM numbered WHERE s.id = numbered.id AND s.serial_no <> numbered.n
"""
)
)
await self._audit_stock(actor, before, before.model_dump(), None, AuditAction.DELETE, ip)
await self.db.commit()
async def _audit_stock(self, actor, item, before, after, action, ip) -> None:
# entity_id is a UUID column; stock rows use integer ids, so derive a stable UUID.
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.PRODUCT,
entity_id=uuid.uuid5(uuid.NAMESPACE_OID, f"stock_inventory:{item.id}"),
action=action,
before=before,
after=after,
ip_address=ip,
)
async def create(self, data: ProductCreate, actor: User, ip: str | None = None) -> Product:
product = Product(company_id=actor.company_id, **data.model_dump())
self.db.add(product)
try:
await self.db.flush()
except IntegrityError as exc:
await self.db.rollback()
raise ConflictError(
"A product with this name already exists", {"cause": "uq_product_company_name"}
) from exc
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.PRODUCT,
entity_id=product.id,
action=AuditAction.CREATE,
after=snapshot(product, _AUDIT_FIELDS),
ip_address=ip,
)
await self.db.commit()
return product
async def update(
self, product_id: uuid.UUID, data: ProductUpdate, actor: User, ip: str | None = None
) -> Product:
product = await self.db.get(Product, product_id)
if product is None or product.company_id != actor.company_id:
raise NotFoundError("Product not found")
before = snapshot(product, _AUDIT_FIELDS)
for field, value in data.model_dump(exclude_unset=True).items():
setattr(product, field, value)
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.PRODUCT,
entity_id=product.id,
action=AuditAction.UPDATE,
before=before,
after=snapshot(product, _AUDIT_FIELDS),
ip_address=ip,
)
try:
await self.db.commit()
except IntegrityError as exc:
await self.db.rollback()
raise ConflictError(
"A product with this name already exists", {"cause": "uq_product_company_name"}
) from exc
return product
View File
+144
View File
@@ -0,0 +1,144 @@
"""The Daily Call Report and its call rows — the core artefact of the MVP."""
import uuid
from datetime import date, datetime, time
from sqlalchemy import (
CheckConstraint,
Date,
DateTime,
Enum,
ForeignKey,
String,
Text,
Time,
UniqueConstraint,
)
from sqlalchemy.dialects.postgresql import UUID as PGUUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.common.enums import CallOutcome, ConversionStatus, DCRStatus, Role
from app.database.base import Base, TimestampMixin, UUIDMixin
class DailyCallReport(Base, UUIDMixin, TimestampMixin):
__tablename__ = "daily_call_report"
__table_args__ = (
# V1 / A9 — ONE report per MR per calendar date. Enforced in the database and
# not only in the service, so a double-submit race cannot create two reports.
UniqueConstraint("mr_user_id", "report_date", name="uq_dcr_mr_date"),
# An approved report must carry its approval timestamp, and nothing else may.
CheckConstraint(
"(status = 'APPROVED' AND approved_at IS NOT NULL) "
"OR (status <> 'APPROVED' AND approved_at IS NULL)",
name="ck_dcr_approved_at",
),
)
mr_user_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="RESTRICT"), nullable=False
)
#: SNAPSHOT of the MR's headquarters at creation time. If the MR is later
#: transferred, historical reports keep the HQ they were filed under (A1).
headquarters_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("headquarters.id", ondelete="RESTRICT"), nullable=False
)
report_date: Mapped[date] = mapped_column(Date, nullable=False)
status: Mapped[DCRStatus] = mapped_column(
Enum(DCRStatus, name="dcr_status_enum", native_enum=False, length=20),
default=DCRStatus.DRAFT,
nullable=False,
)
#: SNAPSHOT of the reviewing AM / approving GM, 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")
)
current_gm_user_id: Mapped[uuid.UUID | None] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="RESTRICT")
)
mr_remarks: Mapped[str | None] = mapped_column(Text)
#: The printed form's "STOCKIST VISIT" and "ORDER" lines.
stockist_visit: Mapped[str | None] = mapped_column(String(200))
order_value: Mapped[str | None] = mapped_column(String(100))
return_reason: Mapped[str | None] = mapped_column(Text)
#: Which role sent it back — data, not a separate status (report §7.2).
returned_by_role: Mapped[Role | None] = mapped_column(
Enum(Role, name="role_enum", native_enum=False, length=10)
)
submitted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
approved_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
pdf_path: Mapped[str | None] = mapped_column(String(500))
mr: Mapped["User"] = relationship(foreign_keys=[mr_user_id]) # noqa: F821
headquarters: Mapped["Headquarters"] = relationship() # noqa: F821
doctor_calls: Mapped[list["DoctorCall"]] = relationship(
back_populates="dcr", cascade="all, delete-orphan", lazy="selectin"
)
chemist_calls: Mapped[list["ChemistCall"]] = relationship(
back_populates="dcr", cascade="all, delete-orphan", lazy="selectin"
)
@property
def is_locked(self) -> bool:
"""APPROVED is the lock. There is no separate LOCKED status (report §7.2)."""
return self.status == DCRStatus.APPROVED
class DoctorCall(Base, UUIDMixin, TimestampMixin):
__tablename__ = "doctor_call"
__table_args__ = (
# V5 / A11 — a doctor may appear only once per report.
UniqueConstraint("dcr_id", "doctor_id", name="uq_call_dcr_doctor"),
)
dcr_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True),
ForeignKey("daily_call_report.id", ondelete="CASCADE"),
nullable=False,
)
doctor_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("doctor.id", ondelete="RESTRICT"), nullable=False
)
visit_time: Mapped[time] = mapped_column(Time, nullable=False)
call_outcome: Mapped[CallOutcome] = mapped_column(
Enum(CallOutcome, name="call_outcome_enum", native_enum=False, length=20),
nullable=False,
)
#: V7 — only permitted when the doctor is a core doctor.
conversion_status: Mapped[ConversionStatus | None] = mapped_column(
Enum(ConversionStatus, name="conversion_status_enum", native_enum=False, length=20)
)
#: The printed form's "PRODUCT PROMOTE" and "PRODUCT SAMPLE" columns.
product_promote: Mapped[str | None] = mapped_column(String(200))
product_sample: Mapped[str | None] = mapped_column(String(200))
remarks: Mapped[str | None] = mapped_column(Text)
dcr: Mapped["DailyCallReport"] = relationship(back_populates="doctor_calls")
doctor: Mapped["Doctor"] = relationship(lazy="selectin") # noqa: F821
class ChemistCall(Base, UUIDMixin, TimestampMixin):
__tablename__ = "chemist_call"
__table_args__ = (
UniqueConstraint("dcr_id", "chemist_id", name="uq_call_dcr_chemist"),
)
dcr_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True),
ForeignKey("daily_call_report.id", ondelete="CASCADE"),
nullable=False,
)
chemist_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("chemist.id", ondelete="RESTRICT"), nullable=False
)
visit_time: Mapped[time] = mapped_column(Time, nullable=False)
#: The printed form's "POB" column.
pob: Mapped[str | None] = mapped_column(String(100))
remarks: Mapped[str | None] = mapped_column(Text)
dcr: Mapped["DailyCallReport"] = relationship(back_populates="chemist_calls")
chemist: Mapped["Chemist"] = relationship(lazy="selectin") # noqa: F821
+99
View File
@@ -0,0 +1,99 @@
import uuid
from datetime import date
from sqlalchemy import func, select
from sqlalchemy.orm import selectinload
from app.common.enums import DCRStatus
from app.common.repository import BaseRepository
from app.reports.models import ChemistCall, DailyCallReport, DoctorCall
class DCRRepository(BaseRepository[DailyCallReport]):
model = DailyCallReport
async def get_full(self, dcr_id: uuid.UUID) -> DailyCallReport | None:
stmt = (
select(DailyCallReport)
.where(DailyCallReport.id == dcr_id)
.options(
selectinload(DailyCallReport.doctor_calls).selectinload(DoctorCall.doctor),
selectinload(DailyCallReport.chemist_calls).selectinload(ChemistCall.chemist),
selectinload(DailyCallReport.mr),
selectinload(DailyCallReport.headquarters),
)
# The session keeps objects after commit (expire_on_commit=False), so without this the
# report comes back with the call lists it had *before* an add or remove.
.execution_options(populate_existing=True)
)
return (await self.db.execute(stmt)).scalar_one_or_none()
async def get_for_date(
self, mr_user_id: uuid.UUID, report_date: date
) -> DailyCallReport | None:
"""V1 pre-check. The database unique constraint is the real guarantee."""
stmt = select(DailyCallReport).where(
DailyCallReport.mr_user_id == mr_user_id,
DailyCallReport.report_date == report_date,
)
return (await self.db.execute(stmt)).scalar_one_or_none()
def _scoped(
self,
*,
mr_user_id: uuid.UUID | None,
hq_ids: set[uuid.UUID] | None,
status: DCRStatus | None,
date_from: date | None,
date_to: date | None,
):
stmt = select(DailyCallReport)
if mr_user_id is not None:
stmt = stmt.where(DailyCallReport.mr_user_id == mr_user_id)
if hq_ids is not None:
# An empty scope must match nothing, not everything.
stmt = stmt.where(DailyCallReport.headquarters_id.in_(hq_ids or [None]))
if status is not None:
stmt = stmt.where(DailyCallReport.status == status)
if date_from is not None:
stmt = stmt.where(DailyCallReport.report_date >= date_from)
if date_to is not None:
stmt = stmt.where(DailyCallReport.report_date <= date_to)
return stmt
async def list_scoped(
self,
*,
mr_user_id: uuid.UUID | None = None,
hq_ids: set[uuid.UUID] | None = None,
status: DCRStatus | None = None,
date_from: date | None = None,
date_to: date | None = None,
limit: int = 50,
offset: int = 0,
) -> list[DailyCallReport]:
stmt = (
self._scoped(
mr_user_id=mr_user_id, hq_ids=hq_ids, status=status,
date_from=date_from, date_to=date_to,
)
.options(
selectinload(DailyCallReport.doctor_calls),
selectinload(DailyCallReport.chemist_calls),
selectinload(DailyCallReport.mr),
selectinload(DailyCallReport.headquarters),
)
.order_by(DailyCallReport.created_at.desc(), DailyCallReport.report_date.desc())
.limit(limit)
.offset(offset)
)
return list((await self.db.execute(stmt)).scalars().all())
async def status_counts(
self, *, mr_user_id: uuid.UUID | None = None, hq_ids: set[uuid.UUID] | None = None
) -> dict[str, int]:
stmt = self._scoped(
mr_user_id=mr_user_id, hq_ids=hq_ids, status=None, date_from=None, date_to=None
).with_only_columns(DailyCallReport.status, func.count()).group_by(DailyCallReport.status)
rows = (await self.db.execute(stmt)).all()
return {str(status): count for status, count in rows}
+204
View File
@@ -0,0 +1,204 @@
import uuid
from datetime import date
from fastapi import APIRouter, Depends, Query, Request, Response, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth.dependencies import client_ip, get_current_user, require_role
from app.common.enums import DCRStatus, Role
from app.common.exceptions import ValidationError
from app.database.session import get_db
from app.pdf.service import PDFService
from app.reports.schemas import (
ApproveRequest,
ChemistCallCreate,
DCRCreate,
DCRListItem,
DCRRead,
DCRUpdate,
DoctorCallCreate,
ReturnRequest,
StatusCounts,
)
from app.reports.serializers import to_list_item, to_read
from app.reports.service import DCRService
from app.users.models import User
router = APIRouter(prefix="/dcr", tags=["reports"])
# ---------------------------------------------------------------- queries
@router.get("", response_model=list[DCRListItem])
async def list_reports(
status_filter: DCRStatus | None = Query(default=None, alias="status"),
date_from: date | None = None,
date_to: date | None = None,
limit: int = Query(default=50, ge=1, le=200),
offset: int = Query(default=0, ge=0),
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
) -> list[DCRListItem]:
"""S2 (MR) and S6 (manager queue). Scope is applied in the service, never here."""
reports = await DCRService(db).list_for(
current_user,
status=status_filter,
date_from=date_from,
date_to=date_to,
limit=limit,
offset=offset,
)
return [to_list_item(r) for r in reports]
@router.get("/counts", response_model=StatusCounts)
async def status_counts(
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
) -> StatusCounts:
"""Header counts — the deliberate, cheap replacement for the cut dashboards."""
return StatusCounts(**await DCRService(db).counts_for(current_user))
@router.get("/{dcr_id}", response_model=DCRRead)
async def get_report(
dcr_id: uuid.UUID,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
return to_read(await DCRService(db).get_for_view(dcr_id, current_user))
@router.get("/{dcr_id}/pdf")
async def download_pdf(
dcr_id: uuid.UUID,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
) -> Response:
"""SEC-7 — served through an authorised endpoint, never as a guessable static path."""
dcr = await DCRService(db).get_for_view(dcr_id, current_user)
if dcr.status != DCRStatus.APPROVED:
raise ValidationError(
"Only a finally approved report can be downloaded",
{"current_status": dcr.status.value},
)
# An approved report never changes, so it is rendered from its data each time: every download
# uses the current form layout, even for reports approved before the layout changed.
content = await PDFService(db).render_bytes(dcr)
filename = f"DCR-{dcr.mr.employee_code}-{dcr.report_date.isoformat()}.pdf"
return Response(
content=content,
media_type="application/pdf",
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
)
# --------------------------------------------------------------- commands
@router.post("", response_model=DCRRead, status_code=status.HTTP_201_CREATED)
async def create_report(
payload: DCRCreate,
request: Request,
current_user: User = Depends(require_role(Role.MR)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
return to_read(await DCRService(db).create(payload, current_user, client_ip(request)))
@router.patch("/{dcr_id}", response_model=DCRRead)
async def update_report(
dcr_id: uuid.UUID,
payload: DCRUpdate,
request: Request,
current_user: User = Depends(require_role(Role.MR)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
return to_read(
await DCRService(db).update_details(
dcr_id, payload.model_dump(exclude_unset=True), current_user, client_ip(request)
)
)
@router.post("/{dcr_id}/calls/doctor", response_model=DCRRead, status_code=201)
async def add_doctor_call(
dcr_id: uuid.UUID,
payload: DoctorCallCreate,
request: Request,
current_user: User = Depends(require_role(Role.MR)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
return to_read(
await DCRService(db).add_doctor_call(dcr_id, payload, current_user, client_ip(request))
)
@router.post("/{dcr_id}/calls/chemist", response_model=DCRRead, status_code=201)
async def add_chemist_call(
dcr_id: uuid.UUID,
payload: ChemistCallCreate,
request: Request,
current_user: User = Depends(require_role(Role.MR)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
return to_read(
await DCRService(db).add_chemist_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)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
return to_read(
await DCRService(db).delete_call(dcr_id, call_id, current_user, client_ip(request))
)
# ------------------------------------------------------------- transitions
@router.post("/{dcr_id}/submit", response_model=DCRRead)
async def submit(
dcr_id: uuid.UUID,
request: Request,
current_user: User = Depends(require_role(Role.MR)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
return to_read(await DCRService(db).submit(dcr_id, current_user, client_ip(request)))
@router.post("/{dcr_id}/return", response_model=DCRRead)
async def return_report(
dcr_id: uuid.UUID,
payload: ReturnRequest,
request: Request,
current_user: User = Depends(require_role(Role.AM)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
return to_read(
await DCRService(db).return_report(
dcr_id, payload.reason, current_user, client_ip(request)
)
)
@router.post("/{dcr_id}/approve", response_model=DCRRead)
async def approve(
dcr_id: uuid.UUID,
payload: ApproveRequest,
request: Request,
current_user: User = Depends(require_role(Role.AM)),
db: AsyncSession = Depends(get_db),
) -> DCRRead:
"""Area 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))
)
+126
View File
@@ -0,0 +1,126 @@
import uuid
from datetime import date, datetime, time
from pydantic import BaseModel, ConfigDict, Field
from app.common.enums import CallOutcome, ConversionStatus, DCRStatus, Role
from app.config.settings import settings
class DoctorCallCreate(BaseModel):
doctor_id: uuid.UUID
visit_time: time
call_outcome: CallOutcome
#: V7 — accepted only when the doctor is flagged as a core doctor.
conversion_status: ConversionStatus | None = None
product_promote: str | None = Field(default=None, max_length=200)
product_sample: str | None = Field(default=None, max_length=200)
remarks: str | None = Field(default=None, max_length=2000)
class ChemistCallCreate(BaseModel):
chemist_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)
id: uuid.UUID
doctor_id: uuid.UUID
doctor_name: str
doctor_speciality: str | None
is_core_doctor: bool
visit_time: time
call_outcome: CallOutcome
conversion_status: ConversionStatus | None
product_promote: str | None
product_sample: str | None
remarks: str | None
class ChemistCallRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
chemist_id: uuid.UUID
chemist_name: str
visit_time: time
pob: str | None
remarks: str | None
class DCRCreate(BaseModel):
report_date: date
mr_remarks: str | None = Field(default=None, max_length=2000)
doctor_calls: list[DoctorCallCreate] = Field(default_factory=list)
chemist_calls: list[ChemistCallCreate] = Field(default_factory=list)
class DCRUpdate(BaseModel):
mr_remarks: str | None = Field(default=None, max_length=2000)
stockist_visit: str | None = Field(default=None, max_length=200)
order_value: str | None = Field(default=None, max_length=100)
class ReturnRequest(BaseModel):
"""V8 — a manager must say WHY. This reason is what makes the audit trail useful."""
reason: str = Field(min_length=settings.MIN_RETURN_REASON_LENGTH, max_length=2000)
class ApproveRequest(BaseModel):
comment: str | None = Field(default=None, max_length=2000)
class DCRListItem(BaseModel):
"""Row for S2/S6 — the list screens that replaced the cut dashboards."""
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
report_date: date
status: DCRStatus
mr_user_id: uuid.UUID
mr_name: str
headquarters_id: uuid.UUID
headquarters_name: str
doctor_call_count: int
chemist_call_count: int
submitted_at: datetime | None
approved_at: datetime | None
returned_by_role: Role | None
class DCRRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
mr_user_id: uuid.UUID
mr_name: str
employee_code: str
headquarters_id: uuid.UUID
headquarters_name: str
report_date: date
status: DCRStatus
is_locked: bool
mr_remarks: str | None
stockist_visit: str | None
order_value: str | None
return_reason: str | None
returned_by_role: Role | None
submitted_at: datetime | None
approved_at: datetime | None
doctor_calls: list[DoctorCallRead]
chemist_calls: list[ChemistCallRead]
class StatusCounts(BaseModel):
"""Header counts on the list screens — the cheap replacement for dashboards."""
DRAFT: int = 0
PENDING_AM: int = 0
RETURNED: int = 0
APPROVED: int = 0
+74
View File
@@ -0,0 +1,74 @@
"""ORM → response-schema mapping for reports."""
from app.reports.models import DailyCallReport
from app.reports.schemas import (
ChemistCallRead,
DCRListItem,
DCRRead,
DoctorCallRead,
)
def to_read(dcr: DailyCallReport) -> DCRRead:
return DCRRead(
id=dcr.id,
mr_user_id=dcr.mr_user_id,
mr_name=dcr.mr.full_name,
employee_code=dcr.mr.employee_code,
headquarters_id=dcr.headquarters_id,
headquarters_name=dcr.headquarters.name,
report_date=dcr.report_date,
status=dcr.status,
is_locked=dcr.is_locked,
mr_remarks=dcr.mr_remarks,
stockist_visit=dcr.stockist_visit,
order_value=dcr.order_value,
return_reason=dcr.return_reason,
returned_by_role=dcr.returned_by_role,
submitted_at=dcr.submitted_at,
approved_at=dcr.approved_at,
doctor_calls=[
DoctorCallRead(
id=c.id,
doctor_id=c.doctor_id,
doctor_name=c.doctor.name,
doctor_speciality=c.doctor.speciality,
is_core_doctor=c.doctor.is_core_doctor,
visit_time=c.visit_time,
call_outcome=c.call_outcome,
conversion_status=c.conversion_status,
product_promote=c.product_promote,
product_sample=c.product_sample,
remarks=c.remarks,
)
for c in sorted(dcr.doctor_calls, key=lambda x: x.visit_time)
],
chemist_calls=[
ChemistCallRead(
id=c.id,
chemist_id=c.chemist_id,
chemist_name=c.chemist.name,
visit_time=c.visit_time,
pob=c.pob,
remarks=c.remarks,
)
for c in sorted(dcr.chemist_calls, key=lambda x: x.visit_time)
],
)
def to_list_item(dcr: DailyCallReport) -> DCRListItem:
return DCRListItem(
id=dcr.id,
report_date=dcr.report_date,
status=dcr.status,
mr_user_id=dcr.mr_user_id,
mr_name=dcr.mr.full_name,
headquarters_id=dcr.headquarters_id,
headquarters_name=dcr.headquarters.name,
doctor_call_count=len(dcr.doctor_calls),
chemist_call_count=len(dcr.chemist_calls),
submitted_at=dcr.submitted_at,
approved_at=dcr.approved_at,
returned_by_role=dcr.returned_by_role,
)
+492
View File
@@ -0,0 +1,492 @@
"""Daily Call Report business rules — validation rules V1-V12 all live here.
Routers never contain rules; repositories never contain rules. This module is the
single place a reviewer needs to read to understand what the system enforces.
"""
import uuid
from datetime import date, timedelta
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.approvals.state_machine import assert_editable, assert_transition
from app.audit.service import AuditService
from app.auth.dependencies import assert_can_view_dcr, visible_hq_ids
from app.chemists.models import Chemist, ChemistAssignment
from app.common.enums import (
AuditAction,
DCRStatus,
EntityType,
Role,
WorkflowAction,
)
from app.common.exceptions import (
ConflictError,
NotFoundError,
ValidationError,
)
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
from app.reports.repository import DCRRepository
from app.reports.schemas import ChemistCallCreate, DCRCreate, DoctorCallCreate
from app.users.models import User
#: Audit fields — the columns worth recording on a state change.
_AUDIT_FIELDS = [
"status",
"report_date",
"mr_remarks",
"stockist_visit",
"order_value",
"return_reason",
"returned_by_role",
"submitted_at",
"approved_at",
]
def _clean(value: str | None) -> str | None:
"""Trimmed text, with blank input stored as NULL."""
value = (value or "").strip()
return value or None
class DCRService:
def __init__(self, db: AsyncSession) -> None:
self.db = db
self.repo = DCRRepository(db)
self.audit = AuditService(db)
# ------------------------------------------------------------------
# Validation helpers
# ------------------------------------------------------------------
def _validate_report_date(self, report_date: date) -> None:
today = local_today()
# V2 — no future reports.
if report_date > today:
raise ValidationError(
"Report date cannot be in the future",
{"report_date": report_date.isoformat(), "today": today.isoformat()},
)
# V3 / A10 / Q8 — back-dating window.
earliest = today - timedelta(days=settings.BACKDATING_WINDOW_DAYS)
if report_date < earliest:
raise ValidationError(
f"Report date is older than the {settings.BACKDATING_WINDOW_DAYS}-day "
"back-dating window",
{"report_date": report_date.isoformat(), "earliest_allowed": earliest.isoformat()},
)
def _check_submission_deadline(self, report_date: date) -> None:
"""A16 / Q9 — report for date D must be submitted by end of D + N days."""
deadline = report_date + timedelta(days=settings.SUBMISSION_DEADLINE_DAYS)
if local_today() > deadline:
raise ValidationError(
"Submission deadline for this report date has passed",
{"report_date": report_date.isoformat(), "deadline": deadline.isoformat()},
)
async def _assigned_doctor_ids(self, mr_user_id: uuid.UUID) -> set[uuid.UUID]:
stmt = select(DoctorAssignment.doctor_id).where(
DoctorAssignment.mr_user_id == mr_user_id,
DoctorAssignment.effective_to.is_(None),
)
return set((await self.db.execute(stmt)).scalars().all())
async def _assigned_chemist_ids(self, mr_user_id: uuid.UUID) -> set[uuid.UUID]:
stmt = select(ChemistAssignment.chemist_id).where(
ChemistAssignment.mr_user_id == mr_user_id,
ChemistAssignment.effective_to.is_(None),
)
return set((await self.db.execute(stmt)).scalars().all())
async def _build_doctor_call(
self, dcr: DailyCallReport, payload: DoctorCallCreate, assigned: set[uuid.UUID]
) -> DoctorCall:
# V6 — only doctors currently assigned to this MR may be called.
if payload.doctor_id not in assigned:
raise ValidationError(
"Doctor is not assigned to this MR",
{"doctor_id": str(payload.doctor_id)},
)
doctor = await self.db.get(Doctor, payload.doctor_id)
if doctor is None:
raise NotFoundError("Doctor not found", {"doctor_id": str(payload.doctor_id)})
# V7 — conversion status is meaningful only for core doctors.
if payload.conversion_status is not None and not doctor.is_core_doctor:
raise ValidationError(
"conversion_status may only be set for a core doctor",
{"doctor_id": str(doctor.id), "is_core_doctor": False},
)
return DoctorCall(
dcr_id=dcr.id,
doctor_id=payload.doctor_id,
visit_time=payload.visit_time,
call_outcome=payload.call_outcome,
conversion_status=payload.conversion_status,
product_promote=_clean(payload.product_promote),
product_sample=_clean(payload.product_sample),
remarks=payload.remarks,
)
async def _build_chemist_call(
self, dcr: DailyCallReport, payload: ChemistCallCreate, assigned: set[uuid.UUID]
) -> ChemistCall:
if payload.chemist_id not in assigned:
raise ValidationError(
"Chemist is not assigned to this MR", {"chemist_id": str(payload.chemist_id)}
)
if await self.db.get(Chemist, payload.chemist_id) is None:
raise NotFoundError("Chemist not found", {"chemist_id": str(payload.chemist_id)})
return ChemistCall(
dcr_id=dcr.id,
chemist_id=payload.chemist_id,
visit_time=payload.visit_time,
pob=_clean(payload.pob),
remarks=payload.remarks,
)
# ------------------------------------------------------------------
# Commands
# ------------------------------------------------------------------
async def create(
self, data: DCRCreate, actor: User, ip: str | None = None
) -> DailyCallReport:
if actor.role != Role.MR or actor.headquarters_id is None:
raise ValidationError("Only an MR with a headquarters can create a report")
self._validate_report_date(data.report_date)
# V1 pre-check for a friendly 409; the unique constraint below is the guarantee.
if await self.repo.get_for_date(actor.id, data.report_date):
raise ConflictError(
"A report already exists for this date",
{"report_date": data.report_date.isoformat()},
)
dcr = DailyCallReport(
id=uuid.uuid4(),
mr_user_id=actor.id,
headquarters_id=actor.headquarters_id, # snapshot (A1)
report_date=data.report_date,
status=DCRStatus.DRAFT,
mr_remarks=data.mr_remarks,
)
self.db.add(dcr)
doctor_ids = await self._assigned_doctor_ids(actor.id)
chemist_ids = await self._assigned_chemist_ids(actor.id)
seen_doctors: set[uuid.UUID] = set()
for payload in data.doctor_calls:
if payload.doctor_id in seen_doctors:
raise ConflictError(
"Duplicate doctor call in the same report",
{"doctor_id": str(payload.doctor_id)},
)
seen_doctors.add(payload.doctor_id)
self.db.add(await self._build_doctor_call(dcr, payload, doctor_ids))
seen_chemists: set[uuid.UUID] = set()
for payload in data.chemist_calls:
if payload.chemist_id in seen_chemists:
raise ConflictError(
"Duplicate chemist call in the same report",
{"chemist_id": str(payload.chemist_id)},
)
seen_chemists.add(payload.chemist_id)
self.db.add(await self._build_chemist_call(dcr, payload, chemist_ids))
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.DCR,
entity_id=dcr.id,
action=AuditAction.CREATE,
after=snapshot(dcr, _AUDIT_FIELDS),
ip_address=ip,
)
try:
await self.db.commit()
except IntegrityError as exc:
await self.db.rollback()
raise ConflictError(
"A report already exists for this MR and date", {"cause": "uq_dcr_mr_date"}
) from exc
return await self.repo.get_full(dcr.id)
async def update_details(
self, dcr_id: uuid.UUID, changes: dict[str, str | None], actor: User, ip: str | None = None
) -> DailyCallReport:
"""Change the report-level free text: MR remarks, stockist visit, order."""
dcr = await self._get_owned_editable(dcr_id, actor)
before = snapshot(dcr, _AUDIT_FIELDS)
for field in ("mr_remarks", "stockist_visit", "order_value"):
if field in changes:
setattr(dcr, field, _clean(changes[field]))
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.DCR,
entity_id=dcr.id,
action=AuditAction.UPDATE,
before=before,
after=snapshot(dcr, _AUDIT_FIELDS),
ip_address=ip,
)
await self.db.commit()
return await self.repo.get_full(dcr.id)
async def add_doctor_call(
self, dcr_id: uuid.UUID, payload: DoctorCallCreate, actor: User, ip: str | None = None
) -> DailyCallReport:
dcr = await self._get_owned_editable(dcr_id, actor)
assigned = await self._assigned_doctor_ids(actor.id)
call = await self._build_doctor_call(dcr, payload, assigned)
self._validate_visit_time(dcr, payload.visit_time)
self.db.add(call)
# Flush the insert on its own so the unique-violation surfaces HERE, as a
# clean 409, rather than escaping from the audit flush or the final commit.
try:
await self.db.flush()
except IntegrityError as exc:
await self.db.rollback()
# V5 — the doctor is already on this report.
raise ConflictError(
"This doctor has already been called on this report",
{"doctor_id": str(payload.doctor_id), "cause": "uq_call_dcr_doctor"},
) from exc
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.DCR,
entity_id=dcr.id,
action=AuditAction.UPDATE,
after={"added_doctor_call": str(payload.doctor_id)},
ip_address=ip,
)
await self.db.commit()
return await self.repo.get_full(dcr.id)
async def add_chemist_call(
self, dcr_id: uuid.UUID, payload: ChemistCallCreate, actor: User, ip: str | None = None
) -> DailyCallReport:
dcr = await self._get_owned_editable(dcr_id, actor)
assigned = await self._assigned_chemist_ids(actor.id)
call = await self._build_chemist_call(dcr, payload, assigned)
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 chemist has already been called on this report",
{"chemist_id": str(payload.chemist_id), "cause": "uq_call_dcr_chemist"},
) from exc
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.DCR,
entity_id=dcr.id,
action=AuditAction.UPDATE,
after={"added_chemist_call": str(payload.chemist_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."""
if dcr.report_date == local_today():
# Visit times are entered in the company's local time (APP_TIMEZONE), so they
# must be compared with local "now" — not the server's UTC clock.
if visit_time > local_now().time() and settings.ENVIRONMENT == "production":
raise ValidationError(
"Visit time cannot be in the future", {"visit_time": str(visit_time)}
)
async def delete_call(
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)
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)
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.DCR,
entity_id=dcr.id,
action=AuditAction.DELETE,
before={"removed_call": str(call_id)},
ip_address=ip,
)
await self.db.commit()
return await self.repo.get_full(dcr.id)
# ------------------------------------------------------------------
# Workflow transitions
# ------------------------------------------------------------------
async def submit(
self, dcr_id: uuid.UUID, actor: User, ip: str | None = None
) -> DailyCallReport:
dcr = await self.repo.get_full(dcr_id)
if dcr is None:
raise NotFoundError("Report not found", {"id": str(dcr_id)})
await assert_can_view_dcr(self.db, actor, dcr)
if dcr.mr_user_id != actor.id:
from app.common.exceptions import ForbiddenError
raise ForbiddenError("Only the owning MR can submit this report")
if dcr.status == DCRStatus.PENDING_AM:
return dcr # already submitted (a double click): nothing more to do
transition = assert_transition(dcr.status, WorkflowAction.SUBMIT, actor.role)
# V4 — at least one doctor call is required to submit.
if not dcr.doctor_calls:
raise ValidationError("A report must contain at least one doctor call to submit")
self._check_submission_deadline(dcr.report_date)
before = snapshot(dcr, _AUDIT_FIELDS)
dcr.status = transition.to_status
dcr.submitted_at = utcnow()
dcr.return_reason = None
dcr.returned_by_role = None
dcr.current_am_user_id = await self._current_am_for_hq(dcr.headquarters_id)
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.DCR,
entity_id=dcr.id,
action=AuditAction.SUBMIT,
before=before,
after=snapshot(dcr, _AUDIT_FIELDS),
ip_address=ip,
)
await self.db.commit()
return await self.repo.get_full(dcr.id)
async def return_report(
self, dcr_id: uuid.UUID, reason: str, actor: User, ip: str | None = None
) -> DailyCallReport:
dcr = await self._get_in_scope(dcr_id, actor)
transition = assert_transition(dcr.status, WorkflowAction.RETURN, actor.role)
before = snapshot(dcr, _AUDIT_FIELDS)
dcr.status = transition.to_status
dcr.return_reason = reason
dcr.returned_by_role = actor.role # data, not a separate status
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.DCR,
entity_id=dcr.id,
action=AuditAction.RETURN,
before=before,
after=snapshot(dcr, _AUDIT_FIELDS),
comment=reason,
ip_address=ip,
)
await self.db.commit()
return await self.repo.get_full(dcr.id)
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."""
dcr = await self._get_in_scope(dcr_id, actor)
if dcr.status == DCRStatus.APPROVED and actor.role == Role.AM:
return dcr # already approved (a double click): the report stays as it is
transition = assert_transition(dcr.status, WorkflowAction.APPROVE, actor.role)
before = snapshot(dcr, _AUDIT_FIELDS)
dcr.status = transition.to_status
dcr.approved_at = utcnow()
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.DCR,
entity_id=dcr.id,
action=AuditAction.APPROVE,
before=before,
after=snapshot(dcr, _AUDIT_FIELDS),
comment=comment,
ip_address=ip,
)
# PDF is generated synchronously — it takes about a second, and adding a task
# queue for one one-second job is infrastructure you must then operate.
from app.pdf.service import PDFService
full = await self.repo.get_full(dcr.id)
dcr.pdf_path = await PDFService(self.db).render_and_store(full, approver=actor)
await self.db.commit()
return await self.repo.get_full(dcr.id)
# ------------------------------------------------------------------
# Queries
# ------------------------------------------------------------------
async def get_for_view(self, dcr_id: uuid.UUID, actor: User) -> DailyCallReport:
dcr = await self.repo.get_full(dcr_id)
if dcr is None:
raise NotFoundError("Report not found", {"id": str(dcr_id)})
await assert_can_view_dcr(self.db, actor, dcr)
return dcr
async def list_for(self, actor: User, **filters) -> list[DailyCallReport]:
if actor.role == Role.MR:
return await self.repo.list_scoped(mr_user_id=actor.id, **filters)
hq_ids = await visible_hq_ids(self.db, actor)
return await self.repo.list_scoped(hq_ids=hq_ids, **filters)
async def counts_for(self, actor: User) -> dict[str, int]:
if actor.role == Role.MR:
return await self.repo.status_counts(mr_user_id=actor.id)
return await self.repo.status_counts(hq_ids=await visible_hq_ids(self.db, actor))
# ------------------------------------------------------------------
# Internals
# ------------------------------------------------------------------
async def _get_owned_editable(self, dcr_id: uuid.UUID, actor: User) -> DailyCallReport:
"""Owner + editable-status guard for every data-changing operation (V9/V10)."""
dcr = await self.repo.get_full(dcr_id)
if dcr is None:
raise NotFoundError("Report not found", {"id": str(dcr_id)})
await assert_can_view_dcr(self.db, actor, dcr)
if actor.role != Role.MR or dcr.mr_user_id != actor.id:
from app.common.exceptions import ForbiddenError
raise ForbiddenError("Only the owning MR can modify report data")
assert_editable(dcr.status)
return dcr
async def _get_in_scope(self, dcr_id: uuid.UUID, actor: User) -> DailyCallReport:
dcr = await self.repo.get_full(dcr_id)
if dcr is None:
raise NotFoundError("Report not found", {"id": str(dcr_id)})
await assert_can_view_dcr(self.db, actor, dcr)
return dcr
async def _current_am_for_hq(self, headquarters_id: uuid.UUID) -> uuid.UUID | None:
from app.organization.models import AMHeadquarters
stmt = select(AMHeadquarters.area_manager_user_id).where(
AMHeadquarters.headquarters_id == headquarters_id,
AMHeadquarters.effective_to.is_(None),
)
return (await self.db.execute(stmt)).scalars().first()
View File
+50
View File
@@ -0,0 +1,50 @@
"""The single `user` table for every role.
`mr_profile` and `area_manager_profile` were merged in (report §13.2): both would
have held the same columns as `user`, and the only MR-specific payload is
`headquarters_id`.
"""
import uuid
from sqlalchemy import Boolean, CheckConstraint, Enum, ForeignKey, String, UniqueConstraint
from sqlalchemy.dialects.postgresql import UUID as PGUUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.common.enums import Role
from app.database.base import Base, TimestampMixin, UUIDMixin
class User(Base, UUIDMixin, TimestampMixin):
__tablename__ = "user"
__table_args__ = (
UniqueConstraint("company_id", "email", name="uq_user_company_email"),
UniqueConstraint("company_id", "employee_code", name="uq_user_company_empcode"),
# An MR must have a headquarters; nobody else may have one (R4, R8).
CheckConstraint(
"(role = 'MR' AND headquarters_id IS NOT NULL) "
"OR (role <> 'MR' AND headquarters_id IS NULL)",
name="ck_user_mr_requires_hq",
),
)
company_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("company.id", ondelete="RESTRICT"), nullable=False
)
email: Mapped[str] = mapped_column(String(255), nullable=False)
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
full_name: Mapped[str] = mapped_column(String(200), nullable=False)
employee_code: Mapped[str] = mapped_column(String(50), nullable=False)
phone: Mapped[str | None] = mapped_column(String(20))
role: Mapped[Role] = mapped_column(
Enum(Role, name="role_enum", native_enum=False, length=10), nullable=False
)
#: MR only — the one headquarters this MR belongs to (R4).
headquarters_id: Mapped[uuid.UUID | None] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("headquarters.id", ondelete="RESTRICT")
)
#: Checked on EVERY request, not only at login (SEC-5).
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
failed_login_attempts: Mapped[int] = mapped_column(default=0, nullable=False)
headquarters: Mapped["Headquarters | None"] = relationship() # noqa: F821
+50
View File
@@ -0,0 +1,50 @@
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.users.models import User
from app.users.schemas import MyProfile, UserCreate, UserRead, UserUpdate
from app.users.service import UserService
router = APIRouter(prefix="/users", tags=["users"])
@router.get("/me/profile", response_model=MyProfile)
async def my_profile(
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
) -> MyProfile:
return await UserService(db).my_profile(current_user)
@router.get("", response_model=list[UserRead])
async def list_users(
role: Role | None = None,
current_user: User = Depends(require_role(Role.ADMIN, Role.GM)),
db: AsyncSession = Depends(get_db),
) -> list[User]:
return await UserService(db).list_users(current_user, role)
@router.post("", response_model=UserRead, status_code=status.HTTP_201_CREATED)
async def create_user(
payload: UserCreate,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> User:
return await UserService(db).create(payload, current_user, client_ip(request))
@router.patch("/{user_id}", response_model=UserRead)
async def update_user(
user_id: uuid.UUID,
payload: UserUpdate,
request: Request,
current_user: User = Depends(require_role(Role.ADMIN)),
db: AsyncSession = Depends(get_db),
) -> User:
return await UserService(db).update(user_id, payload, current_user, client_ip(request))
+65
View File
@@ -0,0 +1,65 @@
import uuid
from pydantic import BaseModel, ConfigDict, EmailStr, Field, model_validator
from app.common.enums import Role
class UserCreate(BaseModel):
email: EmailStr
password: str = Field(min_length=8, max_length=128)
full_name: str = Field(min_length=2, max_length=200)
employee_code: str = Field(min_length=1, max_length=50)
role: Role
phone: str | None = Field(default=None, max_length=20)
#: Required for MR, forbidden for every other role (R4/R8).
headquarters_id: uuid.UUID | None = None
@model_validator(mode="after")
def check_hq_matches_role(self):
if self.role == Role.MR and self.headquarters_id is None:
raise ValueError("headquarters_id is required for an MR")
if self.role != Role.MR and self.headquarters_id is not None:
raise ValueError("headquarters_id may only be set for an MR")
return self
class UserUpdate(BaseModel):
full_name: str | None = Field(default=None, min_length=2, max_length=200)
#: Sign-in credentials. Admin-only (the whole endpoint is); changing them is audited.
email: EmailStr | None = None
employee_code: str | None = Field(default=None, min_length=1, max_length=50)
#: 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)
headquarters_id: uuid.UUID | None = None
is_active: bool | None = None
class UserRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
email: str
full_name: str
employee_code: str
role: Role
phone: str | None
headquarters_id: uuid.UUID | None
is_active: bool
class MyProfile(BaseModel):
"""S4 — the MR profile screen. Includes the DERIVED reporting Area Manager."""
id: uuid.UUID
full_name: str
employee_code: str
email: str
role: Role
phone: str | None
headquarters_id: uuid.UUID | None
headquarters_code: str | None
headquarters_name: str | None
reporting_manager_id: uuid.UUID | None
reporting_manager_name: str | None
+158
View File
@@ -0,0 +1,158 @@
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.security import hash_password
from app.auth.service import AuthService
from app.common.enums import AuditAction, EntityType, Role
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
from app.common.utils import snapshot
from app.organization.models import AMHeadquarters, Headquarters
from app.users.models import User
from app.users.schemas import MyProfile, UserCreate, UserUpdate
_AUDIT_FIELDS = ["email", "full_name", "employee_code", "role", "headquarters_id", "is_active"]
class UserService:
def __init__(self, db: AsyncSession) -> None:
self.db = db
self.audit = AuditService(db)
async def create(self, data: UserCreate, actor: User, ip: str | None = None) -> User:
if data.headquarters_id is not None:
hq = await self.db.get(Headquarters, data.headquarters_id)
if hq is None:
raise NotFoundError("Headquarters not found")
if hq.company_id != actor.company_id:
raise ValidationError("Headquarters belongs to another company")
user = User(
company_id=actor.company_id,
email=str(data.email).lower(),
password_hash=hash_password(data.password),
full_name=data.full_name,
employee_code=data.employee_code,
role=data.role,
phone=data.phone,
headquarters_id=data.headquarters_id,
)
self.db.add(user)
try:
await self.db.flush()
except IntegrityError as exc:
await self.db.rollback()
raise ConflictError("A user with this email or employee code already exists") from exc
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.USER,
entity_id=user.id,
action=AuditAction.CREATE,
after=snapshot(user, _AUDIT_FIELDS),
ip_address=ip,
)
await self.db.commit()
return user
async def update(
self, user_id: uuid.UUID, data: UserUpdate, actor: User, ip: str | None = None
) -> User:
user = await self.db.get(User, user_id)
if user is None:
raise NotFoundError("User not found")
if user.company_id != actor.company_id:
raise NotFoundError("User not found")
before = snapshot(user, _AUDIT_FIELDS)
deactivating = data.is_active is False and user.is_active
changes = data.model_dump(exclude_unset=True)
new_password = changes.pop("password", None)
if "email" in changes:
if changes["email"] is None:
raise ValidationError("Email cannot be empty")
changes["email"] = str(changes["email"]).lower()
for field, value in changes.items():
setattr(user, field, value)
password_reset = new_password is not None
if password_reset:
user.password_hash = hash_password(new_password)
user.failed_login_attempts = 0 # a reset also unlocks the account
# An MR must keep a headquarters; nobody else may gain one (DB check mirrors this).
if user.role == Role.MR and user.headquarters_id is None:
raise ValidationError("An MR must have a headquarters")
if user.role != Role.MR and user.headquarters_id is not None:
raise ValidationError("Only an MR can have a headquarters")
after = snapshot(user, _AUDIT_FIELDS)
if password_reset:
after["password_reset"] = True # the fact is logged, never the password or its hash
try:
await self.audit.log(
actor_user_id=actor.id,
entity_type=EntityType.USER,
entity_id=user.id,
action=AuditAction.DEACTIVATE if deactivating else AuditAction.UPDATE,
before=before,
after=after,
ip_address=ip,
)
await self.db.commit()
except IntegrityError as exc:
await self.db.rollback()
raise ConflictError("A user with this email or employee code already exists") from exc
# SEC-5 — revoke refresh tokens the moment a user is deactivated, or their
# credentials are changed, so an old session cannot outlive the old password/email.
if deactivating or password_reset or "email" in changes:
await AuthService(self.db).logout(user.id)
return user
async def list_users(self, actor: User, role: Role | None = None) -> list[User]:
stmt = select(User).where(User.company_id == actor.company_id)
if role is not None:
stmt = stmt.where(User.role == role)
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."""
hq_code = hq_name = None
manager_id = manager_name = None
if user.headquarters_id:
hq = await self.db.get(Headquarters, user.headquarters_id)
if hq:
hq_code, hq_name = hq.code, hq.name
stmt = (
select(User)
.join(AMHeadquarters, AMHeadquarters.area_manager_user_id == User.id)
.where(
AMHeadquarters.headquarters_id == user.headquarters_id,
AMHeadquarters.effective_to.is_(None),
)
)
manager = (await self.db.execute(stmt)).scalars().first()
if manager:
manager_id, manager_name = manager.id, manager.full_name
return MyProfile(
id=user.id,
full_name=user.full_name,
employee_code=user.employee_code,
email=user.email,
role=user.role,
phone=user.phone,
headquarters_id=user.headquarters_id,
headquarters_code=hq_code,
headquarters_name=hq_name,
reporting_manager_id=manager_id,
reporting_manager_name=manager_name,
)