Production
This commit is contained in:
@@ -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
|
||||
@@ -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",
|
||||
}
|
||||
@@ -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
|
||||
)
|
||||
@@ -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}"'},
|
||||
)
|
||||
Reference in New Issue
Block a user