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
+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}