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